/
main.go
232 lines (219 loc) · 6.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Command gotext-update-templates extracts and merges translations and generates a catalog.
package main
import (
"errors"
"flag"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"text/template/parse"
"golang.org/x/exp/slices"
"golang.org/x/text/language"
"golang.org/x/text/message/pipeline"
"golang.org/x/tools/go/packages"
)
type Config struct {
Dir string
Dirs []string
Lang string
Out string
Packages []string
SrcLang string
TranslateFuncName string
Verbose bool
}
func init() {
log.SetFlags(0)
}
func main() {
// own FlagSet because the global one is already in use
fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
dir := fs.String("dir", "locales", "default subdirectory to store translation files")
lang := fs.String("lang", "en-US", "comma-separated list of languages to process")
out := fs.String("out", "catalog.go", "output file to write to")
srcLang := fs.String("srclang", "en-US", "the source-code language")
trFunc := fs.String("trfunc", "Tr", "name of translate method which is used in templates")
verbose := fs.Bool("v", false, "output list of processed template files")
var dirs sliceFlag
fs.Var(&dirs, "d", "read additional .html and .txt files recursively from this directory (does not follows symlinks in subdirs)")
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s <package>* [flags]\n", os.Args[0])
fs.PrintDefaults()
}
fs.Parse(os.Args[1:])
config := Config{
Dir: *dir,
Dirs: dirs,
Lang: *lang,
Out: *out,
Packages: fs.Args(),
SrcLang: *srcLang,
TranslateFuncName: *trFunc,
Verbose: *verbose,
}
if err := config.Run(); err != nil {
log.Fatalln(err)
}
}
func (config Config) Run() error {
// collect html and txt file paths
var filepaths []string
// from packages
pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedFiles | packages.NeedEmbedFiles}, config.Packages...)
if err != nil {
return err
}
for _, pkg := range pkgs {
if len(pkg.Errors) > 0 {
return errors.New(pkg.Errors[0].Msg)
}
for _, embedFile := range pkg.EmbedFiles {
if ext := filepath.Ext(embedFile); ext == ".html" || ext == ".txt" {
filepaths = append(filepaths, embedFile)
}
}
}
// from other dirs
for _, dir := range config.Dirs {
err := fs.WalkDir(os.DirFS(dir), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if ext := filepath.Ext(d.Name()); ext == ".html" || ext == ".txt" {
filepaths = append(filepaths, filepath.Join(dir, path))
}
return nil
})
if err != nil {
return err
}
}
// collect messages from files
var templateMessages = []pipeline.Message{}
for _, fp := range filepaths {
if config.Verbose {
log.Println(fp)
}
file, err := os.ReadFile(fp)
if err != nil {
return err
}
// similar to parse.Parse but with SkipFuncCheck
trees := make(map[string]*parse.Tree)
t := parse.New("name")
t.Mode |= parse.SkipFuncCheck
if _, err := t.Parse(string(file), "", "", trees); err != nil {
return err
}
for _, tree := range trees {
config.processNode(&templateMessages, tree.Root)
}
}
supported := []language.Tag{}
for _, l := range strings.FieldsFunc(config.Lang, func(r rune) bool { return r == ',' }) {
supported = append(supported, language.Make(l))
}
pconf := &pipeline.Config{
Supported: supported,
SourceLanguage: language.Make(config.SrcLang),
Packages: config.Packages,
Dir: config.Dir,
GenFile: config.Out,
}
// see https://cs.opensource.google/go/x/text/+/master:cmd/gotext/update.go
state, err := pipeline.Extract(pconf)
if err != nil {
return err
}
state.Extracted.Messages = append(state.Extracted.Messages, templateMessages...)
if err := state.Import(); err != nil {
return err
}
if err := state.Merge(); err != nil {
return err
}
if err := state.Export(); err != nil {
return err
}
if err := state.Generate(); err != nil {
return err
}
return nil
}
func (config Config) processNode(templateMessages *[]pipeline.Message, node parse.Node) {
if node.Type() == parse.NodeList {
if listNode, ok := node.(*parse.ListNode); ok {
for _, childNode := range listNode.Nodes {
config.processNode(templateMessages, childNode)
}
}
}
if node.Type() == parse.NodeIf {
if ifNode, ok := node.(*parse.IfNode); ok {
config.processNode(templateMessages, ifNode.List)
if ifNode.ElseList != nil {
config.processNode(templateMessages, ifNode.ElseList)
}
}
}
if node.Type() == parse.NodeWith {
if withNode, ok := node.(*parse.WithNode); ok {
config.processNode(templateMessages, withNode.List)
if withNode.ElseList != nil {
config.processNode(templateMessages, withNode.ElseList)
}
}
}
if node.Type() == parse.NodeRange {
if rangeNode, ok := node.(*parse.RangeNode); ok {
config.processNode(templateMessages, rangeNode.List)
if rangeNode.ElseList != nil {
config.processNode(templateMessages, rangeNode.ElseList)
}
}
}
if node.Type() == parse.NodeAction {
if actionNode, ok := node.(*parse.ActionNode); ok {
for _, cmd := range actionNode.Pipe.Cmds {
if !containsIdentifier(cmd, config.TranslateFuncName) {
continue
}
for _, arg := range cmd.Args {
if arg.Type() == parse.NodeString {
if stringNode, ok := arg.(*parse.StringNode); ok {
text := stringNode.Text
message := pipeline.Message{
ID: pipeline.IDList{text},
Key: text,
Message: pipeline.Text{
Msg: text,
},
}
*templateMessages = append(*templateMessages, message)
}
}
}
}
}
}
}
func containsIdentifier(cmd *parse.CommandNode, identifier string) bool {
if len(cmd.Args) == 0 {
return false
}
arg := cmd.Args[0]
var identifiers []string
switch arg.Type() {
case parse.NodeField:
identifiers = arg.(*parse.FieldNode).Ident
case parse.NodeVariable:
identifiers = arg.(*parse.VariableNode).Ident
}
return slices.Contains(identifiers, identifier)
}