Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/tpl/os
diff options
context:
space:
mode:
authordigitalcraftsman <digitalcraftsman@users.noreply.github.com>2017-09-28 20:52:34 +0300
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2017-09-28 20:52:34 +0300
commit2818878994e906c292cbe00cb2a83f1531a21f32 (patch)
treec4d86e358b82736ff1fb1243d5fe8ef9d5baba82 /tpl/os
parentb6a30283f099ce9578d491ba8fbbf45f673dbf3b (diff)
tpl: Add os.fileExists template function
Fixes #3839
Diffstat (limited to 'tpl/os')
-rw-r--r--tpl/os/init.go7
-rw-r--r--tpl/os/os.go19
-rw-r--r--tpl/os/os_test.go36
3 files changed, 62 insertions, 0 deletions
diff --git a/tpl/os/init.go b/tpl/os/init.go
index 3fc3308f2..012f43b1f 100644
--- a/tpl/os/init.go
+++ b/tpl/os/init.go
@@ -48,6 +48,13 @@ func init() {
},
)
+ ns.AddMethodMapping(ctx.FileExists,
+ []string{"fileExists"},
+ [][2]string{
+ {`{{ fileExists "foo.txt" }}`, `false`},
+ },
+ )
+
return ns
}
diff --git a/tpl/os/os.go b/tpl/os/os.go
index c9ffb81cf..02faa2809 100644
--- a/tpl/os/os.go
+++ b/tpl/os/os.go
@@ -96,3 +96,22 @@ func (ns *Namespace) ReadDir(i interface{}) ([]_os.FileInfo, error) {
return list, nil
}
+
+// FileExists checks whether a file exists under the given path.
+func (ns *Namespace) FileExists(i interface{}) (bool, error) {
+ path, err := cast.ToStringE(i)
+ if err != nil {
+ return false, err
+ }
+
+ if path == "" {
+ return false, errors.New("fileExists needs a path to a file")
+ }
+
+ status, err := afero.Exists(ns.deps.Fs.WorkingDir, path)
+ if err != nil {
+ return false, err
+ }
+
+ return status, nil
+}
diff --git a/tpl/os/os_test.go b/tpl/os/os_test.go
index 383eb88c4..0919f885a 100644
--- a/tpl/os/os_test.go
+++ b/tpl/os/os_test.go
@@ -63,3 +63,39 @@ func TestReadFile(t *testing.T) {
assert.Equal(t, test.expect, result, errMsg)
}
}
+
+func TestFileExists(t *testing.T) {
+ t.Parallel()
+
+ workingDir := "/home/hugo"
+
+ v := viper.New()
+ v.Set("workingDir", workingDir)
+
+ ns := New(&deps.Deps{Fs: hugofs.NewMem(v)})
+
+ afero.WriteFile(ns.deps.Fs.Source, filepath.Join(workingDir, "/f/f1.txt"), []byte("f1-content"), 0755)
+ afero.WriteFile(ns.deps.Fs.Source, filepath.Join("/home", "f2.txt"), []byte("f2-content"), 0755)
+
+ for i, test := range []struct {
+ filename string
+ expect interface{}
+ }{
+ {filepath.FromSlash("/f/f1.txt"), true},
+ {filepath.FromSlash("f/f1.txt"), true},
+ {filepath.FromSlash("../f2.txt"), false},
+ {"b", false},
+ {"", nil},
+ } {
+ errMsg := fmt.Sprintf("[%d] %v", i, test)
+ result, err := ns.FileExists(test.filename)
+
+ if test.expect == nil {
+ require.Error(t, err, errMsg)
+ continue
+ }
+
+ require.NoError(t, err, errMsg)
+ assert.Equal(t, test.expect, result, errMsg)
+ }
+}