forked from orls/envtemplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (66 loc) · 1.86 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
package main
import "bytes"
import "errors"
import "io"
import "os"
import "log"
import "text/template"
import "strings"
func ReadTemplate(instream io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(instream)
return buf.String()
}
func ReadEnvVars(rawEnv []string) (environ map[string]string) {
environ = make(map[string]string)
for _, item := range rawEnv {
parts := strings.SplitN(item, "=", 2)
environ[parts[0]] = parts[1]
}
return
}
func WriteTemplateToStream(tplSource string, environ map[string]string, outStream io.Writer) {
tpl := template.New("_root_")
tpl.Funcs(template.FuncMap{
"split": TplSplitStr,
"exists": TplCheckExists,
})
tpl.Option("missingkey=error")
_, err := tpl.Parse(tplSource)
if err != nil {
log.Fatal(err)
}
err = tpl.Execute(outStream, environ)
if err != nil {
log.Fatal(err)
}
}
func TplSplitStr(args ...interface{}) ([]string, error) {
rawValue := args[0].(string)
sep := args[1].(string)
limit := -1
if len(args) > 2 {
parsedLimit, ok := args[2].(int)
if !ok {
err := errors.New("Limit arg (3rd) to `split` is not integer")
return nil, err
}
limit = parsedLimit
}
return strings.SplitN(rawValue, sep, limit), nil
}
func TplCheckExists(args ...interface{}) (bool, error) {
datamap, ok := args[0].(map[string]string)
if !ok {
return false, errors.New("data-map arg (1st) to `exists` should be a map[string]string, did you mean '.' or '$'?")
}
key, ok := args[1].(string)
if !ok {
return false, errors.New("lookup-key arg (2nd) to `exists` should be a string")
}
_, exists := datamap[key]
return exists, nil
}
func main() {
WriteTemplateToStream(ReadTemplate(os.Stdin), ReadEnvVars(os.Environ()), os.Stdout)
}