use super::current_os;
pub(super) fn shield_spellings(path: &str) -> Vec<String> {
let mut out = vec![path.to_string()];
let mut offer = |p: String| {
if !out.contains(&p) {
out.push(p);
}
};
let on_data_volume = (current_os() == "macos").then(|| strip_prefix_could_be(path, "/System/Volumes/Data")).flatten();
for spelling in std::iter::once(path).chain(on_data_volume) {
offer(spelling.to_string());
if let Some(folded) = crate::engine::resolve::locus::firmlink_fold_case_insensitive(spelling) {
offer(folded);
}
if let Some(home) = home_fold_case_insensitive(spelling) {
offer(home);
}
}
out
}
pub(super) fn strip_prefix_could_be<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
let mut rest = path;
for want in prefix.split('/').filter(|c| !c.is_empty()) {
let after = rest.strip_prefix('/')?;
let end = after.find('/')?;
let component = &after[..end];
let fits = match super::unicode_spelling::wildcard_component(component) {
Some(pattern) => super::metadata::glob_may_match(&pattern, want),
None => component.eq_ignore_ascii_case(want),
};
if !fits {
return None;
}
rest = &after[end..];
}
Some(rest)
}
fn home_fold_case_insensitive(path: &str) -> Option<String> {
if current_os() != "macos" {
return None;
}
let home = crate::pathctx::home_dir().filter(|h| h.len() > 1)?;
let rest = strip_prefix_could_be(path, home.trim_end_matches('/'))?;
Some(format!("~{rest}"))
}
pub(crate) fn absolute_other_home(path: &str) -> bool {
let home = crate::pathctx::home_dir().unwrap_or_default();
let ours = home.rsplit_once('/').map(|(_, name)| name).unwrap_or_default();
let path = strip_prefix_could_be(path, "/System/Volumes/Data").unwrap_or(path);
["/Users", "/home"].iter().any(|parent| {
strip_prefix_could_be(path, parent)
.and_then(|r| r.strip_prefix('/'))
.and_then(|r| r.split('/').next())
.is_some_and(|user| !user.is_empty() && (ours.is_empty() || user != ours))
})
}
#[cfg(test)]
mod tests {
use super::strip_prefix_could_be;
use proptest::prelude::*;
proptest! {
#[test]
fn a_prefix_strips_in_any_case_only_at_a_component_boundary(
prefix in "(/[a-z]{1,6}){1,3}",
rest in "(/[a-zA-Z.]{1,6}){1,3}",
glued in "[a-z]{1,4}",
flips in prop::collection::vec(any::<bool>(), 24),
) {
let cased: String = prefix
.chars()
.zip(flips.iter().cycle())
.map(|(c, &up)| if up { c.to_ascii_uppercase() } else { c })
.collect();
let path = format!("{cased}{rest}");
prop_assert_eq!(strip_prefix_could_be(&path, &prefix), Some(rest.as_str()));
let longer = format!("{cased}{glued}{rest}");
prop_assert_eq!(strip_prefix_could_be(&longer, &prefix), None);
prop_assert_eq!(strip_prefix_could_be(&cased, &prefix), None);
}
}
}