Debian Codegraph @

internal/gen/gen.go

raw
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
5 // Package gen contains common code for the various code generation tools in the
6 // text repository. Its usage ensures consistency between tools.
7 //
8 // This package defines command line flags that are common to most generation
9 // tools. The flags allow for specifying specific Unicode and CLDR versions
10 // in the public Unicode data repository (https://www.unicode.org/Public).
11 //
12 // A local Unicode data mirror can be set through the flag -local or the
13 // environment variable UNICODE_DIR. The former takes precedence. The local
14 // directory should follow the same structure as the public repository.
15 //
16 // IANA data can also optionally be mirrored by putting it in the iana directory
17 // rooted at the top of the local mirror. Beware, though, that IANA data is not
18 // versioned. So it is up to the developer to use the right version.
19 package gen // import "golang.org/x/text/internal/gen"
20
21 import (
22 "bytes"
23 "flag"
24 "fmt"
25 "go/build"
26 "go/format"
27 "io"
28 "log"
29 "net/http"
30 "os"
31 "path"
32 "path/filepath"
33 "regexp"
34 "strings"
35 "sync"
36 "unicode"
37
38 "golang.org/x/text/unicode/cldr"
39 )
40
41 var (
42 url = flag.String("url",
43 "https://www.unicode.org/Public",
44 "URL of Unicode database directory")
45 iana = flag.String("iana",
46 "http://www.iana.org",
47 "URL of the IANA repository")
48 unicodeVersion = flag.String("unicode",
49 getEnv("UNICODE_VERSION", unicode.Version),
50 "unicode version to use")
51 cldrVersion = flag.String("cldr",
52 getEnv("CLDR_VERSION", cldr.Version),
53 "cldr version to use")
54 )
55
56 func getEnv(name, def string) string {
57 if v := os.Getenv(name); v != "" {
58 return v
59 }
60 return def
61 }
62
63 // Init performs common initialization for a gen command. It parses the flags
64 // and sets up the standard logging parameters.
65 func Init() {
66 log.SetPrefix("")
67 log.SetFlags(log.Lshortfile)
68 flag.Parse()
69 }
70
71 const header = `// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT.
72
73 `
74
75 // UnicodeVersion reports the requested Unicode version.
76 func UnicodeVersion() string {
77 return *unicodeVersion
78 }
79
80 // CLDRVersion reports the requested CLDR version.
81 func CLDRVersion() string {
82 return *cldrVersion
83 }
84
85 var tags = []struct{ version, buildTags string }{
86 {"15.0.0", "!go1.27"},
87 {"17.0.0", "go1.27"},
88 }
89
90 // buildTags reports the build tags used for the current Unicode version.
91 func buildTags() string {
92 v := UnicodeVersion()
93 for _, e := range tags {
94 if e.version == v {
95 return e.buildTags
96 }
97 }
98 log.Fatalf("Unknown build tags for Unicode version %q.", v)
99 return ""
100 }
101
102 // IsLocal reports whether data files are available locally.
103 func IsLocal() bool {
104 dir, err := localReadmeFile()
105 if err != nil {
106 return false
107 }
108 if _, err = os.Stat(dir); err != nil {
109 return false
110 }
111 return true
112 }
113
114 // OpenUCDFile opens the requested UCD file. The file is specified relative to
115 // the public Unicode root directory. It will call log.Fatal if there are any
116 // errors.
117 func OpenUCDFile(file string) io.ReadCloser {
118 return openUnicode(path.Join(*unicodeVersion, "ucd", file))
119 }
120
121 // OpenCLDRCoreZip opens the CLDR core zip file. It will call log.Fatal if there
122 // are any errors.
123 func OpenCLDRCoreZip() io.ReadCloser {
124 return OpenUnicodeFile("cldr", *cldrVersion, "core.zip")
125 }
126
127 // OpenUnicodeFile opens the requested file of the requested category from the
128 // root of the Unicode data archive. The file is specified relative to the
129 // public Unicode root directory. If version is "", it will use the default
130 // Unicode version. It will call log.Fatal if there are any errors.
131 func OpenUnicodeFile(category, version, file string) io.ReadCloser {
132 if version == "" {
133 version = UnicodeVersion()
134 }
135 return openUnicode(path.Join(category, version, file))
136 }
137
138 // OpenIANAFile opens the requested IANA file. The file is specified relative
139 // to the IANA root, which is typically either http://www.iana.org or the
140 // iana directory in the local mirror. It will call log.Fatal if there are any
141 // errors.
142 func OpenIANAFile(path string) io.ReadCloser {
143 return Open(*iana, "iana", path)
144 }
145
146 var (
147 dirMutex sync.Mutex
148 localDir string
149 )
150
151 const permissions = 0755
152
153 func localReadmeFile() (string, error) {
154 p, err := build.Import("golang.org/x/text", "", build.FindOnly)
155 if err != nil {
156 return "", fmt.Errorf("Could not locate package: %v", err)
157 }
158 return filepath.Join(p.Dir, "DATA", "README"), nil
159 }
160
161 func getLocalDir() string {
162 dirMutex.Lock()
163 defer dirMutex.Unlock()
164
165 readme, err := localReadmeFile()
166 if err != nil {
167 log.Fatal(err)
168 }
169 dir := filepath.Dir(readme)
170 if _, err := os.Stat(readme); err != nil {
171 if err := os.MkdirAll(dir, permissions); err != nil {
172 log.Fatalf("Could not create directory: %v", err)
173 }
174 os.WriteFile(readme, []byte(readmeTxt), permissions)
175 }
176 return dir
177 }
178
179 const readmeTxt = `Generated by golang.org/x/text/internal/gen. DO NOT EDIT.
180
181 This directory contains downloaded files used to generate the various tables
182 in the golang.org/x/text subrepo.
183
184 Note that the language subtag repo (iana/assignments/language-subtag-registry)
185 and all other times in the iana subdirectory are not versioned and will need
186 to be periodically manually updated. The easiest way to do this is to remove
187 the entire iana directory. This is mostly of concern when updating the language
188 package.
189 `
190
191 // Open opens subdir/path if a local directory is specified and the file exists,
192 // where subdir is a directory relative to the local root, or fetches it from
193 // urlRoot/path otherwise. It will call log.Fatal if there are any errors.
194 func Open(urlRoot, subdir, path string) io.ReadCloser {
195 file := filepath.Join(getLocalDir(), subdir, filepath.FromSlash(path))
196 return open(file, urlRoot, path)
197 }
198
199 func openUnicode(path string) io.ReadCloser {
200 file := filepath.Join(getLocalDir(), filepath.FromSlash(path))
201 return open(file, *url, path)
202 }
203
204 // TODO: automatically periodically update non-versioned files.
205
206 func open(file, urlRoot, path string) io.ReadCloser {
207 if f, err := os.Open(file); err == nil {
208 return f
209 }
210 r := get(urlRoot, path)
211 defer r.Close()
212 b, err := io.ReadAll(r)
213 if err != nil {
214 log.Fatalf("Could not download file: %v", err)
215 }
216 os.MkdirAll(filepath.Dir(file), permissions)
217 if err := os.WriteFile(file, b, permissions); err != nil {
218 log.Fatalf("Could not create file: %v", err)
219 }
220 return io.NopCloser(bytes.NewReader(b))
221 }
222
223 func get(root, path string) io.ReadCloser {
224 url := root + "/" + path
225 fmt.Printf("Fetching %s...", url)
226 defer fmt.Println(" done.")
227 resp, err := http.Get(url)
228 if err != nil {
229 log.Fatalf("HTTP GET: %v", err)
230 }
231 if resp.StatusCode != 200 {
232 log.Fatalf("Bad GET status for %q: %q", url, resp.Status)
233 }
234 return resp.Body
235 }
236
237 // TODO: use Write*Version in all applicable packages.
238
239 // WriteUnicodeVersion writes a constant for the Unicode version from which the
240 // tables are generated.
241 func WriteUnicodeVersion(w io.Writer) {
242 fmt.Fprintf(w, "// UnicodeVersion is the Unicode version from which the tables in this package are derived.\n")
243 fmt.Fprintf(w, "const UnicodeVersion = %q\n\n", UnicodeVersion())
244 }
245
246 // WriteCLDRVersion writes a constant for the CLDR version from which the
247 // tables are generated.
248 func WriteCLDRVersion(w io.Writer) {
249 fmt.Fprintf(w, "// CLDRVersion is the CLDR version from which the tables in this package are derived.\n")
250 fmt.Fprintf(w, "const CLDRVersion = %q\n\n", CLDRVersion())
251 }
252
253 // WriteGoFile prepends a standard file comment and package statement to the
254 // given bytes, applies gofmt, and writes them to a file with the given name.
255 // It will call log.Fatal if there are any errors.
256 func WriteGoFile(filename, pkg string, b []byte) {
257 w, err := os.Create(filename)
258 if err != nil {
259 log.Fatalf("Could not create file %s: %v", filename, err)
260 }
261 defer w.Close()
262 if _, err = WriteGo(w, pkg, "", b); err != nil {
263 log.Fatalf("Error writing file %s: %v", filename, err)
264 }
265 }
266
267 func fileToPattern(filename string) string {
268 suffix := ".go"
269 if strings.HasSuffix(filename, "_test.go") {
270 suffix = "_test.go"
271 }
272 prefix := filename[:len(filename)-len(suffix)]
273 return fmt.Sprint(prefix, "%s", suffix)
274 }
275
276 // tagLines returns the //go:build lines to add to the file.
277 func tagLines(tags string) string {
278 return "//go:build " + strings.ReplaceAll(tags, ",", " && ") + "\n"
279 }
280
281 func updateBuildTags(pattern string) {
282 for _, t := range tags {
283 oldFile := fmt.Sprintf(pattern, t.version)
284 b, err := os.ReadFile(oldFile)
285 if err != nil {
286 continue
287 }
288 b = regexp.MustCompile(`//go:build.*\n`).ReplaceAll(b, []byte(tagLines(t.buildTags)))
289 err = os.WriteFile(oldFile, b, 0644)
290 if err != nil {
291 log.Fatal(err)
292 }
293 }
294 }
295
296 // WriteVersionedGoFile prepends a standard file comment, adds build tags to
297 // version the file for the current Unicode version, and package statement to
298 // the given bytes, applies gofmt, and writes them to a file with the given
299 // name. It will call log.Fatal if there are any errors.
300 func WriteVersionedGoFile(filename, pkg string, b []byte) {
301 pattern := fileToPattern(filename)
302 updateBuildTags(pattern)
303 filename = fmt.Sprintf(pattern, UnicodeVersion())
304
305 w, err := os.Create(filename)
306 if err != nil {
307 log.Fatalf("Could not create file %s: %v", filename, err)
308 }
309 defer w.Close()
310 if _, err = WriteGo(w, pkg, buildTags(), b); err != nil {
311 log.Fatalf("Error writing file %s: %v", filename, err)
312 }
313 }
314
315 // WriteGo prepends a standard file comment and package statement to the given
316 // bytes, applies gofmt, and writes them to w.
317 func WriteGo(w io.Writer, pkg, tags string, b []byte) (n int, err error) {
318 src := []byte(header)
319 if tags != "" {
320 src = append(src, tagLines(tags)...)
321 src = append(src, '\n')
322 }
323 src = append(src, fmt.Sprintf("package %s\n\n", pkg)...)
324 src = append(src, b...)
325 formatted, err := format.Source(src)
326 if err != nil {
327 // Print the generated code even in case of an error so that the
328 // returned error can be meaningfully interpreted.
329 n, _ = w.Write(src)
330 return n, err
331 }
332 return w.Write(formatted)
333 }
334
335 // Repackage rewrites a Go file from belonging to package main to belonging to
336 // the given package.
337 func Repackage(inFile, outFile, pkg string) {
338 src, err := os.ReadFile(inFile)
339 if err != nil {
340 log.Fatalf("reading %s: %v", inFile, err)
341 }
342 const toDelete = "package main\n\n"
343 i := bytes.Index(src, []byte(toDelete))
344 if i < 0 {
345 log.Fatalf("Could not find %q in %s.", toDelete, inFile)
346 }
347 w := &bytes.Buffer{}
348 w.Write(src[i+len(toDelete):])
349 WriteGoFile(outFile, pkg, w.Bytes())
350 }