This repository has been archived by the owner on Aug 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (73 loc) · 1.78 KB
/
main.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
package main
import (
"context"
"flag"
"io"
"os"
"strings"
"github.com/blizzy78/copper/helpers"
"github.com/blizzy78/copper/ranger"
"github.com/blizzy78/copper/template"
)
type templateData struct {
key string
value string
}
type dataFlags []templateData
type argError struct {
msg string
}
func main() {
var dataFl dataFlags
flag.Var(&dataFl, "data", "template data (KEY=VALUE) (multiple)")
flag.Parse()
data := make(map[string]interface{}, len(dataFl))
for _, d := range dataFl {
data[d.key] = d.value
}
if err := render(os.Stdout, os.Stdin, data); err != nil {
panic(err)
}
}
func render(w io.Writer, r io.ReadCloser, data map[string]interface{}) error {
l := template.LoaderFunc(func(name string) (io.ReadCloser, error) {
return r, nil
})
rd := template.NewRenderer(l,
template.WithScopeData("safe", helpers.Safe),
template.WithScopeData("html", helpers.HTML),
template.WithScopeData("has", helpers.Has),
template.WithScopeData("len", helpers.Len),
template.WithScopeData("hasPrefix", helpers.HasPrefix),
template.WithScopeData("hasSuffix", helpers.HasSuffix),
template.WithScopeData("range", ranger.New),
template.WithScopeData("rangeFromTo", ranger.NewFromTo),
template.WithScopeData("rangeInt", ranger.NewInt))
return rd.Render(context.Background(), w, "template", data)
}
func (f *dataFlags) Set(v string) error {
parts := strings.Split(v, "=")
if len(parts) != 2 {
return &argError{
msg: "expected KEY=VALUE",
}
}
key := strings.TrimSpace(parts[0])
if key == "" {
return &argError{
msg: "expected KEY=VALUE",
}
}
val := strings.TrimSpace(parts[1])
*f = append(*f, templateData{
key: key,
value: val,
})
return nil
}
func (f *dataFlags) String() string {
return ""
}
func (e argError) Error() string {
return e.msg
}