-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
288 lines (250 loc) · 6.82 KB
/
main.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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"os"
"path/filepath"
"reflect"
"slices"
"strings"
"text/template"
"unicode"
)
const (
appName = "go-getter"
tplSource = `func (r {{ if .PointerReceiver }}*{{ end}}{{ .StructName }}) {{ .Getter }}() {{ .Return }} { return r.{{ .Field }} }`
tplHelpText = `
NAME:
{{ .AppName }} - generate getter methods for struct fields.
DESCRIPTION:
{{ .AppName }} is a tool to generate getter methods for struct fields.
Usage: {{ .AppName }} [OPTIONS]
OPTIONS:
-h, -help show help.
-typ string the source struct type name.
-src string source file.
-out string output file.
-ptr bool use pointer receiver, default is true.
EXAMPLE:
{{ .AppName }} -typ User -src user.go -out user_getter.go
`
)
var (
getterTpl = template.Must(template.New("getter").Parse(tplSource))
helperTpl = template.Must(template.New("helper").Parse(tplHelpText))
)
func main() {
if err := Run(os.Args[1:]); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "go-getter: failed: %+v", err)
os.Exit(1)
}
}
func Run(args []string) error {
f := flag.NewFlagSet(appName, flag.ExitOnError)
f.Usage = func() {
_ = helperTpl.Execute(os.Stderr, struct{ AppName string }{appName})
}
var (
useptr bool
typname, out, src string
)
f.StringVar(&typname, "typ", "", "the source struct type name")
f.StringVar(&src, "src", "", "source file")
f.StringVar(&out, "out", "", "output file")
f.BoolVar(&useptr, "ptr", true, "use pointer receiver, default is true")
if err := f.Parse(args); err != nil {
return fmt.Errorf("parse flags: %v", err)
}
outfile, err := os.Create(out)
if err != nil {
return fmt.Errorf("open out file %q: %w", out, err)
}
defer outfile.Close()
fileset := token.NewFileSet()
astroot, err := parser.ParseFile(fileset, src, nil, parser.DeclarationErrors)
if err != nil {
return fmt.Errorf("parse source file: %w", err)
}
typ, err := findStructByName(astroot, typname)
if err != nil {
return err
}
var (
fields = make([]Field, 0, len(typ.Fields.List))
includedImports = make(map[string]struct{})
)
for _, field := range typ.Fields.List {
if len(field.Names) >= 1 && !isFieldIgnored(field) {
name := field.Names[0].Name
// excludes exported fields.
if unicode.IsLower(rune(name[0])) {
typ := expr2str(field.Type)
fields = append(fields, Field{Name: name, Type: typ})
// extract package selector and add into import set.
if idx := strings.IndexByte(typ, '.'); idx > 0 {
includedImports[typ[:idx]] = struct{}{}
}
}
}
}
var gen bytes.Buffer
if err := errors.Join(
writeHeader(&gen, astroot.Name.Name, astroot.Imports, includedImports),
writeGeneratedGetter(&gen, fields, typname, useptr),
); err != nil {
return fmt.Errorf("generate code: %w", err)
}
formatted, err := format.Source(gen.Bytes())
if err != nil {
return fmt.Errorf("format generated: %w", err)
}
_, err = outfile.Write(formatted)
return err
}
func writeHeader(buf *bytes.Buffer, pkgName string, imports []*ast.ImportSpec, includedImports map[string]struct{}) error {
_, err1 := fmt.Fprintf(buf, "// Code generated by %s. DO NOT EDIT.\n\n", appName)
_, err2 := fmt.Fprintf(buf, "package %s\n\n", pkgName)
if err := errors.Join(err1, err2); err != nil {
return fmt.Errorf("writing header: %w", err)
}
var closeImports bool
for i, imp := range imports {
if i == 0 {
buf.WriteString("import (")
closeImports = true
}
buf.WriteRune('\n')
impPath := imp.Path.Value
if imp.Name != nil { // using import with alias.
aliasImport := imp.Name.Name
if _, ok := includedImports[aliasImport]; ok {
buf.WriteString(aliasImport)
buf.WriteString(" ")
buf.WriteString(impPath)
}
} else { // normal import.
unquotedSelector := filepath.Base(impPath[1 : len(impPath)-1])
if _, ok := includedImports[unquotedSelector]; ok {
buf.WriteString(impPath)
}
}
}
if closeImports {
buf.WriteString(")\n\n")
}
return nil
}
func writeGeneratedGetter(buf *bytes.Buffer, fields []Field, typname string, useptr bool) error {
for _, f := range fields {
err := getterTpl.Execute(buf, struct {
StructName string
Getter string
Return string
Field string
PointerReceiver bool
}{
StructName: typname,
Getter: strings.ToUpper(f.Name[:1]) + f.Name[1:],
Return: f.Type,
Field: f.Name,
PointerReceiver: useptr,
})
if err != nil {
return fmt.Errorf("excute template for field: %+v, err: %w", f, err)
}
buf.WriteRune('\n')
}
return nil
}
func findStructByName(node ast.Node, name string) (*ast.StructType, error) {
var spec *ast.TypeSpec
ast.Inspect(node, func(v ast.Node) bool {
if t, ok := v.(*ast.TypeSpec); ok {
spec = t
}
return spec == nil
})
if spec == nil {
return nil, fmt.Errorf("findStructByName: spec %q is not found", name)
}
t, ok := spec.Type.(*ast.StructType)
if !ok {
return nil, fmt.Errorf("findStructByName: %q is not a struct type", name)
}
return t, nil
}
type Field struct {
Name string
Type string
}
func isFieldIgnored(f *ast.Field) bool {
if f.Tag != nil {
tag := reflect.StructTag(f.Tag.Value[1 : len(f.Tag.Value)-1])
value, ok := tag.Lookup(appName)
return ok && slices.Contains(strings.Split(value, ","), "ignored")
}
return false
}
func expr2str(expr ast.Expr) string {
switch t := expr.(type) {
default:
return ""
case *ast.BasicLit:
return t.Value
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", t.X, t.Sel)
case *ast.StarExpr:
return "*" + expr2str(t.X)
case *ast.ArrayType:
l, e := expr2str(t.Len), expr2str(t.Elt)
return fmt.Sprintf("[%s]%s", l, e)
case *ast.IndexExpr: // generic type.
x, idx := expr2str(t.X), expr2str(t.Index)
return fmt.Sprintf("%s[%s]", x, idx)
case *ast.FuncType:
return funcExpr2str(expr)
case *ast.MapType:
key, val := expr2str(t.Key), expr2str(t.Value)
return fmt.Sprintf("map[%s]%s", key, val)
case *ast.ChanType:
val := expr2str(t.Value)
if t.Dir == ast.SEND {
return fmt.Sprintf("chan<- %s", val)
}
if t.Dir == ast.RECV {
return fmt.Sprintf("<-chan %s", val)
}
return fmt.Sprintf("chan %s", val)
}
}
func funcExpr2str(expr ast.Expr) string {
t, ok := expr.(*ast.FuncType)
if !ok {
return "<unexpected func expr>"
}
params := make([]string, 0, len(t.Params.List))
for _, p := range t.Params.List {
params = append(params, expr2str(p.Type))
}
results := make([]string, 0, len(t.Results.List))
for _, r := range t.Results.List {
results = append(results, expr2str(r.Type))
}
ps := strings.Join(params, ", ")
if len(results) == 0 {
return fmt.Sprintf("func(%s)", ps)
}
rs := strings.Join(results, ", ")
if len(results) == 1 {
return fmt.Sprintf("func(%s) %s", ps, rs)
}
return fmt.Sprintf("func(%s) (%s)", ps, rs)
}