-
Notifications
You must be signed in to change notification settings - Fork 3
/
structor.go
179 lines (152 loc) · 3.65 KB
/
structor.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
package main
import (
"bufio"
"go/ast"
"go/parser"
"go/token"
"html/template"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
)
type Structor struct {
pDir string // package directory
getTemplate *template.Template
setTemplate *template.Template
}
type parsedFile struct {
PackageName string
Imports []string
StructName string
Fields []parsedField
}
type parsedField struct {
SName string
FName string
FType string
CName string
}
func newParsedFile(name string) parsedFile {
return parsedFile{
PackageName: name,
Imports: make([]string, 0),
Fields: make([]parsedField, 0),
}
}
func (s *Structor) Generate() error {
pFiles, err := s.parse()
if err != nil {
return err
}
// for each struct let's create the accessors
for _, pFile := range pFiles {
w, err := s.getWriter(pFile.StructName)
if err != nil {
return err
}
w.WriteString("// DO NOT EDIT: file has been automatically generated\n")
w.WriteString("package " + pFile.PackageName + "\n\n")
for _, i := range pFile.Imports {
w.WriteString("import " + i + "\n")
}
for _, f := range pFile.Fields {
err := s.getTemplate.Execute(w, f)
if err != nil {
return err
}
err = s.setTemplate.Execute(w, f)
if err != nil {
return err
}
}
w.Flush()
}
return nil
}
func (s *Structor) getWriter(stName string) (*bufio.Writer, error) {
fn := structAccessorFileName(stName)
f, err := os.Create(path.Join(s.pDir, fn))
if err != nil {
return nil, err
}
return bufio.NewWriter(f), nil
}
func (s *Structor) parse() ([]parsedFile, error) {
pFiles := make([]parsedFile, 0)
files, err := ioutil.ReadDir(s.pDir)
if err != nil {
return nil, err
}
for _, file := range files {
if file.IsDir() {
continue
}
if strings.HasSuffix(file.Name(), "_accessors.go") {
continue
}
fn := path.Join(s.pDir, file.Name())
src, err := ioutil.ReadFile(fn)
if err != nil {
return nil, err
}
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, fn, src, 0)
if err != nil {
return nil, err
}
// Inspect the AST and print all identifiers and literals.
pFile := newParsedFile(f.Name.Name)
ast.Inspect(f, func(n ast.Node) bool {
switch t := n.(type) {
case *ast.TypeSpec:
e, ok := t.Type.(*ast.StructType)
if ok {
pFile.StructName = t.Name.Name
for _, f := range e.Fields.List {
pFile.Fields = append(pFile.Fields, parsedField{
SName: t.Name.Name,
FName: f.Names[0].Name,
CName: strings.Title(f.Names[0].Name),
FType: string(src[f.Type.Pos()-1 : f.Type.End()-1]),
})
}
}
case *ast.ImportSpec:
pFile.Imports = append(pFile.Imports, t.Path.Value)
}
return true
})
pFiles = append(pFiles, pFile)
}
return pFiles, nil
}
func structAccessorFileName(name string) string {
sn := toSnakeCase(name)
return sn + "_accessors.go"
}
func toSnakeCase(str string) string {
// https://gist.github.com/stoewer/fbe273b711e6a06315d19552dd4d33e6
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
func NewStructor(pDirectory string) *Structor {
return &Structor{
pDir: pDirectory,
getTemplate: template.Must(template.New("getter").Parse(`
func (t *{{.SName}}) Get{{ .CName }}() {{ .FType }} {
return t.{{ .FName }}
}
`)),
setTemplate: template.Must(template.New("setter").Parse(`
func (t *{{.SName}}) Set{{ .CName }}(f {{ .FType }}) {
t.{{ .FName}} = f
}
`)),
}
}