diff options
| author | Dave Henderson <dhenderson@gmail.com> | 2018-02-10 10:13:58 -0500 |
|---|---|---|
| committer | Dave Henderson <dhenderson@gmail.com> | 2018-03-03 10:58:05 -0500 |
| commit | 96ab610f904c48fa4e85bb42e212f49eb3a4ff1c (patch) | |
| tree | 81caae2b83298694798eea978a2e28380e29ef62 /funcs | |
| parent | 5f47dac2c1273e189f4b70b74a6dfea68cf788ff (diff) | |
Adding file namespace
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
Diffstat (limited to 'funcs')
| -rw-r--r-- | funcs/file.go | 57 | ||||
| -rw-r--r-- | funcs/file_test.go | 32 |
2 files changed, 89 insertions, 0 deletions
diff --git a/funcs/file.go b/funcs/file.go new file mode 100644 index 00000000..1f1a30bd --- /dev/null +++ b/funcs/file.go @@ -0,0 +1,57 @@ +package funcs + +import ( + "os" + "sync" + + "github.com/hairyhenderson/gomplate/file" + "github.com/spf13/afero" +) + +var ( + ff *FileFuncs + ffInit sync.Once +) + +// FileNS - the File namespace +func FileNS() *FileFuncs { + ffInit.Do(func() { ff = &FileFuncs{afero.NewOsFs()} }) + return ff +} + +// AddFileFuncs - +func AddFileFuncs(f map[string]interface{}) { + f["file"] = FileNS +} + +// FileFuncs - +type FileFuncs struct { + fs afero.Fs +} + +// Read - +func (f *FileFuncs) Read(path string) (string, error) { + return file.Read(path) +} + +// Stat - +func (f *FileFuncs) Stat(path string) (os.FileInfo, error) { + return f.fs.Stat(path) +} + +// Exists - +func (f *FileFuncs) Exists(path string) bool { + _, err := f.Stat(path) + return err == nil +} + +// IsDir - +func (f *FileFuncs) IsDir(path string) bool { + i, err := f.Stat(path) + return err == nil && i.IsDir() +} + +// ReadDir - +func (f *FileFuncs) ReadDir(path string) ([]string, error) { + return file.ReadDir(path) +} diff --git a/funcs/file_test.go b/funcs/file_test.go new file mode 100644 index 00000000..2a3ce9a9 --- /dev/null +++ b/funcs/file_test.go @@ -0,0 +1,32 @@ +package funcs + +import ( + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" +) + +func TestFileExists(t *testing.T) { + fs := afero.NewMemMapFs() + ff := &FileFuncs{fs} + + _ = fs.Mkdir("/tmp", 0777) + f, _ := fs.Create("/tmp/foo") + _, _ = f.Write([]byte("foo")) + + assert.True(t, ff.Exists("/tmp/foo")) + assert.False(t, ff.Exists("/tmp/bar")) +} + +func TestFileIsDir(t *testing.T) { + fs := afero.NewMemMapFs() + ff := &FileFuncs{fs} + + _ = fs.Mkdir("/tmp", 0777) + f, _ := fs.Create("/tmp/foo") + _, _ = f.Write([]byte("foo")) + + assert.True(t, ff.IsDir("/tmp")) + assert.False(t, ff.IsDir("/tmp/foo")) +} |
