use std::path::{Path, PathBuf};
pub fn primary_root(roots: &[PathBuf]) -> PathBuf {
roots.first().cloned().unwrap_or_else(|| PathBuf::from("."))
}
pub fn resolve_path(root: &Path, path: PathBuf) -> PathBuf {
if path.is_absolute() { path } else { root.join(path) }
}
#[derive(Debug, thiserror::Error)]
#[error("file path is required and cannot be empty")]
pub struct EmptyFilePathError;
pub fn resolve_file(root: &Path, raw: &str) -> Result<PathBuf, EmptyFilePathError> {
if raw.trim().is_empty() {
return Err(EmptyFilePathError);
}
Ok(resolve_path(root, PathBuf::from(raw)))
}
pub fn resolve_dir(root: &Path, raw: Option<&str>) -> PathBuf {
match raw {
Some(raw) if !raw.trim().is_empty() => resolve_path(root, PathBuf::from(raw)),
_ => root.to_path_buf(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn primary_root_falls_back_to_dot_when_empty() {
assert_eq!(primary_root(&[]), PathBuf::from("."));
assert_eq!(primary_root(&[PathBuf::from("/a"), PathBuf::from("/b")]), PathBuf::from("/a"));
}
#[test]
fn resolves_relative_path_against_root() {
assert_eq!(
resolve_path(Path::new("/workspace"), PathBuf::from("src/main.rs")),
PathBuf::from("/workspace/src/main.rs")
);
}
#[test]
fn leaves_absolute_path_untouched() {
assert_eq!(resolve_path(Path::new("/workspace"), PathBuf::from("/etc/passwd")), PathBuf::from("/etc/passwd"));
}
#[test]
fn preserves_non_empty_file_path_text() {
let resolved = resolve_file(Path::new("/workspace"), " leading space.txt ").unwrap();
assert_eq!(resolved, PathBuf::from("/workspace/ leading space.txt "));
}
#[test]
fn rejects_whitespace_only_required_file_path() {
let err = resolve_file(Path::new("/workspace"), " \t ").unwrap_err();
assert!(err.to_string().contains("file path is required"));
}
#[test]
fn optional_empty_dir_resolves_to_root() {
assert_eq!(resolve_dir(Path::new("/workspace"), Some(" ")), PathBuf::from("/workspace"));
assert_eq!(resolve_dir(Path::new("/workspace"), None), PathBuf::from("/workspace"));
}
}