diff --git a/docs/index.md b/docs/index.md index 80a0d3b..be72e1e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ The Sprig library provides over 70 template functions for Go's template language - [Flow Control Functions](flow_control.md): `fail` - Advanced Functions - [UUID Functions](uuid.md): `uuidv4` - - [OS Functions](os.md): `env`, `expandenv` + - [OS Functions](os.md): `env`, `expandenv`, `mustEnv` - [Version Comparison Functions](semver.md): `semver`, `semverCompare` - [Reflection](reflection.md): `typeOf`, `kindIs`, `typeIsLike`, etc. - [Cryptographic and Security Functions](crypto.md): `derivePassword`, `sha256sum`, `genPrivateKey`, etc. diff --git a/docs/os.md b/docs/os.md index e6120c0..e8ef803 100644 --- a/docs/os.md +++ b/docs/os.md @@ -22,3 +22,15 @@ To substitute environment variables in a string, use `expandenv`: ``` expandenv "Your path is set to $PATH" ``` + +## mustEnv + +`mustEnv` function reads an environment variable, and returns an error if that env var does not exist. + +``` +# works +mustEnv "HOME" + +# errors +mustEnv "INVALID" +``` diff --git a/functions.go b/functions.go index cda47d2..1b4df1d 100644 --- a/functions.go +++ b/functions.go @@ -88,7 +88,7 @@ var nonhermeticFunctions = []string{ // OS "env", "expandenv", - + "mustEnv", // Network "getHostByName", } @@ -269,7 +269,7 @@ var genericMap = map[string]interface{}{ // OS: "env": os.Getenv, "expandenv": os.ExpandEnv, - + "mustEnv": mustEnv, // Network: "getHostByName": getHostByName, diff --git a/os.go b/os.go new file mode 100644 index 0000000..7965a8a --- /dev/null +++ b/os.go @@ -0,0 +1,15 @@ +package sprig + +import ( + "fmt" + "os" +) + +func mustEnv(env string) (string, error){ + v, ok := os.LookupEnv(env) + if !ok { + return v, fmt.Errorf("env var \"%s\" does not exist", env) + } + + return v, nil +} \ No newline at end of file diff --git a/os_test.go b/os_test.go new file mode 100644 index 0000000..8743628 --- /dev/null +++ b/os_test.go @@ -0,0 +1,20 @@ +package sprig + +import ( + "testing" +) + +func TestMustEnv(t *testing.T) { + tpl := `{{ mustEnv "INVALID" }}` + if err := runt(tpl, "foo"); err == nil { + t.Errorf("expected error, got: %v", err) + } + + t.Setenv("TMP", "OK") + + tpl = `{{ mustEnv "TMP" }}` + if err := runt(tpl, "OK"); err != nil { + t.Error(err) + } + +}