use std::path::{Path, PathBuf};
use super::out_paths::{warn_output_extension_mismatch, OutputKind};
#[cfg(doc)]
use super::stdio::write_output;
use mds::{effective_parent, MdsError};
use miette::Result;
#[derive(Clone, Copy)]
pub(crate) struct EntryPaths<'a> {
pub(crate) typed: &'a Path,
pub(crate) canonical: &'a Path,
}
impl<'a> EntryPaths<'a> {
pub(crate) fn as_typed(path: &'a Path) -> Self {
Self {
typed: path,
canonical: path,
}
}
}
fn file_identity(path: &Path) -> Option<PathBuf> {
let name = path.file_name()?;
let file = resolve_dir_as_created(effective_parent(path))?.join(name);
let is_link = std::fs::symlink_metadata(&file).is_ok_and(|m| m.file_type().is_symlink());
if !is_link {
if let Ok(canonical) = file.canonicalize() {
return Some(canonical);
}
}
Some(file)
}
pub(crate) fn resolve_dir_as_created(dir: &Path) -> Option<PathBuf> {
use std::path::Component;
if let Ok(canonical) = dir.canonicalize() {
return Some(canonical);
}
let absolute = std::path::absolute(dir).ok()?;
let mut resolved = PathBuf::new();
let mut created: usize = 0;
for component in absolute.components() {
match component {
Component::Prefix(_) | Component::RootDir => resolved.push(component),
Component::CurDir => {}
Component::ParentDir => {
resolved.pop();
created = created.saturating_sub(1);
}
Component::Normal(name) => {
let next = resolved.join(name);
if created > 0 {
resolved = next;
created += 1;
} else if let Ok(existing) = next.canonicalize() {
resolved = existing;
} else {
resolved = next;
created = 1;
}
}
}
}
Some(resolved)
}
fn refuse_output_over_entry(output: Option<&Path>, entry: EntryPaths<'_>) -> Result<(), MdsError> {
let Some(output) = output else {
return Ok(());
};
match (file_identity(output), file_identity(entry.canonical)) {
(Some(output), Some(canonical)) if output == canonical => Err(MdsError::Io {
message: format!(
"output would overwrite the entry file: \"{}\"; \
write it elsewhere with -o <file> or --out-dir <dir>",
mds::escape_path_for_message(&entry.typed.to_string_lossy())
),
}),
_ => Ok(()),
}
}
pub(crate) fn admit_output(
output_path: Option<&Path>,
entry: EntryPaths<'_>,
output_arg: &Option<String>,
kind: OutputKind,
quiet: bool,
) -> Result<(), MdsError> {
refuse_output_over_entry(output_path, entry)?;
warn_output_extension_mismatch(output_arg, kind, quiet);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn admit_output_refuses_naming_the_entry_as_typed() {
let dir = tempfile::TempDir::new().unwrap();
std::fs::create_dir(dir.path().join("sub")).unwrap();
std::fs::write(dir.path().join("page.md"), "x").unwrap();
let typed = dir.path().join("sub").join("..").join("page.md");
let canonical = dir.path().join("page.md").canonicalize().unwrap();
let entry = EntryPaths {
typed: &typed,
canonical: &canonical,
};
let admit = |output: Option<&Path>| {
admit_output(output, entry, &None, OutputKind::Markdown, true)
.map_err(|e| e.to_string())
};
let refused = admit(Some(&canonical)).unwrap_err();
assert_eq!(
refused,
format!(
"output would overwrite the entry file: \"{}\"; \
write it elsewhere with -o <file> or --out-dir <dir>",
typed.display()
)
);
assert!(
!refused.contains(&*canonical.to_string_lossy()),
"{refused}"
);
assert_eq!(
admit(Some(&dir.path().join("sub").join("..").join("page.md"))),
Err(refused),
"another spelling of the entry is the entry"
);
assert_eq!(admit(Some(&dir.path().join("out.md"))), Ok(()), "control");
assert_eq!(admit(None), Ok(()), "stdout is never the entry");
}
#[test]
fn file_identity_resolves_a_directory_the_write_creates() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::write(root.join("page.md"), "x").unwrap();
let page = root.join("page.md");
let case_insensitive = root.join("PAGE.md").exists();
let variant = if case_insensitive {
page.clone()
} else {
root.join("PAGE.md")
};
let rows = [
("page.md", page.clone()),
("sub/../page.md", page.clone()),
("newdir/../page.md", page.clone()),
("a/b/../../page.md", page.clone()),
("sub/new/../../page.md", page.clone()),
("new/./x/../../page.md", page.clone()),
("newdir/page.md", root.join("newdir").join("page.md")),
(
"sub/new/page.md",
root.join("sub").join("new").join("page.md"),
),
("PAGE.md", variant.clone()),
("newdir/../PAGE.md", variant.clone()),
("a/b/../../PAGE.md", variant),
];
let mismatches: Vec<String> = rows
.iter()
.filter_map(|(rel, expected)| {
let got = file_identity(&dir.path().join(rel));
(got.as_ref() != Some(expected)).then(|| format!("{rel}: {got:?}"))
})
.collect();
assert!(mismatches.is_empty(), "{mismatches:#?}");
#[cfg(unix)]
{
std::os::unix::fs::symlink(&root, root.join("lnk")).unwrap();
assert_eq!(
file_identity(&dir.path().join("newdir/../lnk/page.md")),
Some(page.clone())
);
}
assert!(!root.join("newdir").exists() && !root.join("a").exists());
}
}