-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexportable_gen.go
More file actions
242 lines (203 loc) · 5.73 KB
/
exportable_gen.go
File metadata and controls
242 lines (203 loc) · 5.73 KB
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
package entx
import (
"bytes"
"fmt"
"os"
"sort"
"text/template"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
"github.com/stoewer/go-strcase"
"golang.org/x/tools/imports"
)
// ExportableGenerator handles the generation of exportable schema validation.
//
// This generator scans ent schemas for the Exportable annotation and generates
// validation code that can be used to verify export requests.
//
// Usage:
//
// // In your entc.go file:
// generator := entx.NewExportableGenerator("./schema", "./internal/hooks")
// err := generator.Generate()
// if err != nil {
// log.Fatal(err)
// }
//
// The generator will create a file with functions like:
//
// func IsSchemaExportable(schemaName string) bool {
// return ExportableSchemas[strings.ToLower(schemaName)]
// }
//
// func ValidateExportType(exportType string) error {
// // Returns error if schema is not exportable
// }
//
// Example schema annotation:
//
// func (MySchema) Annotations() []schema.Annotation {
// return []schema.Annotation{
// entx.NewExportable(), // Marks this schema as exportable
// }
// }
type ExportableGenerator struct {
// SchemaPath is the path to the schema directory
SchemaPath string
// OutputDir is the directory where the generated file will be written
OutputDir string
// Package is the package name for the generated file
Package string
// ImportPath is the import path for the enums package
ImportPath string
}
// NewExportableGenerator creates a new ExportableGenerator with default settings.
func NewExportableGenerator(schemaPath, outputDir string) *ExportableGenerator {
return &ExportableGenerator{
SchemaPath: schemaPath,
OutputDir: outputDir,
Package: "hooks",
ImportPath: "github.com/theopenlane/core/common/enums",
}
}
// WithPackage sets the package name for the generated file.
func (e *ExportableGenerator) WithPackage(pkg string) *ExportableGenerator {
e.Package = pkg
return e
}
// WithImportPath sets the import path for the enums package.
func (e *ExportableGenerator) WithImportPath(importPath string) *ExportableGenerator {
e.ImportPath = importPath
return e
}
const exportableGeneratedFileTemplate = `// Code generated by entx. DO NOT EDIT.
package {{.Package}}
import (
"fmt"
)
type info struct {
hasOwnerField bool
hasSystemOwnedField bool
}
// ExportableSchemas contains all schemas that have Exportable annotation
var ExportableSchemas = map[string]info{
{{- range .Schemas}}
{{- range $key, $val := .}} "{{$key}}": info{
hasOwnerField: {{ $val.HasOwnerField}},
hasSystemOwnedField: {{ $val.HasSystemOwnedField}},
},
{{- end}}
{{- end}}
}
// IsSchemaExportable checks if a schema name is exportable
func IsSchemaExportable(schemaName string) bool {
_, ok := ExportableSchemas[schemaName]
return ok
}
// HasOwnerField checks if a schema has an owner field
func HasOwnerField(schemaName string) bool {
info, ok := ExportableSchemas[schemaName]
if !ok {
return false
}
return info.hasOwnerField
}
// HasSystemOwnedField checks if a schema has a system owned field
func HasSystemOwnedField(schemaName string) bool {
info, ok := ExportableSchemas[schemaName]
if !ok {
return false
}
return info.hasSystemOwnedField
}
// ValidateExportType validates that an export type corresponds to an exportable schema
func ValidateExportType(exportType string) error {
if !IsSchemaExportable(exportType) {
return fmt.Errorf("invalid export type provided ( %s )", exportType)
}
return nil
}
`
// Generate generates the exportable schemas validation code and ExportType enum.
func (e *ExportableGenerator) Generate(flags ...string) error {
graph, err := entc.LoadGraph(e.SchemaPath, &gen.Config{
BuildFlags: flags,
})
if err != nil {
return fmt.Errorf("loading graph: %w", err)
}
schemas := e.findExportableSchemas(graph)
err = e.generateValidationFile(schemas)
if err != nil {
return err
}
return nil
}
type Info struct {
HasOwnerField bool
HasSystemOwnedField bool
}
func (e *ExportableGenerator) findExportableSchemas(graph *gen.Graph) []map[string]Info {
var exportableSchemas []map[string]Info
ant := &Exportable{}
for _, schema := range graph.Schemas {
if raw, ok := schema.Annotations[ant.Name()]; ok {
if err := ant.Decode(raw); err == nil {
exportableSchemas = append(exportableSchemas, map[string]Info{
strcase.UpperSnakeCase(schema.Name): {
HasOwnerField: ant.OrgOwned,
HasSystemOwnedField: ant.HasSystemOwned,
},
})
}
}
}
// sort schemas for consistent output by the schema name which is a string comparison
exportableSchemas = sortExportableSchemas(exportableSchemas)
return exportableSchemas
}
func sortExportableSchemas(schemas []map[string]Info) []map[string]Info {
sort.SliceStable(schemas, func(i, j int) bool {
for keyI := range schemas[i] {
for keyJ := range schemas[j] {
return keyI < keyJ
}
}
return false
})
return schemas
}
func (e *ExportableGenerator) generateValidationFile(schemas []map[string]Info) error {
tmpl, err := template.New("generated").Parse(exportableGeneratedFileTemplate)
if err != nil {
return err
}
filePath := fmt.Sprintf("%s/exportable_generated.go", e.OutputDir)
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
data := struct {
Package string
ImportPath string
Schemas []map[string]Info
}{
Package: e.Package,
ImportPath: e.ImportPath,
Schemas: schemas,
}
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "generated", data); err != nil {
return err
}
// run gofmt and goimports on the file contents
formatted, err := imports.Process(filePath, buf.Bytes(), nil)
if err != nil {
return fmt.Errorf("%w: failed to format file", err)
}
if _, err := file.Write(formatted); err != nil {
return err
}
return nil
}