Skip to content

Commit

Permalink
Helper to recursively return all files of a path and its subpaths
Browse files Browse the repository at this point in the history
  • Loading branch information
zimmski committed Aug 4, 2018
1 parent 43a0e24 commit f52be9c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
26 changes: 26 additions & 0 deletions files.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package osutil

import (
"os"
"path/filepath"
)

// FilesRecursive returns all files in a given path and its subpaths.
func FilesRecursive(path string) (files []string, err error) {
var fs []string

err = filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if f.IsDir() {
return nil
}

fs = append(fs, path)

return err
})
if err != nil {
return nil, err
}

return fs, nil
}
35 changes: 35 additions & 0 deletions files_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package osutil

import (
"io/ioutil"
"os"
"sort"
"testing"

"github.com/stretchr/testify/assert"
)

func TestFilesRecursive(t *testing.T) {
path, err := ioutil.TempDir("", "os-util")
assert.NoError(t, err)

assert.NoError(t, os.MkdirAll(path+"/a/b", 0750))
assert.NoError(t, ioutil.WriteFile(path+"/c.txt", []byte("foobar"), 0640))
assert.NoError(t, ioutil.WriteFile(path+"/a/d.txt", []byte("foobar"), 0640))
assert.NoError(t, ioutil.WriteFile(path+"/a/b/e.txt", []byte("foobar"), 0640))

fs, err := FilesRecursive(path)
assert.NoError(t, err)

sort.Strings(fs)

assert.Equal(
t,
[]string{
path + "/a/b/e.txt",
path + "/a/d.txt",
path + "/c.txt",
},
fs,
)
}

0 comments on commit f52be9c

Please sign in to comment.