forked from leonelquinteros/gotext
/
golang.go
312 lines (269 loc) · 6.48 KB
/
golang.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
package pkg_tree
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"golang.org/x/tools/go/packages"
"github.com/bitvcat/gotext/cli/xgotext/parser"
)
const gotextPkgPath = "github.com/bitvcat/gotext"
type GetterDef struct {
Id int
Plural int
Context int
Domain int
}
// MaxArgIndex returns the largest argument index
func (d *GetterDef) maxArgIndex() int {
m := d.Id
if d.Plural > m {
m = d.Plural
}
if d.Context > m {
m = d.Context
}
if d.Domain > m {
m = d.Domain
}
return m
}
// list of supported getter
var gotextGetter = map[string]GetterDef{
"Get": {0, -1, -1, -1},
"GetN": {0, 1, -1, -1},
"GetD": {1, -1, -1, 0},
"GetND": {1, 2, -1, 0},
"GetC": {0, -1, 1, -1},
"GetNC": {0, 1, 3, -1},
"GetDC": {1, -1, 2, 0},
"GetNDC": {1, 2, 4, 0},
}
// ParsePkgTree parse go package tree
func ParsePkgTree(pkgPath string, data *parser.DomainMap, verbose bool) error {
basePath, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return pkgParser(pkgPath, basePath, data, verbose)
}
func pkgParser(dirPath, basePath string, data *parser.DomainMap, verbose bool) error {
mainPkg, err := loadPackage(dirPath)
if err != nil {
return err
}
for _, pkg := range filterPkgs(mainPkg) {
if verbose {
fmt.Println(pkg.ID)
}
for _, node := range pkg.Syntax {
file := GoFile{
filePath: pkg.Fset.Position(node.Package).Filename,
basePath: basePath,
data: data,
fileSet: pkg.Fset,
importedPackages: map[string]*packages.Package{
pkg.Name: pkg,
},
}
ast.Inspect(node, file.inspectFile)
}
}
return nil
}
var pkgCache = make(map[string]*packages.Package)
func loadPackage(name string) (*packages.Package, error) {
fileSet := token.NewFileSet()
conf := &packages.Config{
Mode: packages.NeedName |
packages.NeedFiles |
packages.NeedSyntax |
packages.NeedTypes |
packages.NeedTypesInfo |
packages.NeedImports |
packages.NeedDeps,
Fset: fileSet,
Dir: name,
}
pkgs, err := packages.Load(conf)
if err != nil {
return nil, err
}
return pkgs[0], nil
}
func getPkgPath(pkg *packages.Package) string {
if len(pkg.GoFiles) == 0 {
return pkg.PkgPath
}
pkgPath, _ := filepath.Split(pkg.GoFiles[0])
return strings.TrimRight(pkgPath, "/")
}
func filterPkgs(pkg *packages.Package) []*packages.Package {
result := filterPkgsRec(pkg)
return result
}
func filterPkgsRec(pkg *packages.Package) []*packages.Package {
result := make([]*packages.Package, 0, 100)
pkgCache[pkg.ID] = pkg
for _, importedPkg := range pkg.Imports {
if importedPkg.ID == gotextPkgPath {
result = append(result, pkg)
}
if _, ok := pkgCache[importedPkg.ID]; ok {
continue
}
result = append(result, filterPkgsRec(importedPkg)...)
}
return result
}
// GoFile handles the parsing of one go file
type GoFile struct {
filePath string
basePath string
data *parser.DomainMap
fileSet *token.FileSet
pkgConf *packages.Config
importedPackages map[string]*packages.Package
}
// getPackage loads module by name
func (g *GoFile) getPackage(name string) (*packages.Package, error) {
pkg, ok := pkgCache[name]
if !ok {
return nil, fmt.Errorf("not found in cache")
}
return pkg, nil
}
// getType from ident object
func (g *GoFile) getType(ident *ast.Ident) types.Object {
for _, pkg := range g.importedPackages {
if pkg.Types == nil {
continue
}
if obj, ok := pkg.TypesInfo.Uses[ident]; ok {
return obj
}
}
return nil
}
func (g *GoFile) inspectFile(n ast.Node) bool {
switch x := n.(type) {
// get names of imported packages
case *ast.ImportSpec:
packageName, _ := strconv.Unquote(x.Path.Value)
pkg, err := g.getPackage(packageName)
if err != nil {
log.Printf("failed to load package %s: %s", packageName, err)
} else {
if x.Name == nil {
g.importedPackages[pkg.Name] = pkg
} else {
g.importedPackages[x.Name.Name] = pkg
}
}
// check each function call
case *ast.CallExpr:
g.inspectCallExpr(x)
default:
print()
}
return true
}
// checkType for gotext object
func (g *GoFile) checkType(rawType types.Type) bool {
switch t := rawType.(type) {
case *types.Pointer:
return g.checkType(t.Elem())
case *types.Named:
if t.Obj().Pkg() == nil || t.Obj().Pkg().Path() != gotextPkgPath {
return false
}
default:
return false
}
return true
}
func (g *GoFile) inspectCallExpr(n *ast.CallExpr) {
// must be a selector expression otherwise it is a local function call
expr, ok := n.Fun.(*ast.SelectorExpr)
if !ok {
return
}
switch e := expr.X.(type) {
// direct call
case *ast.Ident:
// object is a package if the Obj is not set
if e.Obj != nil {
// validate type of object
t := g.getType(e)
if t == nil || !g.checkType(t.Type()) {
return
}
}
// call to attribute
case *ast.SelectorExpr:
// validate type of object
t := g.getType(e.Sel)
if t == nil || !g.checkType(t.Type()) {
return
}
default:
return
}
// convert args
args := make([]*ast.BasicLit, len(n.Args))
for idx, arg := range n.Args {
args[idx], _ = arg.(*ast.BasicLit)
}
// get position
path, _ := filepath.Rel(g.basePath, g.filePath)
position := fmt.Sprintf("%s:%d", path, g.fileSet.Position(n.Lparen).Line)
// handle getters
if def, ok := gotextGetter[expr.Sel.String()]; ok {
g.parseGetter(def, args, position)
return
}
}
func (g *GoFile) parseGetter(def GetterDef, args []*ast.BasicLit, pos string) {
// check if enough arguments are given
if len(args) < def.maxArgIndex() {
return
}
// get domain
var domain string
if def.Domain != -1 {
domain, _ = strconv.Unquote(args[def.Domain].Value)
}
// only handle function calls with strings as ID
if args[def.Id] == nil || args[def.Id].Kind != token.STRING {
log.Printf("ERR: Unsupported call at %s (ID not a string)", pos)
return
}
msgID, _ := strconv.Unquote(args[def.Id].Value)
trans := parser.Translation{
MsgId: msgID,
SourceLocations: []string{pos},
}
if def.Plural > 0 {
// plural ID must be a string
if args[def.Plural] == nil || args[def.Plural].Kind != token.STRING {
log.Printf("ERR: Unsupported call at %s (Plural not a string)", pos)
return
}
msgIDPlural, _ := strconv.Unquote(args[def.Plural].Value)
trans.MsgIdPlural = msgIDPlural
}
if def.Context > 0 {
// Context must be a string
if args[def.Context] == nil || args[def.Context].Kind != token.STRING {
log.Printf("ERR: Unsupported call at %s (Context not a string)", pos)
return
}
trans.Context = args[def.Context].Value
}
g.data.AddTranslation(domain, &trans)
}