/
generate.go
167 lines (149 loc) · 3.81 KB
/
generate.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
package go_constructor
import (
"bytes"
"fmt"
"go/ast"
"go/token"
"go/types"
"reflect"
"strings"
"text/template"
"github.com/hori-ryota/go-codegen/util/gocodeutil"
"github.com/hori-ryota/go-codegen/util/typeutil"
"github.com/hori-ryota/go-strcase"
"golang.org/x/tools/go/loader"
)
const (
commentMarker = "//genconstructor"
pointerOpts = "-p"
)
func Generate(pkgInfo *loader.PackageInfo) (string, error) {
allImported := typeutil.AllImported(pkgInfo)
pkgPathToName := make(map[string]string, len(allImported))
for _, imported := range allImported {
pkgPathToName[imported.Path()] = imported.Name()
}
printer := typeutil.NewPrinter(pkgInfo.Pkg)
printer.SetPkgPathToName(pkgPathToName)
b := new(bytes.Buffer)
for _, file := range pkgInfo.Files {
for _, decl := range file.Decls {
decl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
if decl.Tok != token.TYPE {
continue
}
for _, spec := range decl.Specs {
spec := spec.(*ast.TypeSpec)
docs := make([]*ast.Comment, 0, 10)
if spec.Doc != nil {
docs = append(docs, spec.Doc.List...)
}
if decl.Doc != nil {
docs = append(docs, decl.Doc.List...)
}
if len(docs) == 0 {
continue
}
hasMarker := false
hasPointerOpts := false
for _, comment := range docs {
if strings.HasPrefix(strings.TrimSpace(comment.Text), commentMarker) {
hasMarker = true
for _, s := range strings.Fields(comment.Text) {
if s == pointerOpts {
hasPointerOpts = true
break
}
}
break
}
}
if !hasMarker {
continue
}
obj, ok := pkgInfo.Defs[spec.Name]
if !ok {
return "", fmt.Errorf("definition not found for '%s'", spec.Name)
}
named := obj.Type().(*types.Named)
if err := template.Must(template.New("constructor").Funcs(map[string]interface{}{
"ToLowerCamel": strcase.ToLowerCamel,
"PrintRelativeType": printer.PrintRelativeType,
}).Parse(`
func New{{.Struct.Obj.Name}}(
{{- range .Fields}}
{{- if not .ConstValue}}
{{ToLowerCamel .Name}} {{PrintRelativeType .Type}},
{{- end}}
{{- end}}
) {{if .IsPointer}}*{{end}}{{PrintRelativeType .Struct}} {
return {{if .IsPointer}}&{{end}}{{PrintRelativeType .Struct}}{
{{- range .Fields}}
{{- if .ConstValue}}
{{.Name}}: {{.ConstValue}},
{{- else }}
{{.Name}}: {{ToLowerCamel .Name}},
{{- end}}
{{- end}}
}
}
`)).Execute(b, map[string]interface{}{
"Struct": named,
"Fields": parseFields(named),
"IsPointer": hasPointerOpts,
"printer": printer,
}); err != nil {
return "", err
}
}
}
}
if b.Len() == 0 {
return "", nil
}
out := new(bytes.Buffer)
err := template.Must(template.New("out").Parse(`
// Code generated by go-codegen go_constructor; DO NOT EDIT.
package {{ .PackageName }}
{{ .ImportPackages }}
{{ .Body }}
`)).Execute(out, map[string]string{
"PackageName": pkgInfo.Pkg.Name(),
"ImportPackages": typeutil.FmtImports(allImported, pkgInfo.Pkg),
"Body": b.String(),
})
if err != nil {
return "", err
}
dst, err := gocodeutil.FormatGoFileFromString(out.String())
if err != nil {
return out.String(), err
}
return dst, nil
}
type Field struct {
Type types.Type
Name string
ConstValue string
}
func parseFields(s types.Type) []Field {
fields := typeutil.TypeToFields(s)
tags := typeutil.TypeToTags(s)
dst := make([]Field, 0, len(fields))
for i := range fields {
tag := reflect.StructTag(strings.Trim(tags[i], "`"))
constValue, hasTag := tag.Lookup("required")
if !hasTag {
continue
}
dst = append(dst, Field{
Type: fields[i].Type(),
Name: fields[i].Name(),
ConstValue: constValue,
})
}
return dst
}