-
Notifications
You must be signed in to change notification settings - Fork 2
/
generate.go
101 lines (86 loc) · 1.81 KB
/
generate.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
package i18n
import (
"fmt"
"log"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"text/template"
)
// Generate catalog.go
func Generate(pkgName string, paths []string, outFile string) error {
if len(paths) == 0 {
paths = []string{"."}
}
if err := os.MkdirAll(path.Dir(outFile), os.ModePerm); err != nil {
return err
}
goFile, err := os.Create(outFile)
if err != nil {
log.Fatal(err)
}
data := map[string]*Message{}
for _, path := range paths {
if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
messages, err := unmarshal(path)
if err != nil {
return err
}
lang := info.Name()[0 : len(info.Name())-5]
data[lang] = messages
fmt.Printf("Generate %+v ...\n", path)
return nil
}); err != nil {
return err
}
}
err = i18nTmpl.Execute(goFile, struct {
Data map[string]*Message
BackQuote string
Package string
}{
data,
"`",
pkgName,
})
return err
}
var funcs = template.FuncMap{
"funcName": func(lang string) string {
lang = strings.ReplaceAll(lang, "_", "")
lang = strings.ReplaceAll(lang, "-", "")
lang = strings.ToUpper(lang[:1]) + lang[1:]
return lang
},
"quote": func(text string) string {
return strconv.Quote(text)
},
}
var i18nTmpl = template.Must(template.New("i18n").Funcs(funcs).Parse(`package {{.Package}}
import (
"golang.org/x/text/language"
"golang.org/x/text/message"
)
// init
func init() {
{{- range $k, $v := .Data }}
init{{ funcName $k }}(language.Make("{{ $k }}"))
{{- end }}
}
{{- range $k, $v := .Data }}
// init{{ funcName $k }} will init {{ $k }} support.
func init{{ funcName $k }}(tag language.Tag) {
{{- range $k, $v := $v }}
message.SetString(tag, {{quote $k}}, {{quote $v}})
{{- end }}
}
{{- end }}
`))