Add fileStat to tpl/os/os
authorsatotake <doublequotation@gmail.com>
Sun, 5 Aug 2018 03:37:20 +0000 (12:37 +0900)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Mon, 6 Aug 2018 07:54:26 +0000 (09:54 +0200)
tpl/os/init.go
tpl/os/os.go
tpl/os/os_test.go

index 3ef8702d6a23366e19ab4afc65201b7ea43a0f46..08a36fe7b6fe1919dfe34dee4dbd66dc71bad8b3 100644 (file)
@@ -55,6 +55,13 @@ func init() {
                        },
                )
 
+               ns.AddMethodMapping(ctx.FileStat,
+                       []string{"fileStat"},
+                       [][2]string{
+                               {`{{ (fileExists "files/README.txt").Size }}`, `11`},
+                       },
+               )
+
                return ns
 
        }
index 79d035d7ea76aa971225246680a233505e21fb65..04f151ec91a25fa6cead9350af4ddd877a27693e 100644 (file)
@@ -130,3 +130,22 @@ func (ns *Namespace) FileExists(i interface{}) (bool, error) {
 
        return status, nil
 }
+
+// FileStat Stat returns the os.FileInfo structure describing file.
+func (ns *Namespace) FileStat(i interface{}) (_os.FileInfo, error) {
+       path, err := cast.ToStringE(i)
+       if err != nil {
+               return nil, err
+       }
+
+       if path == "" {
+               return nil, errors.New("fileStat needs a path to a file")
+       }
+
+       r, err := ns.readFileFs.Stat(path)
+       if err != nil {
+               return nil, err
+       }
+
+       return r, nil
+}
index 0919f885ab1604f517df73354eef2e0a527e7ca6..60e6b1f63fe98379d11b3210ca0e6a51db59cc95 100644 (file)
@@ -99,3 +99,37 @@ func TestFileExists(t *testing.T) {
                assert.Equal(t, test.expect, result, errMsg)
        }
 }
+
+func TestFileStat(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)
+
+       for i, test := range []struct {
+               filename string
+               expect   interface{}
+       }{
+               {filepath.FromSlash("/f/f1.txt"), int64(10)},
+               {filepath.FromSlash("f/f1.txt"), int64(10)},
+               {"b", nil},
+               {"", nil},
+       } {
+               errMsg := fmt.Sprintf("[%d] %v", i, test)
+               result, err := ns.FileStat(test.filename)
+
+               if test.expect == nil {
+                       require.Error(t, err, errMsg)
+                       continue
+               }
+
+               require.NoError(t, err, errMsg)
+               assert.Equal(t, test.expect, result.Size(), errMsg)
+       }
+}