Skip to content

Commit 4d50bea

Browse files
authored
uucore(fs): expand path normalization (#10532)
* uucore(fs): expand path normalization and add tests for edge cases * fs: improved path normalization
1 parent aee49f1 commit 4d50bea

File tree

1 file changed

+44
-2
lines changed
  • src/uucore/src/lib/features

1 file changed

+44
-2
lines changed

src/uucore/src/lib/features/fs.rs

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,13 +249,24 @@ pub fn normalize_path(path: &Path) -> PathBuf {
249249
}
250250
Component::CurDir => {}
251251
Component::ParentDir => {
252-
ret.pop();
252+
if ret.as_os_str().is_empty()
253+
|| matches!(ret.components().next_back(), Some(Component::ParentDir))
254+
{
255+
ret.push("..");
256+
} else {
257+
ret.pop();
258+
}
253259
}
254260
Component::Normal(c) => {
255261
ret.push(c);
256262
}
257263
}
258264
}
265+
266+
if ret.as_os_str().is_empty() {
267+
ret.push(".");
268+
}
269+
259270
ret
260271
}
261272

@@ -874,7 +885,38 @@ mod tests {
874885
test: &'a str,
875886
}
876887

877-
const NORMALIZE_PATH_TESTS: [NormalizePathTestCase; 8] = [
888+
const NORMALIZE_PATH_TESTS: [NormalizePathTestCase; 15] = [
889+
NormalizePathTestCase {
890+
path: "foo/bar/../..",
891+
test: ".",
892+
},
893+
NormalizePathTestCase {
894+
path: ".",
895+
test: ".",
896+
},
897+
// Should not try to eliminate leading .. components,
898+
// as it may point to a sibling of the current dir
899+
NormalizePathTestCase {
900+
path: "../foo",
901+
test: "../foo",
902+
},
903+
// Try to go down, then escape above current dir and back down again
904+
NormalizePathTestCase {
905+
path: "foo/../../../bar/baz",
906+
test: "../../bar/baz",
907+
},
908+
NormalizePathTestCase {
909+
path: "../../foo/..",
910+
test: "../..",
911+
},
912+
NormalizePathTestCase {
913+
path: "foo/../../..",
914+
test: "../..",
915+
},
916+
NormalizePathTestCase {
917+
path: "foo/bar/../../..",
918+
test: "..",
919+
},
878920
NormalizePathTestCase {
879921
path: "./foo/bar.txt",
880922
test: "foo/bar.txt",

0 commit comments

Comments
 (0)