-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
132 lines (114 loc) · 2.19 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
package main
import (
"bytes"
"strings"
"text/template"
)
var entTemplate = `
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"time"
)
var _ time.Month
var _ entsql.Annotation
var _ index.Descriptor
type {{.MessageName}} struct {
ent.Schema
}
func ({{.MessageName}}) Fields() []ent.Field {
{{- if .HasFields}}
return []ent.Field{
{{- range .Fields}}
{{.FieldLine}},{{end}}
}
{{- else}}
return nil{{end}}
}
func ({{.MessageName}}) Edges() []ent.Edge {
{{- if .HasEdges}}
return []ent.Edge{
{{- range .Edges}}
{{.Relation}},{{end}}
}
{{- else}}
return nil{{end}}
}
func ({{.MessageName}}) Indexes() []ent.Index {
{{- if .HasIndexes}}
return []ent.Index{
{{- range .Indexes}}
{{.Relation}},{{end}}
}
{{- else}}
return nil{{end}}
}
func ({{.MessageName}}) Mixin() []ent.Mixin {
{{- if .HasMixin}}
return []ent.Mixin{
{{- range .Mixin}}
{{.Relation}},{{end}}
}
{{- else}}
return nil{{end}}
}
func ({{.MessageName}}) Annotations() []schema.Annotation {
{{- if .HasAnnotations}}
return []schema.Annotation{
{{- range .Annotations}}
{{.Relation}},{{end}}
}
{{- else}}
return nil{{end}}
}`
var mixinTemplate = `
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
)
var _ time.Month
type {{.MessageName}} struct {
mixin.Schema
}
func ({{.MessageName}}) Fields() []ent.Field {
return []ent.Field{
{{- range .Fields}}
{{.FieldLine}},{{end}}
}
}`
type messageDesc struct {
MessageType string // User
MessageName string // User
HasFields bool
Fields []*fieldDesc
HasEdges bool
Edges []*relation
HasIndexes bool
Indexes []*relation
HasAnnotations bool
Annotations []*relation
HasMixin bool
Mixin []*relation
}
type fieldDesc struct {
FieldLine string
}
type relation struct {
Relation string
}
func (s *messageDesc) execute(tpl string) string {
buf := new(bytes.Buffer)
tmpl, err := template.New("ent").Parse(strings.TrimSpace(tpl))
if err != nil {
panic(err)
}
if err := tmpl.Execute(buf, s); err != nil {
panic(err)
}
return strings.Trim(buf.String(), "\r\n")
}