-
Notifications
You must be signed in to change notification settings - Fork 0
/
genInterface.go
396 lines (314 loc) · 9.08 KB
/
genInterface.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
package gen
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"time"
"unicode"
"github.com/macinnir/dvc/core/lib"
)
// GenInterface takes makes the interface into a byte array
func GenInterface(comment, pkgName, ifaceName, ifaceComment string, methods []string, imports []string) ([]byte, error) {
output := []string{"// " + comment, "", "package " + pkgName, "import ("}
output = append(output, imports...)
output = append(output, ")", "")
if len(ifaceComment) > 0 {
output = append(output, fmt.Sprintf("// %s", strings.Replace(ifaceComment, "\n", "\n// ", -1)))
}
output = append(output, fmt.Sprintf("type %s interface {", ifaceName))
output = append(output, methods...)
output = append(output, "}")
code := strings.Join(output, "\n")
return lib.FormatCode(code)
}
func fetchExistingInterfaceFiles(srcDir string) ([]string, error) {
// fmt.Println("Fetching files for dir ", srcDir)
filePaths := []string{}
var files []os.FileInfo
var e error
// DAL
if files, e = ioutil.ReadDir(srcDir); e != nil {
return filePaths, e
}
for k := range files {
f := files[k]
filePath := path.Join(srcDir, files[k].Name())
if files[k].IsDir() {
var subFiles []string
if subFiles, e = fetchExistingInterfaceFiles(filePath); e != nil {
return filePaths, e
}
filePaths = append(filePaths, subFiles...)
continue
}
// Filter out files that don't have upper case first letter names
if !unicode.IsUpper([]rune(f.Name())[0]) {
continue
}
// Verify this is a go file
if f.Name()[len(f.Name())-3:] != ".go" {
continue
}
filePaths = append(filePaths, filePath)
}
return filePaths, nil
}
func fetchSrcFilesForInterfaces(srcDir string) ([]string, error) {
// fmt.Println("Fetching files for dir ", srcDir)
filePaths := []string{}
var files []os.FileInfo
var e error
// DAL
if files, e = ioutil.ReadDir(srcDir); e != nil {
return filePaths, e
}
for k := range files {
f := files[k]
filePath := path.Join(srcDir, files[k].Name())
if files[k].IsDir() {
var subFiles []string
if subFiles, e = fetchSrcFilesForInterfaces(filePath); e != nil {
return filePaths, e
}
filePaths = append(filePaths, subFiles...)
continue
}
// Filter out files that don't have upper case first letter names
if !unicode.IsUpper([]rune(f.Name())[0]) {
continue
}
// Verify this is a go file
if f.Name()[len(f.Name())-3:] != ".go" {
continue
}
// Remove the go extension
baseName := f.Name()[0 : len(f.Name())-3]
// Skip over EXT files
if baseName[len(baseName)-3:] == "Ext" {
continue
}
// Skip over test files
if baseName[len(baseName)-5:] == "_test" {
continue
}
filePaths = append(filePaths, filePath)
}
return filePaths, nil
}
// services/services.go
func GenServicesBootstrap(config *lib.Config) error {
lib.EnsureDir("app/definitions")
lib.EnsureDir("core/definitions")
var files []os.FileInfo
var e error
files, e = ioutil.ReadDir("core/services")
packages := []string{}
for k := range files {
if files[k].IsDir() {
packages = append(packages, path.Join("core/services", files[k].Name()))
}
}
files, e = ioutil.ReadDir("app/services")
for k := range files {
if files[k].IsDir() {
packages = append(packages, path.Join("app/services", files[k].Name()))
}
}
// tpl := `// DO NOT EDIT; Auto generated
// package services
// import (
// "` + path.Join(config.BasePackage, config.Dirs.Integrations) + `"
// "` + path.Join(config.BasePackage, "gen/dal") + `"
// "` + path.Join(config.BasePackage, "core/definitions") + `"
// "` + path.Join(config.BasePackage, "core") + `"
// "` + path.Join(config.BasePackage, "core/repos") + `"
// "` + path.Join(config.BasePackage, "core/cache") + `"
// `
// for k := range packages {
// tpl += "\t\"" + path.Join(config.BasePackage, packages[k]) + "\"\n"
// }
// tpl += `
// )
// func bootstrapServices(
// d *dal.DAL,
// config *core.Config,
// i *integrations.Integrations,
// a *AuthLog,
// r *repos.Repos,
// c *cache.Cache,
// ) *definitions.Services {
// return &definitions.Services {
// `
// for k := range packages {
// packageName := path.Base(packages[k])
// tpl += "\t\t" + strings.ToUpper(packageName[0:1]) + packageName[1:] + ": " + packageName + ".NewServices(d, config, i, a, r, c),\n"
// }
// tpl += ` }
// }
// `
// ioutil.WriteFile(path.Join(config.Dirs.Services, "services.go"), []byte(tpl), 0777)
// Write Definitions file
tpl := `// DO NOT EDIT; Auto generated
package definitions
import (
"` + path.Join(config.BasePackage, "core") + `"
"` + path.Join(config.BasePackage, "gen/dal") + `"
"` + path.Join(config.BasePackage, "core/integrations") + `"
i "` + path.Join(config.BasePackage, "core/definitions/integrations") + `"
`
for k := range packages {
tpl += "\t\"" + path.Join(config.BasePackage, packages[k]) + "\"\n"
}
tpl += `)
// Services is a container for all services
type Services struct {
`
for k := range packages {
packageName := path.Base(packages[k])
tpl += "\t" + strings.ToUpper(packageName[0:1]) + packageName[1:] + " *" + packageName + ".Services\n"
}
tpl += `}
// App is a container for the services layer down
type App struct {
Config *core.Config
DAL *dal.DAL
Services *Services
Integrations *integrations.Integrations
Log i.ILog
APILog i.IAuthLog
}
// Finish cleans up any connections from the app
func (a *App) Finish() {
for schemaName := range a.Integrations.DB {
for k := range a.Integrations.DB[schemaName] {
a.Integrations.DB[schemaName][k].Close()
}
}
}
`
ioutil.WriteFile("gen/definitions/app.go", []byte(tpl), 0777)
return e
}
func GenInterfaces(srcDir, destDir string) error {
existingInterfaces, _ := fetchExistingInterfaceFiles(destDir)
existingInterfaceMap := map[string]bool{}
for k := range existingInterfaces {
baseName := path.Base(existingInterfaces[k])
s := baseName[1 : len(baseName)-3]
existingInterfaceMap[s] = true
// fmt.Println(path.Base(existingInterfaces[k][1 : len(existingInterfaces[k])-3])
}
start := time.Now()
lib.EnsureDir(destDir)
var e error
generatedInterfaces := 0
var files []string
if files, e = fetchSrcFilesForInterfaces(srcDir); e != nil {
return e
}
// removeInterface := []string{}
addedInterfaceMap := map[string]bool{}
for k := range files {
srcFile := files[k]
baseName := filepath.Base(srcFile)
structName := baseName[0 : len(baseName)-3]
addedInterfaceMap[structName] = true
interfaceName := "I" + structName
packageName := filepath.Base(filepath.Dir(srcFile))
destDirName := filepath.Base(destDir)
// TODO verbose flag?
// fmt.Println("DestDir: ", destDirName)
subDestDir := destDir
if packageName != destDirName {
subDestDir = path.Join(destDir, packageName)
}
// fmt.Println("SubDestDir: ", subDestDir)
destFile := path.Join(subDestDir, interfaceName+".go")
srcFiles := []string{srcFile}
// fmt.Println("Generating interface: " + srcFile + " ==> " + destFile)
// Check if EXT file exists
extFile := srcFile[0:len(srcFile)-3] + "Ext.go"
if _, e = os.Stat(extFile); e == nil {
srcFiles = append(srcFiles, extFile)
}
var i []byte
i, e = genInterfaces(
srcFiles,
structName,
"Generated Code; DO NOT EDIT.",
packageName,
interfaceName,
fmt.Sprintf("%s describes the %s", interfaceName, baseName),
true,
true,
)
if e != nil {
fmt.Println("ERROR: " + srcFile + " => " + e.Error())
return e
}
lib.EnsureDir(subDestDir)
// TODO verbose flag
// fmt.Printf("Generating interface %s...\n", destFile)
ioutil.WriteFile(destFile, i, 0644)
generatedInterfaces++
}
for k := range existingInterfaceMap {
if _, ok := addedInterfaceMap[k]; !ok {
fullPath := path.Join(destDir, "I"+k+".go")
// if e = os.Remove(fullPath); e != nil {
// return fmt.Errorf("remove file %s: %e", fullPath, e)
// }
fmt.Println("Removed interface at ", fullPath)
}
}
fmt.Printf("Generated %d interfaces to %s in %f seconds\n", generatedInterfaces, destDir, time.Since(start).Seconds())
return nil
}
// GenInterfaces runs GenInterface on all the target files
func genInterfaces(
files []string,
structType,
comment,
pkgName,
ifaceName,
ifaceComment string,
copyDocuments,
copyTypeDoc bool,
) (result []byte, e error) {
// fmt.Printf("Generating interface: %s\n", files[0])
allMethods := []string{}
allImports := []string{}
mset := make(map[string]struct{})
iset := make(map[string]struct{})
var typeDoc string
for _, f := range files {
var src []byte
if src, e = ioutil.ReadFile(f); e != nil {
return
}
methods, imports, parsedTypeDoc := lib.ParseStruct(src, structType, copyDocuments, copyTypeDoc, pkgName)
for _, m := range methods {
if _, ok := mset[m.Code]; !ok {
allMethods = append(allMethods, m.Lines()...)
mset[m.Code] = struct{}{}
}
}
for _, i := range imports {
if _, ok := iset[i]; !ok {
allImports = append(allImports, i)
iset[i] = struct{}{}
}
}
if typeDoc == "" {
typeDoc = parsedTypeDoc
}
}
if typeDoc != "" {
ifaceComment += "\n" + typeDoc
}
result, e = GenInterface(comment, pkgName, ifaceName, ifaceComment, allMethods, allImports)
return
}