/
rewrite_package.go
674 lines (552 loc) · 20.3 KB
/
rewrite_package.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
// Copyright © 2015-2023 The Knative Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmds
import (
"bytes"
"fmt"
"os"
"regexp"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"github.com/maximilien/i18n4go/common"
"github.com/spf13/cobra"
"path/filepath"
"strconv"
"strings"
)
const (
INIT_CODE_SNIPPET = `package __PACKAGE__NAME__
import (
"path/filepath"
i18n "github.com/maximilien/i18n4go/i18n"
)
var T i18n.TranslateFunc
func init() {
T = i18n.Init(__FULL_IMPORT_PATH__, i18n.GetResourcesPath())
}`
)
type rewritePackage struct {
options common.Options
Filename string
OutputDirname string
I18nStringsFilename string
I18nStringsDirname string
RootPath string
InitCodeSnippetFilename string
Dirname string
Recurse bool
ExtractedStrings map[string]common.I18nStringInfo
UpdatedExtractedStrings map[string]common.I18nStringInfo
SaveExtractedStrings bool
TotalStrings int
TotalFiles int
IgnoreRegexp *regexp.Regexp
}
func NewRewritePackage(options *common.Options) *rewritePackage {
var compiledRegexp *regexp.Regexp
if options.IgnoreRegexpFlag != "" {
compiledReg, err := regexp.Compile(options.IgnoreRegexpFlag)
if err != nil {
fmt.Println("WARNING compiling ignore-regexp:", err)
}
compiledRegexp = compiledReg
}
return &rewritePackage{options: *options,
Filename: options.FilenameFlag,
OutputDirname: options.OutputDirFlag,
I18nStringsFilename: options.I18nStringsFilenameFlag,
I18nStringsDirname: options.I18nStringsDirnameFlag,
RootPath: options.RootPathFlag,
InitCodeSnippetFilename: options.InitCodeSnippetFilenameFlag,
ExtractedStrings: nil,
UpdatedExtractedStrings: nil,
SaveExtractedStrings: false,
Dirname: options.DirnameFlag,
Recurse: options.RecurseFlag,
IgnoreRegexp: compiledRegexp,
}
}
// NewRewritePackageCommand implements 'i18n4go rewrite-package' command
func NewRewritePackageCommand(options *common.Options) *cobra.Command {
rewritePackageCmd := &cobra.Command{
Use: "rewrite-package",
Short: "Rewrite translated packages from go source files",
RunE: func(cmd *cobra.Command, args []string) error {
return NewRewritePackage(options).Run()
},
}
rewritePackageCmd.Flags().BoolVar(&options.PoFlag, "po", false, "generate standard .po file for translation")
rewritePackageCmd.Flags().BoolVarP(&options.RecurseFlag, "recursive", "r", false, "recursively rewrite packages from all files in the same directory as filename or dirName")
rewritePackageCmd.Flags().StringVarP(&options.FilenameFlag, "file", "f", "", "the source go file to be rewritten")
rewritePackageCmd.Flags().StringVarP(&options.DirnameFlag, "directory", "d", "", "the dir name for which all .go files will have their strings extracted")
rewritePackageCmd.Flags().StringVar(&options.I18nStringsFilenameFlag, "i18n-strings-filename", "", "a JSON file with the strings that should be i18n enabled, typically the output of the extract-strings command")
rewritePackageCmd.Flags().StringVar(&options.I18nStringsDirnameFlag, "i18n-strings-dirname", "", "a directory with the extracted JSON files, using -output-match-package with extract-strings command this directory should match the input files package name")
rewritePackageCmd.Flags().StringVarP(&options.OutputDirFlag, "output", "o", "", "output directory where the translation files will be placed")
rewritePackageCmd.Flags().StringVar(&options.RootPathFlag, "root-path", "", "the root path to the Go source files whose packages are being rewritten, defaults to working directory, if not specified")
rewritePackageCmd.Flags().StringVar(&options.InitCodeSnippetFilenameFlag, "init-code-snippet-filename", "", "[optional] the path to a file containing the template snippet for the code that is used for go-i18n initialization")
rewritePackageCmd.Flags().StringVar(&options.IgnoreRegexpFlag, "ignore-regexp", ".*test.*", "a perl-style regular expression for files to ignore, e.g., \".*test.*\"")
return rewritePackageCmd
}
func (rp *rewritePackage) Options() common.Options {
return rp.options
}
func (rp *rewritePackage) Println(a ...interface{}) (int, error) {
if rp.options.VerboseFlag {
return fmt.Println(a...)
}
return 0, nil
}
func (rp *rewritePackage) Printf(msg string, a ...interface{}) (int, error) {
if rp.options.VerboseFlag {
return fmt.Printf(msg, a...)
}
return 0, nil
}
func (rp *rewritePackage) Run() error {
var err error
if rp.options.FilenameFlag != "" {
if err = rp.loadStringsToBeTranslated(rp.I18nStringsFilename); err != nil {
return err
}
err = rp.processFilename(rp.options.FilenameFlag)
} else {
err = rp.processDir(rp.options.DirnameFlag, rp.options.RecurseFlag)
}
rp.Println()
rp.Println("Total files parsed:", rp.TotalFiles)
rp.Println("Total rewritten strings:", rp.TotalStrings)
return err
}
func (rp *rewritePackage) loadStringsToBeTranslated(fileName string) error {
if fileName != "" {
stringList, err := common.LoadI18nStringInfos(fileName)
if err != nil {
return err
}
rp.ExtractedStrings, err = common.CreateI18nStringInfoMap(stringList)
if err != nil {
return err
}
rp.UpdatedExtractedStrings = common.CopyI18nStringInfoMap(rp.ExtractedStrings)
}
return nil
}
func (rp *rewritePackage) processDir(dirName string, recursive bool) error {
rp.Printf("i18n4go: rewriting strings in dir %s, recursive: %t\n", dirName, recursive)
rp.Println()
fileInfos, _ := ioutil.ReadDir(dirName)
for _, fileInfo := range fileInfos {
if fileInfo.IsDir() {
if recursive {
rp.processDir(filepath.Join(dirName, fileInfo.Name()), recursive)
} else {
continue
}
} else if rp.ignoreFile(filepath.Base(fileInfo.Name())) {
i18nFilename := rp.I18nStringsFilename
if rp.I18nStringsDirname != "" {
i18nFilename = filepath.Base(fileInfo.Name()) + "." + rp.options.SourceLanguageFlag + ".json"
}
rp.I18nStringsFilename = filepath.Join(rp.I18nStringsDirname, i18nFilename)
rp.Printf("i18n4go: loading JSON strings from file: %s\n", rp.I18nStringsFilename)
if err := rp.loadStringsToBeTranslated(rp.I18nStringsFilename); err != nil {
rp.Println("i18n4go: WARNING could not find JSON file:", rp.I18nStringsFilename, err.Error())
rp.resetProcessing()
continue
}
err := rp.processFilename(filepath.Join(dirName, fileInfo.Name()))
if err != nil {
rp.Println(err)
return err
}
if rp.I18nStringsDirname != "" {
rp.resetProcessing()
}
}
}
return nil
}
func (rp *rewritePackage) resetProcessing() {
rp.ExtractedStrings = nil
rp.UpdatedExtractedStrings = nil
rp.I18nStringsFilename = ""
rp.SaveExtractedStrings = false
}
func (rp *rewritePackage) ignoreFile(fileName string) bool {
return fileName != "i18n_init.go" &&
!strings.HasPrefix(fileName, ".") &&
strings.HasSuffix(fileName, ".go") &&
rp.IgnoreRegexp != nil && !rp.IgnoreRegexp.MatchString(fileName)
}
func (rp *rewritePackage) processFilename(fileName string) error {
rp.TotalFiles += 1
rp.Println("i18n4go: rewriting strings for source file:", fileName)
fileSet := token.NewFileSet()
var absFilePath = fileName
if !filepath.IsAbs(absFilePath) {
absFilePath = filepath.Join(os.Getenv("PWD"), absFilePath)
}
astFile, err := parser.ParseFile(fileSet, absFilePath, nil, parser.ParseComments|parser.AllErrors)
if err != nil {
rp.Println(err)
return err
}
if strings.HasSuffix(fileName, "_test.go") {
rp.Println("cowardly refusing to translate the strings in test file:", fileName)
return nil
}
importPath, err := rp.determineImportPath(absFilePath)
if err != nil {
rp.Println("i18n4go: error determining the import path:", err.Error())
return err
}
if rp.OutputDirname == "" {
rp.OutputDirname = filepath.Dir(fileName)
}
outputDir := filepath.Join(rp.OutputDirname, filepath.Dir(rp.relativePathForFile(fileName)))
err = rp.addInitFuncToPackage(astFile.Name.Name, outputDir, importPath)
if err != nil {
rp.Println("i18n4go: error adding init() func to package:", err.Error())
return err
}
err = rp.insertTFuncCall(astFile)
if err != nil {
rp.Println("i18n4go: error appending T() to AST file:", err.Error())
return err
}
relativeFilePath := rp.relativePathForFile(fileName)
err = rp.saveASTFile(relativeFilePath, fileName, astFile, fileSet)
if err != nil {
rp.Println("i18n4go: error saving AST file:", err.Error())
return err
}
if rp.SaveExtractedStrings {
i18nStringInfos := common.I18nStringInfoMapValues2Array(rp.UpdatedExtractedStrings)
err := common.SaveI18nStringInfos(rp, rp.Options(), i18nStringInfos, rp.I18nStringsFilename)
if err != nil {
rp.Println("i18n4go: error saving updated i18n strings file:", err.Error())
return err
}
}
return err
}
func (rp *rewritePackage) determineImportPath(filePath string) (string, error) {
dirName := filepath.Dir(filePath)
var (
pkgImportPath string
otherPkgImportPath string
)
if rp.options.RootPathFlag == "" {
rp.Println("i18n4go: using the PWD as the rootPath:", os.Getenv("PWD"))
rp.RootPath = os.Getenv("PWD")
}
rp.Println("i18n4go: determining import path using root path:", rp.RootPath)
pkg, err := build.Default.ImportDir(rp.RootPath, build.ImportMode(1))
if err != nil {
rp.Println("i18n4go: error getting root path import:", err.Error())
return "", err
}
if build.IsLocalImport(pkg.ImportPath) {
pkgImportPath = pkg.Dir
rp.Printf("i18n4go: got a local import %s so using %s instead for root pkg", pkg.ImportPath, pkg.Dir)
} else {
pkgImportPath = pkg.ImportPath
rp.Println("i18n4go: got a root pkg with import path:", pkg.ImportPath)
}
otherPkg, err := build.Default.ImportDir(dirName, build.ImportMode(0))
if err != nil {
rp.Println("i18n4go: error getting root path import:", err.Error())
return "", err
}
if build.IsLocalImport(otherPkg.ImportPath) {
otherPkgImportPath = otherPkg.Dir
rp.Printf("i18n4go: got a local import %s so using %s instead for pkg", otherPkg.ImportPath, otherPkg.Dir)
} else {
otherPkgImportPath = otherPkg.ImportPath
rp.Println("i18n4go: got a pkg with import:", otherPkg.ImportPath)
}
importPath := otherPkgImportPath
importPath = strings.Replace(importPath, pkgImportPath, "", 1)
if strings.HasPrefix(importPath, "/") {
importPath = strings.TrimLeft(importPath, "/")
}
rp.Println("i18n4go: using import path as:", importPath)
return importPath, nil
}
func (rp *rewritePackage) insertTFuncCall(astFile *ast.File) error {
rp.Println("i18n4go: inserting T() calls for strings that need to be translated")
var declarations []ast.Decl
if len(astFile.Imports) > 0 {
declarations = astFile.Decls[1:]
} else {
declarations = astFile.Decls[0:]
}
for _, decl := range declarations {
ast.Inspect(decl, func(node ast.Node) bool {
switch node.(type) {
case *ast.CallExpr:
if !rp.callExprTFunc(node.(*ast.CallExpr)) {
return false // don't recurse infinitely
}
case *ast.AssignStmt:
rp.assignStmtTFunc(node.(*ast.AssignStmt))
case *ast.ValueSpec:
rp.valueSpecTFunc(node.(*ast.ValueSpec))
case *ast.CompositeLit:
rp.compositeLitTFunc(node.(*ast.CompositeLit))
case *ast.KeyValueExpr:
rp.keyValueExprTFunc(node.(*ast.KeyValueExpr))
case *ast.ReturnStmt:
rp.returnStmtTFunc(node.(*ast.ReturnStmt))
case *ast.BinaryExpr:
rp.binaryExprTFunc(node.(*ast.BinaryExpr))
case *ast.IndexExpr:
rp.indexExprTFunc(node.(*ast.IndexExpr))
}
return true
})
}
return nil
}
func (rp *rewritePackage) indexExprTFunc(indexExpr *ast.IndexExpr) {
if index, ok := indexExpr.Index.(*ast.BasicLit); ok {
indexExpr.Index = rp.wrapBasicLitWithT(index)
}
}
func (rp *rewritePackage) binaryExprTFunc(binaryExpr *ast.BinaryExpr) {
if x, ok := binaryExpr.X.(*ast.BasicLit); ok {
binaryExpr.X = rp.wrapBasicLitWithT(x)
}
if y, ok := binaryExpr.Y.(*ast.BasicLit); ok {
binaryExpr.Y = rp.wrapBasicLitWithT(y)
}
}
func (rp *rewritePackage) returnStmtTFunc(returnStmt *ast.ReturnStmt) {
for index, arg := range returnStmt.Results {
if asLit, ok := arg.(*ast.BasicLit); ok {
returnStmt.Results[index] = rp.wrapBasicLitWithT(asLit)
}
}
}
func (rp *rewritePackage) keyValueExprTFunc(keyValueExpr *ast.KeyValueExpr) {
if key, ok := keyValueExpr.Key.(*ast.BasicLit); ok {
keyValueExpr.Key = rp.wrapBasicLitWithT(key)
}
if value, ok := keyValueExpr.Value.(*ast.BasicLit); ok {
keyValueExpr.Value = rp.wrapBasicLitWithT(value)
}
}
func (rp *rewritePackage) compositeLitTFunc(compositeLit *ast.CompositeLit) bool {
for index, arg := range compositeLit.Elts {
if asLit, ok := arg.(*ast.BasicLit); ok {
compositeLit.Elts[index] = rp.wrapBasicLitWithT(asLit)
}
}
return true
}
func (rp *rewritePackage) assignStmtTFunc(assignStmt *ast.AssignStmt) bool {
for index, arg := range assignStmt.Rhs {
if asLit, ok := arg.(*ast.BasicLit); ok {
assignStmt.Rhs[index] = rp.wrapBasicLitWithT(asLit)
}
}
return true
}
func (rp *rewritePackage) valueSpecTFunc(valueSpec *ast.ValueSpec) bool {
for index, arg := range valueSpec.Values {
if asLit, ok := arg.(*ast.BasicLit); ok {
valueSpec.Values[index] = rp.wrapBasicLitWithT(asLit)
}
}
return true
}
func (rp *rewritePackage) callExprTFunc(callExpr *ast.CallExpr) bool {
callFuncIdent, ok := callExpr.Fun.(*ast.Ident)
if ok && (callFuncIdent.Name == "T") { // yeah, not the best
return false
}
switch len(callExpr.Args) {
case 0:
return false
case 1:
if basicLit, ok := callExpr.Args[0].(*ast.BasicLit); ok {
callExpr.Args[0] = rp.wrapBasicLitWithT(basicLit)
}
default:
rp.wrapMultiArgsCallExpr(callExpr)
}
return true
}
func (rp *rewritePackage) wrapMultiArgsCallExpr(callExpr *ast.CallExpr) {
for i, arg := range callExpr.Args {
if basicLit, ok := arg.(*ast.BasicLit); ok {
if basicLit.Kind == token.STRING {
valueWithoutQuotes, _ := strconv.Unquote(basicLit.Value) //basicLit.Value[1 : len(basicLit.Value)-1]
if common.IsTemplatedString(valueWithoutQuotes) {
rp.wrapCallExprWithTemplatedT(basicLit, callExpr, i)
} else if common.IsInterpolatedString(valueWithoutQuotes) {
rp.wrapCallExprWithInterpolatedT(basicLit, callExpr, i)
} else {
rp.wrapExprArgs(callExpr.Args)
}
} else {
rp.wrapExprArgs(callExpr.Args)
}
}
}
}
func (rp *rewritePackage) wrapCallExprWithInterpolatedT(basicLit *ast.BasicLit, callExpr *ast.CallExpr, argIndex int) {
valueWithoutQuotes, _ := strconv.Unquote(basicLit.Value)
i18nStringInfo, ok := rp.ExtractedStrings[valueWithoutQuotes]
if !ok && rp.ExtractedStrings != nil {
rp.wrapExprArgs(callExpr.Args)
return
}
templatedString := common.ConvertToTemplatedString(valueWithoutQuotes)
basicLit.Value = strconv.Quote(templatedString)
if rp.ExtractedStrings != nil {
rp.updateExtractedStrings(i18nStringInfo, templatedString)
}
rp.wrapCallExprWithTemplatedT(basicLit, callExpr, argIndex)
}
func (rp *rewritePackage) wrapCallExprWithTemplatedT(basicLit *ast.BasicLit, callExpr *ast.CallExpr, argIndex int) {
templatedCallExpr := rp.wrapBasicLitWithTemplatedT(basicLit, callExpr.Args, callExpr, argIndex)
if templatedCallExpr != callExpr {
newArgs := []ast.Expr{}
if argIndex != 0 {
for i, arg := range callExpr.Args {
if i < argIndex {
newArgs = append(newArgs, arg)
}
}
}
callExpr.Args = append(newArgs, templatedCallExpr)
}
}
func (rp *rewritePackage) wrapExprArgs(exprArgs []ast.Expr) {
for i, _ := range exprArgs {
if basicLit, ok := exprArgs[i].(*ast.BasicLit); ok {
exprArgs[i] = rp.wrapBasicLitWithT(basicLit)
} else if callExpr, ok := exprArgs[i].(*ast.CallExpr); ok {
rp.callExprTFunc(callExpr)
}
}
}
func (rp *rewritePackage) wrapBasicLitWithTemplatedT(basicLit *ast.BasicLit, args []ast.Expr, callExpr *ast.CallExpr, argIndex int) ast.Expr {
valueWithoutQuotes, _ := strconv.Unquote(basicLit.Value) //basicLit.Value[1 : len(basicLit.Value)-1]
_, ok := rp.ExtractedStrings[valueWithoutQuotes]
if !ok && rp.ExtractedStrings != nil {
return callExpr
}
rp.TotalStrings++
tIdent := &ast.Ident{Name: "T"}
argNames := common.GetTemplatedStringArgs(valueWithoutQuotes)
compositeExpr := []ast.Expr{}
processedArgsMap := make(map[string]bool)
for i, argName := range argNames {
if callExpr, ok := args[argIndex+i+1].(*ast.CallExpr); ok {
rp.callExprTFunc(callExpr)
} else if basicLit, ok := args[argIndex+i+1].(*ast.BasicLit); ok {
args[argIndex+i] = rp.wrapBasicLitWithT(basicLit)
}
if processedArgsMap[argName] != true {
quotedArgName := "\"" + argName + "\""
basicLit.ValuePos = 0
valueExpr := args[argIndex+i+1]
if basicLit, ok := args[argIndex+i+1].(*ast.BasicLit); ok {
valueExpr = rp.wrapBasicLitWithT(basicLit)
}
keyValueExpr := &ast.KeyValueExpr{Key: &ast.BasicLit{Kind: 9, Value: quotedArgName}, Value: valueExpr}
processedArgsMap[argName] = true
compositeExpr = append(compositeExpr, keyValueExpr)
}
}
mapInterfaceType := &ast.InterfaceType{Interface: 142, Methods: &ast.FieldList{List: nil, Opening: 1, Closing: 2}, Incomplete: false}
mapType := &ast.MapType{Map: 131, Key: &ast.Ident{Name: "string"}, Value: mapInterfaceType}
compositeLit := &ast.CompositeLit{Type: mapType, Elts: compositeExpr}
return &ast.CallExpr{Fun: tIdent, Args: []ast.Expr{basicLit, compositeLit}}
}
func (rp *rewritePackage) wrapBasicLitWithT(basicLit *ast.BasicLit) ast.Expr {
if basicLit.Kind != token.STRING {
return basicLit
}
valueWithoutQuotes, _ := strconv.Unquote(basicLit.Value) //basicLit.Value[1 : len(basicLit.Value)-1]
_, ok := rp.ExtractedStrings[valueWithoutQuotes]
if !ok && rp.ExtractedStrings != nil {
return basicLit
}
rp.TotalStrings++
tIdent := &ast.Ident{Name: "T"}
return &ast.CallExpr{Fun: tIdent, Args: []ast.Expr{basicLit}}
}
func (rp *rewritePackage) addInitFuncToPackage(packageName, outputDir, importPath string) error {
rp.Println("i18n4go: adding init func to package:", packageName, " to output dir:", outputDir)
common.CreateOutputDirsIfNeeded(outputDir)
pieces := strings.Split(importPath, "/")
for index, str := range pieces {
pieces[index] = `"` + str + `"`
}
joinedImportPath := "filepath.Join(" + strings.Join(pieces, ", ") + ")"
content := rp.getInitFuncCodeSnippetContent(packageName, joinedImportPath)
return ioutil.WriteFile(filepath.Join(outputDir, "i18n_init.go"), []byte(content), 0666)
}
func (rp *rewritePackage) getInitFuncCodeSnippetContent(packageName, importPath string) string {
snippetContent := INIT_CODE_SNIPPET
if rp.InitCodeSnippetFilename != "" {
bytes, err := ioutil.ReadFile(rp.InitCodeSnippetFilename)
if err != nil {
rp.Printf("i18n4go: error reading content of init code snippet file: %s\n, using default", rp.InitCodeSnippetFilename)
} else {
snippetContent = string(bytes)
}
}
content := strings.Replace(snippetContent, "__PACKAGE__NAME__", packageName, -1)
content = strings.Replace(content, "__FULL_IMPORT_PATH__", importPath, -1)
return content
}
func (rp *rewritePackage) saveASTFile(relativeFilePath, fileName string, astFile *ast.File, fileSet *token.FileSet) error {
var buffer bytes.Buffer
if err := format.Node(&buffer, fileSet, astFile); err != nil {
return err
}
pathToFile := filepath.Join(rp.OutputDirname, relativeFilePath)
fileInfo, err := os.Stat(fileName)
if err != nil {
return err
}
common.CreateOutputDirsIfNeeded(filepath.Dir(pathToFile))
rp.Println("saving file to path", pathToFile)
ioutil.WriteFile(pathToFile, buffer.Bytes(), fileInfo.Mode())
return nil
}
func (rp *rewritePackage) relativePathForFile(fileName string) string {
if rp.Dirname != "" {
return strings.Replace(fileName, rp.Dirname, "", -1)
} else {
return filepath.Base(fileName)
}
}
func (rp *rewritePackage) updateExtractedStrings(i18nStringInfo common.I18nStringInfo, templatedString string) {
oldID := i18nStringInfo.ID
i18nStringInfo.ID = templatedString
i18nStringInfo.Translation = templatedString
rp.ExtractedStrings[templatedString] = i18nStringInfo
rp.UpdatedExtractedStrings[templatedString] = i18nStringInfo
delete(rp.UpdatedExtractedStrings, oldID)
rp.SaveExtractedStrings = true
}