-
Notifications
You must be signed in to change notification settings - Fork 890
/
template.go
423 lines (398 loc) · 10.4 KB
/
template.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package gen
import (
"bytes"
"embed"
"errors"
"fmt"
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"text/template"
"text/template/parse"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
)
type (
// TypeTemplate specifies a template that is executed with
// each Type object of the graph.
TypeTemplate struct {
Name string // template name.
Format func(*Type) string // file name format.
ExtendPatterns []string // extend patterns.
}
// GraphTemplate specifies a template that is executed with
// the Graph object.
GraphTemplate struct {
Name string // template name.
Skip func(*Graph) bool // skip condition (storage constraints or gated by a feature-flag).
Format string // file name format.
ExtendPatterns []string // extend patterns.
}
)
var (
// Templates holds the template information for a file that the graph is generating.
Templates = []TypeTemplate{
{
Name: "create",
Format: pkgf("%s_create.go"),
ExtendPatterns: []string{
"dialect/*/create/fields/additional/*",
"dialect/*/create_bulk/fields/additional/*",
},
},
{
Name: "update",
Format: pkgf("%s_update.go"),
},
{
Name: "delete",
Format: pkgf("%s_delete.go"),
},
{
Name: "query",
Format: pkgf("%s_query.go"),
ExtendPatterns: []string{
"dialect/*/query/fields/additional/*",
},
},
{
Name: "model",
Format: pkgf("%s.go"),
},
{
Name: "where",
Format: pkgf("%s/where.go"),
ExtendPatterns: []string{
"where/additional/*",
},
},
{
Name: "meta",
Format: func(t *Type) string {
return fmt.Sprintf("%[1]s/%[1]s.go", t.PackageDir())
},
ExtendPatterns: []string{
"meta/additional/*",
},
},
}
// GraphTemplates holds the templates applied on the graph.
GraphTemplates = []GraphTemplate{
{
Name: "base",
Format: "ent.go",
},
{
Name: "client",
Format: "client.go",
ExtendPatterns: []string{
"client/fields/additional/*",
"dialect/*/query/fields/init/*",
},
},
{
Name: "context",
Format: "context.go",
},
{
Name: "tx",
Format: "tx.go",
},
{
Name: "config",
Format: "config.go",
ExtendPatterns: []string{
"dialect/*/config/*/*",
},
},
{
Name: "mutation",
Format: "mutation.go",
},
{
Name: "migrate",
Format: "migrate/migrate.go",
Skip: func(g *Graph) bool { return !g.SupportMigrate() },
},
{
Name: "schema",
Format: "migrate/schema.go",
Skip: func(g *Graph) bool { return !g.SupportMigrate() },
},
{
Name: "predicate",
Format: "predicate/predicate.go",
},
{
Name: "hook",
Format: "hook/hook.go",
},
{
Name: "privacy",
Format: "privacy/privacy.go",
Skip: func(g *Graph) bool {
return !g.featureEnabled(FeaturePrivacy)
},
},
{
Name: "entql",
Format: "entql.go",
Skip: func(g *Graph) bool {
return !g.featureEnabled(FeatureEntQL)
},
},
{
Name: "runtime/ent",
Format: "runtime.go",
},
{
Name: "enttest",
Format: "enttest/enttest.go",
},
{
Name: "runtime/pkg",
Format: "runtime/runtime.go",
},
}
// patterns for extending partial-templates (included by other templates).
partialPatterns = [...]string{
"client/additional/*",
"client/additional/*/*",
"config/*/*",
"create/additional/*",
"delete/additional/*",
"dialect/*/*/*/spec/*",
"dialect/*/*/spec/*",
"dialect/*/config/*/*",
"dialect/*/import/additional/*",
"dialect/*/query/selector/*",
"dialect/sql/create/additional/*",
"dialect/sql/create_bulk/additional/*",
"dialect/sql/model/additional/*",
"dialect/sql/model/edges/*",
"dialect/sql/model/edges/fields/additional/*",
"dialect/sql/model/fields/*",
"dialect/sql/select/additional/*",
"dialect/sql/predicate/edge/*/*",
"dialect/sql/query/additional/*",
"dialect/sql/query/from/*",
"dialect/sql/query/path/*",
"import/additional/*",
"model/additional/*",
"model/comment/additional/*",
"model/edges/fields/additional/*",
"update/additional/*",
"query/additional/*",
}
// importPkg are the import packages used for code generation.
importPkg = make(map[string]string)
// templates holds the Go templates for the code generation.
templates *Template
//go:embed template/*
templateDir embed.FS
)
func initTemplates() {
templates = MustParse(NewTemplate("templates").
ParseFS(templateDir, "template/*.tmpl", "template/*/*.tmpl", "template/*/*/*.tmpl", "template/*/*/*/*.tmpl"))
b := bytes.NewBuffer([]byte("package main\n"))
check(templates.ExecuteTemplate(b, "import", Type{Config: &Config{}}), "load imports")
f, err := parser.ParseFile(token.NewFileSet(), "", b, parser.ImportsOnly)
check(err, "parse imports")
for _, spec := range f.Imports {
path, err := strconv.Unquote(spec.Path.Value)
check(err, "unquote import path")
importPkg[filepath.Base(path)] = path
}
for _, s := range drivers {
for _, path := range s.Imports {
importPkg[filepath.Base(path)] = path
}
}
}
// Template wraps the standard template.Template to
// provide additional functionality for ent extensions.
type Template struct {
*template.Template
FuncMap template.FuncMap
}
// NewTemplate creates an empty template with the standard codegen functions.
func NewTemplate(name string) *Template {
t := &Template{Template: template.New(name)}
return t.Funcs(Funcs)
}
// Funcs merges the given funcMap with the template functions.
func (t *Template) Funcs(funcMap template.FuncMap) *Template {
t.Template.Funcs(funcMap)
if t.FuncMap == nil {
t.FuncMap = template.FuncMap{}
}
for name, f := range funcMap {
if _, ok := t.FuncMap[name]; !ok {
t.FuncMap[name] = f
}
}
return t
}
// Parse parses text as a template body for t.
func (t *Template) Parse(text string) (*Template, error) {
if _, err := t.Template.Parse(text); err != nil {
return nil, err
}
return t, nil
}
// ParseFiles parses a list of files as templates and associate them with t.
// Each file can be a standalone template.
func (t *Template) ParseFiles(filenames ...string) (*Template, error) {
if _, err := t.Template.ParseFiles(filenames...); err != nil {
return nil, err
}
return t, nil
}
// ParseGlob parses the files that match the given pattern as templates and
// associate them with t.
func (t *Template) ParseGlob(pattern string) (*Template, error) {
if _, err := t.Template.ParseGlob(pattern); err != nil {
return nil, err
}
return t, nil
}
// ParseDir walks on the given dir path and parses the given matches with aren't Go files.
func (t *Template) ParseDir(path string) (*Template, error) {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk path %s: %w", path, err)
}
if info.IsDir() || strings.HasSuffix(path, ".go") {
return nil
}
_, err = t.ParseFiles(path)
return err
})
return t, err
}
// ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys
// instead of the host operating system's file system.
func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error) {
if _, err := t.Template.ParseFS(fsys, patterns...); err != nil {
return nil, err
}
return t, nil
}
// AddParseTree adds the given parse tree to the template.
func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) {
if _, err := t.Template.AddParseTree(name, tree); err != nil {
return nil, err
}
return t, nil
}
// MustParse is a helper that wraps a call to a function returning (*Template, error)
// and panics if the error is non-nil.
func MustParse(t *Template, err error) *Template {
if err != nil {
panic(err)
}
return t
}
type (
// Dependencies wraps a list of dependencies as codegen
// annotation.
Dependencies []*Dependency
// Dependency allows configuring optional dependencies as struct fields on the
// generated builders. For example:
//
// DependencyAnnotation{
// Field: "HTTPClient",
// Type: "*http.Client",
// Option: "WithClient",
// }
//
// Although the Dependency and the DependencyAnnotation are exported, used should
// use the entc.Dependency option in order to build this annotation.
Dependency struct {
// Field defines the struct field name on the builders.
// It defaults to the full type name. For example:
//
// http.Client => HTTPClient
// net.Conn => NetConn
// url.URL => URL
//
Field string
// Type defines the type identifier. For example, `*http.Client`.
Type *field.TypeInfo
// Option defines the name of the config option.
// It defaults to the field name.
Option string
}
)
// Name describes the annotation name.
func (Dependencies) Name() string {
return "Dependencies"
}
// Merge implements the schema.Merger interface.
func (d Dependencies) Merge(other schema.Annotation) schema.Annotation {
if deps, ok := other.(Dependencies); ok {
return append(d, deps...)
}
return d
}
var _ interface {
schema.Annotation
schema.Merger
} = (*Dependencies)(nil)
// Build builds the annotation and fails if it is invalid.
func (d *Dependency) Build() error {
if d.Type == nil {
return errors.New("entc/gen: missing dependency type")
}
if d.Field == "" {
name, err := d.defaultName()
if err != nil {
return err
}
d.Field = name
}
if d.Option == "" {
d.Option = d.Field
}
return nil
}
func (d *Dependency) defaultName() (string, error) {
var pkg, name string
switch parts := strings.Split(strings.TrimLeft(d.Type.Ident, "[]*"), "."); len(parts) {
case 1:
name = parts[0]
case 2:
name = parts[1]
// Avoid stuttering.
if !strings.EqualFold(parts[0], name) {
pkg = parts[0]
}
default:
return "", fmt.Errorf("entc/gen: unexpected number of parts: %q", parts)
}
if r := d.Type.RType; r != nil && (r.Kind == reflect.Array || r.Kind == reflect.Slice) {
name = plural(name)
}
return pascal(pkg) + pascal(name), nil
}
func pkgf(s string) func(t *Type) string {
return func(t *Type) string { return fmt.Sprintf(s, t.PackageDir()) }
}
// match reports if the given name matches the extended pattern.
func match(patterns []string, name string) bool {
for _, pat := range patterns {
matched, _ := filepath.Match(pat, name)
if matched {
return true
}
}
return false
}