diff --git a/README.md b/README.md index 78058790..14f93821 100644 --- a/README.md +++ b/README.md @@ -377,6 +377,7 @@ For example, this is a JSON version of an emitted RuntimeContainer struct: - [Functions from Sprig v3](https://masterminds.github.io/sprig/), except for those that have the same name as one of the following functions. - _`closest $array $value`_: Returns the longest matching substring in `$array` that matches `$value` - _`coalesce ...`_: Returns the first non-nil argument. +- _`comment $delimiter $string`_: Returns `$string` with each line prefixed by `$delimiter` (helpful for debugging combined with Sprig `toPrettyJson`: `{{ toPrettyJson $ | comment "#" }}`). - _`contains $map $key`_: Returns `true` if `$map` contains `$key`. Takes maps from `string` to any type. - _`dir $path`_: Returns an array of filenames in the specified `$path`. - _`exists $path`_: Returns `true` if `$path` refers to an existing file or directory. Takes a string. diff --git a/internal/template/functions.go b/internal/template/functions.go index 091ab4e2..e828bf51 100644 --- a/internal/template/functions.go +++ b/internal/template/functions.go @@ -9,6 +9,7 @@ import ( "log" "os" "reflect" + "regexp" "strings" ) @@ -57,6 +58,12 @@ func intersect(l1, l2 []string) []string { return keys } +// comment prefix each line of the source string with the provided comment delimiter string +func comment(delimiter string, source string) string { + regexPattern := regexp.MustCompile(`(?m)^`) + return regexPattern.ReplaceAllString(source, delimiter) +} + func contains(input interface{}, key interface{}) bool { if input == nil { return false diff --git a/internal/template/functions_test.go b/internal/template/functions_test.go index fdcc0c01..79ca29e2 100644 --- a/internal/template/functions_test.go +++ b/internal/template/functions_test.go @@ -12,6 +12,24 @@ import ( "github.com/stretchr/testify/assert" ) +func TestComment(t *testing.T) { + env := map[string]string{ + "bar": "baz", + "foo": "test", + } + + expected := `# { +# "bar": "baz", +# "foo": "test" +# }` + + tests := templateTestList{ + {`{{toPrettyJson . | comment "# "}}`, env, expected}, + } + + tests.run(t) +} + func TestContainsString(t *testing.T) { env := map[string]string{ "PORT": "1234", diff --git a/internal/template/template.go b/internal/template/template.go index aa627dc4..c7c0607d 100644 --- a/internal/template/template.go +++ b/internal/template/template.go @@ -60,6 +60,7 @@ func newTemplate(name string) *template.Template { tmpl.Funcs(sprig.TxtFuncMap()).Funcs(template.FuncMap{ "closest": arrayClosest, "coalesce": coalesce, + "comment": comment, "contains": contains, "dir": dirList, "eval": eval,