-
Notifications
You must be signed in to change notification settings - Fork 4
/
template.go
111 lines (91 loc) · 2.29 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
package flagvar
import (
"fmt"
"io/ioutil"
"text/template"
)
// Template is a `flag.Value` for `text.Template` arguments.
// The value of the `Root` field is used as a root template when specified.
type Template struct {
Root *template.Template
Value *template.Template
Text string
}
// Help returns a string suitable for inclusion in a flag help message.
func (fv *Template) Help() string {
return "a go template"
}
// Set is flag.Value.Set
func (fv *Template) Set(v string) error {
root := fv.Root
if root == nil {
root = template.New("")
}
t, err := root.New(fmt.Sprintf("%T(%p)", fv, fv)).Parse(v)
if err == nil {
fv.Value = t
}
return err
}
func (fv *Template) String() string {
return fv.Text
}
// Templates is a `flag.Value` for `text.Template` arguments.
// The value of the `Root` field is used as a root template when specified.
type Templates struct {
Root *template.Template
Values []*template.Template
Texts []string
}
// Help returns a string suitable for inclusion in a flag help message.
func (fv *Templates) Help() string {
return "a go template"
}
// Set is flag.Value.Set
func (fv *Templates) Set(v string) error {
root := fv.Root
if root == nil {
root = template.New("")
}
t, err := root.New(fmt.Sprintf("%T(%p)", fv, fv)).Parse(v)
if err == nil {
fv.Texts = append(fv.Texts, v)
fv.Values = append(fv.Values, t)
}
return err
}
func (fv *Templates) String() string {
return fmt.Sprint(fv.Texts)
}
// Template is a `flag.Value` for `text.Template` arguments.
// The value of the `Root` field is used as a root template when specified.
// The value specified on the command line is the path to the template
type TemplateFile struct {
Root *template.Template
Value *template.Template
Text string
}
// Help returns a string suitable for inclusion in a flag help message.
func (fv *TemplateFile) Help() string {
return "file system path to a go template"
}
// Set is flag.Value.Set
func (fv *TemplateFile) Set(v string) error {
_template, err := ioutil.ReadFile(v)
if err != nil {
return err
}
root := fv.Root
if root == nil {
root = template.New("")
}
t, err := root.New(fmt.Sprintf("%T(%p)", fv, fv)).Parse(string(_template))
if err == nil {
fv.Text = v
fv.Value = t
}
return err
}
func (fv *TemplateFile) String() string {
return fv.Text
}