diff --git a/docs/templating_funcs.md b/docs/templating_funcs.md index a0cc85fd..18a665f7 100644 --- a/docs/templating_funcs.md +++ b/docs/templating_funcs.md @@ -39,6 +39,13 @@ The `isFile` function allows you to check if a file exists. On failure, the temp {{ if isFile "./myfile" }} ``` +#### `isDir` +The `isDir` function allows you to check if a directory exists. On failure, the template rendering will fail with an error message. + +```yaml +{{ if isDir "./mydirectory" }} +``` + #### `readFile` The `readFile` function allows you to read a file and return its content as the function output. On failure, the template rendering will fail with an error message. diff --git a/pkg/tmpl/context_funcs.go b/pkg/tmpl/context_funcs.go index 2e618ca5..82f8bf0e 100644 --- a/pkg/tmpl/context_funcs.go +++ b/pkg/tmpl/context_funcs.go @@ -61,6 +61,7 @@ func (c *Context) createFuncMap() template.FuncMap { "envExec": c.EnvExec, "exec": c.Exec, "isFile": c.IsFile, + "isDir": c.IsDir, "readFile": c.ReadFile, "readDir": c.ReadDir, "readDirEntries": c.ReadDirEntries, @@ -229,6 +230,24 @@ func (c *Context) IsFile(filename string) (bool, error) { return false, err } +func (c *Context) IsDir(filename string) (bool, error) { + var path string + if filepath.IsAbs(filename) { + path = filename + } else { + path = filepath.Join(c.basePath, filename) + } + + stat, err := os.Stat(path) + if err == nil { + return stat.IsDir(), nil + } + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + return false, err +} + func (c *Context) ReadFile(filename string) (string, error) { var path string if filepath.IsAbs(filename) {