Skip to content

Commit

Permalink
Pipeline: Add template function 'isDir'
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 cc26cc8 commit 6a85f1d
Show file tree
Hide file tree
Showing 3 changed files with 22 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 @@ -36,6 +36,7 @@ func renderTemplate(tmplStr string, data interface{}, fm template.FuncMap) (stri
"unflatten": unflattenFunc,
"fileExists": fileExistsFunc,
"mergeFiles": mergeFilesFunc,
"isDir": isDirFunc,
})
_, err := tmpl.Parse(tmplStr)
if err != nil {
Expand Down
10 changes: 10 additions & 0 deletions pipeline/template_engine_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ func fileExistsFunc(f string) bool {
return true
}

// isDirFunc checks if provided path points to directory.
// Any error is swallowed and will cause function to return false.
func isDirFunc(path string) bool {
fi, err := os.Stat(path)
if err != nil {
return false
}
return fi.IsDir()
}

// mergeFilesFunc merges 0 or more files into single map[string]interface{}
func mergeFilesFunc(files ...string) (map[string]interface{}, error) {
ds := analytics.NewDocumentSet()
Expand Down
11 changes: 11 additions & 0 deletions pipeline/template_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,14 @@ func TestTemplateFuncMergeFilesInvalid(t *testing.T) {
_ = os.Remove(f2.Name())
})
}

func TestTemplateFuncIsDir(t *testing.T) {
d, err := os.MkdirTemp("", "yt*")
assert.NoError(t, err)
t.Cleanup(func() {
t.Logf("deleting temporary directory %s", d)
_ = os.RemoveAll(d)
})
assert.True(t, isDirFunc(d))
assert.False(t, isDirFunc("/i hope/this/path/does/not/exist"))
}

0 comments on commit 6a85f1d

Please sign in to comment.