Debian Codegraph @

debian/go/src/github.com/gohugoio/go-i18n/v2/goi18n/extract_command.go

raw
1 package main
2
3 import (
4 "flag"
5 "fmt"
6 "go/ast"
7 "go/parser"
8 "go/token"
9 "os"
10 "path/filepath"
11 "reflect"
12 "strconv"
13 "strings"
14
15 "github.com/gohugoio/go-i18n/v2/i18n"
16 )
17
18 func usageExtract() {
19 fmt.Fprintf(os.Stderr, `usage: goi18n extract [options] [paths]
20
21 Extract walks the files and directories in paths and extracts all messages to a single file.
22 If no files or paths are provided, it walks the current working directory.
23
24 xx-yy.active.format
25 This file contains messages that should be loaded at runtime.
26
27 Flags:
28
29 -sourceLanguage tag
30 The language tag of the extracted messages (e.g. en, en-US, zh-Hant-CN).
31 Default: en
32
33 -outdir directory
34 Write message files to this directory.
35 Default: .
36
37 -format format
38 Output message files in this format.
39 Supported formats: json, toml, yaml
40 Default: toml
41 `)
42 }
43
44 type extractCommand struct {
45 paths []string
46 sourceLanguage languageTag
47 outdir string
48 format string
49 }
50
51 func (ec *extractCommand) name() string {
52 return "extract"
53 }
54
55 func (ec *extractCommand) parse(args []string) error {
56 flags := flag.NewFlagSet("extract", flag.ExitOnError)
57 flags.Usage = usageExtract
58
59 flags.Var(&ec.sourceLanguage, "sourceLanguage", "en")
60 flags.StringVar(&ec.outdir, "outdir", ".", "")
61 flags.StringVar(&ec.format, "format", "toml", "")
62 if err := flags.Parse(args); err != nil {
63 return err
64 }
65
66 ec.paths = flags.Args()
67 return nil
68 }
69
70 func (ec *extractCommand) execute() error {
71 if len(ec.paths) == 0 {
72 ec.paths = []string{"."}
73 }
74 messages := []*i18n.Message{}
75 for _, path := range ec.paths {
76 if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
77 if err != nil {
78 return err
79 }
80 if info.IsDir() {
81 return nil
82 }
83 if filepath.Ext(path) != ".go" {
84 return nil
85 }
86
87 // Don't extract from test files.
88 if strings.HasSuffix(path, "_test.go") {
89 return nil
90 }
91
92 buf, err := os.ReadFile(path)
93 if err != nil {
94 return err
95 }
96 msgs, err := extractMessages(buf)
97 if err != nil {
98 return err
99 }
100 messages = append(messages, msgs...)
101 return nil
102 }); err != nil {
103 return err
104 }
105 }
106 messageTemplates := map[string]*i18n.MessageTemplate{}
107 for _, m := range messages {
108 if mt := i18n.NewMessageTemplate(m); mt != nil {
109 if duplicateMessage, ok := messageTemplates[m.ID]; ok && !reflect.DeepEqual(mt, duplicateMessage) {
110 return &duplicateMessageIDErr{messageID: m.ID}
111 }
112 messageTemplates[m.ID] = mt
113 }
114 }
115 path, content, err := writeFile(ec.outdir, "active", ec.sourceLanguage.Tag(), ec.format, messageTemplates, true)
116 if err != nil {
117 return err
118 }
119 return os.WriteFile(path, content, 0666)
120 }
121
122 type duplicateMessageIDErr struct {
123 messageID string
124 }
125
126 func (e *duplicateMessageIDErr) Error() string {
127 return fmt.Sprintf("duplicate message ID: %s", e.messageID)
128 }
129
130 // extractMessages extracts messages from the bytes of a Go source file.
131 func extractMessages(buf []byte) ([]*i18n.Message, error) {
132 fset := token.NewFileSet()
133 file, err := parser.ParseFile(fset, "", buf, parser.AllErrors)
134 if err != nil {
135 return nil, err
136 }
137 extractor := newExtractor(file)
138 ast.Walk(extractor, file)
139 return extractor.messages, nil
140 }
141
142 func newExtractor(file *ast.File) *extractor {
143 return &extractor{i18nPackageName: i18nPackageName(file)}
144 }
145
146 type extractor struct {
147 i18nPackageName string
148 messages []*i18n.Message
149 }
150
151 func (e *extractor) Visit(node ast.Node) ast.Visitor {
152 e.extractMessages(node)
153 return e
154 }
155
156 func (e *extractor) extractMessages(node ast.Node) {
157 cl, ok := node.(*ast.CompositeLit)
158 if !ok {
159 return
160 }
161 switch t := cl.Type.(type) {
162 case *ast.SelectorExpr:
163 if !e.isMessageType(t) {
164 return
165 }
166 e.extractMessage(cl)
167 case *ast.ArrayType:
168 if !e.isMessageType(t.Elt) {
169 return
170 }
171 for _, el := range cl.Elts {
172 ecl, ok := el.(*ast.CompositeLit)
173 if !ok {
174 continue
175 }
176 e.extractMessage(ecl)
177 }
178 case *ast.MapType:
179 if !e.isMessageType(t.Value) {
180 return
181 }
182 for _, el := range cl.Elts {
183 kve, ok := el.(*ast.KeyValueExpr)
184 if !ok {
185 continue
186 }
187 vcl, ok := kve.Value.(*ast.CompositeLit)
188 if !ok {
189 continue
190 }
191 e.extractMessage(vcl)
192 }
193 }
194 }
195
196 func (e *extractor) isMessageType(expr ast.Expr) bool {
197 se := unwrapSelectorExpr(expr)
198 if se == nil {
199 return false
200 }
201 if se.Sel.Name != "Message" && se.Sel.Name != "LocalizeConfig" {
202 return false
203 }
204 x, ok := se.X.(*ast.Ident)
205 if !ok {
206 return false
207 }
208 return x.Name == e.i18nPackageName
209 }
210
211 func unwrapSelectorExpr(e ast.Expr) *ast.SelectorExpr {
212 switch et := e.(type) {
213 case *ast.SelectorExpr:
214 return et
215 case *ast.StarExpr:
216 se, _ := et.X.(*ast.SelectorExpr)
217 return se
218 default:
219 return nil
220 }
221 }
222
223 func (e *extractor) extractMessage(cl *ast.CompositeLit) {
224 data := make(map[string]string)
225 for _, elt := range cl.Elts {
226 kve, ok := elt.(*ast.KeyValueExpr)
227 if !ok {
228 continue
229 }
230 key, ok := kve.Key.(*ast.Ident)
231 if !ok {
232 continue
233 }
234 v, ok := extractStringLiteral(kve.Value)
235 if !ok {
236 continue
237 }
238 data[key.Name] = v
239 }
240 if len(data) == 0 {
241 return
242 }
243 if messageID := data["MessageID"]; messageID != "" {
244 data["ID"] = messageID
245 }
246 e.messages = append(e.messages, i18n.MustNewMessage(data))
247 }
248
249 func extractStringLiteral(expr ast.Expr) (string, bool) {
250 switch v := expr.(type) {
251 case *ast.BasicLit:
252 if v.Kind != token.STRING {
253 return "", false
254 }
255 s, err := strconv.Unquote(v.Value)
256 if err != nil {
257 return "", false
258 }
259 return s, true
260 case *ast.BinaryExpr:
261 if v.Op != token.ADD {
262 return "", false
263 }
264 x, ok := extractStringLiteral(v.X)
265 if !ok {
266 return "", false
267 }
268 y, ok := extractStringLiteral(v.Y)
269 if !ok {
270 return "", false
271 }
272 return x + y, true
273 case *ast.Ident:
274 if v.Obj == nil {
275 return "", false
276 }
277 switch z := v.Obj.Decl.(type) {
278 case *ast.ValueSpec:
279 if len(z.Values) == 0 {
280 return "", false
281 }
282 s, ok := extractStringLiteral(z.Values[0])
283 if !ok {
284 return "", false
285 }
286 return s, true
287 }
288 case *ast.CallExpr:
289 if fun, ok := v.Fun.(*ast.Ident); ok && fun.Name == "string" {
290 return extractStringLiteral(v.Args[0])
291 }
292 }
293 return "", false
294 }
295
296 func i18nPackageName(file *ast.File) string {
297 for _, i := range file.Imports {
298 if i.Path.Kind == token.STRING && i.Path.Value == `"github.com/gohugoio/go-i18n/v2/i18n"` {
299 if i.Name == nil {
300 return "i18n"
301 }
302 return i.Name.Name
303 }
304 }
305 return ""
306 }