gen.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. // +build ignore
  5. // gen runs go generate on Unicode- and CLDR-related package in the text
  6. // repositories, taking into account dependencies and versions.
  7. package main
  8. import (
  9. "bytes"
  10. "flag"
  11. "fmt"
  12. "go/build"
  13. "go/format"
  14. "io/ioutil"
  15. "os"
  16. "os/exec"
  17. "path"
  18. "path/filepath"
  19. "regexp"
  20. "runtime"
  21. "strings"
  22. "sync"
  23. "unicode"
  24. "golang.org/x/text/collate"
  25. "golang.org/x/text/internal/gen"
  26. "golang.org/x/text/language"
  27. )
  28. var (
  29. verbose = flag.Bool("v", false, "verbose output")
  30. force = flag.Bool("force", false, "ignore failing dependencies")
  31. doCore = flag.Bool("core", false, "force an update to core")
  32. excludeList = flag.String("exclude", "",
  33. "comma-separated list of packages to exclude")
  34. // The user can specify a selection of packages to build on the command line.
  35. args []string
  36. )
  37. func exclude(pkg string) bool {
  38. if len(args) > 0 {
  39. return !contains(args, pkg)
  40. }
  41. return contains(strings.Split(*excludeList, ","), pkg)
  42. }
  43. // TODO:
  44. // - Better version handling.
  45. // - Generate tables for the core unicode package?
  46. // - Add generation for encodings. This requires some retooling here and there.
  47. // - Running repo-wide "long" tests.
  48. var vprintf = fmt.Printf
  49. func main() {
  50. gen.Init()
  51. args = flag.Args()
  52. if !*verbose {
  53. // Set vprintf to a no-op.
  54. vprintf = func(string, ...interface{}) (int, error) { return 0, nil }
  55. }
  56. // TODO: create temporary cache directory to load files and create and set
  57. // a "cache" option if the user did not specify the UNICODE_DIR environment
  58. // variable. This will prevent duplicate downloads and also will enable long
  59. // tests, which really need to be run after each generated package.
  60. updateCore := *doCore
  61. if gen.UnicodeVersion() != unicode.Version {
  62. fmt.Printf("Requested Unicode version %s; core unicode version is %s.\n",
  63. gen.UnicodeVersion(),
  64. unicode.Version)
  65. c := collate.New(language.Und, collate.Numeric)
  66. if c.CompareString(gen.UnicodeVersion(), unicode.Version) < 0 && !*force {
  67. os.Exit(2)
  68. }
  69. updateCore = true
  70. goroot := os.Getenv("GOROOT")
  71. appendToFile(
  72. filepath.Join(goroot, "api", "except.txt"),
  73. fmt.Sprintf("pkg unicode, const Version = %q\n", unicode.Version),
  74. )
  75. const lines = `pkg unicode, const Version = %q
  76. // TODO: add a new line of the following form for each new script and property.
  77. pkg unicode, var <new script or property> *RangeTable
  78. `
  79. appendToFile(
  80. filepath.Join(goroot, "api", "next.txt"),
  81. fmt.Sprintf(lines, gen.UnicodeVersion()),
  82. )
  83. }
  84. var unicode = &dependency{}
  85. if updateCore {
  86. fmt.Printf("Updating core to version %s...\n", gen.UnicodeVersion())
  87. unicode = generate("unicode")
  88. // Test some users of the unicode packages, especially the ones that
  89. // keep a mirrored table. These may need to be corrected by hand.
  90. generate("regexp", unicode)
  91. generate("strconv", unicode) // mimics Unicode table
  92. generate("strings", unicode)
  93. generate("testing", unicode) // mimics Unicode table
  94. }
  95. var (
  96. cldr = generate("./unicode/cldr", unicode)
  97. language = generate("./language", cldr)
  98. internal = generate("./internal", unicode, language)
  99. norm = generate("./unicode/norm", unicode)
  100. rangetable = generate("./unicode/rangetable", unicode)
  101. cases = generate("./cases", unicode, norm, language, rangetable)
  102. width = generate("./width", unicode)
  103. bidi = generate("./unicode/bidi", unicode, norm, rangetable)
  104. mib = generate("./encoding/internal/identifier", unicode)
  105. number = generate("./internal/number", unicode, cldr, language, internal)
  106. _ = generate("./encoding/htmlindex", unicode, language, mib)
  107. _ = generate("./encoding/ianaindex", unicode, language, mib)
  108. _ = generate("./secure/precis", unicode, norm, rangetable, cases, width, bidi)
  109. _ = generate("./internal/cldrtree", language)
  110. _ = generate("./currency", unicode, cldr, language, internal, number)
  111. _ = generate("./feature/plural", unicode, cldr, language, internal, number)
  112. _ = generate("./internal/export/idna", unicode, bidi, norm)
  113. _ = generate("./language/display", unicode, cldr, language, internal, number)
  114. _ = generate("./collate", unicode, norm, cldr, language, rangetable)
  115. _ = generate("./search", unicode, norm, cldr, language, rangetable)
  116. )
  117. all.Wait()
  118. // Copy exported packages to the destination golang.org repo.
  119. copyExported("golang.org/x/net/idna")
  120. if updateCore {
  121. copyVendored()
  122. }
  123. if hasErrors {
  124. fmt.Println("FAIL")
  125. os.Exit(1)
  126. }
  127. vprintf("SUCCESS\n")
  128. }
  129. func appendToFile(file, text string) {
  130. fmt.Println("Augmenting", file)
  131. w, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
  132. if err != nil {
  133. fmt.Println("Failed to open file:", err)
  134. os.Exit(1)
  135. }
  136. defer w.Close()
  137. if _, err := w.WriteString(text); err != nil {
  138. fmt.Println("Failed to write to file:", err)
  139. os.Exit(1)
  140. }
  141. }
  142. var (
  143. all sync.WaitGroup
  144. hasErrors bool
  145. )
  146. type dependency struct {
  147. sync.WaitGroup
  148. hasErrors bool
  149. }
  150. func generate(pkg string, deps ...*dependency) *dependency {
  151. var wg dependency
  152. if exclude(pkg) {
  153. return &wg
  154. }
  155. wg.Add(1)
  156. all.Add(1)
  157. go func() {
  158. defer wg.Done()
  159. defer all.Done()
  160. // Wait for dependencies to finish.
  161. for _, d := range deps {
  162. d.Wait()
  163. if d.hasErrors && !*force {
  164. fmt.Printf("--- ABORT: %s\n", pkg)
  165. wg.hasErrors = true
  166. return
  167. }
  168. }
  169. vprintf("=== GENERATE %s\n", pkg)
  170. args := []string{"generate"}
  171. if *verbose {
  172. args = append(args, "-v")
  173. }
  174. args = append(args, pkg)
  175. cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  176. w := &bytes.Buffer{}
  177. cmd.Stderr = w
  178. cmd.Stdout = w
  179. if err := cmd.Run(); err != nil {
  180. fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
  181. hasErrors = true
  182. wg.hasErrors = true
  183. return
  184. }
  185. vprintf("=== TEST %s\n", pkg)
  186. args[0] = "test"
  187. cmd = exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  188. wt := &bytes.Buffer{}
  189. cmd.Stderr = wt
  190. cmd.Stdout = wt
  191. if err := cmd.Run(); err != nil {
  192. fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(wt), err)
  193. hasErrors = true
  194. wg.hasErrors = true
  195. return
  196. }
  197. vprintf("--- SUCCESS: %s\n\t%v\n", pkg, indent(w))
  198. fmt.Print(wt.String())
  199. }()
  200. return &wg
  201. }
  202. // copyExported copies a package in x/text/internal/export to the
  203. // destination repository.
  204. func copyExported(p string) {
  205. copyPackage(
  206. filepath.Join("internal", "export", path.Base(p)),
  207. filepath.Join("..", filepath.FromSlash(p[len("golang.org/x"):])),
  208. "golang.org/x/text/internal/export/"+path.Base(p),
  209. p)
  210. }
  211. // copyVendored copies packages used by Go core into the vendored directory.
  212. func copyVendored() {
  213. root := filepath.Join(build.Default.GOROOT, filepath.FromSlash("src/vendor/golang_org/x"))
  214. err := filepath.Walk(root, func(dir string, info os.FileInfo, err error) error {
  215. if err != nil || !info.IsDir() || root == dir {
  216. return err
  217. }
  218. src := dir[len(root)+1:]
  219. const slash = string(filepath.Separator)
  220. if c := strings.Split(src, slash); c[0] == "text" {
  221. // Copy a text repo package from its normal location.
  222. src = strings.Join(c[1:], slash)
  223. } else {
  224. // Copy the vendored package if it exists in the export directory.
  225. src = filepath.Join("internal", "export", filepath.Base(src))
  226. }
  227. copyPackage(src, dir, "golang.org", "golang_org")
  228. return nil
  229. })
  230. if err != nil {
  231. fmt.Printf("Seeding directory %s has failed %v:", root, err)
  232. os.Exit(1)
  233. }
  234. }
  235. // goGenRE is used to remove go:generate lines.
  236. var goGenRE = regexp.MustCompile("//go:generate[^\n]*\n")
  237. // copyPackage copies relevant files from a directory in x/text to the
  238. // destination package directory. The destination package is assumed to have
  239. // the same name. For each copied file go:generate lines are removed and
  240. // and package comments are rewritten to the new path.
  241. func copyPackage(dirSrc, dirDst, search, replace string) {
  242. err := filepath.Walk(dirSrc, func(file string, info os.FileInfo, err error) error {
  243. base := filepath.Base(file)
  244. if err != nil || info.IsDir() ||
  245. !strings.HasSuffix(base, ".go") ||
  246. strings.HasSuffix(base, "_test.go") ||
  247. // Don't process subdirectories.
  248. filepath.Dir(file) != dirSrc {
  249. return nil
  250. }
  251. b, err := ioutil.ReadFile(file)
  252. if err != nil || bytes.Contains(b, []byte("\n// +build ignore")) {
  253. return err
  254. }
  255. // Fix paths.
  256. b = bytes.Replace(b, []byte(search), []byte(replace), -1)
  257. // Remove go:generate lines.
  258. b = goGenRE.ReplaceAllLiteral(b, nil)
  259. comment := "// Code generated by running \"go generate\" in golang.org/x/text. DO NOT EDIT.\n\n"
  260. if *doCore {
  261. comment = "// Code generated by running \"go run gen.go -core\" in golang.org/x/text. DO NOT EDIT.\n\n"
  262. }
  263. if !bytes.HasPrefix(b, []byte(comment)) {
  264. b = append([]byte(comment), b...)
  265. }
  266. if b, err = format.Source(b); err != nil {
  267. fmt.Println("Failed to format file:", err)
  268. os.Exit(1)
  269. }
  270. file = filepath.Join(dirDst, base)
  271. vprintf("=== COPY %s\n", file)
  272. return ioutil.WriteFile(file, b, 0666)
  273. })
  274. if err != nil {
  275. fmt.Println("Copying exported files failed:", err)
  276. os.Exit(1)
  277. }
  278. }
  279. func contains(a []string, s string) bool {
  280. for _, e := range a {
  281. if s == e {
  282. return true
  283. }
  284. }
  285. return false
  286. }
  287. func indent(b *bytes.Buffer) string {
  288. return strings.Replace(strings.TrimSpace(b.String()), "\n", "\n\t", -1)
  289. }