Skip to content

Commit f61b032

Browse files
committed
Added RelFrom command and tests (also for RelTo)
1 parent 51e4dba commit f61b032

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

paths.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,10 @@ func (p *Path) HasSuffix(suffixies ...string) bool {
128128
}
129129

130130
// RelTo returns a relative Path that is lexically equivalent to r when
131-
// joined to the current Path
131+
// joined to the current Path.
132+
//
133+
// For example paths.New("/my/path/ab/cd").RelTo(paths.New("/my/path"))
134+
// returns "../..".
132135
func (p *Path) RelTo(r *Path) (*Path, error) {
133136
rel, err := filepath.Rel(p.path, r.path)
134137
if err != nil {
@@ -137,6 +140,19 @@ func (p *Path) RelTo(r *Path) (*Path, error) {
137140
return New(rel), nil
138141
}
139142

143+
// RelFrom returns a relative Path that when joined with r is lexically
144+
// equivalent to the current path.
145+
//
146+
// For example paths.New("/my/path/ab/cd").RelFrom(paths.New("/my/path"))
147+
// returns "ab/cd".
148+
func (p *Path) RelFrom(r *Path) (*Path, error) {
149+
rel, err := filepath.Rel(r.path, p.path)
150+
if err != nil {
151+
return nil, err
152+
}
153+
return New(rel), nil
154+
}
155+
140156
// Abs returns the absolute path of the current Path
141157
func (p *Path) Abs() (*Path, error) {
142158
abs, err := filepath.Abs(p.path)

paths_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,3 +311,29 @@ func TestEquivalentPaths(t *testing.T) {
311311
require.True(t, wd.Join("file1").EquivalentTo(New("file1")))
312312
require.True(t, wd.Join("file1").EquivalentTo(New("file1", "abc", "..")))
313313
}
314+
315+
func TestRelativeTo(t *testing.T) {
316+
res, err := New("/my/abs/path/123/456").RelTo(New("/my/abs/path"))
317+
require.NoError(t, err)
318+
require.Equal(t, "../..", res.String())
319+
320+
res, err = New("/my/abs/path").RelTo(New("/my/abs/path/123/456"))
321+
require.NoError(t, err)
322+
require.Equal(t, "123/456", res.String())
323+
324+
res, err = New("my/path").RelTo(New("/other/path"))
325+
require.Error(t, err)
326+
require.Nil(t, res)
327+
328+
res, err = New("/my/abs/path/123/456").RelFrom(New("/my/abs/path"))
329+
require.Equal(t, "123/456", res.String())
330+
require.NoError(t, err)
331+
332+
res, err = New("/my/abs/path").RelFrom(New("/my/abs/path/123/456"))
333+
require.NoError(t, err)
334+
require.Equal(t, "../..", res.String())
335+
336+
res, err = New("my/path").RelFrom(New("/other/path"))
337+
require.Error(t, err)
338+
require.Nil(t, res)
339+
}

0 commit comments

Comments
 (0)