This commit is contained in:
@@ -198,3 +198,39 @@ func IsInternal(file string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Canonicalize checks that the file path is valid and returns it in the "canonical" form:
|
||||
// - /foo/bar -> foo/bar
|
||||
// - / -> "."
|
||||
func Canonicalize(file string) (string, error) {
|
||||
pathSep := string(PathSeparator)
|
||||
|
||||
if strings.HasPrefix(file, pathSep+pathSep) {
|
||||
// The relative path may pretend to be an absolute path within
|
||||
// the root, but the double path separator on Windows implies
|
||||
// something else and is out of spec.
|
||||
return "", ErrNotRelative
|
||||
}
|
||||
|
||||
// The relative path should be clean from internal dotdots and similar
|
||||
// funkyness.
|
||||
file = filepath.Clean(file)
|
||||
|
||||
// It is not acceptable to attempt to traverse upwards.
|
||||
switch file {
|
||||
case "..":
|
||||
return "", ErrNotRelative
|
||||
}
|
||||
if strings.HasPrefix(file, ".."+pathSep) {
|
||||
return "", ErrNotRelative
|
||||
}
|
||||
|
||||
if strings.HasPrefix(file, pathSep) {
|
||||
if file == pathSep {
|
||||
return ".", nil
|
||||
}
|
||||
return file[1:], nil
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user