Skip to content

Commit

Permalink
handle backslashes correctly
Browse files Browse the repository at this point in the history
Signed-off-by: Miguel Molina <[email protected]>
  • Loading branch information
erizocosmico committed May 20, 2019
1 parent 1e1a095 commit d42dde8
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions path_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import (
var RegMatchChars = regexp.MustCompile(`(^|[^\\])([*[?])`)

// StripPrefix removes the root path from the given path. Root may be a glob.
// The returned string has all backslashes replaced with slashes.
func StripPrefix(root, path string) (string, error) {
var err error
root, err = filepath.Abs(cleanGlob(root))
if err != nil {
return "", err
}

if !strings.HasSuffix(root, string(filepath.Separator)) {
if !strings.HasSuffix(root, "/") {
root += string(filepath.Separator)
}

Expand All @@ -28,21 +29,23 @@ func StripPrefix(root, path string) (string, error) {
return "", err
}

return strings.TrimPrefix(path, root), nil
return strings.TrimPrefix(filepath.ToSlash(path), root), nil
}

// cleanGlob removes all the parts of a glob that are not fixed.
// cleanGlob removes all the parts of a glob that are not fixed. It also
// converts all slashes or backslashes to /.
func cleanGlob(pattern string) string {
pattern = filepath.ToSlash(pattern)
var parts []string
for _, part := range strings.Split(pattern, string(filepath.Separator)) {
for _, part := range strings.Split(pattern, "/") {
if strings.ContainsAny(part, "*?[\\") {
break
}

parts = append(parts, part)
}

return strings.Join(parts, string(filepath.Separator))
return strings.Join(parts, "/")
}

// PatternMatches returns the paths matched and any error found.
Expand Down

0 comments on commit d42dde8

Please sign in to comment.