From f867f3564dc2e3337f9481c684edd0c33df25648 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 13 Apr 2018 13:56:19 +0200 Subject: New function proposal: `files.Walk` (#281) * Update file.go Glob function * returns all the paths of every file inside a directory * added TrimPrefix function * avoiding errors when no directory or file is founded * adapted TrimPrefix to work on pipelines * tests added for string.TrimPrefix * strings.TrimSuffix function removed from this PR * Walk function created * WalkTest modified to make it compatible with other OS * first path must be os agnostic too --- funcs/file.go | 13 +++++++++++++ funcs/file_test.go | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) (limited to 'funcs') diff --git a/funcs/file.go b/funcs/file.go index 1f1a30bd..04de4e85 100644 --- a/funcs/file.go +++ b/funcs/file.go @@ -55,3 +55,16 @@ func (f *FileFuncs) IsDir(path string) bool { func (f *FileFuncs) ReadDir(path string) ([]string, error) { return file.ReadDir(path) } + +// Walk - +func (f *FileFuncs) Walk(path string) ([]string, error) { + files := make([]string, 0) + afero.Walk(f.fs, path, func(subpath string, finfo os.FileInfo, err error) error { + if err != nil { + return err + } + files = append(files, subpath) + return nil + }) + return files, nil +} diff --git a/funcs/file_test.go b/funcs/file_test.go index 2a3ce9a9..56651421 100644 --- a/funcs/file_test.go +++ b/funcs/file_test.go @@ -1,6 +1,7 @@ package funcs import ( + "path/filepath" "testing" "github.com/spf13/afero" @@ -30,3 +31,25 @@ func TestFileIsDir(t *testing.T) { assert.True(t, ff.IsDir("/tmp")) assert.False(t, ff.IsDir("/tmp/foo")) } + +func TestFileWalk(t *testing.T) { + fs := afero.NewMemMapFs() + ff := &FileFuncs{fs} + + _ = fs.Mkdir("/tmp", 0777) + _ = fs.Mkdir("/tmp/bar", 0777) + _ = fs.Mkdir("/tmp/bar/baz", 0777) + f, _ := fs.Create("/tmp/bar/baz/foo") + _, _ = f.Write([]byte("foo")) + + expectedLists := [][]string{{"tmp"}, {"tmp", "bar" }, {"tmp", "bar", "baz"}, {"tmp", "bar", "baz", "foo"}} + expectedPaths := make([]string, 0) + for _, path := range expectedLists { + expectedPaths = append(expectedPaths, string(filepath.Separator) + filepath.Join(path...)) + } + + actualPaths, err := ff.Walk(string(filepath.Separator) + "tmp") + + assert.NoError(t, err) + assert.Equal(t, expectedPaths, actualPaths) +} -- cgit v1.2.3