Skip to content

Commit aa361d8

Browse files
authored
Merge pull request #20 from arduino/fix_isinsidedir
Fix `Pahts.IsInsideDir` method when paths belongs to different drives/filesystem
2 parents ce00145 + 657985f commit aa361d8

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

paths.go

+8-3
Original file line numberDiff line numberDiff line change
@@ -188,12 +188,17 @@ func (p *Path) Clean() *Path {
188188

189189
// IsInsideDir returns true if the current path is inside the provided
190190
// dir
191-
func (p *Path) IsInsideDir(dir *Path) (bool, error) {
191+
func (p *Path) IsInsideDir(dir *Path) bool {
192192
rel, err := filepath.Rel(dir.path, p.path)
193193
if err != nil {
194-
return false, err
194+
// If the dir cannot be made relative to this path it means
195+
// that it belong to a different filesystems, so it cannot be
196+
// inside this path.
197+
return false
195198
}
196-
return !strings.Contains(rel, ".."+string(os.PathSeparator)) && rel != ".." && rel != ".", nil
199+
return !strings.Contains(rel, ".."+string(os.PathSeparator)) &&
200+
rel != ".." &&
201+
rel != "."
197202
}
198203

199204
// Parent returns all but the last element of path, typically the path's

paths_test.go

+14-11
Original file line numberDiff line numberDiff line change
@@ -154,16 +154,13 @@ func TestResetStatCacheWhenFollowingSymlink(t *testing.T) {
154154
}
155155

156156
func TestIsInsideDir(t *testing.T) {
157-
inside := func(a, b *Path) {
158-
in, err := a.IsInsideDir(b)
159-
require.NoError(t, err)
160-
require.True(t, in, "%s is inside %s", a, b)
157+
notInside := func(a, b *Path) {
158+
require.False(t, a.IsInsideDir(b), "%s is inside %s", a, b)
161159
}
162160

163-
notInside := func(a, b *Path) {
164-
in, err := a.IsInsideDir(b)
165-
require.NoError(t, err)
166-
require.False(t, in, "%s is inside %s", a, b)
161+
inside := func(a, b *Path) {
162+
require.True(t, a.IsInsideDir(b), "%s is inside %s", a, b)
163+
notInside(b, a)
167164
}
168165

169166
f1 := New("/a/b/c")
@@ -196,6 +193,14 @@ func TestIsInsideDir(t *testing.T) {
196193
f5 := New("/home/megabug/a15/packages")
197194
notInside(f5, f4)
198195
notInside(f4, f5)
196+
197+
if runtime.GOOS == "windows" {
198+
f6 := New("C:\\", "A")
199+
f7 := New("C:\\", "A", "B", "C")
200+
f8 := New("E:\\", "A", "B", "C")
201+
inside(f7, f6)
202+
notInside(f8, f6)
203+
}
199204
}
200205

201206
func TestReadFileAsLines(t *testing.T) {
@@ -372,9 +377,7 @@ func TestWriteToTempFile(t *testing.T) {
372377
defer tmp.Remove()
373378
require.NoError(t, err)
374379
require.True(t, strings.HasPrefix(tmp.Base(), "prefix"))
375-
inside, err := tmp.IsInsideDir(tmpDir)
376-
require.NoError(t, err)
377-
require.True(t, inside)
380+
require.True(t, tmp.IsInsideDir(tmpDir))
378381
data, err := tmp.ReadFile()
379382
require.NoError(t, err)
380383
require.Equal(t, tmpData, data)

0 commit comments

Comments
 (0)