Add template function isFile (#2045)

* Add template function isFile

* Update context_funcs.go
This commit is contained in:
Quan TRAN 2022-03-31 03:59:10 +02:00 committed by GitHub
parent 45be24da53
commit ed436ba68b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 20 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package tmpl
import (
"errors"
"fmt"
"io"
"os"
@ -20,6 +21,7 @@ type Values = map[string]interface{}
func (c *Context) createFuncMap() template.FuncMap {
funcMap := template.FuncMap{
"exec": c.Exec,
"isFile": c.IsFile,
"readFile": c.ReadFile,
"readDir": c.ReadDir,
"toYaml": ToYaml,
@ -117,6 +119,24 @@ func (c *Context) Exec(command string, args []interface{}, inputs ...string) (st
return string(bytes), nil
}
func (c *Context) IsFile(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) {