This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.go
323 lines (273 loc) · 8.07 KB
/
gen.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
// Copyright (c) 2022 MindStand Technologies, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// gen provides code to generate link and unlink functions for gogm structs
package gen
import (
"bytes"
"errors"
"fmt"
"go/format"
"html/template"
"log"
"os"
"path"
"path/filepath"
"strings"
dsl "github.com/mindstand/go-cypherdsl"
"github.com/mindstand/gogm/v2/cmd/gogmcli/util"
)
// Generate searches for all go source files, then generates link and unlink functions for all gogm structs
// takes in root directory and whether to log in debug mode
// note: Generate is not recursive, it only looks in the target directory
func Generate(directory string, debug bool, generator string) error {
confs := map[string][]*relConf{}
imps := map[string][]string{}
var edges []string
packageName := ""
err := filepath.Walk(directory, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return errors.New("file info is nil")
}
if info.IsDir() && filePath != directory {
if debug {
log.Printf("skipping [%s] as it is a directory\n", filePath)
}
return filepath.SkipDir
}
if path.Ext(filePath) == ".go" {
if debug {
log.Printf("parsing go file [%s]\n", filePath)
}
err := parseFile(filePath, &confs, &edges, imps, &packageName, debug)
if err != nil {
if debug {
log.Printf("failed to parse go file [%s] with error '%s'\n", filePath, err.Error())
}
return err
}
if debug {
log.Printf("successfully parsed go file [%s]\n", filePath)
}
} else if debug {
log.Printf("skipping non go file [%s]\n", filePath)
}
return nil
})
if err != nil {
return err
}
if debug {
log.Printf("found [%v] confs and [%v] rels", len(confs), len(edges))
}
var imports []string
for _, imp := range imps {
imports = append(imports, imp...)
}
imports = util.RemoveDuplicates(imports)
for i := 0; i < len(imports); i++ {
imports[i] = strings.Replace(imports[i], "\"", "", -1)
}
relations := make(map[string][]*relConf)
if debug {
log.Println("sorting relationships")
}
// sort out relationships
for node, fields := range confs {
if debug {
log.Printf("sorting relationships for node [%s] with [%v] fields", node, len(fields))
}
for _, field := range fields {
if field == nil {
return errors.New("field can not be nil")
}
if debug {
log.Printf("adding relationship [%s] from field [%s]", field.RelationshipName, field.Field)
}
relations[field.RelationshipName] = append(relations[field.RelationshipName], field)
}
}
if debug {
log.Printf("there are [%v] relations\n", len(relations))
}
// validate relationships (i.e even number)
for name, rels := range relations {
nonBothSelfRelCount := 0
for _, rel := range rels {
if rel.Direction != dsl.DirectionBoth || rel.NodeName != rel.Type {
nonBothSelfRelCount += 1
}
}
if nonBothSelfRelCount%2 != 0 {
return fmt.Errorf("relationship [%s] is invalid", name)
}
}
funcs := make(map[string][]*tplRelConf)
// set template stuff
for _, rels := range relations {
for _, rel := range rels {
tplRel := &tplRelConf{
StructName: rel.NodeName,
StructField: rel.Field,
OtherStructName: rel.Type,
StructFieldIsMany: rel.IsMany,
}
var isSpecialEdge bool
if util.StringSliceContains(edges, rel.Type) {
tplRel.UsesSpecialEdge = true
tplRel.SpecialEdgeType = rel.Type
tplRel.SpecialEdgeDirection = rel.Direction == dsl.DirectionOutgoing
isSpecialEdge = true
}
err = parseDirection(rel, &rels, tplRel, isSpecialEdge, debug)
if err != nil {
return err
}
if tplRel.OtherStructField == "" {
return fmt.Errorf("opposite side not found for node [%s] on relationship [%s] and field [%s]", rel.NodeName, rel.RelationshipName, rel.Field)
}
if debug {
log.Printf("adding function to node [%s]", rel.NodeName)
}
funcs[rel.NodeName] = append(funcs[rel.NodeName], tplRel)
}
}
//write templates out
tpl := template.New("linkFile")
//register templates
for _, templateString := range []string{singleLink, linkMany, linkSpec, unlinkSingle, unlinkMulti, unlinkSpec, masterTpl} {
tpl, err = tpl.Parse(templateString)
if err != nil {
return err
}
}
if debug {
log.Printf("packageName: [%s]\n", packageName)
}
if len(funcs) == 0 {
log.Printf("no functions to write, exiting")
return nil
}
buf := new(bytes.Buffer)
err = tpl.Execute(buf, templateConfig{
Generator: generator,
Imports: imports,
PackageName: packageName,
Funcs: funcs,
})
if err != nil {
return err
}
// format generated code
formatted, err := format.Source(buf.Bytes())
if err != nil {
return err
}
// create the file
f, err := os.Create(path.Join(directory, "linking.go"))
if err != nil {
return err
}
// write code to the file
lenBytes, err := f.Write(formatted)
if err != nil {
return err
}
if debug {
log.Printf("done after writing [%v] bytes!", lenBytes)
}
// close the buffer
err = f.Close()
if err != nil {
return err
}
log.Printf("wrote link functions to file [%s/linking.go]", directory)
return nil
}
// parseDirection parses gogm struct tags and writes to a holder struct
func parseDirection(rel *relConf, rels *[]*relConf, tplRel *tplRelConf, isSpecialEdge, debug bool) error {
for _, lookup := range *rels {
// validate that these edges can point to each other
if isSpecialEdge {
if rel.Type != lookup.Type || lookup.RelationshipName != rel.RelationshipName {
continue
}
} else {
if rel.Type != lookup.NodeName || lookup.Type != rel.NodeName || lookup.RelationshipName != rel.RelationshipName {
continue
}
}
if debug {
log.Printf("[%s]->[%s]", rel.Type, lookup.NodeName)
log.Printf("[%s]<-[%s]", lookup.Type, rel.NodeName)
log.Printf("[%s] and [%s]", lookup.RelationshipName, rel.RelationshipName)
}
switch rel.Direction {
case dsl.DirectionOutgoing:
if lookup.Direction == dsl.DirectionIncoming {
tplRel.OtherStructField = lookup.Field
tplRel.OtherStructFieldIsMany = lookup.IsMany
if isSpecialEdge {
tplRel.OtherStructName = lookup.NodeName
}
return nil
} else {
continue
}
case dsl.DirectionIncoming:
if lookup.Direction == dsl.DirectionOutgoing {
tplRel.OtherStructField = lookup.Field
tplRel.OtherStructFieldIsMany = lookup.IsMany
if isSpecialEdge {
tplRel.OtherStructName = lookup.NodeName
}
return nil
} else {
continue
}
case dsl.DirectionNone:
if lookup.Direction == dsl.DirectionNone {
tplRel.OtherStructField = lookup.Field
tplRel.OtherStructFieldIsMany = lookup.IsMany
if isSpecialEdge {
tplRel.OtherStructName = lookup.NodeName
}
return nil
} else {
continue
}
case dsl.DirectionBoth:
if lookup.Direction == dsl.DirectionBoth {
tplRel.OtherStructField = lookup.Field
tplRel.OtherStructFieldIsMany = lookup.IsMany
if isSpecialEdge {
tplRel.OtherStructName = lookup.NodeName
}
return nil
} else {
continue
}
default:
return fmt.Errorf("invalid direction [%v]", rel.Direction)
}
}
return nil
}