Skip to content

Commit

Permalink
Steal regexMatch from consul-template (goss-org#219)
Browse files Browse the repository at this point in the history
Makes it possible to do pattern-based template blocks.
  • Loading branch information
blalor authored and BenjaminHerbert committed May 28, 2020
1 parent f0913b1 commit 4cff465
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
5 changes: 3 additions & 2 deletions docs/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,7 @@ Available functions beyond text/template [built-in functions](https://golang.org
* `getEnv "var" ["default"]` - A more forgiving env var lookup. If key is missing either "" or default (if provided) is returned.
* `readFile "fileName"` - Reads file content into a a string, trims whitespace. Useful when a file contains a token.
* **NOTE:** Goss will error out during during the parsing phase if the file does not exist, no tests will be executed.
* `regexMatch "(some)?reg[eE]xp"` - Tests the piped input against the regular expression argument.

**NOTE:** gossfiles containing text/template `{{}}` controls will no longer work with `goss add/autoadd`. One way to get around this is to split your template and static goss files and use [gossfile](#gossfile) to import.

Expand Down Expand Up @@ -829,8 +830,8 @@ package:
{{end}}
{{end}}
# This test is only when OS=centos variable is defined
{{if eq .Env.OS "centos"}}
# This test is only when the OS environment variable matches the pattern
{{if .Env.OS | "[Cc]ent(OS|os)"}}
libselinux:
installed: true
{{end}}
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/goss/goss-service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ service:
foobar:
enabled: false
running: false
{{if eq .Env.OS "centos7"}}
{{ if .Env.OS | regexMatch "centos[7]" }}
httpd:
{{else}}
apache2:
Expand Down
17 changes: 14 additions & 3 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"text/template"
)
Expand All @@ -32,10 +33,20 @@ func getEnv(key string, def ...string) string {
return os.Getenv(key)
}

func regexMatch(re, s string) (bool, error) {
compiled, err := regexp.Compile(re)
if err != nil {
return false, err
}

return compiled.MatchString(s), nil
}

var funcMap = map[string]interface{}{
"mkSlice": mkSlice,
"readFile": readFile,
"getEnv": getEnv,
"mkSlice": mkSlice,
"readFile": readFile,
"getEnv": getEnv,
"regexMatch": regexMatch,
}

func NewTemplateFilter(varsFile string) func([]byte) []byte {
Expand Down

0 comments on commit 4cff465

Please sign in to comment.