Skip to content

Commit

Permalink
feat(mustEnv): add mustEnv function
Browse files Browse the repository at this point in the history
  • Loading branch information
FalcoSuessgott committed Sep 5, 2024
1 parent e708470 commit fdecb4a
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 3 deletions.
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions docs/os.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
```
4 changes: 2 additions & 2 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ var nonhermeticFunctions = []string{
// OS
"env",
"expandenv",

"mustEnv",
// Network
"getHostByName",
}
Expand Down Expand Up @@ -269,7 +269,7 @@ var genericMap = map[string]interface{}{
// OS:
"env": os.Getenv,
"expandenv": os.ExpandEnv,

"mustEnv": mustEnv,
// Network:
"getHostByName": getHostByName,

Expand Down
15 changes: 15 additions & 0 deletions os.go
Original file line number Diff line number Diff line change
@@ -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
}
20 changes: 20 additions & 0 deletions os_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

}

0 comments on commit fdecb4a

Please sign in to comment.