libc/utils: simplify CleanPath

This simplifies the code flow and basically removes the last
filepath.Clean, which is not necessary in either case:

 - for absolute path, single filepath.Clean is enough (as it is
   guaranteed to remove all dot and dot-dot elements);

 - for relative path, filepath.Rel calls Clean at the end
   (which is even documented).

Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
This commit is contained in:
Kir Kolyshkin
2025-02-12 19:56:00 -08:00
parent 35a28ad0a4
commit 8db6ffbeef
+5 -5
View File
@@ -50,19 +50,19 @@ func CleanPath(path string) string {
// Ensure that all paths are cleaned (especially problematic ones like
// "/../../../../../" which can cause lots of issues).
path = filepath.Clean(path)
if filepath.IsAbs(path) {
return filepath.Clean(path)
}
// If the path isn't absolute, we need to do more processing to fix paths
// such as "../../../../<etc>/some/path". We also shouldn't convert absolute
// paths to relative ones.
if !filepath.IsAbs(path) {
path = filepath.Clean(string(os.PathSeparator) + path)
// This can't fail, as (by definition) all paths are relative to root.
path, _ = filepath.Rel(string(os.PathSeparator), path)
}
// Clean the path again for good measure.
return filepath.Clean(path)
return path
}
// stripRoot returns the passed path, stripping the root path if it was