-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
115 lines (102 loc) · 2.07 KB
/
utils.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
111
112
113
114
115
package main
import (
"fmt"
"strings"
"text/template"
)
var renderTemplate = template.New("")
type TemplateData struct {
Input map[string]any
Env map[string]string
}
func (td TemplateData) getInput(name string) any {
if v, ok := td.Input[name]; ok {
return v
} else {
return nil
}
}
func (td TemplateData) getEnv(name string) any {
if v, ok := td.Env[name]; ok {
return v
} else {
return nil
}
}
func (td *TemplateData) Funcs() template.FuncMap {
return template.FuncMap{
"input": td.getInput,
"env": td.getEnv,
}
}
func NewTemplateData(input map[string]any, env []string) TemplateData {
safeInputs := make(map[string]any)
for name, value := range input {
safeName := strings.ReplaceAll(name, "-", "_")
safeInputs[safeName] = value
}
return TemplateData{
Input: safeInputs,
Env: NewEnvMap(env),
}
}
type EnvMap map[string]string
func (em EnvMap) Merge(other map[string]string) EnvMap {
for name, value := range other {
em[name] = value
}
return em
}
func (em EnvMap) ToList() []string {
var env []string
for name, value := range em {
env = append(env, fmt.Sprintf("%s=%s", name, value))
}
return env
}
func NewEnvMap(env []string) EnvMap {
m := make(EnvMap, len(env))
for _, item := range env {
entry := strings.SplitN(item, "=", 2)
if len(entry) > 1 {
m[entry[0]] = entry[1]
} else {
m[entry[0]] = ""
}
}
return m
}
func RenderTemplate(text interface{}, data TemplateData) (string, error) {
var tmpl *template.Template
var err error
b := strings.Builder{}
switch t := text.(type) {
case *template.Template:
tmpl = t
case string:
tmpl, err = renderTemplate.Parse(t)
if err != nil {
return "", err
}
default:
return "", fmt.Errorf("unsupported type: %v", t)
}
if err = tmpl.Execute(&b, data); err != nil {
return "", err
} else {
return b.String(), nil
}
}
func DiffStrings(a, b []string) []string {
mb := make(map[string]struct{}, len(b))
for _, x := range b {
mb[x] = struct{}{}
}
var diff []string
for _, x := range a {
if _, found := mb[x]; !found {
diff = append(diff, x)
}
}
return diff
}