-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
tmpl.go
100 lines (90 loc) · 2.17 KB
/
tmpl.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
package pipotron // import "moul.io/pipotron/pipotron"
import (
"bytes"
"fmt"
"math/rand"
"strings"
"text/template"
"github.com/Masterminds/sprig"
"moul.io/godev"
)
func Generate(ctx *Context) (string, error) {
_, err := executeTemplate(`{{pick "init"}}`, ctx)
if err != nil {
return "", err
}
return executeTemplate(`{{pick "output"}}`, ctx)
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func executeTemplate(input string, ctx *Context) (string, error) {
funcMap := template.FuncMap{}
for k, v := range sprig.FuncMap() {
funcMap[k] = v
}
funcMap["pick"] = func(key string) string {
opts := ctx.Dict[key]
if len(opts) < 1 {
return "$$$ INVALID OPTION $$$"
}
elem := opts[rand.Intn(len(opts))]
evaluated, err := executeTemplate(elem, ctx)
if err != nil {
return elem
}
return evaluated
}
funcMap["randString"] = randStringBytes
funcMap["title"] = strings.Title
funcMap["lower"] = strings.ToLower
funcMap["upper"] = strings.ToUpper
funcMap["rand"] = rand.Float64
funcMap["randIntn"] = rand.Intn
funcMap["debug"] = func(v interface{}) string {
fmt.Println(godev.PrettyJSON(v))
return fmt.Sprintf("%#v", v)
}
funcMap["N"] = func(n int) (stream chan int) {
stream = make(chan int)
go func() {
for i := 0; i <= n; i++ {
stream <- i
}
close(stream)
}()
return
}
funcMap["randMinMax"] = func(min, max int) int { return rand.Intn(max-min) + min + 1 }
funcMap["pick_once"] = func(key string) string {
opts := ctx.Dict[key]
if len(opts) < 1 {
return "$$$ INVALID OPTION $$$"
}
i := rand.Intn(len(opts))
elem := opts[i]
opts = append(opts[:i], opts[i+1:]...)
evaluated, err := executeTemplate(elem, ctx)
if err != nil {
return elem
}
return evaluated
}
tmpl, err := template.New("").Funcs(funcMap).Parse(input)
if err != nil {
return "", err
}
var tpl bytes.Buffer
if err = tmpl.Execute(&tpl, ctx); err != nil {
return "", err
}
if tpl.String() == input {
return input, nil
}
return executeTemplate(tpl.String(), ctx)
}