forked from rainycape/gondola
/
strings.go
120 lines (111 loc) · 2.24 KB
/
strings.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
package astutil
import (
"gnd.la/internal/pkgutil"
"gnd.la/util/stringutil"
"gnd.la/util/structs"
"go/ast"
"go/token"
)
type String struct {
Value string
Position *token.Position
}
func (s *String) fields() []string {
fields, err := stringutil.SplitFields(s.Value, "|")
if err != nil {
// TODO: Do something better here
panic(err)
}
return fields
}
func (s *String) Singular() string {
fields := s.fields()
if len(fields) == 1 {
return fields[0]
}
return fields[1]
}
func (s *String) Plural() string {
fields := s.fields()
if len(fields) > 2 {
return fields[2]
}
return ""
}
func (s *String) Context() string {
fields := s.fields()
if len(fields) > 1 {
return fields[0]
}
return ""
}
// Strings returns a list of string declarations of the given type
// (as a qualified name).
func Strings(fset *token.FileSet, f *ast.File, typ string) ([]*String, error) {
pkg, tname := pkgutil.SplitQualifiedName(typ)
pname, ok := Imports(f, pkg)
if !ok {
// Not imported
return nil, nil
}
var strings []*String
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.ValueSpec:
p, t := Selector(x.Type)
if p == pname && t == tname {
for _, v := range x.Values {
if s, pos := StringLiteral(fset, v); s != "" && pos != nil {
strings = append(strings, &String{s, pos})
}
}
}
}
return true
})
return strings, nil
}
func TagFields(fset *token.FileSet, f *ast.File, tagField string) ([]*String, error) {
var strings []*String
var err error
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.Field:
if x.Tag != nil {
if s, pos := StringLiteral(fset, x.Tag); s != "" && pos != nil {
for _, v := range tagKeys(s) {
t := structs.NewStringTagNamed(s, v)
if val := t.Value(tagField); val != "" {
strings = append(strings, &String{val, pos})
}
}
}
}
}
return true
})
if err != nil {
return nil, err
}
return strings, nil
}
func tagKeys(tag string) []string {
var keys []string
s := 0
for ii := 0; ii < len(tag); ii++ {
if tag[ii] == ' ' {
s = ii + 1
continue
}
if tag[ii] == ':' {
keys = append(keys, tag[s:ii])
}
if tag[ii] == '"' {
ii++
for tag[ii] != '"' {
ii++
}
}
}
return keys
}