Skip to content

Commit

Permalink
Simplify the implementation of WithinDirectory
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhuGongpu committed Jul 7, 2020
1 parent 07e86c4 commit d5d6d78
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 9 deletions.
13 changes: 5 additions & 8 deletions internal/util/pathutil/pathutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,12 @@ func IsInsideDir(path string, directory string) (isInside bool, err error) {
return
}

separator := string(os.PathSeparator)
// Trim the ending separator if any
directory = strings.TrimRight(directory, separator)
directoryWithSeparator := fmt.Sprintf("%s%s", directory, separator)
rel, err := filepath.Rel(directory, path)
if err != nil {
return false, err
}

isInside = path == directory || strings.HasPrefix(
path,
directoryWithSeparator,
)
isInside = rel == "." || !strings.HasPrefix(rel, ".")

return
}
2 changes: 1 addition & 1 deletion internal/util/pathutil/pathutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func TestIsInsideDirectory(t *testing.T) {
result, err = IsInsideDir(file, base)
assert.NilError(t, err)
assert.Equal(t, result, true)
result, err = IsInsideDir(path.Join(base, file), baseWithSeparator)
result, err = IsInsideDir(file, baseWithSeparator)
assert.NilError(t, err)
assert.Equal(t, result, true)
result, err = IsInsideDir(path.Join(base, ".."), base)
Expand Down

0 comments on commit d5d6d78

Please sign in to comment.