-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
91 lines (73 loc) · 2.1 KB
/
template.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
//go:build ignore
// go generate
package main
import (
"bytes"
_ "embed"
"fmt"
"go/format"
"html/template"
"os"
"strings"
"github.com/iancoleman/strcase"
)
type templateInfos struct {
TypeName string
}
//go:embed type_attribute.go.tmpl
var templateTypeAttribute string
//go:embed supertype_attribute.go.tmpl
var templateSuperTypeAttribute string
var templateFuncs = template.FuncMap{
"trimSuffix": func(s, suffix string) string {
return strings.TrimSuffix(s, suffix)
},
}
func main() {
fmt.Println("generating types files...")
tA := []string{"string", "bool", "float64", "int64", "list", "list_nested", "object", "single_nested", "set", "set_nested", "number", "map", "map_nested"}
for _, t := range tA {
infos := templateInfos{
TypeName: strcase.ToCamel(t),
}
tmplType, err := template.New("template").Funcs(templateFuncs).Parse(templateTypeAttribute)
if err != nil {
fmt.Printf("error from template parse : %v\n", err)
os.Exit(1)
}
tmplSuperType, err := template.New("template").Funcs(templateFuncs).Parse(templateSuperTypeAttribute)
if err != nil {
fmt.Printf("error from template parse : %v\n", err)
os.Exit(1)
}
var (
tpl bytes.Buffer
tplSuper bytes.Buffer
)
if err := tmplType.Execute(&tpl, infos); err != nil {
fmt.Printf("error from template execute : %v\n", err)
os.Exit(1)
}
if err := tmplSuperType.Execute(&tplSuper, infos); err != nil {
fmt.Printf("error from template execute : %v\n", err)
os.Exit(1)
}
// format the code
formattedTmplType, errFormat := format.Source(tpl.Bytes())
if errFormat != nil {
fmt.Printf("error from format : %v\n", errFormat)
os.Exit(1)
}
formattedTmplSuperType, errFormat := format.Source(tplSuper.Bytes())
if errFormat != nil {
fmt.Printf("error from format : %v\n", errFormat)
os.Exit(1)
}
if err := os.WriteFile(t+"_attribute.go", formattedTmplType, 0644); err != nil {
fmt.Printf("write to file error : %v\n", err)
}
if err := os.WriteFile("super"+t+"_attribute.go", formattedTmplSuperType, 0644); err != nil {
fmt.Printf("write to file error : %v\n", err)
}
}
}