forked from XSAM/optionGen
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgen.go
414 lines (370 loc) · 12.5 KB
/
gen.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package optiongen
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"log"
"os/exec"
"sort"
"strings"
"myitcv.io/gogenerate"
"github.com/sandwich-go/boost/annotation"
"github.com/sandwich-go/boost/xmap"
"github.com/sandwich-go/boost/xstrings"
"github.com/sandwich-go/boost/xtag"
)
type FieldType int
const (
FieldTypeFunc FieldType = iota
FieldTypeVar
)
const (
defaultOptionPrefix = "With"
defaultAppendPrefix = "Append"
)
type fileOptionGen struct {
FilePath string
NameDeclare string
FileName string
PkgName string
ImportPath []string
Comments []string
ClassName string
ClassOptionFields []optionField
Annotations []annotation.Annotation
}
func (g *fileOptionGen) ParseAnnotations() (err error) {
var allComments []string
for _, v := range g.ClassOptionFields {
allComments = append(allComments, v.LastRowComments...)
allComments = append(allComments, v.SameRowComment)
allComments = append(allComments, v.MethodComments...)
}
allComments = append(allComments, g.Comments...)
g.Annotations, err = annotation.NewRegistry().ResolveAnnotationsErrorDuplicate(allComments)
if AtomicConfig().GetDebug() {
fmt.Printf("\n===>>> ParseAnnotations all comments ===>>> \n %s \n", strings.Join(allComments, "\n"))
fmt.Printf("\n===>>> ParseAnnotations annotations ===>>> \n %v \n", g.Annotations)
}
return
}
func (g *fileOptionGen) GetAnnotation(name string) annotation.Annotation {
for _, v := range g.Annotations {
if v.Name == name {
return v
}
}
for _, v := range g.Annotations {
if strings.EqualFold(v.Name, name) {
return v
}
}
return annotation.Annotation{}
}
type optionField struct {
FieldType FieldType
Name string
Type string
Body string
LastRowComments []string
SameRowComment string
MethodComments []string
}
type templateData struct {
ClassOptionInfo []optionInfo
ClassComments []string
ClassName string
ClassNameTitle string
ClassOptionTypeName string
ClassOptionFunctionTypeName string
ClassNewFuncSignature string
ClassNewFuncName string
XConf bool
OptionReturnPrevious bool
VisitorName string
InterfaceName string
}
type optionInfo struct {
ArgIndex int
FieldType FieldType
Name string
NameAsParameter string
OptionFuncName string
AppendFuncName string
VisitFuncName string
VisitFuncReturnType template.HTML
GenOptionFunc bool
GenVisitFunc bool
Slice bool
SliceElemType template.HTML
Type template.HTML
Body template.HTML
LastRowComments []string
SameRowComment string
OptionComment string
AppendComment string
VisitFuncComment string
Tags []string
TagString string
Inline bool
OnlyAppend bool
}
func cleanAsTag(s ...string) string {
var tmp []string
for _, v := range s {
tmp = append(tmp, xstrings.Trim(v, "//"))
}
return xstrings.EscapeStringBackslash(strings.Join(tmp, " , "))
}
func (g fileOptionGen) fatal(location string, err error, info ...string) {
var infos []string
infos = append(infos, "----------------------------------------- >>>>>>>>> optiongen got fatal")
infos = append(infos, fmt.Sprintf("file: %s", g.FilePath))
infos = append(infos, fmt.Sprintf("option: %s", g.NameDeclare))
infos = append(infos, fmt.Sprintf("location: %s", location))
infos = append(infos, fmt.Sprintf("error: %s", err.Error()))
infos = append(infos, info...)
infos = append(infos, "----------------------------------------- <<<<<<<<<")
panic(strings.Join(infos, "\n"))
}
func (g fileOptionGen) gen() {
buf := BufWrite{
buf: bytes.NewBuffer(nil),
}
buf.wln(fmt.Sprintf("// Code generated by %s. DO NOT EDIT.", OptionGen))
buf.wln(fmt.Sprintf("// %s: %s", OptionGen, "github.com/timestee/optiongen"))
buf.wln()
buf.wf("package %v\n", g.PkgName)
for _, importPath := range g.ImportPath {
buf.wf("import %v\n", importPath)
}
tmp := templateData{XConf: AtomicConfig().GetXConf(), OptionReturnPrevious: AtomicConfig().GetOptionReturnPrevious()}
className := g.ClassName
indexGot := make(map[int]string)
for _, val := range g.ClassOptionFields {
name := strings.Trim(val.Name, "\"")
funcName := defaultOptionPrefix
prefix := funcName
if AtomicConfig().GetOptionPrefix() != "" {
funcName = AtomicConfig().GetOptionPrefix()
prefix = funcName
} else {
if AtomicConfig().GetOptionWithStructName() {
funcName = funcName + strings.Title(className)
}
if strings.HasSuffix(funcName, "Options") {
funcName = funcName[:len(funcName)-1]
}
if strings.HasSuffix(funcName, "Opts") {
funcName = funcName[:len(funcName)-1]
}
}
if strings.HasPrefix(val.Type, "(") && strings.HasSuffix(val.Type, ")") {
val.Type = val.Type[1 : len(val.Type)-1]
}
name = strings.Split(name, "@")[0]
nameSnakeCase := xstrings.SnakeCase(name)
funcName += strings.Title(name)
appendFuncName := defaultAppendPrefix + strings.TrimPrefix(funcName, prefix)
an := g.GetAnnotation(name)
private := an.GetBool(AnnotationKeyPrivate, strings.HasSuffix(name, "_") || strings.HasSuffix(name, "Inner"))
onlyAppend := an.GetBool(AnnotationKeySliceOnlyAppend, AtomicConfig().GetSliceOnlyAppend())
if AtomicConfig().GetDebug() {
fmt.Printf("===>>> Field Annotation name: %s attributes: %v\n", name, an.Attributes)
}
tagValues := make(map[string]string)
for k, v := range an.Attributes {
if strings.HasPrefix(k, AnnotationKeyTag) {
tagValues[strings.TrimPrefix(k, AnnotationKeyTag)] = v
}
}
xconfTag := an.GetString(AnnotationKeyXConfTag, nameSnakeCase)
argIndex := an.GetInt(AnnotationKeyArg)
getterType := an.GetString(AnnotationKeyGetter, val.Type)
optionFuncName := an.GetString(AnnotationKeyOption, funcName)
appendFuncName = an.GetString(AnnotationKeyAppend, appendFuncName)
visitFuncName := an.GetString(AnnotationKeyVisit, "Get"+strings.Title(name))
comment := an.GetString(AnnotationKeyComment)
deprecated := an.GetString(AnnotationKeyDeprecated)
if argIndex != 0 {
if got, ok := indexGot[argIndex]; ok {
g.fatal("parse annotation "+AnnotationKeyArg, fmt.Errorf("got same index,%s and %s ", got, val.Name))
}
indexGot[argIndex] = name
}
if AtomicConfig().GetXConf() {
name = strings.Title(name)
}
info := optionInfo{
ArgIndex: argIndex,
FieldType: val.FieldType,
Name: name,
NameAsParameter: xstrings.FirstLower(name),
GenOptionFunc: !private && argIndex == 0 && optionFuncName != "-",
GenVisitFunc: visitFuncName != "-",
OptionFuncName: optionFuncName,
AppendFuncName: appendFuncName,
VisitFuncName: visitFuncName,
VisitFuncReturnType: template.HTML(getterType),
Slice: strings.HasPrefix(val.Type, "[]"),
SliceElemType: template.HTML(strings.Replace(val.Type, "[]", "", 1)),
Type: template.HTML(val.Type),
Body: template.HTML(val.Body),
LastRowComments: val.LastRowComments,
SameRowComment: val.SameRowComment,
Inline: an.GetBool(AnnotationKeyInline, false),
OnlyAppend: onlyAppend,
}
methodComments := val.MethodComments
if comment != "" {
if len(methodComments) == 0 {
methodComments = append(methodComments, comment)
}
}
for index, v := range methodComments {
methodComments[index] = xstrings.Trim(v, "//", ",", ".")
}
info.OptionComment = funcComment(info.Name, "option", info.OptionFuncName, deprecated, methodComments)
info.AppendComment = funcComment(info.Name, "append", info.AppendFuncName, deprecated, methodComments)
infoForUsage := methodComments
if deprecated != "" {
info.VisitFuncComment += fmt.Sprintf("\n// %s visitor func for filed %s", info.VisitFuncName, info.Name)
info.VisitFuncComment += "\n//"
info.VisitFuncComment += "\n// Deprecated: " + deprecated
infoForUsage = append(infoForUsage, "Deprecated: "+deprecated)
}
if AtomicConfig().GetXConf() {
if xconfTag == "" {
xconfTag = xstrings.SnakeCase(info.Name)
}
if AtomicConfig().GetXConfTrimPrefix() != "" {
xconfTag = strings.TrimPrefix(xconfTag, AtomicConfig().GetXConfTrimPrefix())
}
if deprecated != "" && !strings.Contains(xconfTag, "deprecated") {
xconfTag += ",deprecated"
}
info.Tags = append(info.Tags, fmt.Sprintf(`xconf:"%s"`, xconfTag))
}
if AtomicConfig().GetUsageTagName() != "" {
s := cleanAsTag(infoForUsage...)
if s != "" {
info.Tags = append(info.Tags, fmt.Sprintf(`%s:"%s"`, AtomicConfig().GetUsageTagName(), s))
}
}
xmap.WalkMapDeterministic(tagValues, func(k, v string) bool {
info.Tags = append(info.Tags, fmt.Sprintf(`%s:"%s"`, k, v))
return true
})
if len(info.Tags) > 0 {
tag := strings.Join(info.Tags, " ")
info.TagString = fmt.Sprintf("`%s`", tag)
if err := xtag.ValidateStructTag(tag); err != nil {
g.fatal("tag", err, "tag: "+tag)
}
}
// []byte不作为数组类型处理
if strings.TrimSpace(strings.TrimLeft(val.Type, "[]")) == "byte" {
info.Slice = false
}
tmp.ClassOptionInfo = append(tmp.ClassOptionInfo, info)
}
optionTypeName := className + "Option"
if strings.HasSuffix(className, "Options") {
optionTypeName = className[:len(className)-1]
}
if strings.HasSuffix(className, "Opts") {
optionTypeName = className[:len(className)-1]
}
optionTypeName = strings.Title(optionTypeName)
tmp.ClassOptionTypeName = optionTypeName
tmp.ClassOptionFunctionTypeName = fmt.Sprintf("%sFunc", optionTypeName)
tmp.ClassComments = g.Comments
tmp.ClassName = g.ClassName
tmp.ClassNameTitle = strings.Title(tmp.ClassName)
tmp.VisitorName = fmt.Sprintf("%sVisitor", tmp.ClassNameTitle)
tmp.InterfaceName = fmt.Sprintf("%sInterface", tmp.ClassNameTitle)
newFuncReturn := "*" + className
if AtomicConfig().GetNewFuncReturn() == NewFuncReturnVisitor {
newFuncReturn = tmp.VisitorName
} else if AtomicConfig().GetNewFuncReturn() == NewFuncReturnInterface {
newFuncReturn = tmp.InterfaceName
}
newFuncName := AtomicConfig().GetNewFunc()
if newFuncName == "" {
newFuncName = fmt.Sprintf("New%s", strings.Title(className))
}
sort.Slice(tmp.ClassOptionInfo, func(i, j int) bool {
return tmp.ClassOptionInfo[i].ArgIndex < tmp.ClassOptionInfo[j].ArgIndex
})
var pameters []string
for _, v := range tmp.ClassOptionInfo {
if v.ArgIndex == 0 {
continue
}
pameters = append(pameters, fmt.Sprintf("%s %s", v.NameAsParameter, v.Type))
}
if len(pameters) == 0 {
tmp.ClassNewFuncSignature = fmt.Sprintf("func %s(opts... %s) %s", newFuncName, optionTypeName, newFuncReturn)
} else {
tmp.ClassNewFuncSignature = fmt.Sprintf("func %s(%s, opts... %s) %s", newFuncName, strings.Join(pameters, ","), optionTypeName, newFuncReturn)
}
tmp.ClassNewFuncName = newFuncName
funcMap := template.FuncMap{
"unescaped": unescaped,
}
t := template.Must(template.New("tmp").Funcs(funcMap).Parse(templateTextWithPreviousSupport))
err := t.Execute(buf.buf, tmp)
if err != nil {
g.fatal("tempalt_execute", err)
}
if strings.HasPrefix(g.FileName, "gen_") {
g.FileName = strings.TrimLeft(g.FileName, "gen_")
}
genName := gogenerate.NameFile(g.FileName, OptionGen)
source := g.goimportsBuf(buf.buf)
if err := ioutil.WriteFile(genName, source.Bytes(), 0644); err != nil {
g.fatal("write_file", err)
}
if AtomicConfig().GetDebug() {
log.Println(fmt.Sprintf("%s/%s", g.PkgName, genName))
}
}
func (g fileOptionGen) goimportsBuf(buf *bytes.Buffer) *bytes.Buffer {
out := bytes.NewBuffer(nil)
cmd := exec.Command("goimports")
data := buf.Bytes()
cmd.Stdin = bytes.NewReader(data)
cmd.Stdout = out
err := cmd.Run()
if err != nil {
g.fatal("goimports", err, "==========> INVALID SOURCE CODE <==========", string(data))
}
return out
}
func unescaped(str string) template.HTML { return template.HTML(str) }
var commentPrefix = "//"
func cleanAsComment(s string) string {
ss := strings.Split(xstrings.Trim(s), "\n")
for i, s := range ss {
if !strings.HasPrefix(s, commentPrefix) {
s = fmt.Sprintf("// %s", s)
}
ss[i] = s
}
return strings.Join(ss, "\n")
}
func funcComment(name, funcType, funcName, deprecated string, methodComments []string) string {
comment := ""
if len(methodComments) == 0 {
comment = fmt.Sprintf("%s %s func for filed %s", funcName, funcType, name)
} else {
comment = xstrings.Wrap(fmt.Sprintf("%s %s", funcName, xstrings.Trim(strings.Join(methodComments, ","))), 200)
}
comment = cleanAsComment(comment)
if deprecated != "" {
comment += "\n//"
comment += "\n// Deprecated: " + deprecated
}
return comment
}