-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
102 lines (83 loc) · 2.13 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
package nero
import (
"fmt"
"reflect"
"text/template"
"github.com/stevenferrer/mira"
)
// Template is an interface that wraps the Filename and Content method
type Template interface {
// Filename is the filename of the generated file
Filename() string
// Content is returns the template content
Content() string
}
// ParseTemplate parses the repository template
func ParseTemplate(t Template) (*template.Template, error) {
return template.New(t.Filename() + ".tmpl").
Funcs(NewFuncMap()).Parse(t.Content())
}
// NewFuncMap returns a template func map
func NewFuncMap() template.FuncMap {
return template.FuncMap{
"type": typeFunc,
"rawType": rawTypeFunc,
"zeroValue": zeroValueFunc,
"prependToFields": prependToFields,
"fileHeaders": fileHeadersFunc,
"isType": isTypeFunc,
}
}
// typeFunc returns the type of the value
func typeFunc(v interface{}) string {
t := reflect.TypeOf(v)
if t.Kind() != reflect.Ptr {
return fmt.Sprintf("%T", v)
}
ev := reflect.New(resolveType(t)).Elem().Interface()
return fmt.Sprintf("%T", ev)
}
// rawTypeFunc returns the raw type of the value
func rawTypeFunc(v interface{}) string {
return fmt.Sprintf("%T", v)
}
// resolveType resolves the type of the value
func resolveType(t reflect.Type) reflect.Type {
switch t.Kind() {
case reflect.Ptr:
return resolveType(t.Elem())
}
return t
}
// zeroValueFunc returns zero value as a string
func zeroValueFunc(v interface{}) string {
ti := mira.NewTypeInfo(v)
if ti.IsNillable() {
return "nil"
}
if ti.IsNumeric() {
return "0"
}
switch ti.T().Kind() {
case reflect.Bool:
return "false"
case reflect.Struct,
reflect.Array:
return fmt.Sprintf("(%T{})", v)
}
return "\"\""
}
// prependToFields prepends a field to the list of fields
func prependToFields(field *Field, fields []*Field) []*Field {
return append([]*Field{field}, fields...)
}
const fileHeaders = `
// Code generated by nero, DO NOT EDIT.
`
// fileHeadersFunc returns the standard file headers
func fileHeadersFunc() string {
return fileHeaders
}
func isTypeFunc(v interface{}, typeStr string) bool {
return typeFunc(v) == typeStr
}