-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.go
170 lines (136 loc) · 3.73 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
168
169
170
package main
import (
"bytes"
"fmt"
"github.com/pkg/errors"
"golang.org/x/tools/imports"
"io"
"log"
"sort"
"strings"
"unicode"
)
func writeImports(w io.Writer, imports []string) {
if imports == nil || len(imports) == 0 {
return
}
fmt.Fprintln(w, "import (")
for _, i := range imports {
fmt.Fprintln(w, i)
}
fmt.Fprintln(w, ")")
}
func bool2int(b bool) int {
if b {
return 1
}
return 0
}
func buildInputParams(fields []genField) string {
var fieldList []string
// sort fields, required first
sort.SliceStable(fields, func(i, j int) bool {
return bool2int(fields[i].optional) < bool2int(fields[j].optional)
})
for _, f := range fields {
if f.skip {
continue
}
var optionalStr string
if f.optional && !f.array {
optionalStr = "*"
}
if f.array {
if f.ptr {
fieldList = append(fieldList, fmt.Sprintf("%s %s[]*%s", f.name, optionalStr, f.typ))
} else {
fieldList = append(fieldList, fmt.Sprintf("%s %s[]%s", f.name, optionalStr, f.typ))
}
} else {
fieldList = append(fieldList, fmt.Sprintf("%s %s%s", f.name, optionalStr, f.typ))
}
}
return strings.Join(fieldList, ",")
}
func buildBody(name string, fields []genField) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("result := &%s {\n", name))
// process required fields
for _, f := range fields {
if f.skip || f.optional {
continue
}
// if field is required, not an array, and a pointer, then set to the address of the input param
if f.ptr && !f.array {
sb.WriteString(fmt.Sprintf("%s: &%s,\n", f.name, f.name))
} else {
sb.WriteString(fmt.Sprintf("%s: %s,\n", f.name, f.name))
}
}
sb.WriteString("}\n")
// process optional fields
for _, f := range fields {
if f.skip || !f.optional {
continue
}
if f.ptr {
sb.WriteString(fmt.Sprintf("if %s != nil {\nresult.%s = %s\n}\n", f.name, f.name, f.name))
} else {
sb.WriteString(fmt.Sprintf("if %s != nil {\nresult.%s = *%s\n}\n", f.name, f.name, f.name))
}
}
sb.WriteString("return result\n")
return sb.String()
}
func formatStructName(in string) string {
return "New" + string(unicode.ToUpper(rune(in[0]))) + in[1:]
}
func writeStruct(w io.Writer, s genStruct) {
fmFuncName := formatStructName(s.name)
comment := fmt.Sprintf("// %s generated factory method for %s", fmFuncName, s.name)
// struct comment
fmt.Fprintln(w, comment)
// struct method signature
fmt.Fprintf(w, "func %s(%s) *%s{\n", fmFuncName, buildInputParams(s.fields), s.name)
// build struct body
fmt.Fprintf(w, buildBody(s.name, s.fields))
fmt.Fprintln(w, "}")
}
func writePackageFile(w io.Writer, pkg string, pkgImports []string, structs []genStruct) {
var buf bytes.Buffer
var err error
// write the header comment
fmt.Fprintln(&buf, `// Code generated by "fmgen". DO NOT EDIT.`)
// write the package
fmt.Fprintln(&buf, fmt.Sprintf("package %s", pkg))
// write the imports
writeImports(&buf, pkgImports)
// write factory methods for each struct
for _, s := range structs {
if !s.Skip() {
writeStruct(&buf, s)
}
}
output := fmt.Sprintf("%s/%s", pkg, generatedFileName)
log.Printf("generating factory method file for package [%s]", pkg)
opts := &imports.Options{
Fragment: false,
AllErrors: true,
Comments: true,
TabIndent: false,
TabWidth: 4,
FormatOnly: false,
}
// process imports twice due to issues noticed with imports not being removed
processed := buf.Bytes()
for i := 0; i < 2; i++ {
processed, err = imports.Process(output, processed, opts)
if err != nil {
log.Panicf("unable to process generated file to remove unused imports - %v", errors.WithStack(err))
}
}
_, err = io.Copy(w, bytes.NewReader(processed))
if err != nil {
log.Panicf("unable to copy processed results to writer - %v", errors.WithStack(err))
}
}