use std::path::{Path, PathBuf};
use mds::MdsError;
pub(crate) fn resolve_directory_argument(typed: &Path) -> Result<PathBuf, MdsError> {
let canonical = mds::NativeFs::check_directory(typed).map_err(|e| match e {
MdsError::ImportError { .. } => refusal(typed, "must not be a symlink"),
other => other,
})?;
if is_filesystem_root(&canonical) {
return Err(refusal(typed, "must not be the filesystem root"));
}
Ok(canonical)
}
fn is_filesystem_root(path: &Path) -> bool {
path.has_root() && path.parent().is_none()
}
fn refusal(typed: &Path, rule: &str) -> MdsError {
MdsError::Io {
message: format!(
"directory argument {rule}: \"{}\"",
mds::escape_path_for_message(&typed.to_string_lossy())
),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filesystem_root_predicate_covers_every_root_form() {
let mut rows: Vec<(&str, bool)> = vec![
("", false),
(".", false),
("..", false),
("src", false),
("./src", false),
("sub/..", false),
];
#[cfg(unix)]
rows.extend([("/", true), ("/src", false), ("/src/..", false)]);
#[cfg(windows)]
rows.extend([
(r"C:\", true),
(r"\\?\C:\", true),
(r"\\server\share", true),
(r"\\server\share\", true),
(r"\\?\UNC\server\share", true),
(r"C:", false),
(r"C:\src", false),
(r"\\?\C:\src", false),
(r"\\server\share\src", false),
]);
for (path, expected) in rows {
assert_eq!(is_filesystem_root(Path::new(path)), expected, "{path:?}");
}
}
#[test]
fn resolve_directory_argument_takes_every_path_shape() {
let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
.canonicalize()
.unwrap();
for (typed, expected) in [
(".", crate_dir.clone()),
("./", crate_dir.clone()),
("src/..", crate_dir.clone()),
("..", crate_dir.parent().unwrap().to_path_buf()),
("src", crate_dir.join("src")),
("src/", crate_dir.join("src")),
] {
let canonical = resolve_directory_argument(Path::new(typed))
.unwrap_or_else(|e| panic!("{typed:?}: {e}"));
assert_eq!(canonical, expected, "{typed:?}");
}
let err = resolve_directory_argument(Path::new("")).unwrap_err();
assert!(
matches!(&err, MdsError::FileNotFound { path, .. } if path.is_empty()),
"the empty path: {err:?}"
);
let root = crate_dir.ancestors().last().unwrap();
let err = resolve_directory_argument(root).unwrap_err();
assert_eq!(
err.to_string(),
format!(
"directory argument must not be the filesystem root: \"{}\"",
root.display()
)
);
}
#[test]
fn resolve_directory_argument_refuses_a_forbidden_character_as_typed() {
let typed = format!("no-such-dir{}x", '\u{1b}');
let err = resolve_directory_argument(Path::new(&typed)).unwrap_err();
assert_eq!(
err.to_string(),
format!(
"path contains forbidden character U+001B: \"no-such-dir{}u001Bx\"",
'\\'
)
);
}
}