gen.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/format"
  13. "io/ioutil"
  14. "os"
  15. "os/exec"
  16. "path"
  17. "path/filepath"
  18. "regexp"
  19. "runtime"
  20. "strings"
  21. "sync"
  22. "unicode"
  23. "golang.org/x/text/collate"
  24. "golang.org/x/text/internal/gen"
  25. "golang.org/x/text/language"
  26. )
  27. var (
  28. verbose = flag.Bool("v", false, "verbose output")
  29. force = flag.Bool("force", false, "ignore failing dependencies")
  30. doCore = flag.Bool("core", false, "force an update to core")
  31. skipTest = flag.Bool("skiptest", false, "skip tests")
  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. unicodeInternal := generate("./internal/export/unicode")
  88. unicode = generate("unicode", unicodeInternal)
  89. // Test some users of the unicode packages, especially the ones that
  90. // keep a mirrored table. These may need to be corrected by hand.
  91. generate("regexp", unicode)
  92. generate("strconv", unicode) // mimics Unicode table
  93. generate("strings", unicode)
  94. generate("testing", unicode) // mimics Unicode table
  95. }
  96. var (
  97. cldr = generate("./unicode/cldr", unicode)
  98. compact = generate("./internal/language/compact", cldr)
  99. language = generate("./language", cldr, compact)
  100. internal = generate("./internal", unicode, language)
  101. norm = generate("./unicode/norm", unicode)
  102. rangetable = generate("./unicode/rangetable", unicode)
  103. cases = generate("./cases", unicode, norm, language, rangetable)
  104. width = generate("./width", unicode)
  105. bidi = generate("./unicode/bidi", unicode, norm, rangetable)
  106. mib = generate("./encoding/internal/identifier", unicode)
  107. number = generate("./internal/number", unicode, cldr, language, internal)
  108. cldrtree = generate("./internal/cldrtree", language, internal)
  109. _ = generate("./unicode/runenames", unicode)
  110. _ = generate("./encoding/htmlindex", unicode, language, mib)
  111. _ = generate("./encoding/ianaindex", unicode, language, mib)
  112. _ = generate("./secure/precis", unicode, norm, rangetable, cases, width, bidi)
  113. _ = generate("./currency", unicode, cldr, language, internal, number)
  114. _ = generate("./feature/plural", unicode, cldr, language, internal, number)
  115. _ = generate("./internal/export/idna", unicode, bidi, norm)
  116. _ = generate("./language/display", unicode, cldr, language, internal, number)
  117. _ = generate("./collate", unicode, norm, cldr, language, rangetable)
  118. _ = generate("./search", unicode, norm, cldr, language, rangetable)
  119. _ = generate("./date", cldr, language, cldrtree)
  120. )
  121. all.Wait()
  122. // Copy exported packages to the destination golang.org repo.
  123. copyExported("golang.org/x/net/idna")
  124. if hasErrors {
  125. fmt.Println("FAIL")
  126. os.Exit(1)
  127. }
  128. vprintf("SUCCESS\n")
  129. }
  130. func appendToFile(file, text string) {
  131. fmt.Println("Augmenting", file)
  132. w, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
  133. if err != nil {
  134. fmt.Println("Failed to open file:", err)
  135. os.Exit(1)
  136. }
  137. defer w.Close()
  138. if _, err := w.WriteString(text); err != nil {
  139. fmt.Println("Failed to write to file:", err)
  140. os.Exit(1)
  141. }
  142. }
  143. var (
  144. all sync.WaitGroup
  145. hasErrors bool
  146. )
  147. type dependency struct {
  148. sync.WaitGroup
  149. hasErrors bool
  150. }
  151. func generate(pkg string, deps ...*dependency) *dependency {
  152. var wg dependency
  153. if exclude(pkg) {
  154. return &wg
  155. }
  156. wg.Add(1)
  157. all.Add(1)
  158. go func() {
  159. defer wg.Done()
  160. defer all.Done()
  161. // Wait for dependencies to finish.
  162. for _, d := range deps {
  163. d.Wait()
  164. if d.hasErrors && !*force {
  165. fmt.Printf("--- ABORT: %s\n", pkg)
  166. wg.hasErrors = true
  167. return
  168. }
  169. }
  170. vprintf("=== GENERATE %s\n", pkg)
  171. args := []string{"generate"}
  172. if *verbose {
  173. args = append(args, "-v")
  174. }
  175. args = append(args, pkg)
  176. cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  177. w := &bytes.Buffer{}
  178. cmd.Stderr = w
  179. cmd.Stdout = w
  180. if err := cmd.Run(); err != nil {
  181. fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
  182. hasErrors = true
  183. wg.hasErrors = true
  184. return
  185. }
  186. if *skipTest {
  187. return
  188. }
  189. vprintf("=== TEST %s\n", pkg)
  190. args[0] = "test"
  191. cmd = exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  192. wt := &bytes.Buffer{}
  193. cmd.Stderr = wt
  194. cmd.Stdout = wt
  195. if err := cmd.Run(); err != nil {
  196. fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(wt), err)
  197. hasErrors = true
  198. wg.hasErrors = true
  199. return
  200. }
  201. vprintf("--- SUCCESS: %s\n\t%v\n", pkg, indent(w))
  202. fmt.Print(wt.String())
  203. }()
  204. return &wg
  205. }
  206. // copyExported copies a package in x/text/internal/export to the
  207. // destination repository.
  208. func copyExported(p string) {
  209. copyPackage(
  210. filepath.Join("internal", "export", path.Base(p)),
  211. filepath.Join("..", filepath.FromSlash(p[len("golang.org/x"):])),
  212. "golang.org/x/text/internal/export/"+path.Base(p),
  213. p)
  214. }
  215. // goGenRE is used to remove go:generate lines.
  216. var goGenRE = regexp.MustCompile("//go:generate[^\n]*\n")
  217. // copyPackage copies relevant files from a directory in x/text to the
  218. // destination package directory. The destination package is assumed to have
  219. // the same name. For each copied file go:generate lines are removed and
  220. // package comments are rewritten to the new path.
  221. func copyPackage(dirSrc, dirDst, search, replace string) {
  222. err := filepath.Walk(dirSrc, func(file string, info os.FileInfo, err error) error {
  223. base := filepath.Base(file)
  224. if err != nil || info.IsDir() ||
  225. !strings.HasSuffix(base, ".go") ||
  226. strings.HasSuffix(base, "_test.go") ||
  227. // Don't process subdirectories.
  228. filepath.Dir(file) != dirSrc {
  229. return nil
  230. }
  231. if strings.HasPrefix(base, "tables") {
  232. if !strings.HasSuffix(base, gen.UnicodeVersion()+".go") {
  233. return nil
  234. }
  235. base = "tables.go"
  236. }
  237. b, err := ioutil.ReadFile(file)
  238. if err != nil || bytes.Contains(b, []byte("\n// +build ignore")) {
  239. return err
  240. }
  241. // Fix paths.
  242. b = bytes.Replace(b, []byte(search), []byte(replace), -1)
  243. b = bytes.Replace(b, []byte("internal/export"), []byte(""), -1)
  244. // Remove go:generate lines.
  245. b = goGenRE.ReplaceAllLiteral(b, nil)
  246. comment := "// Code generated by running \"go generate\" in golang.org/x/text. DO NOT EDIT.\n\n"
  247. if !bytes.HasPrefix(b, []byte(comment)) {
  248. b = append([]byte(comment), b...)
  249. }
  250. if b, err = format.Source(b); err != nil {
  251. fmt.Println("Failed to format file:", err)
  252. os.Exit(1)
  253. }
  254. file = filepath.Join(dirDst, base)
  255. vprintf("=== COPY %s\n", file)
  256. return ioutil.WriteFile(file, b, 0666)
  257. })
  258. if err != nil {
  259. fmt.Println("Copying exported files failed:", err)
  260. os.Exit(1)
  261. }
  262. }
  263. func contains(a []string, s string) bool {
  264. for _, e := range a {
  265. if s == e {
  266. return true
  267. }
  268. }
  269. return false
  270. }
  271. func indent(b *bytes.Buffer) string {
  272. return strings.Replace(strings.TrimSpace(b.String()), "\n", "\n\t", -1)
  273. }