| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "flag" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "regexp" |
| 11 | ) |
| 12 | |
| 13 | func infof(w io.Writer, format string, a ...interface{}) { |
| 14 | if !*verbose { |
| 15 | return |
| 16 | } |
| 17 | fmt.Fprintf(w, format, a...) |
| 18 | } |
| 19 | |
| 20 | func warnf(w io.Writer, format string, a ...interface{}) { |
| 21 | fmt.Fprintf(w, format, a...) |
| 22 | } |
| 23 | |
| 24 | func readPoDir() (string, []os.DirEntry) { |
| 25 | rootDirs := []string{ |
| 26 | ".", |
| 27 | "..", |
| 28 | "../..", |
| 29 | } |
| 30 | |
| 31 | var err error |
| 32 | for _, rootDir := range rootDirs { |
| 33 | fs, err := os.ReadDir(filepath.Join(rootDir, "po", "build")) |
| 34 | if err == nil { |
| 35 | return rootDir, fs |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // In this case, we don't care about the fact that the build dir doesn't |
| 40 | // exist since that just means there are no translations built. That's |
| 41 | // fine for us, so just exit successfully. |
| 42 | infof(os.Stderr, "Failed to open po dir: %v\n", err) |
| 43 | os.Exit(0) |
| 44 | return "", nil |
| 45 | } |
| 46 | |
| 47 | var ( |
| 48 | verbose = flag.Bool("verbose", false, "Show verbose output.") |
| 49 | ) |
| 50 | |
| 51 | func main() { |
| 52 | flag.Parse() |
| 53 | |
| 54 | infof(os.Stderr, "Converting po files into translations...\n") |
| 55 | rootDir, fs := readPoDir() |
| 56 | poDir := filepath.Join(rootDir, "po", "build") |
| 57 | out, err := os.Create(filepath.Join(rootDir, "tr", "tr_gen.go")) |
| 58 | if err != nil { |
| 59 | warnf(os.Stderr, "Failed to create go file: %v\n", err) |
| 60 | os.Exit(2) |
| 61 | } |
| 62 | out.WriteString("package tr\n\nfunc init() {\n") |
| 63 | out.WriteString("\t// THIS FILE IS GENERATED, DO NOT EDIT\n") |
| 64 | out.WriteString("\t// Use 'go generate ./tr/trgen' to update\n") |
| 65 | fileregex := regexp.MustCompile(`([A-Za-z\-_]+).mo`) |
| 66 | count := 0 |
| 67 | for _, f := range fs { |
| 68 | if match := fileregex.FindStringSubmatch(f.Name()); match != nil { |
| 69 | infof(os.Stderr, "%v\n", f.Name()) |
| 70 | cmd := match[1] |
| 71 | content, err := os.ReadFile(filepath.Join(poDir, f.Name())) |
| 72 | if err != nil { |
| 73 | warnf(os.Stderr, "Failed to open %v: %v\n", f.Name(), err) |
| 74 | os.Exit(2) |
| 75 | } |
| 76 | fmt.Fprintf(out, "\tlocales[\"%s\"] = \"%s\"\n", cmd, base64.StdEncoding.EncodeToString(content)) |
| 77 | count++ |
| 78 | } |
| 79 | } |
| 80 | out.WriteString("}\n") |
| 81 | infof(os.Stderr, "Successfully processed %d translations.\n", count) |
| 82 | |
| 83 | } |