diff --git a/paths.go b/paths.go index b969606..a9e752b 100644 --- a/paths.go +++ b/paths.go @@ -188,12 +188,17 @@ func (p *Path) Clean() *Path { // IsInsideDir returns true if the current path is inside the provided // dir -func (p *Path) IsInsideDir(dir *Path) (bool, error) { +func (p *Path) IsInsideDir(dir *Path) bool { rel, err := filepath.Rel(dir.path, p.path) if err != nil { - return false, err + // If the dir cannot be made relative to this path it means + // that it belong to a different filesystems, so it cannot be + // inside this path. + return false } - return !strings.Contains(rel, ".."+string(os.PathSeparator)) && rel != ".." && rel != ".", nil + return !strings.Contains(rel, ".."+string(os.PathSeparator)) && + rel != ".." && + rel != "." } // Parent returns all but the last element of path, typically the path's diff --git a/paths_test.go b/paths_test.go index 4e7817a..fba0481 100644 --- a/paths_test.go +++ b/paths_test.go @@ -154,16 +154,13 @@ func TestResetStatCacheWhenFollowingSymlink(t *testing.T) { } func TestIsInsideDir(t *testing.T) { - inside := func(a, b *Path) { - in, err := a.IsInsideDir(b) - require.NoError(t, err) - require.True(t, in, "%s is inside %s", a, b) + notInside := func(a, b *Path) { + require.False(t, a.IsInsideDir(b), "%s is inside %s", a, b) } - notInside := func(a, b *Path) { - in, err := a.IsInsideDir(b) - require.NoError(t, err) - require.False(t, in, "%s is inside %s", a, b) + inside := func(a, b *Path) { + require.True(t, a.IsInsideDir(b), "%s is inside %s", a, b) + notInside(b, a) } f1 := New("/a/b/c") @@ -196,6 +193,14 @@ func TestIsInsideDir(t *testing.T) { f5 := New("/home/megabug/a15/packages") notInside(f5, f4) notInside(f4, f5) + + if runtime.GOOS == "windows" { + f6 := New("C:\\", "A") + f7 := New("C:\\", "A", "B", "C") + f8 := New("E:\\", "A", "B", "C") + inside(f7, f6) + notInside(f8, f6) + } } func TestReadFileAsLines(t *testing.T) { @@ -372,9 +377,7 @@ func TestWriteToTempFile(t *testing.T) { defer tmp.Remove() require.NoError(t, err) require.True(t, strings.HasPrefix(tmp.Base(), "prefix")) - inside, err := tmp.IsInsideDir(tmpDir) - require.NoError(t, err) - require.True(t, inside) + require.True(t, tmp.IsInsideDir(tmpDir)) data, err := tmp.ReadFile() require.NoError(t, err) require.Equal(t, tmpData, data)