Skip to content

Commit 66d69f0

Browse files
silvanocerzacmaglie
authored andcommitted
Added ReadDirRecursive method
1 parent ae9722a commit 66d69f0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

paths.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,30 @@ func (p *Path) ReadDir() (PathList, error) {
302302
return paths, nil
303303
}
304304

305+
// ReadDirRecursive returns a PathList containing the content of the directory
306+
// and its subdirectories pointed by the current Path
307+
func (p *Path) ReadDirRecursive() (PathList, error) {
308+
infos, err := ioutil.ReadDir(p.path)
309+
if err != nil {
310+
return nil, err
311+
}
312+
paths := PathList{}
313+
for _, info := range infos {
314+
path := p.Clone().Join(info.Name())
315+
paths.Add(path)
316+
317+
if path.IsDir() {
318+
subPaths, err := path.ReadDirRecursive()
319+
if err != nil {
320+
return nil, err
321+
}
322+
paths.AddAll(subPaths)
323+
}
324+
325+
}
326+
return paths, nil
327+
}
328+
305329
// CopyTo copies the contents of the file named src to the file named
306330
// by dst. The file will be created if it does not already exist. If the
307331
// destination file exists, all it's contents will be replaced by the contents

paths_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,3 +243,26 @@ func TestParents(t *testing.T) {
243243
require.Equal(t, "a", parents2[3].String())
244244
require.Equal(t, ".", parents2[4].String())
245245
}
246+
247+
func TestReadDirRecursive(t *testing.T) {
248+
testPath := New("_testdata")
249+
250+
list, err := testPath.ReadDirRecursive()
251+
require.NoError(t, err)
252+
require.Len(t, list, 14)
253+
254+
require.Equal(t, "_testdata/anotherFile", list[0].String())
255+
require.Equal(t, "_testdata/file", list[1].String())
256+
require.Equal(t, "_testdata/folder", list[2].String())
257+
require.Equal(t, "_testdata/folder/.hidden", list[3].String())
258+
require.Equal(t, "_testdata/folder/file2", list[4].String())
259+
require.Equal(t, "_testdata/folder/file3", list[5].String())
260+
require.Equal(t, "_testdata/folder/subfolder", list[6].String())
261+
require.Equal(t, "_testdata/folder/subfolder/file4", list[7].String())
262+
require.Equal(t, "_testdata/symlinktofolder", list[8].String())
263+
require.Equal(t, "_testdata/symlinktofolder/.hidden", list[9].String())
264+
require.Equal(t, "_testdata/symlinktofolder/file2", list[10].String())
265+
require.Equal(t, "_testdata/symlinktofolder/file3", list[11].String())
266+
require.Equal(t, "_testdata/symlinktofolder/subfolder", list[12].String())
267+
require.Equal(t, "_testdata/symlinktofolder/subfolder/file4", list[13].String())
268+
}

0 commit comments

Comments
 (0)