summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorA Farzat <a@farzat.xyz>2026-06-03 11:30:31 +0300
committerA Farzat <a@farzat.xyz>2026-06-03 11:30:31 +0300
commit921006d9321948b29df30c3785b16a81f622f451 (patch)
treefdaf3130123034c1ddae9083e115dbf8fd25234e
parenta2ccf993970284e2f19fcb74b66013a7dd6c7319 (diff)
downloadrepo2markdown-921006d9321948b29df30c3785b16a81f622f451.tar.gz
repo2markdown-921006d9321948b29df30c3785b16a81f622f451.zip
Make normalize_to_root return best-effort
The previous verion failed if recursive `root.parent()` reached an error, but thinking about it, if the two paths have different starting points (like Windows drives), then the desirable function would be to return the absolute target path as-is. Naturally, the current funtion gives a wrong output if the supplied arguments are not absolute, but that shall be enforced using a future test.
-rw-r--r--src/lib.rs19
1 files changed, 12 insertions, 7 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 9e9afcf..a78a767 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -26,13 +26,18 @@ pub fn normalize_path(root: &Path, origin: &Path, input: &Path) -> Result<PathBu
Ok(normalize_to_root(&normalized_origin_join_input, root))
}
-fn normalize_to_root(target_path: &Path, root: &Path,) -> PathBuf {
- match target_path.strip_prefix(root) {
- Ok(normalized_path) => normalized_path.to_path_buf(),
- Err(_) => {
- let root_parent = root.parent().expect("failed cuz target_path is not absolute");
- PathBuf::from("..").join(normalize_to_root(target_path, root_parent))
- },
+fn normalize_to_root(target: &Path, mut root: &Path) -> PathBuf {
+ let mut prefix = PathBuf::new();
+ loop {
+ if let Ok(suffix) = target.strip_prefix(root) {
+ return prefix.join(suffix);
+ }
+ if let Some(new_root) = root.parent() {
+ prefix.push("..");
+ root = new_root;
+ } else {
+ return target.to_path_buf();
+ }
}
}