You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

328 lines
9.6 KiB

  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. 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 updateCore {
  125. copyInternal()
  126. }
  127. if hasErrors {
  128. fmt.Println("FAIL")
  129. os.Exit(1)
  130. }
  131. vprintf("SUCCESS\n")
  132. }
  133. func appendToFile(file, text string) {
  134. fmt.Println("Augmenting", file)
  135. w, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0600)
  136. if err != nil {
  137. fmt.Println("Failed to open file:", err)
  138. os.Exit(1)
  139. }
  140. defer w.Close()
  141. if _, err := w.WriteString(text); err != nil {
  142. fmt.Println("Failed to write to file:", err)
  143. os.Exit(1)
  144. }
  145. }
  146. var (
  147. all sync.WaitGroup
  148. hasErrors bool
  149. )
  150. type dependency struct {
  151. sync.WaitGroup
  152. hasErrors bool
  153. }
  154. func generate(pkg string, deps ...*dependency) *dependency {
  155. var wg dependency
  156. if exclude(pkg) {
  157. return &wg
  158. }
  159. wg.Add(1)
  160. all.Add(1)
  161. go func() {
  162. defer wg.Done()
  163. defer all.Done()
  164. // Wait for dependencies to finish.
  165. for _, d := range deps {
  166. d.Wait()
  167. if d.hasErrors && !*force {
  168. fmt.Printf("--- ABORT: %s\n", pkg)
  169. wg.hasErrors = true
  170. return
  171. }
  172. }
  173. vprintf("=== GENERATE %s\n", pkg)
  174. args := []string{"generate"}
  175. if *verbose {
  176. args = append(args, "-v")
  177. }
  178. args = append(args, pkg)
  179. cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
  180. w := &bytes.Buffer{}
  181. cmd.Stderr = w
  182. cmd.Stdout = w
  183. if err := cmd.Run(); err != nil {
  184. fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
  185. hasErrors = true
  186. wg.hasErrors = true
  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. // copyInternal copies packages used by Go core into the internal directory.
  216. func copyInternal() {
  217. root := filepath.Join(build.Default.GOROOT, filepath.FromSlash("src/internal/x"))
  218. err := filepath.Walk(root, func(dir string, info os.FileInfo, err error) error {
  219. if err != nil || !info.IsDir() || root == dir {
  220. return err
  221. }
  222. src := dir[len(root)+1:]
  223. const slash = string(filepath.Separator)
  224. if c := strings.Split(src, slash); c[0] == "text" {
  225. // Copy a text repo package from its normal location.
  226. src = strings.Join(c[1:], slash)
  227. } else {
  228. // Copy the vendored package if it exists in the export directory.
  229. src = filepath.Join("internal", "export", filepath.Base(src))
  230. }
  231. copyPackage(src, dir, "golang.org", "internal")
  232. return nil
  233. })
  234. if err != nil {
  235. fmt.Printf("Seeding directory %s has failed %v:", root, err)
  236. os.Exit(1)
  237. }
  238. }
  239. // goGenRE is used to remove go:generate lines.
  240. var goGenRE = regexp.MustCompile("//go:generate[^\n]*\n")
  241. // copyPackage copies relevant files from a directory in x/text to the
  242. // destination package directory. The destination package is assumed to have
  243. // the same name. For each copied file go:generate lines are removed and
  244. // package comments are rewritten to the new path.
  245. func copyPackage(dirSrc, dirDst, search, replace string) {
  246. err := filepath.Walk(dirSrc, func(file string, info os.FileInfo, err error) error {
  247. base := filepath.Base(file)
  248. if err != nil || info.IsDir() ||
  249. !strings.HasSuffix(base, ".go") ||
  250. strings.HasSuffix(base, "_test.go") ||
  251. // Don't process subdirectories.
  252. filepath.Dir(file) != dirSrc {
  253. return nil
  254. }
  255. if strings.HasPrefix(base, "tables") {
  256. if !strings.HasSuffix(base, gen.UnicodeVersion()+".go") {
  257. return nil
  258. }
  259. base = "tables.go"
  260. }
  261. b, err := ioutil.ReadFile(file)
  262. if err != nil || bytes.Contains(b, []byte("\n// +build ignore")) {
  263. return err
  264. }
  265. // Fix paths.
  266. b = bytes.Replace(b, []byte(search), []byte(replace), -1)
  267. b = bytes.Replace(b, []byte("internal/export"), []byte(""), -1)
  268. // Remove go:generate lines.
  269. b = goGenRE.ReplaceAllLiteral(b, nil)
  270. comment := "// Code generated by running \"go generate\" in golang.org/x/text. DO NOT EDIT.\n\n"
  271. if !bytes.HasPrefix(b, []byte(comment)) {
  272. b = append([]byte(comment), b...)
  273. }
  274. if b, err = format.Source(b); err != nil {
  275. fmt.Println("Failed to format file:", err)
  276. os.Exit(1)
  277. }
  278. file = filepath.Join(dirDst, base)
  279. vprintf("=== COPY %s\n", file)
  280. return ioutil.WriteFile(file, b, 0666)
  281. })
  282. if err != nil {
  283. fmt.Println("Copying exported files failed:", err)
  284. os.Exit(1)
  285. }
  286. }
  287. func contains(a []string, s string) bool {
  288. for _, e := range a {
  289. if s == e {
  290. return true
  291. }
  292. }
  293. return false
  294. }
  295. func indent(b *bytes.Buffer) string {
  296. return strings.Replace(strings.TrimSpace(b.String()), "\n", "\n\t", -1)
  297. }