use std::path::{Component, Path, PathBuf};
pub(crate) fn resolve_through_symlinks(path: &Path) -> Option<PathBuf> {
let mut result = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) | Component::RootDir => result.push(component.as_os_str()),
Component::CurDir => {}
Component::ParentDir => {
result.pop();
}
Component::Normal(name) => {
result.push(name);
if let Ok(real) = std::fs::canonicalize(&result) {
result = real;
}
}
}
}
if result.as_os_str().is_empty() {
None
} else {
Some(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_root(dir: &tempfile::TempDir) -> PathBuf {
std::fs::canonicalize(dir.path()).expect("tempdir canonicalizes")
}
#[test]
fn a_leaf_symlink_resolves_to_its_target() {
let dir = tempfile::tempdir().unwrap();
let root = temp_root(&dir);
let target = root.join("real.conf");
std::fs::write(&target, b"x").unwrap();
let link = root.join("link.conf");
std::os::unix::fs::symlink(&target, &link).unwrap();
assert_eq!(resolve_through_symlinks(&link), Some(target));
}
#[test]
fn a_symlinked_ancestor_resolves() {
let dir = tempfile::tempdir().unwrap();
let root = temp_root(&dir);
std::fs::create_dir_all(root.join("real/sub")).unwrap();
let file = root.join("real/sub/f.conf");
std::fs::write(&file, b"x").unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
assert_eq!(
resolve_through_symlinks(&root.join("link/sub/f.conf")),
Some(file)
);
}
#[test]
fn dotdot_folds_against_the_resolved_parent() {
let dir = tempfile::tempdir().unwrap();
let root = temp_root(&dir);
std::fs::create_dir(root.join("real")).unwrap();
let sibling = root.join("sibling.conf");
std::fs::write(&sibling, b"x").unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
assert_eq!(
resolve_through_symlinks(&root.join("link/../sibling.conf")),
Some(sibling)
);
}
#[test]
fn a_missing_tail_keeps_the_resolved_ancestors() {
let dir = tempfile::tempdir().unwrap();
let root = temp_root(&dir);
std::fs::create_dir(root.join("real")).unwrap();
std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
assert_eq!(
resolve_through_symlinks(&root.join("link/absent.conf")),
Some(root.join("real/absent.conf"))
);
}
#[test]
fn a_loop_yields_unresolved_text() {
let dir = tempfile::tempdir().unwrap();
let root = temp_root(&dir);
let first = root.join("first");
let second = root.join("second");
std::os::unix::fs::symlink(&second, &first).unwrap();
std::os::unix::fs::symlink(&first, &second).unwrap();
let resolved = resolve_through_symlinks(&first).expect("a non-empty path resolves");
assert!(
std::fs::symlink_metadata(&resolved)
.expect("the link node exists")
.file_type()
.is_symlink(),
"a loop leaves the result a symlink: {resolved:?}"
);
}
#[test]
fn an_empty_path_has_no_target() {
assert_eq!(resolve_through_symlinks(Path::new("")), None);
}
}