Skip to content

Commit

Permalink
Add a utility for checking if vars are set:
Browse files Browse the repository at this point in the history
...since strict-mode is now enabled
  • Loading branch information
Owen Smith committed Nov 29, 2016
1 parent 7f518ee commit 28771d9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 16 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ func ReadEnvVars(rawEnv []string) (environ map[string]string) {
func WriteTemplateToStream(tplSource string, environ map[string]string, outStream io.Writer) {
tpl := template.New("_root_")
tpl.Funcs(template.FuncMap{
"split": TplSplitStr,
"split": TplSplitStr,
"exists": TplCheckExists,
})
tpl.Option("missingkey=error")
_, err := tpl.Parse(tplSource)
Expand All @@ -47,14 +48,27 @@ func TplSplitStr(args ...interface{}) ([]string, error) {
if len(args) > 2 {
parsedLimit, ok := args[2].(int)
if !ok {
err := errors.New("Limit parameter (3rd)is not integer")
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)
}
2 changes: 1 addition & 1 deletion main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func ExampleWriteTemplateToStream_basic() {
"TARGET_PLANET": "earth",
}
WriteTemplateToStream("Hello, {{ .TARGET_PLANET }}!\n", env, buf)
WriteTemplateToStream("{{ if not .BEGIN_INVASION}}We mean you no{{ else }}Prepare yourselves for{{ end }} harm.", env, buf)
WriteTemplateToStream("{{ if not (exists . \"BEGIN_INVASION\")}}We mean you no{{ else }}Prepare yourselves for{{ end }} harm.", env, buf)
fmt.Println(buf.String())
// Output:
// Hello, earth!
Expand Down

0 comments on commit 28771d9

Please sign in to comment.