gen.go 8.6 KB

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