feat: add isDir template function (#1657)

This commit is contained in:
Simon Schröter 2024-08-06 15:39:00 +02:00 committed by GitHub
parent 5d8598a7d7
commit 505da8a31c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 0 deletions

View File

@ -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.

View File

@ -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) {