Skip to content

Commit

Permalink
Pipeline: Add 'glob' template function
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Kosegi <richard.kosegi@gmail.com>
  • Loading branch information
rkosegi committed Aug 12, 2024
1 parent 6a85f1d commit 5a156e0
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions pipeline/template_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func renderTemplate(tmplStr string, data interface{}, fm template.FuncMap) (stri
"fileExists": fileExistsFunc,
"mergeFiles": mergeFilesFunc,
"isDir": isDirFunc,
"glob": globFunc,
})
_, err := tmpl.Parse(tmplStr)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions pipeline/template_engine_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/rkosegi/yaml-toolkit/dom"
"github.com/rkosegi/yaml-toolkit/utils"
"os"
"path/filepath"
"strings"
"text/template"
)
Expand Down Expand Up @@ -83,6 +84,11 @@ func isDirFunc(path string) bool {
return fi.IsDir()
}

// globFunc exposes filepath.Glob
func globFunc(pattern string) ([]string, error) {
return filepath.Glob(pattern)
}

// mergeFilesFunc merges 0 or more files into single map[string]interface{}
func mergeFilesFunc(files ...string) (map[string]interface{}, error) {
ds := analytics.NewDocumentSet()
Expand Down
13 changes: 13 additions & 0 deletions pipeline/template_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,16 @@ func TestTemplateFuncIsDir(t *testing.T) {
assert.True(t, isDirFunc(d))
assert.False(t, isDirFunc("/i hope/this/path/does/not/exist"))
}

func TestTemplateFuncGlob(t *testing.T) {
d, err := os.MkdirTemp("", "yt*")
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(d+"/1.yaml", []byte{}, 0o664))
t.Cleanup(func() {
t.Logf("deleting temporary directory %s", d)
_ = os.RemoveAll(d)
})
files, err := globFunc(d + "/*.yaml")
assert.NoError(t, err)
assert.Equal(t, 1, len(files))
}

0 comments on commit 5a156e0

Please sign in to comment.