-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.go
More file actions
72 lines (58 loc) · 1.49 KB
/
builder.go
File metadata and controls
72 lines (58 loc) · 1.49 KB
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
package main
import (
"fmt"
"io"
"text/template"
)
type StructField struct {
Name string
Type string
}
type StructInfo struct {
ImportPath string
OutputPackageName string
BuilderTypeName string
OutputTypeName string
Fields []StructField
}
func (s *StructInfo) String() string {
return fmt.Sprintf("ImportPath: %s\nOutputPackageName: %s\nBuilderTypeName: %s\nOutputTypeName: %s\nFields: %v\n", s.ImportPath, s.OutputPackageName, s.BuilderTypeName, s.OutputTypeName, s.Fields)
}
// Go template for generating a builder
const builderTemplate = `// Code generated by structbuilder. DO NOT EDIT.
package {{.OutputPackageName}}
import "{{.ImportPath}}"
type {{.BuilderTypeName}}Builder struct {
{{- range .Fields}}
{{.Name}} {{.Type}}
{{- end}}
}
func New{{.BuilderTypeName}}Builder() *{{.BuilderTypeName}}Builder {
return &{{.BuilderTypeName}}Builder{}
}{{ "\n" }}
{{- range .Fields}}
func (b *{{$.BuilderTypeName}}Builder) With{{.Name}}(value {{.Type}}) *{{$.BuilderTypeName}}Builder {
b.{{.Name}} = value
return b
}{{ "\n" }}
{{- end}}
func (b *{{.BuilderTypeName}}Builder) Build() *{{.OutputTypeName}} {
return &{{.OutputTypeName}}{
{{- range .Fields}}
{{.Name}}: b.{{.Name}},
{{- end}}
}
}
`
func executeTemplate(structInfo *StructInfo, w io.Writer) error {
tmpl, err := template.New("struct_builder").Parse(builderTemplate)
if err != nil {
return err
}
// Execute the template
err = tmpl.Execute(w, structInfo)
if err != nil {
return err
}
return nil
}