entc/gen: improve the api for custom templates

This commit is contained in:
Ariel Mashraki
2020-09-15 15:16:42 +03:00
committed by Ariel Mashraki
parent bd4d2a553c
commit e26e99b643
8 changed files with 139 additions and 44 deletions

View File

@@ -0,0 +1,17 @@
// 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.
// Code generated by entc, DO NOT EDIT.
package ent
import "github.com/facebook/ent/dialect"
func (c *UserClient) Debug() *UserClient {
if c.debug {
return c
}
cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks}
return &UserClient{config: cfg}
}

View File

@@ -16,6 +16,13 @@ import (
)
func main() {
// A usage for custom templates with external functions.
// One template is defined in the option below, and the
// second template is provided with the `Templates` field.
opts := []entc.Option{
entc.Funcs(template.FuncMap{"title": strings.ToTitle}),
entc.TemplateFiles("template/static.tmpl"),
}
err := entc.Generate("./schema", &gen.Config{
Header: `
// Copyright 2019-present Facebook Inc. All rights reserved.
@@ -24,11 +31,12 @@ func main() {
// Code generated by entc, DO NOT EDIT.
`,
// A usage for custom templates with external functions.
Template: template.Must(template.New("template").
Funcs(template.FuncMap{"title": strings.ToTitle}).
ParseFiles("template/static.tmpl")),
})
Templates: []*template.Template{
template.Must(template.New("debug").
Funcs(gen.Funcs).
ParseFiles("template/debug.tmpl")),
},
}, opts...)
if err != nil {
log.Fatal("running ent codegen:", err)
}

View File

@@ -0,0 +1,22 @@
{{ define "debug" }}
{{/* A template that will be generated to a file named "debug.go" and
add the functionality for running each client <T> in debug mode */}}
{{/* Add the base header for the generated file */}}
{{ $pkg := base $.Config.Package }}
{{ template "header" $ }}
{{/* Loop over all nodes and add option the "Debug()" method */}}
{{ range $n := $.Nodes }}
{{ $client := print $n.Name "Client" }}
func (c *{{ $client }}) Debug() *{{ $client }} {
if c.debug {
return c
}
cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks}
return &{{ $client }}{config: cfg}
}
{{ end }}
{{ end }}