-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
183 lines (160 loc) · 4.26 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
package main
import (
"fmt"
"go/types"
"os"
"strings"
"unicode"
"unicode/utf8"
. "github.com/dave/jennifer/jen"
"golang.org/x/tools/go/packages"
)
func main() {
// 1. Handle arguments to command
if len(os.Args) != 2 {
failErr(fmt.Errorf("expected exactly one argument: <source type>"))
}
sourceType := os.Args[1]
sourceTypePackage, sourceTypeName := splitSourceType(sourceType)
// 2. Inspect package and use type checker to infer imported types
pkg := loadPackage(sourceTypePackage)
fmt.Println("original package path: " + sourceTypePackage)
// 3. Lookup the given source type name in the package declarations
obj := pkg.Types.Scope().Lookup(sourceTypeName)
if obj == nil {
failErr(fmt.Errorf("%s not found in declared types of %s",
sourceTypeName, pkg))
}
// 4. We check if it is a declared type
if _, ok := obj.(*types.TypeName); !ok {
failErr(fmt.Errorf("%v is not a named type", obj))
}
// 5. We expect the underlying type to be a struct
structType, ok := obj.Type().Underlying().(*types.Struct)
if !ok {
failErr(fmt.Errorf("type %v is not a struct", obj))
}
err := generateBuilder(sourceTypePackage, sourceTypeName, structType)
if err != nil {
failErr(err)
}
}
func loadPackage(path string) *packages.Package {
cfg := &packages.Config{Mode: packages.NeedTypes | packages.NeedImports}
pkgs, err := packages.Load(cfg, path)
if err != nil {
failErr(fmt.Errorf("loading packages for inspection: %v", err))
}
if packages.PrintErrors(pkgs) > 0 {
os.Exit(1)
}
return pkgs[0]
}
func splitSourceType(sourceType string) (string, string) {
idx := strings.LastIndexByte(sourceType, '.')
if idx == -1 {
failErr(fmt.Errorf(`expected qualified type as "pkg/path.MyType"`))
}
sourceTypePackage := sourceType[0:idx]
sourceTypeName := sourceType[idx+1:]
return sourceTypePackage, sourceTypeName
}
func failErr(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func generateBuilder(sourcePackagePath string, sourceTypeName string, structType *types.Struct) error {
// 1. Get the package of the file with go:generate comment
goPackage := os.Getenv("GOPACKAGE")
// 2. Start a new file in this package
f := NewFile(goPackage)
// 3. Add a package comment, so IDEs detect files as generated
f.PackageComment("Code generated by generator, DO NOT EDIT.")
// 5. Generate changeset type
builderName := sourceTypeName + "Builder"
typeLowerCase := firstToLower(sourceTypeName)
f.Type().Id(builderName).Struct(
Id(typeLowerCase).Id("*" + sourceTypeName),
)
f.Func().
Id("New" + builderName).
Params().
Id("*" + builderName).
Block(
Return(Op("&").Id(builderName).Op("{}")),
)
for i := 0; i < structType.NumFields(); i++ {
field := structType.Field(i)
fieldNameLowerCase := firstToLower(field.Name())
code := Id(fieldNameLowerCase)
switch v := field.Type().(type) {
case *types.Basic:
code.Id(v.String())
case *types.Pointer:
switch ut := v.Elem().(type) {
case *types.Basic:
code.Op("*").Id(ut.String())
case *types.Named:
typeName := ut.Obj()
if typeName.Pkg().Path() == sourcePackagePath {
code.Op("*").Id(typeName.Name())
} else {
code.Op("*").Qual(
typeName.Pkg().Path(),
typeName.Name(),
)
}
}
case *types.Named:
typeName := v.Obj()
if typeName.Pkg().Path() == sourcePackagePath {
code.Id(typeName.Name())
} else {
code.Qual(
typeName.Pkg().Path(),
typeName.Name(),
)
}
default:
return fmt.Errorf("struct field type not hanled: %T", v)
}
f.Func().
Params(
Id("b").Id("*"+builderName),
).
Id("With"+field.Name()).
Params(
code,
).Id("*"+builderName).
Block(
Id("b").Dot(typeLowerCase).Dot(field.Name()).Op("=").Id(fieldNameLowerCase),
Return(Id("b")),
)
}
f.Func().
Params(
Id("b").Id("*" + builderName),
).
Id("Build").
Params().
Id("*" + sourceTypeName).
Block(
Return(Id("b").Dot(typeLowerCase)),
)
targetFilename := strings.ToLower(sourceTypeName) + "_builder_gen.go"
// 7. Write generated file
return f.Save(targetFilename)
}
func firstToLower(s string) string {
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && size <= 1 {
return s
}
lc := unicode.ToLower(r)
if r == lc {
return s
}
return string(lc) + s[size:]
}