use std::os::unix::ffi::OsStrExt; use std::path::Path; use crate::core; pub fn cwd_relative(root: &Path) -> Option { let current = std::env::current_dir().ok()?; let current = std::fs::canonicalize(current).ok()?; let root = std::fs::canonicalize(root).ok()?; if current == root { return Some(String::new()); } let relative = current.strip_prefix(&root).ok()?; Some(String::from_utf8_lossy(relative.as_os_str().as_bytes()).into_owned()) } fn normalize_components(input: &str) -> Option { let mut components: Vec<&str> = Vec::new(); let mut start = 0; for index in 0..=input.len() { let at_end = index == input.len(); if !at_end && input.as_bytes()[index] != b'/' { continue; } let component = &input[start..index]; if !component.is_empty() && component != "." { if component == ".." { if components.is_empty() { return None; } components.pop(); } else { components.push(component); } } start = index + 1; } Some(components.join("/")) } fn join_relative(base: &str, argument: &str) -> String { if base.is_empty() { argument.to_string() } else if argument.is_empty() { base.to_string() } else { format!("{base}/{argument}") } } pub fn pathspec_normalize(root: &Path, cwd_rel: &str, argument: &str) -> Option { if argument.is_empty() { return None; } if argument.starts_with('/') { let normalized = normalize_components(argument)?; let mut root_view = core::path_display(root); if root_view.starts_with('/') { root_view.remove(0); } if normalized.len() > root_view.len() && normalized.starts_with(&root_view) && normalized.as_bytes()[root_view.len()] == b'/' { return Some(normalized[root_view.len() + 1..].to_string()); } return None; } normalize_components(&join_relative(cwd_rel, argument)) } pub fn pathspec_has_glob(value: &str) -> bool { value.contains('*') || value.contains('?') }