-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
211 lines (175 loc) · 4.35 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
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"golang.org/x/tools/go/packages"
)
var (
typeName = flag.String("type", "", "struct names. must be present in go file. -type=Config")
exportPrivate = flag.Bool("private", false, "should you want to include private fields in struct as well")
)
func main() {
log.SetFlags(0)
log.SetPrefix("getter: ")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of geterator:\n")
fmt.Fprintf(os.Stderr, "\tgeterator -type=Stuct -private")
flag.PrintDefaults()
}
flag.Parse()
if len(*typeName) == 0 {
log.Fatal("type name is missing")
}
cfg := &packages.Config{
Mode: packages.LoadSyntax,
Tests: false,
}
dirs := flag.Args()
if len(dirs) == 0 {
dirs = []string{"."}
}
var dir string
if len(dirs) == 1 && isDirectory(dirs[0]) {
dir = dirs[0]
} else {
dir = filepath.Dir(dirs[0])
}
pkgs, err := packages.Load(cfg, dir)
if err != nil {
log.Fatal(err)
}
var pkg *packages.Package
for _, p := range pkgs {
if p.Types == nil {
continue
}
for _, f := range p.Syntax {
ast.Inspect(f, func(node ast.Node) bool {
// Look for a type definition with the given name.
if typeSpec, ok := node.(*ast.TypeSpec); ok {
if typeSpec.Name.Name == *typeName {
pkg = p
return false // we found a match. so skipping rest.
}
}
return true
})
// we found the desired package of the struct.
// so process the declarations now
if pkg != nil {
break
}
}
if pkg != nil {
break
}
}
if pkg == nil {
log.Fatalf("error: type %q not found\n", *typeName)
}
var buf = bytes.Buffer{}
buf.WriteString("// Code generated by \"go generate\"; DO NOT EDIT.\n\n")
buf.WriteString(fmt.Sprintf("package %s\n", pkg.Name))
for _, f := range pkg.Syntax {
ast.Inspect(f, func(node ast.Node) bool {
// Look for a type definition with the given name.
if typeSpec, ok := node.(*ast.TypeSpec); ok {
// if the struct name is not the same, skip it
if typeSpec.Name.Name != *typeName {
return false
}
// Generate getters for the fields of the struct.
if structType, ok := typeSpec.Type.(*ast.StructType); ok {
for _, field := range structType.Fields.List {
// Skip unexported fields.
if field.Names == nil {
continue
}
f := field.Names[0]
if !(*exportPrivate) && !f.IsExported() {
continue
}
fieldType := exprToString(field.Type)
buf.WriteString(
fmt.Sprintf("func (c %s) Get%s() %s {\n", *typeName, toUpperFirst(f.Name), fieldType),
)
buf.WriteString(fmt.Sprintf("return c.%s\n", f.Name))
buf.WriteString("}\n")
}
}
}
return true
})
}
out, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
filename := fmt.Sprintf("%s_gen.go", strings.ToLower(*typeName))
path := filepath.Join(dir, filename)
file, err := os.Create(path)
if err != nil {
log.Fatalf("error: %v\n", err)
}
defer file.Close()
if _, err := file.Write(out); err != nil {
log.Fatal(err)
}
}
func exprToString(expr ast.Expr) string {
switch e := expr.(type) {
case *ast.Ident:
return e.Name
case *ast.StarExpr:
return "*" + exprToString(e.X)
case *ast.ArrayType:
return "[]" + exprToString(e.Elt)
case *ast.MapType:
return fmt.Sprintf("map[%s]%s", exprToString(e.Key), exprToString(e.Value))
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", e.X, e.Sel)
case *ast.StructType:
return "struct{}"
default:
log.Fatal("unsupported type")
}
return "interface{}"
}
// containsGenerateDirective returns true if the specified file contains a go:generate directive.
func containsGenerateDirective(pkg *packages.Package, filename string) bool {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
log.Fatalf("error parsing file: %v", err)
}
for _, commentGroup := range node.Comments {
for _, comment := range commentGroup.List {
if strings.HasPrefix(comment.Text, "//go:generate") {
return true
}
}
}
return false
}
func isDirectory(name string) bool {
info, err := os.Stat(name)
if err != nil {
log.Fatal(err)
}
return info.IsDir()
}
func toUpperFirst(str string) string {
if len(str) < 1 {
return str
}
return string([]rune(strings.ToUpper(str[:1]))) + str[1:]
}