-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
203 lines (185 loc) · 4.99 KB
/
main.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
package main
import (
"bytes"
"embed"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"text/template"
"time"
"golang.org/x/tools/go/ast/astutil"
)
//go:embed templates/*
var templateFiles embed.FS
var (
domain string
domainTitle string
templates = []string{"domain", "http", "mem_store", "service"}
)
func main() {
log.Println("Starting Generator...")
flag.StringVar(&domain, "domain", "test", "name of domain to generate")
flag.Parse()
if strings.TrimSpace(domain) == "" {
log.Fatal("failed to generate api domain, no domain passed")
}
domain = strings.ToLower(domain)
domainTitle = strings.Title(domain)
log.Println("Inputs successfully parsed, starting generation of new domain...")
generateDomain()
log.Println("All code generated successfully, updating routes.go with new route constant...")
updateRoutes()
updateMain()
log.Println("Generation completed")
}
func generateDomain() {
args := map[string]string{
"Domain": domain,
"DomainTitle": domainTitle,
"Date": time.Now().Format(time.RFC3339),
}
if err := os.Mkdir("../../"+domain+"s", 0755); err != nil {
log.Fatalf("failed to create %s directory %s", domain, err)
}
for _, tmplName := range templates {
log.Printf("Creating %s.go file\n", tmplName)
tmpl, err := template.ParseFS(templateFiles, "templates/"+tmplName+".go.tmpl")
if err != nil {
log.Fatalf("failed to read template %s.go.tmpl: %s", tmplName, err)
}
buf := bytes.Buffer{}
if err := tmpl.Execute(&buf, args); err != nil {
log.Fatalf("failed to parse template %s: %s", tmplName, err)
}
fn := tmplName + ".go"
if tmplName == "domain" {
fn = domain + "s.go"
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
log.Fatalf("go/format: %s", err)
}
if err := ioutil.WriteFile("../../"+domain+"s/"+fn, formatted, 0644); err != nil {
log.Fatalf("failed to write template %s: %s", tmplName, err)
}
log.Printf("Created %s.go file successfully\n", tmplName)
}
}
func updateRoutes() {
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "../../routes.go", nil, parser.AllErrors)
if err != nil {
log.Fatalf("failed to parse AST from routes.go: %s", err)
}
routes := []string{
fmt.Sprintf("Route%ss", domainTitle),
fmt.Sprintf("Route%s", domainTitle),
}
consts := make(map[string]bool, 0)
d, _ := f.Decls[0].(*ast.GenDecl)
if d.Tok == token.CONST {
for _, s := range d.Specs {
c := s.(*ast.ValueSpec)
for _, n := range c.Names {
consts[n.Name] = true
}
}
}
for _, r := range routes {
if !consts[r] {
addConstant(d, r)
}
}
formatAndSave(fs, f, "../../routes.go")
}
func addConstant(d *ast.GenDecl, c string) {
fmt.Printf("Constant for this domain not previously defined, updating routes.go with %s\n", c)
con := ast.NewIdent(c)
con.Obj = ast.NewObj(ast.Con, c)
conVal := &ast.BasicLit{
Kind: token.STRING,
Value: "\"" + "/api/v1/" + domain + "s\"",
}
vspec := &ast.ValueSpec{
Names: []*ast.Ident{con},
Values: []ast.Expr{
conVal,
},
}
d.Specs = append(d.Specs, vspec)
sort.Slice(d.Specs, func(i, j int) bool {
return d.Specs[i].(*ast.ValueSpec).Names[0].Name < d.Specs[j].(*ast.ValueSpec).Names[0].Name
})
fmt.Printf("%s constant successfully added to routes.go\n", c)
}
func updateMain() {
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "../api/main.go", nil, parser.AllErrors)
if err != nil {
log.Fatalf("failed to parse AST from main.go: %s", err)
}
astutil.AddImport(fs, f, fmt.Sprintf("github.com/theflyingcodr/gogenerate-meetup/05-api-gen/%ss", domain))
ast.Inspect(f, func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
route := &ast.ExprStmt{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: &ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(domain + "s"),
Sel: ast.NewIdent("NewHttpHandler"),
},
Args: []ast.Expr{
&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(domain + "s"),
Sel: ast.NewIdent("New" + domainTitle + "Svc"),
},
Args: []ast.Expr{
&ast.CallExpr{
Fun: &ast.SelectorExpr{
X: ast.NewIdent(domain + "s"),
Sel: ast.NewIdent("NewMemoryStore"),
},
},
},
},
},
},
Sel: ast.NewIdent("Register"),
},
},
}
fn.Body.List = append([]ast.Stmt{route}, fn.Body.List...)
return false
})
fp := "../api/main.go"
formatAndSave(fs, f, fp)
fmt.Printf("main.go wired up with new endpoint")
}
func formatAndSave(fs *token.FileSet, f *ast.File, filePath string) {
var output []byte
buffer := bytes.NewBuffer(output)
if err := printer.Fprint(buffer, fs, f); err != nil {
log.Fatalf("failed to add constant to resources.go: %s", err)
}
bb, err := format.Source(buffer.Bytes())
if err != nil {
log.Fatalf("failed to format file %s", err)
}
if err := ioutil.WriteFile(filePath, bb, 0755); err != nil {
log.Fatalf("failed to create %s", err)
}
}