Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

entc/gen: add conditional-write option to external templates #2542

Merged
merged 1 commit into from May 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions entc/gen/graph.go
Expand Up @@ -660,6 +660,7 @@ func (g *Graph) templates() (*Template, []GraphTemplate) {
external = append(external, GraphTemplate{
Name: name,
Format: snake(name) + ".go",
Skip: rootT.condition,
})
roots[name] = struct{}{}
}
Expand Down
5 changes: 4 additions & 1 deletion entc/gen/graph_test.go
Expand Up @@ -307,11 +307,12 @@ func TestGraph_Gen(t *testing.T) {
require.NoError(os.MkdirAll(target, os.ModePerm), "creating tmpdir")
defer os.RemoveAll(target)
external := MustParse(NewTemplate("external").Parse("package external"))
skipped := MustParse(NewTemplate("skipped").SkipIf(func(*Graph) bool { return true }).Parse("package external"))
graph, err := NewGraph(&Config{
Package: "entc/gen",
Target: target,
Storage: drivers[0],
Templates: []*Template{external},
Templates: []*Template{external, skipped},
IDType: &field.TypeInfo{Type: field.TypeInt},
Features: AllFeatures,
}, &load.Schema{
Expand Down Expand Up @@ -340,6 +341,8 @@ func TestGraph_Gen(t *testing.T) {
}
_, err = os.Stat(filepath.Join(target, "external.go"))
require.NoError(err)
_, err = os.Stat(filepath.Join(target, "skipped.go"))
require.True(os.IsNotExist(err))

// Generated feature templates.
_, err = os.Stat(filepath.Join(target, "internal", "schema.go"))
Expand Down
9 changes: 8 additions & 1 deletion entc/gen/template.go
Expand Up @@ -231,7 +231,8 @@ func initTemplates() {
// provide additional functionality for ent extensions.
type Template struct {
*template.Template
FuncMap template.FuncMap
FuncMap template.FuncMap
condition func(*Graph) bool
}

// NewTemplate creates an empty template with the standard codegen functions.
Expand All @@ -254,6 +255,12 @@ func (t *Template) Funcs(funcMap template.FuncMap) *Template {
return t
}

// SkipIf allows registering a function to determine if the template needs to be skipped or not.
func (t *Template) SkipIf(cond func(*Graph) bool) *Template {
t.condition = cond
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 {
Expand Down