-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathextension.go
More file actions
82 lines (71 loc) · 1.52 KB
/
Copy pathextension.go
File metadata and controls
82 lines (71 loc) · 1.52 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
package admin
import (
"embed"
"strings"
"text/template"
"unicode"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
"entgo.io/ent/schema/field"
)
var (
//go:embed templates
templateDir embed.FS
)
// Extension is the Ent extension that generates code to support the entity admin panel.
type Extension struct {
entc.DefaultExtension
}
func (*Extension) Templates() []*gen.Template {
funcs := make(template.FuncMap)
for k, v := range gen.Funcs {
funcs[k] = v
}
funcs["fieldLabel"] = FieldLabel
funcs["fieldIsPointer"] = fieldIsPointer
return []*gen.Template{
gen.MustParse(
gen.NewTemplate("admin").
Funcs(funcs).
ParseFS(templateDir, "templates/*tmpl"),
),
}
}
// FieldLabel provides a label for an entity field name (ie, user_id -> User ID).
func FieldLabel(name string) string {
if len(name) == 0 {
return name
}
parts := strings.Split(name, "_")
for i := 0; i < len(parts); i++ {
if parts[i] == "id" {
parts[i] = "ID"
}
if i == 0 {
parts[i] = upperFirst(parts[i])
}
}
return strings.Join(parts, " ")
}
// fieldIsPointer determines if a given entity field should be a pointer on the struct.
func fieldIsPointer(f *gen.Field) bool {
switch {
case f.Type.Type == field.TypeBool:
return false
case f.Optional,
f.Default,
f.Sensitive(),
f.Nillable:
return true
}
return false
}
// upperFirst uppercases the first character of a given string.
func upperFirst(s string) string {
if len(s) == 0 {
return s
}
out := []rune(s)
out[0] = unicode.ToUpper(out[0])
return string(out)
}