From 28771d9156942b7e0b44e54d17353f58487307bf Mon Sep 17 00:00:00 2001 From: Owen Smith Date: Tue, 29 Nov 2016 16:50:03 +0000 Subject: [PATCH] Add a utility for checking if vars are set: ...since strict-mode is now enabled --- main.go | 18 ++++++++++++++++-- main_test.go | 2 +- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index f4c097c..628a021 100644 --- a/main.go +++ b/main.go @@ -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) @@ -47,7 +48,7 @@ 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 @@ -55,6 +56,19 @@ func TplSplitStr(args ...interface{}) ([]string, error) { 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) } diff --git a/main_test.go b/main_test.go index b0c8c5d..4f5ea42 100644 --- a/main_test.go +++ b/main_test.go @@ -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!