From fdecb4aaeecd49b085f7a9174aed2afc3dd779b3 Mon Sep 17 00:00:00 2001 From: Tom Morelly Date: Fri, 6 Sep 2024 09:25:20 +1000 Subject: [PATCH] feat(mustEnv): add mustEnv function --- docs/index.md | 2 +- docs/os.md | 12 ++++++++++++ functions.go | 4 ++-- os.go | 15 +++++++++++++++ os_test.go | 20 ++++++++++++++++++++ 5 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 os.go create mode 100644 os_test.go diff --git a/docs/index.md b/docs/index.md index 80a0d3b6..be72e1ed 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 e6120c03..e8ef803b 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 cda47d26..1b4df1de 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 00000000..7965a8ab --- /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 00000000..87436283 --- /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) + } + +}