forked from maximilien/i18n4go
/
fixup.go
378 lines (299 loc) · 9.8 KB
/
fixup.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package cmds
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"sort"
"strconv"
"strings"
"go/ast"
"go/parser"
"go/token"
"github.com/maximilien/i18n4go/common"
)
type Fixup struct {
options common.Options
I18nStringInfos []common.I18nStringInfo
English []common.I18nStringInfo
Source map[string]int
Locales map[string]map[string]string
}
func NewFixup(options common.Options) Fixup {
return Fixup{
options: options,
I18nStringInfos: []common.I18nStringInfo{},
}
}
func (fix *Fixup) Options() common.Options {
return fix.options
}
func (fix *Fixup) Println(a ...interface{}) (int, error) {
if fix.options.VerboseFlag {
return fmt.Println(a...)
}
return 0, nil
}
func (fix *Fixup) Printf(msg string, a ...interface{}) (int, error) {
if fix.options.VerboseFlag {
return fmt.Printf(msg, a...)
}
return 0, nil
}
func (fix *Fixup) Run() error {
//FIND PROBLEMS HERE AND RETURN AN ERROR
source, err := fix.findSourceStrings()
fix.Source = source
if err != nil {
fmt.Println(fmt.Sprintf("Couldn't find any source strings: %s", err.Error()))
return err
}
locales := findTranslationFiles(".")
englishFile := locales["en_US"][0]
if englishFile == "" {
fmt.Println("Could not find an i18n file for locale: en_US")
return errors.New("Could not find an i18n file for locale: en_US")
}
englishStringInfos, err := fix.findI18nStrings(englishFile)
if err != nil {
fmt.Println(fmt.Sprintf("Couldn't find the english strings: %s", err.Error()))
return err
}
//Check english to all other files before source
for locale, i18nFile := range locales {
if locale != "en_US" {
foreignStringInfos, _ := fix.findI18nStrings(i18nFile[0])
foreignAdditionalTranslations := getAdditionalForeignTranslations(englishStringInfos, foreignStringInfos)
foreignMissingTranslations := getMissingForeignTranslations(englishStringInfos, foreignStringInfos)
if len(foreignMissingTranslations) > 0 {
addTranslations(foreignStringInfos, i18nFile[0], foreignMissingTranslations)
}
if len(foreignAdditionalTranslations) > 0 {
removeTranslations(foreignStringInfos, i18nFile[0], foreignAdditionalTranslations)
}
writeStringInfoMapToJSON(foreignStringInfos, i18nFile[0])
}
}
//rewrite everything now
potentialAdditionalTranslations := getAdditionalTranslations(source, englishStringInfos)
removedTranslations := getRemovedTranslations(source, englishStringInfos)
additionalTranslations := []string{}
updatedTranslations := make(map[string]string)
if len(potentialAdditionalTranslations) > 0 && len(removedTranslations) > 0 {
for _, newUpdatedTranslation := range potentialAdditionalTranslations {
if len(removedTranslations) > 0 {
var input string
escape := false
updated := false
for !escape {
fmt.Printf("Is the string \"%s\" a new or updated string? [new/upd]\n", newUpdatedTranslation)
_, err := fmt.Scanf("%s\n", &input)
if err != nil {
panic(err)
}
input = strings.ToLower(input)
switch input {
case "new":
additionalTranslations = append(additionalTranslations, newUpdatedTranslation)
escape = true
case "upd":
fmt.Println("Select the number for the previous translation:")
for index, value := range removedTranslations {
fmt.Printf("\t%d. %s\n", (index + 1), value)
}
var updSelection int
for !updated {
_, err := fmt.Scanf("%d\n", &updSelection)
if err == nil && updSelection > 0 && updSelection <= len(removedTranslations) {
updSelection = updSelection - 1
updatedTranslations[removedTranslations[updSelection]] = newUpdatedTranslation
removedTranslations = removeFromSlice(removedTranslations, updSelection)
updated = true
} else {
fmt.Println("Invalid response.")
}
}
escape = true
case "exit":
fmt.Println("Canceling fixup")
os.Exit(0)
default:
fmt.Println("Invalid response.")
}
}
} else {
additionalTranslations = append(additionalTranslations, newUpdatedTranslation)
}
}
} else {
additionalTranslations = potentialAdditionalTranslations
}
for locale, i18nFiles := range locales {
translatedStrings, err := fix.findI18nStrings(i18nFiles[0])
if err != nil {
fmt.Println(fmt.Sprintf("Couldn't get the strings from %s: %s", locale, err.Error()))
return err
}
if len(updatedTranslations) > 0 {
updateTranslations(translatedStrings, i18nFiles[0], locale, updatedTranslations)
}
if len(additionalTranslations) > 0 {
addTranslations(translatedStrings, i18nFiles[0], additionalTranslations)
}
if len(removedTranslations) > 0 {
removeTranslations(translatedStrings, i18nFiles[0], removedTranslations)
}
err = writeStringInfoMapToJSON(translatedStrings, i18nFiles[0])
}
if err == nil {
fmt.Printf("OK")
}
return err
}
func (fix *Fixup) inspectFile(file string) (translatedStrings []string, err error) {
fset := token.NewFileSet()
astFile, err := parser.ParseFile(fset, file, nil, parser.AllErrors)
if err != nil {
fix.Println(err)
return
}
ast.Inspect(astFile, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.CallExpr:
switch x.Fun.(type) {
case *ast.Ident:
funName := x.Fun.(*ast.Ident).Name
if funName == "T" || funName == "t" {
if stringArg, ok := x.Args[0].(*ast.BasicLit); ok {
translatedString, err := strconv.Unquote(stringArg.Value)
if err != nil {
panic(err.Error())
}
translatedStrings = append(translatedStrings, translatedString)
}
}
default:
//Skip!
}
}
return true
})
return
}
func (fix *Fixup) findSourceStrings() (sourceStrings map[string]int, err error) {
sourceStrings = make(map[string]int)
files := getGoFiles(".")
for _, file := range files {
fileStrings, err := fix.inspectFile(file)
if err != nil {
fmt.Println("Error when inspecting go file: ", file)
return sourceStrings, err
}
for _, string := range fileStrings {
sourceStrings[string]++
}
}
return
}
func (fix *Fixup) findI18nStrings(i18nFile string) (i18nStrings map[string]common.I18nStringInfo, err error) {
i18nStrings = make(map[string]common.I18nStringInfo)
stringInfos, err := common.LoadI18nStringInfos(i18nFile)
if err != nil {
return nil, err
}
return common.CreateI18nStringInfoMap(stringInfos)
}
func getAdditionalTranslations(sourceTranslations map[string]int, englishTranslations map[string]common.I18nStringInfo) []string {
additionalTranslations := []string{}
for id, _ := range sourceTranslations {
if _, ok := englishTranslations[id]; !ok {
additionalTranslations = append(additionalTranslations, id)
}
}
return additionalTranslations
}
func getAdditionalForeignTranslations(englishTranslations, foreignTranslations map[string]common.I18nStringInfo) []string {
additionalForeignTranslations := []string{}
for key, _ := range foreignTranslations {
if (englishTranslations[key] == common.I18nStringInfo{}) {
additionalForeignTranslations = append(additionalForeignTranslations, key)
}
}
return additionalForeignTranslations
}
func getRemovedTranslations(sourceTranslations map[string]int, englishTranslations map[string]common.I18nStringInfo) []string {
removedTranslations := []string{}
for id, _ := range englishTranslations {
if _, ok := sourceTranslations[id]; !ok {
removedTranslations = append(removedTranslations, id)
}
}
return removedTranslations
}
func getMissingForeignTranslations(englishTranslations, foreignTranslations map[string]common.I18nStringInfo) []string {
missingForeignTranslations := []string{}
for key, _ := range englishTranslations {
if (foreignTranslations[key] == common.I18nStringInfo{}) {
missingForeignTranslations = append(missingForeignTranslations, key)
}
}
return missingForeignTranslations
}
func writeStringInfoMapToJSON(localeMap map[string]common.I18nStringInfo, localeFile string) error {
localeArray := common.I18nStringInfoMapValues2Array(localeMap)
sort.Sort(array(localeArray))
encodedLocale, err := json.MarshalIndent(localeArray, "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(localeFile, encodedLocale, 0644)
if err != nil {
return err
}
return nil
}
func addTranslations(localeMap map[string]common.I18nStringInfo, localeFile string, addTranslations []string) {
fmt.Printf("Adding these strings to the %s translation file:\n", localeFile)
for _, id := range addTranslations {
localeMap[id] = common.I18nStringInfo{ID: id, Translation: id}
fmt.Println("\t", id)
}
}
func removeTranslations(localeMap map[string]common.I18nStringInfo, localeFile string, remTranslations []string) error {
var err error
fmt.Printf("Removing these strings from the %s translation file:\n", localeFile)
for _, id := range remTranslations {
delete(localeMap, id)
fmt.Println("\t", id)
}
return err
}
func updateTranslations(localMap map[string]common.I18nStringInfo, localeFile string, locale string, updTranslations map[string]string) {
fmt.Printf("Updating the following strings from the %s translation file:\n", localeFile)
for key, value := range updTranslations {
fmt.Println("\t", key)
if locale == "en_US" {
localMap[value] = common.I18nStringInfo{ID: value, Translation: value}
} else {
localMap[value] = common.I18nStringInfo{ID: value, Translation: localMap[key].Translation, Modified: true}
}
delete(localMap, key)
}
}
func removeFromSlice(slice []string, index int) []string {
return append(slice[:index], slice[index+1:]...)
}
//Interface for sort
type array []common.I18nStringInfo
func (stringInfos array) Len() int {
return len(stringInfos)
}
func (stringInfos array) Less(i, j int) bool {
return stringInfos[i].ID < stringInfos[j].ID
}
func (stringInfos array) Swap(i, j int) {
tmpI18nStringInfo := stringInfos[i]
stringInfos[i] = stringInfos[j]
stringInfos[j] = tmpI18nStringInfo
}