-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathfuncs.go
59 lines (49 loc) · 1.39 KB
/
funcs.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
package main
import (
"bytes"
"fmt"
"os/exec"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
func getFuncMap(t *template.Template) template.FuncMap {
f := sprig.TxtFuncMap()
f["include"] = include(t)
f["shell"] = shell
f["toYaml"] = toYaml
return f
}
func include(t *template.Template) func(templateName string, vars ...interface{}) (string, error) {
return func(templateName string, vars ...interface{}) (string, error) {
if len(vars) > 1 {
return "", errors.New(fmt.Sprintf("Call to include may pass zero or one vars structure, got %v.", len(vars)))
}
buf := bytes.NewBuffer(nil)
included := t.Lookup(templateName)
if included == nil {
return "", errors.New(fmt.Sprintf("No such template '%v' found while calling 'include'.", templateName))
}
if err := included.ExecuteTemplate(buf, templateName, vars[0]); err != nil {
return "", err
}
return buf.String(), nil
}
}
func shell(cmd ...string) (string, error) {
out, err := exec.Command("bash", "-c", strings.Join(cmd[:], "")).Output()
output := strings.TrimSpace(string(out))
if err != nil {
return "", errors.Wrap(err, "Issue running command: "+output)
}
return output, nil
}
func toYaml(v interface{}) (string, error) {
data, err := yaml.Marshal(v)
if err != nil {
return "", errors.Wrap(err, "Issue marsahling yaml")
}
return string(data), nil
}