Skip to content

Commit c3c98d1

Browse files
committed
Added Path.Parents() function
1 parent 751652d commit c3c98d1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

paths.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,25 @@ func (p *Path) EquivalentTo(other *Path) bool {
444444
return p.Clean().path == other.Clean().path
445445
}
446446

447+
// Parents returns all the parents directories of the current path. If the path is absolute
448+
// it starts from the current path to the root, if the path is relative is starts from the
449+
// current path to the current directory.
450+
// The path should be clean for this method to work properly (no .. or . or other shortcuts).
451+
// This function does not performs any check on the returned paths.
452+
func (p *Path) Parents() []*Path {
453+
res := []*Path{}
454+
dir := p
455+
for {
456+
res = append(res, dir)
457+
parent := dir.Parent()
458+
if parent.EquivalentTo(dir) {
459+
break
460+
}
461+
dir = parent
462+
}
463+
return res
464+
}
465+
447466
func (p *Path) String() string {
448467
return p.path
449468
}

paths_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,21 @@ func TestCopyDir(t *testing.T) {
225225
err = src.Join("file").CopyDirTo(tmp.Join("dest2"))
226226
require.Error(t, err, "copying file as dir")
227227
}
228+
229+
func TestParents(t *testing.T) {
230+
parents := New("/a/very/long/path").Parents()
231+
require.Len(t, parents, 5)
232+
require.Equal(t, "/a/very/long/path", parents[0].String())
233+
require.Equal(t, "/a/very/long", parents[1].String())
234+
require.Equal(t, "/a/very", parents[2].String())
235+
require.Equal(t, "/a", parents[3].String())
236+
require.Equal(t, "/", parents[4].String())
237+
238+
parents2 := New("a/very/relative/path").Parents()
239+
require.Len(t, parents, 5)
240+
require.Equal(t, "a/very/relative/path", parents2[0].String())
241+
require.Equal(t, "a/very/relative", parents2[1].String())
242+
require.Equal(t, "a/very", parents2[2].String())
243+
require.Equal(t, "a", parents2[3].String())
244+
require.Equal(t, ".", parents2[4].String())
245+
}

0 commit comments

Comments
 (0)