-
Notifications
You must be signed in to change notification settings - Fork 3
/
gen_tmpl_func_list.go
96 lines (78 loc) · 1.97 KB
/
gen_tmpl_func_list.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
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
// +build ignore
package main
import (
"bytes"
"flag"
"go/format"
"io/ioutil"
"log"
"reflect"
"strings"
"text/template"
libconfd "openpitrix.io/libconfd"
)
var flagOutput = flag.String("output", "tmpl_funcs_zz.go", "set output file")
type FuncInfo struct {
GoFuncName string
TmplFuncName string
}
func main() {
flag.Parse()
var funcs []FuncInfo
var tmplFuncType = reflect.TypeOf(libconfd.TemplateFunc{})
for i := 0; i < tmplFuncType.NumMethod(); i++ {
method := tmplFuncType.Method(i)
funcs = append(funcs, FuncInfo{
GoFuncName: method.Name,
TmplFuncName: strings.ToLower(method.Name[:1]) + method.Name[1:],
})
}
code := genFuncCode(funcs)
data, err := format.Source([]byte(code))
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(*flagOutput, data, 0644)
if err != nil {
log.Fatal(err)
}
}
func genFuncCode(funcs []FuncInfo) string {
var buf bytes.Buffer
t := template.Must(template.New("").Funcs(tmplFuncMap).Parse(tmpl))
err := t.Execute(&buf, funcs)
if err != nil {
log.Fatal(err)
}
return buf.String()
}
var tmplFuncMap = template.FuncMap{
"strings_Title": strings.Title,
"strings_ToLower": strings.ToLower,
"strings_ToUpper": strings.ToUpper,
"strings_TrimPrefix": strings.TrimPrefix,
"strings_TrimSuffix": strings.TrimSuffix,
}
const tmpl = `
{{- $FuncList := . -}}
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
// Auto generated by go generate, DO NOT EDIT!!!
package libconfd
import (
"text/template"
)
func init() {
_TemplateFunc_initFuncMap = func(p *TemplateFunc) {
p.FuncMap = template.FuncMap{
{{range $_, $FuncInfo := $FuncList -}}
"{{$FuncInfo.TmplFuncName}}": p.{{$FuncInfo.GoFuncName}},
{{end -}}
}
}
}
`