gen.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package gen contains common code for the various code generation tools in the
  5. // text repository. Its usage ensures consistency between tools.
  6. //
  7. // This package defines command line flags that are common to most generation
  8. // tools. The flags allow for specifying specific Unicode and CLDR versions
  9. // in the public Unicode data repository (http://www.unicode.org/Public).
  10. //
  11. // A local Unicode data mirror can be set through the flag -local or the
  12. // environment variable UNICODE_DIR. The former takes precedence. The local
  13. // directory should follow the same structure as the public repository.
  14. //
  15. // IANA data can also optionally be mirrored by putting it in the iana directory
  16. // rooted at the top of the local mirror. Beware, though, that IANA data is not
  17. // versioned. So it is up to the developer to use the right version.
  18. package gen // import "golang.org/x/text/internal/gen"
  19. import (
  20. "bytes"
  21. "flag"
  22. "fmt"
  23. "go/build"
  24. "go/format"
  25. "io"
  26. "io/ioutil"
  27. "log"
  28. "net/http"
  29. "os"
  30. "path"
  31. "path/filepath"
  32. "sync"
  33. "unicode"
  34. "golang.org/x/text/unicode/cldr"
  35. )
  36. var (
  37. url = flag.String("url",
  38. "http://www.unicode.org/Public",
  39. "URL of Unicode database directory")
  40. iana = flag.String("iana",
  41. "http://www.iana.org",
  42. "URL of the IANA repository")
  43. unicodeVersion = flag.String("unicode",
  44. getEnv("UNICODE_VERSION", unicode.Version),
  45. "unicode version to use")
  46. cldrVersion = flag.String("cldr",
  47. getEnv("CLDR_VERSION", cldr.Version),
  48. "cldr version to use")
  49. )
  50. func getEnv(name, def string) string {
  51. if v := os.Getenv(name); v != "" {
  52. return v
  53. }
  54. return def
  55. }
  56. // Init performs common initialization for a gen command. It parses the flags
  57. // and sets up the standard logging parameters.
  58. func Init() {
  59. log.SetPrefix("")
  60. log.SetFlags(log.Lshortfile)
  61. flag.Parse()
  62. }
  63. const header = `// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
  64. package %s
  65. `
  66. // UnicodeVersion reports the requested Unicode version.
  67. func UnicodeVersion() string {
  68. return *unicodeVersion
  69. }
  70. // UnicodeVersion reports the requested CLDR version.
  71. func CLDRVersion() string {
  72. return *cldrVersion
  73. }
  74. // IsLocal reports whether data files are available locally.
  75. func IsLocal() bool {
  76. dir, err := localReadmeFile()
  77. if err != nil {
  78. return false
  79. }
  80. if _, err = os.Stat(dir); err != nil {
  81. return false
  82. }
  83. return true
  84. }
  85. // OpenUCDFile opens the requested UCD file. The file is specified relative to
  86. // the public Unicode root directory. It will call log.Fatal if there are any
  87. // errors.
  88. func OpenUCDFile(file string) io.ReadCloser {
  89. return openUnicode(path.Join(*unicodeVersion, "ucd", file))
  90. }
  91. // OpenCLDRCoreZip opens the CLDR core zip file. It will call log.Fatal if there
  92. // are any errors.
  93. func OpenCLDRCoreZip() io.ReadCloser {
  94. return OpenUnicodeFile("cldr", *cldrVersion, "core.zip")
  95. }
  96. // OpenUnicodeFile opens the requested file of the requested category from the
  97. // root of the Unicode data archive. The file is specified relative to the
  98. // public Unicode root directory. If version is "", it will use the default
  99. // Unicode version. It will call log.Fatal if there are any errors.
  100. func OpenUnicodeFile(category, version, file string) io.ReadCloser {
  101. if version == "" {
  102. version = UnicodeVersion()
  103. }
  104. return openUnicode(path.Join(category, version, file))
  105. }
  106. // OpenIANAFile opens the requested IANA file. The file is specified relative
  107. // to the IANA root, which is typically either http://www.iana.org or the
  108. // iana directory in the local mirror. It will call log.Fatal if there are any
  109. // errors.
  110. func OpenIANAFile(path string) io.ReadCloser {
  111. return Open(*iana, "iana", path)
  112. }
  113. var (
  114. dirMutex sync.Mutex
  115. localDir string
  116. )
  117. const permissions = 0755
  118. func localReadmeFile() (string, error) {
  119. p, err := build.Import("golang.org/x/text", "", build.FindOnly)
  120. if err != nil {
  121. return "", fmt.Errorf("Could not locate package: %v", err)
  122. }
  123. return filepath.Join(p.Dir, "DATA", "README"), nil
  124. }
  125. func getLocalDir() string {
  126. dirMutex.Lock()
  127. defer dirMutex.Unlock()
  128. readme, err := localReadmeFile()
  129. if err != nil {
  130. log.Fatal(err)
  131. }
  132. dir := filepath.Dir(readme)
  133. if _, err := os.Stat(readme); err != nil {
  134. if err := os.MkdirAll(dir, permissions); err != nil {
  135. log.Fatalf("Could not create directory: %v", err)
  136. }
  137. ioutil.WriteFile(readme, []byte(readmeTxt), permissions)
  138. }
  139. return dir
  140. }
  141. const readmeTxt = `Generated by golang.org/x/text/internal/gen. DO NOT EDIT.
  142. This directory contains downloaded files used to generate the various tables
  143. in the golang.org/x/text subrepo.
  144. Note that the language subtag repo (iana/assignments/language-subtag-registry)
  145. and all other times in the iana subdirectory are not versioned and will need
  146. to be periodically manually updated. The easiest way to do this is to remove
  147. the entire iana directory. This is mostly of concern when updating the language
  148. package.
  149. `
  150. // Open opens subdir/path if a local directory is specified and the file exists,
  151. // where subdir is a directory relative to the local root, or fetches it from
  152. // urlRoot/path otherwise. It will call log.Fatal if there are any errors.
  153. func Open(urlRoot, subdir, path string) io.ReadCloser {
  154. file := filepath.Join(getLocalDir(), subdir, filepath.FromSlash(path))
  155. return open(file, urlRoot, path)
  156. }
  157. func openUnicode(path string) io.ReadCloser {
  158. file := filepath.Join(getLocalDir(), filepath.FromSlash(path))
  159. return open(file, *url, path)
  160. }
  161. // TODO: automatically periodically update non-versioned files.
  162. func open(file, urlRoot, path string) io.ReadCloser {
  163. if f, err := os.Open(file); err == nil {
  164. return f
  165. }
  166. r := get(urlRoot, path)
  167. defer r.Close()
  168. b, err := ioutil.ReadAll(r)
  169. if err != nil {
  170. log.Fatalf("Could not download file: %v", err)
  171. }
  172. os.MkdirAll(filepath.Dir(file), permissions)
  173. if err := ioutil.WriteFile(file, b, permissions); err != nil {
  174. log.Fatalf("Could not create file: %v", err)
  175. }
  176. return ioutil.NopCloser(bytes.NewReader(b))
  177. }
  178. func get(root, path string) io.ReadCloser {
  179. url := root + "/" + path
  180. fmt.Printf("Fetching %s...", url)
  181. defer fmt.Println(" done.")
  182. resp, err := http.Get(url)
  183. if err != nil {
  184. log.Fatalf("HTTP GET: %v", err)
  185. }
  186. if resp.StatusCode != 200 {
  187. log.Fatalf("Bad GET status for %q: %q", url, resp.Status)
  188. }
  189. return resp.Body
  190. }
  191. // TODO: use Write*Version in all applicable packages.
  192. // WriteUnicodeVersion writes a constant for the Unicode version from which the
  193. // tables are generated.
  194. func WriteUnicodeVersion(w io.Writer) {
  195. fmt.Fprintf(w, "// UnicodeVersion is the Unicode version from which the tables in this package are derived.\n")
  196. fmt.Fprintf(w, "const UnicodeVersion = %q\n\n", UnicodeVersion())
  197. }
  198. // WriteCLDRVersion writes a constant for the CLDR version from which the
  199. // tables are generated.
  200. func WriteCLDRVersion(w io.Writer) {
  201. fmt.Fprintf(w, "// CLDRVersion is the CLDR version from which the tables in this package are derived.\n")
  202. fmt.Fprintf(w, "const CLDRVersion = %q\n\n", CLDRVersion())
  203. }
  204. // WriteGoFile prepends a standard file comment and package statement to the
  205. // given bytes, applies gofmt, and writes them to a file with the given name.
  206. // It will call log.Fatal if there are any errors.
  207. func WriteGoFile(filename, pkg string, b []byte) {
  208. w, err := os.Create(filename)
  209. if err != nil {
  210. log.Fatalf("Could not create file %s: %v", filename, err)
  211. }
  212. defer w.Close()
  213. if _, err = WriteGo(w, pkg, b); err != nil {
  214. log.Fatalf("Error writing file %s: %v", filename, err)
  215. }
  216. }
  217. // WriteGo prepends a standard file comment and package statement to the given
  218. // bytes, applies gofmt, and writes them to w.
  219. func WriteGo(w io.Writer, pkg string, b []byte) (n int, err error) {
  220. src := []byte(fmt.Sprintf(header, pkg))
  221. src = append(src, b...)
  222. formatted, err := format.Source(src)
  223. if err != nil {
  224. // Print the generated code even in case of an error so that the
  225. // returned error can be meaningfully interpreted.
  226. n, _ = w.Write(src)
  227. return n, err
  228. }
  229. return w.Write(formatted)
  230. }
  231. // Repackage rewrites a Go file from belonging to package main to belonging to
  232. // the given package.
  233. func Repackage(inFile, outFile, pkg string) {
  234. src, err := ioutil.ReadFile(inFile)
  235. if err != nil {
  236. log.Fatalf("reading %s: %v", inFile, err)
  237. }
  238. const toDelete = "package main\n\n"
  239. i := bytes.Index(src, []byte(toDelete))
  240. if i < 0 {
  241. log.Fatalf("Could not find %q in %s.", toDelete, inFile)
  242. }
  243. w := &bytes.Buffer{}
  244. w.Write(src[i+len(toDelete):])
  245. WriteGoFile(outFile, pkg, w.Bytes())
  246. }