use std::borrow::Cow;
use std::ffi::OsStr;
use std::io::{IsTerminal, Write as _};
use std::path::{Path, PathBuf};
use miette::Result;
use crate::build::{MdsConfig, OutputKind};
pub(crate) const STDIN_DISPLAY_LABEL: &str = "<stdin>";
pub(crate) struct StdinRelabeledError {
inner: mds::MdsError,
source: Option<miette::NamedSource<String>>,
}
impl StdinRelabeledError {
pub(crate) fn inner(&self) -> &mds::MdsError {
&self.inner
}
}
impl std::fmt::Display for StdinRelabeledError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.inner, f)
}
}
impl std::fmt::Debug for StdinRelabeledError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.inner, f)
}
}
impl std::error::Error for StdinRelabeledError {}
impl miette::Diagnostic for StdinRelabeledError {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
miette::Diagnostic::code(&self.inner)
}
fn severity(&self) -> Option<miette::Severity> {
miette::Diagnostic::severity(&self.inner)
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
miette::Diagnostic::help(&self.inner)
}
fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
miette::Diagnostic::url(&self.inner)
}
fn labels<'a>(&'a self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + 'a>> {
miette::Diagnostic::labels(&self.inner)
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
match &self.source {
Some(ns) => Some(ns as &dyn miette::SourceCode),
None => miette::Diagnostic::source_code(&self.inner),
}
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
miette::Diagnostic::related(&self.inner)
}
fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
miette::Diagnostic::diagnostic_source(&self.inner)
}
}
pub(crate) fn relabel_stdin_error(e: &mds::MdsError, source: &str) -> miette::Report {
miette::Report::new(StdinRelabeledError {
source: if e.is_string_source() {
miette::Diagnostic::source_code(e)
.map(|_| mds::named_source_for_render(STDIN_DISPLAY_LABEL, source))
} else {
None
},
inner: e.clone(),
})
}
#[derive(Debug, Clone)]
pub(crate) enum OutputBase {
Dir(PathBuf),
NextToSource,
}
pub(crate) fn canonicalize_out_dir(out_dir: Option<&PathBuf>) -> Option<PathBuf> {
out_dir.map(|d| {
let abs = if d.is_absolute() {
d.clone()
} else {
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(d)
};
abs.canonicalize().unwrap_or(abs)
})
}
pub(crate) fn resolve_output_base(
abs_out_dir: Option<&Path>,
config: &Option<(MdsConfig, PathBuf)>,
) -> Result<OutputBase> {
if let Some(d) = abs_out_dir {
return Ok(OutputBase::Dir(d.to_path_buf()));
}
if let Some((cfg, config_dir)) = config {
if let Some(ref output_dir) = cfg.build.output_dir {
let traversal = Path::new(output_dir)
.components()
.any(|c| c == std::path::Component::ParentDir);
if traversal {
return Err(miette::miette!(
"mds.json output_dir '{}' must not contain '..' components",
output_dir
));
}
return Ok(OutputBase::Dir(config_dir.join(output_dir)));
}
}
Ok(OutputBase::NextToSource)
}
pub(crate) fn output_path_for(source: &Path, root: &Path, base: &OutputBase, ext: &str) -> PathBuf {
match base {
OutputBase::Dir(d) => {
let mirrored = mirror_stem(source, root, d);
let flattened = matches!(mirrored, MirroredStem::Flattened(_));
let no_ext = mirrored.into_path();
let mut name = no_ext
.file_name()
.unwrap_or_else(|| OsStr::new("output"))
.to_os_string();
name.push(".");
name.push(ext);
let out = no_ext.parent().unwrap_or(d.as_path()).join(&name);
let out = if out.starts_with(d) {
out
} else {
debug_assert!(
false,
"output_path_for: AC-M7 violated — output {out:?} escaped out-dir {d:?}"
);
let flat_name = {
let mut n = source
.file_stem()
.unwrap_or_else(|| OsStr::new("output"))
.to_os_string();
n.push(".");
n.push(ext);
n
};
d.join(flat_name)
};
if flattened {
eprint_warning(&format!(
"warning: {} is outside the build root {}; its output is written flat \
as {} (another source outside the root with the same file name would \
overwrite it)",
safe_path(source),
safe_path(root),
safe_path(&out)
));
}
out
}
OutputBase::NextToSource => output_base_no_ext(source, root, base).with_extension(ext),
}
}
pub(crate) struct WalkResult {
pub files: Vec<PathBuf>,
pub excluded_by_default: usize,
}
pub(crate) fn collect_mds_files_detailed(
root: &Path,
max_depth: usize,
exclude_prefix: Option<&Path>,
) -> WalkResult {
let mut files = Vec::new();
let mut excluded_by_default = 0;
collect_mds_files_inner(
root,
0,
max_depth,
exclude_prefix,
&mut files,
&mut excluded_by_default,
);
WalkResult {
files,
excluded_by_default,
}
}
pub(crate) fn collect_mds_files(
root: &Path,
max_depth: usize,
exclude_prefix: Option<&Path>,
) -> Vec<PathBuf> {
collect_mds_files_detailed(root, max_depth, exclude_prefix).files
}
pub(crate) fn is_default_excluded_dir(name: &str) -> bool {
name.starts_with('.') || name == "node_modules"
}
pub(crate) fn is_within_default_excluded_dir(root: &Path, path: &Path) -> bool {
let rel = match path.strip_prefix(root) {
Err(_) => return false,
Ok(r) => r,
};
let mut ancestor = rel.parent();
while let Some(dir) = ancestor {
if let Some(name) = dir.file_name().and_then(|n| n.to_str()) {
if is_default_excluded_dir(name) {
return true;
}
}
ancestor = dir.parent();
}
false
}
fn collect_mds_files_inner(
dir: &Path,
depth: usize,
max_depth: usize,
exclude_prefix: Option<&Path>,
results: &mut Vec<PathBuf>,
excluded_count: &mut usize,
) {
if depth > max_depth {
eprint_warning(&format!(
"warning: directory depth limit ({max_depth}) reached at {}; \
deeper files will not be processed",
safe_path(dir)
));
return;
}
let read_dir = match std::fs::read_dir(dir) {
Ok(rd) => rd,
Err(_) => return,
};
for entry in read_dir.flatten() {
let path = entry.path();
if let Some(excl) = exclude_prefix {
if path.starts_with(excl) {
continue;
}
}
let file_type = match entry.file_type() {
Ok(ft) => ft,
Err(_) => continue,
};
if file_type.is_symlink() {
continue;
}
if file_type.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if is_default_excluded_dir(name) {
count_mds_in_excluded_dir(&path, depth + 1, max_depth, excluded_count);
continue;
}
}
collect_mds_files_inner(
&path,
depth + 1,
max_depth,
exclude_prefix,
results,
excluded_count,
);
} else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds") {
results.push(path);
}
}
}
fn count_mds_in_excluded_dir(dir: &Path, depth: usize, max_depth: usize, count: &mut usize) {
if depth > max_depth {
return;
}
let Ok(rd) = std::fs::read_dir(dir) else {
return;
};
for entry in rd.flatten() {
let path = entry.path();
let Ok(ft) = entry.file_type() else { continue };
if ft.is_symlink() {
continue;
}
if ft.is_dir() {
count_mds_in_excluded_dir(&path, depth + 1, max_depth, count);
} else if ft.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds") {
*count += 1;
}
}
}
pub(crate) fn is_partial(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
.map(|s| s.starts_with('_'))
.unwrap_or(false)
}
pub(crate) fn partials_only(files: &[PathBuf]) -> Option<usize> {
if files.is_empty() {
return None;
}
files.iter().all(|f| is_partial(f)).then_some(files.len())
}
pub(crate) fn probe_and_remove_stale(base_no_ext: &Path, kind: OutputKind) {
let stale_ext = kind.stale_extension();
let stale_path = base_no_ext.with_extension(stale_ext);
if stale_path.exists() {
match std::fs::remove_file(&stale_path) {
Ok(()) => {
}
Err(e) => {
eprint_warning(&format!(
"warning: could not remove stale output {}: {}",
safe_path(&stale_path),
safe_inline(&e)
));
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum MirroredStem {
Mirrored(PathBuf),
Flattened(PathBuf),
}
impl MirroredStem {
pub(crate) fn into_path(self) -> PathBuf {
match self {
Self::Mirrored(p) | Self::Flattened(p) => p,
}
}
}
fn mirror_stem(source: &Path, root: &Path, d: &Path) -> MirroredStem {
match source.strip_prefix(root) {
Ok(rel) => {
let stem = rel.file_stem().unwrap_or(rel.as_os_str()).to_os_string();
MirroredStem::Mirrored(d.join(rel.parent().unwrap_or(Path::new(""))).join(stem))
}
Err(_) => {
let stem = source.file_stem().unwrap_or_else(|| OsStr::new("output"));
MirroredStem::Flattened(d.join(stem))
}
}
}
pub(crate) fn output_base_no_ext(source: &Path, root: &Path, base: &OutputBase) -> PathBuf {
match base {
OutputBase::Dir(d) => mirror_stem(source, root, d).into_path(),
OutputBase::NextToSource => {
source.with_extension("")
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Durability {
Fsync,
RenameOnly,
}
pub(crate) fn atomic_write_file(path: &Path, content: &str, durability: Durability) -> Result<()> {
use mds::{effective_parent, NativeFs};
let parent = effective_parent(path);
let existing = match path.symlink_metadata() {
Ok(m) => Some(m),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(miette::miette!("cannot stat {}: {e}", path.display())),
};
if let Some(m) = &existing {
if m.file_type().is_symlink() {
return Err(miette::miette!(
"cannot write {}: refusing to replace a symlink",
path.display()
));
}
NativeFs::check_symlink(path)
.map_err(|e| miette::miette!("cannot write {}: {e}", path.display()))?;
}
#[cfg(unix)]
let original_mode: Option<u32> = {
use std::os::unix::fs::PermissionsExt as _;
existing.as_ref().map(|m| m.permissions().mode())
};
let mut builder = tempfile::Builder::new();
builder.prefix(".mds-tmp-").suffix(".tmp");
#[cfg(unix)]
if original_mode.is_none() {
use std::os::unix::fs::PermissionsExt as _;
builder.permissions(std::fs::Permissions::from_mode(0o666));
}
let mut tmp = builder
.tempfile_in(parent)
.map_err(|e| miette::miette!("cannot create temp file for {}: {e}", path.display()))?;
#[cfg(unix)]
if let Some(mode) = original_mode {
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(mode & 0o7777))
.map_err(|e| {
miette::miette!(
"cannot set permissions on temp file for {}: {e}",
path.display()
)
})?;
}
tmp.write_all(content.as_bytes())
.map_err(|e| miette::miette!("cannot write {}: {e}", path.display()))?;
if durability == Durability::Fsync {
tmp.as_file()
.sync_all()
.map_err(|e| miette::miette!("cannot fsync {}: {e}", path.display()))?;
}
tmp.persist(path)
.map_err(|e| miette::miette!("cannot rename temp file to {}: {e}", path.display()))?;
Ok(())
}
pub(crate) use mds::neutralize_source_for_render;
struct SanitizedReport {
inner: miette::Report,
message: String,
help: Option<String>,
source: Option<SanitizedNode>,
related: Vec<SanitizedNode>,
diagnostic_source: Option<SanitizedNode>,
}
const MAX_AUX_DEPTH: usize = 16;
struct SanitizedNode {
message: String,
help: Option<String>,
code: Option<String>,
url: Option<String>,
severity: Option<miette::Severity>,
labels: Option<Vec<miette::LabeledSpan>>,
source: Option<Box<SanitizedNode>>,
related: Vec<SanitizedNode>,
diagnostic_source: Option<Box<SanitizedNode>>,
}
fn escape_display(d: Option<Box<dyn std::fmt::Display + '_>>) -> Option<String> {
d.map(|v| mds::sanitize_control_chars(&v.to_string()).into_owned())
}
fn escape_labels(d: &dyn miette::Diagnostic) -> Option<Vec<miette::LabeledSpan>> {
Some(
d.labels()?
.map(|label| {
let text = label
.label()
.map(|t| mds::sanitize_control_chars(t).into_owned());
let span = *label.inner();
if label.primary() {
miette::LabeledSpan::new_primary_with_span(text, span)
} else {
miette::LabeledSpan::new_with_span(text, span)
}
})
.collect(),
)
}
impl SanitizedNode {
fn from_diagnostic(d: &dyn miette::Diagnostic, depth: usize) -> Self {
Self {
message: mds::sanitize_control_chars(&d.to_string()).into_owned(),
help: escape_display(d.help()),
code: escape_display(d.code()),
url: escape_display(d.url()),
severity: d.severity(),
labels: escape_labels(d),
source: Self::chain_from_error(std::error::Error::source(d), depth),
related: Self::related_from(d, depth),
diagnostic_source: Self::boxed_from_diagnostic(d.diagnostic_source(), depth),
}
}
fn from_error(e: &(dyn std::error::Error + 'static), depth: usize) -> Self {
Self {
message: mds::sanitize_control_chars(&e.to_string()).into_owned(),
help: None,
code: None,
url: None,
severity: None,
labels: None,
source: Self::chain_from_error(e.source(), depth),
related: Vec::new(),
diagnostic_source: None,
}
}
fn chain_from_error(
e: Option<&(dyn std::error::Error + 'static)>,
depth: usize,
) -> Option<Box<SanitizedNode>> {
if depth >= MAX_AUX_DEPTH {
return None;
}
e.map(|e| Box::new(Self::from_error(e, depth + 1)))
}
fn boxed_from_diagnostic(
d: Option<&dyn miette::Diagnostic>,
depth: usize,
) -> Option<Box<SanitizedNode>> {
if depth >= MAX_AUX_DEPTH {
return None;
}
d.map(|d| Box::new(Self::from_diagnostic(d, depth + 1)))
}
fn related_from(d: &dyn miette::Diagnostic, depth: usize) -> Vec<SanitizedNode> {
if depth >= MAX_AUX_DEPTH {
return Vec::new();
}
d.related()
.map(|rs| {
rs.map(|r| SanitizedNode::from_diagnostic(r, depth + 1))
.collect()
})
.unwrap_or_default()
}
}
impl std::fmt::Display for SanitizedNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::fmt::Debug for SanitizedNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SanitizedNode")
.field("message", &self.message)
.field("help", &self.help)
.finish_non_exhaustive()
}
}
impl std::error::Error for SanitizedNode {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|n| n as &(dyn std::error::Error + 'static))
}
}
impl miette::Diagnostic for SanitizedNode {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
boxed_str(self.code.as_deref())
}
fn severity(&self) -> Option<miette::Severity> {
self.severity
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
boxed_str(self.help.as_deref())
}
fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
boxed_str(self.url.as_deref())
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
Some(Box::new(self.labels.as_ref()?.iter().cloned()))
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
related_iter(&self.related)
}
fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
self.diagnostic_source
.as_deref()
.map(|n| n as &dyn miette::Diagnostic)
}
}
fn boxed_str(s: Option<&str>) -> Option<Box<dyn std::fmt::Display + '_>> {
s.map(|s| -> Box<dyn std::fmt::Display + '_> { Box::new(s) })
}
fn related_iter(
nodes: &[SanitizedNode],
) -> Option<Box<dyn Iterator<Item = &dyn miette::Diagnostic> + '_>> {
if nodes.is_empty() {
return None;
}
Some(Box::new(nodes.iter().map(|n| n as &dyn miette::Diagnostic)))
}
impl SanitizedReport {
fn new(inner: miette::Report) -> Self {
let message = mds::sanitize_control_chars(&inner.to_string()).into_owned();
let help = escape_display(inner.help());
let source = SanitizedNode::chain_from_error(std::error::Error::source(&*inner), 0)
.map(|boxed| *boxed);
let related = SanitizedNode::related_from(inner.as_ref(), 0);
let diagnostic_source =
SanitizedNode::boxed_from_diagnostic(inner.diagnostic_source(), 0).map(|boxed| *boxed);
Self {
inner,
message,
help,
source,
related,
diagnostic_source,
}
}
}
impl std::fmt::Display for SanitizedReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::fmt::Debug for SanitizedReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SanitizedReport")
.field("message", &self.message)
.field("help", &self.help)
.finish_non_exhaustive()
}
}
impl std::error::Error for SanitizedReport {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_ref()
.map(|n| n as &(dyn std::error::Error + 'static))
}
}
impl miette::Diagnostic for SanitizedReport {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
self.inner.code()
}
fn severity(&self) -> Option<miette::Severity> {
self.inner.severity()
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
boxed_str(self.help.as_deref())
}
fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
self.inner.url()
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
self.inner.source_code()
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
Some(Box::new(escape_labels(self.inner.as_ref())?.into_iter()))
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
related_iter(&self.related)
}
fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
self.diagnostic_source
.as_ref()
.map(|n| n as &dyn miette::Diagnostic)
}
}
fn sanitize_report(report: miette::Report) -> miette::Report {
miette::Report::new(SanitizedReport::new(report))
}
fn render_error_sanitized(report: miette::Report) -> String {
let report = sanitize_report(report);
format!("{report:?}")
}
pub(crate) fn eprint_error(report: miette::Report) {
eprintln!("{}", render_error_sanitized(report));
}
pub(crate) fn eprint_warning(w: &str) {
eprintln!("{}", mds::sanitize_control_chars(w));
}
#[must_use]
pub(crate) fn preview_text_for(writer_is_tty: bool, text: &str) -> Cow<'_, str> {
if writer_is_tty {
neutralize_source_for_render(text)
} else {
Cow::Borrowed(text)
}
}
#[must_use]
pub(crate) fn render_unified_diff(original: &str, modified: &str, label: &str) -> String {
let is_tty = std::io::stdout().is_terminal();
let original = preview_text_for(is_tty, original);
let modified = preview_text_for(is_tty, modified);
let diff = similar::TextDiff::from_lines(original.as_ref(), modified.as_ref());
let unified = diff
.unified_diff()
.context_radius(3)
.header(label, label)
.to_string();
if unified.is_empty() || !is_tty {
return unified;
}
colorize_unified_diff(&unified)
}
pub(crate) fn colorize_unified_diff(unified: &str) -> String {
const RED: &str = "\x1b[31m";
const GREEN: &str = "\x1b[32m";
const CYAN: &str = "\x1b[36m";
const RESET: &str = "\x1b[0m";
let mut out = String::with_capacity(unified.len() + 64);
let mut in_hunk = false;
for line in unified.split_inclusive('\n') {
let color = if line.starts_with("@@") {
in_hunk = true;
CYAN
} else if !in_hunk && (line.starts_with("---") || line.starts_with("+++")) {
CYAN
} else if in_hunk && line.starts_with('+') {
GREEN
} else if in_hunk && line.starts_with('-') {
RED
} else {
""
};
if color.is_empty() {
out.push_str(line);
continue;
}
out.push_str(color);
match line.strip_suffix('\n') {
Some(stripped) => {
out.push_str(stripped);
out.push_str(RESET);
out.push('\n');
}
None => {
out.push_str(line);
out.push_str(RESET);
}
}
}
out
}
pub(crate) fn safe_path(p: &std::path::Path) -> String {
safe_inline(p.display())
}
pub(crate) fn safe_file_display(name: &str) -> String {
safe_inline(name)
}
pub(crate) fn safe_inline(value: impl std::fmt::Display) -> String {
mds::sanitize_control_chars_wire(&value.to_string()).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn output_path_for_json_extension_dir_mode() {
let source = PathBuf::from("/root/src/chat.mds");
let root = PathBuf::from("/root");
let base = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "json");
assert_eq!(result, PathBuf::from("/out/src/chat.json"));
}
#[test]
fn output_path_for_md_extension_dir_mode() {
let source = PathBuf::from("/root/src/page.mds");
let root = PathBuf::from("/root");
let base = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "md");
assert_eq!(result, PathBuf::from("/out/src/page.md"));
}
#[test]
fn output_path_for_next_to_source() {
let source = PathBuf::from("/root/src/page.mds");
let root = PathBuf::from("/root");
let base = OutputBase::NextToSource;
let result = output_path_for(&source, &root, &base, "md");
assert_eq!(result, PathBuf::from("/root/src/page.md"));
}
#[test]
fn output_path_for_next_to_source_json() {
let source = PathBuf::from("/root/src/chat.mds");
let root = PathBuf::from("/root");
let base = OutputBase::NextToSource;
let result = output_path_for(&source, &root, &base, "json");
assert_eq!(result, PathBuf::from("/root/src/chat.json"));
}
#[test]
fn output_path_for_outside_root_falls_back_to_flat() {
let source = PathBuf::from("/other/page.mds");
let root = PathBuf::from("/root");
let base = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "md");
assert!(
result.starts_with("/out"),
"output must be inside /out; got {result:?}"
);
assert_eq!(result, PathBuf::from("/out/page.md"));
}
fn fn_body(src: &str, header: &str) -> Option<String> {
let start = src.find(header)?;
let open = start + src[start..].find('{')?;
let mut depth = 0usize;
for (i, c) in src[open..].char_indices() {
match c {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some(src[open..open + i + 1].to_string());
}
}
_ => {}
}
}
None
}
#[test]
fn mirror_stem_classifies_out_of_root_as_flattened() {
assert_eq!(
mirror_stem(
Path::new("/other/page.mds"),
Path::new("/root"),
Path::new("/out"),
),
MirroredStem::Flattened(PathBuf::from("/out/page")),
"a source outside the root loses its subtree and must say so"
);
assert_eq!(
mirror_stem(
Path::new("/root/a/page.mds"),
Path::new("/root"),
Path::new("/out"),
),
MirroredStem::Mirrored(PathBuf::from("/out/a/page")),
"a source below the root keeps its subtree and must NOT be reported"
);
}
#[test]
fn stemless_source_never_escapes_out_dir() {
let source = Path::new("/");
let root = Path::new("/root");
let base = OutputBase::Dir(PathBuf::from("/out"));
assert_eq!(
output_base_no_ext(source, root, &base),
PathBuf::from("/out/output"),
"the probe oracle must keep a stem-less source inside the out-dir"
);
assert_eq!(
output_path_for(source, root, &base, "md"),
PathBuf::from("/out/output.md"),
"the write oracle must not join an absolute stem"
);
}
#[test]
fn flatten_warning_lives_in_the_write_oracle_only() {
const SRC: &str = include_str!("output.rs");
const NEEDLE: &str = "is outside the build root";
let oracle = fn_body(SRC, "fn output_path_for(")
.expect("non-vacuity: fn output_path_for must be present in this file");
let probe = fn_body(SRC, "fn output_base_no_ext(")
.expect("non-vacuity: fn output_base_no_ext must be present in this file");
assert!(
oracle.contains("eprint_warning("),
"the write oracle must report the flattened arm; body: {oracle}"
);
assert!(
oracle.contains(NEEDLE),
"the write oracle's report must name the out-of-root condition; body: {oracle}"
);
assert!(
!probe.contains("eprint_warning("),
"the probe oracle must stay silent — it runs on bookkeeping, not on writes; \
body: {probe}"
);
assert!(
!probe.contains(NEEDLE),
"the probe oracle must not carry the report text either; body: {probe}"
);
}
#[test]
fn collect_mds_files_ignores_write_atomic_temp_names() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("t.mds"), "real").unwrap();
std::fs::write(dir.path().join(".t.mds.tmp-4242-7"), "in flight").unwrap();
let files = collect_mds_files(dir.path(), 64, None);
assert_eq!(files.len(), 1, "temp file must not be collected: {files:?}");
std::fs::write(dir.path().join(".tmp-4242-8.t.mds"), "wrong shape").unwrap();
assert_eq!(collect_mds_files(dir.path(), 64, None).len(), 2);
}
#[test]
fn is_partial_detects_underscore_prefix() {
assert!(is_partial(Path::new("/dir/_partial.mds")));
assert!(!is_partial(Path::new("/dir/main.mds")));
assert!(!is_partial(Path::new("/dir/not_partial.mds")));
}
#[test]
fn partials_only_answers() {
assert_eq!(partials_only(&[]), None);
assert_eq!(partials_only(&[PathBuf::from("_a.mds")]), Some(1));
assert_eq!(
partials_only(&[PathBuf::from("_a.mds"), PathBuf::from("b.mds")]),
None
);
assert_eq!(
partials_only(&[PathBuf::from("_a.mds"), PathBuf::from("_b.mds")]),
Some(2)
);
}
#[test]
fn hidden_dir_is_excluded() {
assert!(is_default_excluded_dir(".git"));
assert!(is_default_excluded_dir(".cache"));
assert!(is_default_excluded_dir(".hidden"));
}
#[test]
fn node_modules_is_excluded() {
assert!(is_default_excluded_dir("node_modules"));
}
#[test]
fn ordinary_dirs_are_not_excluded() {
assert!(!is_default_excluded_dir("src"));
assert!(!is_default_excluded_dir("prompts"));
assert!(!is_default_excluded_dir("templates"));
}
#[test]
fn path_inside_node_modules_is_excluded() {
assert!(is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/node_modules/foo.mds")
));
}
#[test]
fn path_inside_git_dir_is_excluded() {
assert!(is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/.git/config")
));
}
#[test]
fn path_inside_hidden_subdir_is_excluded() {
assert!(is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/.cache/something.mds")
));
}
#[test]
fn normal_path_under_root_is_not_excluded() {
assert!(!is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/src/main.mds")
));
}
#[test]
fn hidden_file_at_root_level_is_not_excluded() {
assert!(!is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/.dotfile.mds")
));
}
#[test]
fn path_outside_root_is_not_excluded() {
assert!(!is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/other/node_modules/foo.mds")
));
}
#[test]
fn walker_skips_node_modules_subdir() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
let nm = dir.path().join("node_modules");
std::fs::create_dir(&nm).unwrap();
std::fs::write(nm.join("lib.mds"), "lib").unwrap();
let files = collect_mds_files(dir.path(), 64, None);
assert_eq!(
files.len(),
1,
"node_modules/lib.mds should be excluded; found: {files:?}"
);
assert!(files[0].ends_with("main.mds"));
}
#[test]
fn walker_skips_hidden_subdir() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
let hidden = dir.path().join(".git");
std::fs::create_dir(&hidden).unwrap();
std::fs::write(hidden.join("config.mds"), "not a real file").unwrap();
let files = collect_mds_files(dir.path(), 64, None);
assert_eq!(
files.len(),
1,
".git/*.mds should be excluded; found: {files:?}"
);
}
#[test]
fn walker_collects_hidden_file_at_root_level() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("main.mds"), "hello").unwrap();
std::fs::write(dir.path().join(".dotfile.mds"), "dot").unwrap();
let mut files = collect_mds_files(dir.path(), 64, None);
files.sort();
assert_eq!(
files.len(),
2,
"hidden file should still be collected; found: {files:?}"
);
}
#[test]
fn walker_processes_explicitly_passed_hidden_root() {
let dir = tempfile::tempdir().unwrap();
let hidden_root = dir.path().join(".myhidden");
std::fs::create_dir(&hidden_root).unwrap();
std::fs::write(hidden_root.join("template.mds"), "hello").unwrap();
let files = collect_mds_files(&hidden_root, 64, None);
assert_eq!(
files.len(),
1,
"explicitly-passed hidden root should be processed; found: {files:?}"
);
}
#[test]
fn walk_result_empty_dir_has_zero_excluded() {
let dir = tempfile::tempdir().unwrap();
let result = collect_mds_files_detailed(dir.path(), 64, None);
assert_eq!(result.files.len(), 0);
assert_eq!(
result.excluded_by_default, 0,
"genuinely empty dir must have 0 excluded"
);
}
#[test]
fn walk_result_all_excluded_counts_skipped_files() {
let dir = tempfile::tempdir().unwrap();
let hidden = dir.path().join(".prompts");
std::fs::create_dir(&hidden).unwrap();
std::fs::write(hidden.join("a.mds"), "a").unwrap();
std::fs::write(hidden.join("b.mds"), "b").unwrap();
let result = collect_mds_files_detailed(dir.path(), 64, None);
assert_eq!(result.files.len(), 0, "no files should be in results");
assert_eq!(
result.excluded_by_default, 2,
"excluded_by_default must equal the count of skipped .mds files; got {}",
result.excluded_by_default
);
}
#[test]
fn walk_result_mixed_counts_excluded_and_collects_normal() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("normal.mds"), "hello").unwrap();
let nm = dir.path().join("node_modules");
std::fs::create_dir(&nm).unwrap();
std::fs::write(nm.join("excluded.mds"), "lib").unwrap();
let result = collect_mds_files_detailed(dir.path(), 64, None);
assert_eq!(result.files.len(), 1, "only normal.mds should be collected");
assert_eq!(
result.excluded_by_default, 1,
"one file in node_modules should be counted as excluded"
);
}
#[test]
fn single_component_path_is_not_inside_excluded_dir() {
assert!(!is_within_default_excluded_dir(
Path::new("/root"),
Path::new("/root/foo.mds")
));
}
#[test]
fn output_base_no_ext_dir_mode() {
let source = PathBuf::from("/root/src/chat.mds");
let root = PathBuf::from("/root");
let base = OutputBase::Dir(PathBuf::from("/out"));
let result = output_base_no_ext(&source, &root, &base);
assert_eq!(result, PathBuf::from("/out/src/chat"));
}
#[test]
fn output_base_no_ext_next_to_source() {
let source = PathBuf::from("/root/src/chat.mds");
let root = PathBuf::from("/root");
let base = OutputBase::NextToSource;
let result = output_base_no_ext(&source, &root, &base);
assert_eq!(result, PathBuf::from("/root/src/chat"));
}
#[test]
fn preview_text_for_tty_neutralizes_esc_preserves_byte_length() {
let hostile = "hello\x1bworld"; let result = preview_text_for(true, hostile);
assert_eq!(
result.len(),
hostile.len(),
"byte length must be preserved on TTY path"
);
assert!(
!result.contains('\x1b'),
"raw ESC must be absent from TTY output; got: {result:?}"
);
assert!(
result.contains('?'),
"ESC must be replaced with '?' on TTY path; got: {result:?}"
);
}
#[test]
fn preview_text_for_not_tty_returns_borrowed_passthrough() {
let hostile = "hello\x1bworld";
let result = preview_text_for(false, hostile);
assert!(
matches!(result, Cow::Borrowed(_)),
"piped path must return Cow::Borrowed (no allocation); got Owned"
);
assert_eq!(
result.as_ref(),
hostile,
"piped path must be byte-identical to input"
);
}
#[test]
fn preview_text_for_tty_clean_string_unchanged() {
let clean = "hello world\n";
let result = preview_text_for(true, clean);
assert_eq!(
result.as_ref(),
clean,
"clean string must be unchanged on TTY path"
);
}
#[test]
fn safe_path_sanitizes_esc_byte() {
let raw = format!("dir/fo{}o.mds", '\x1b');
let p = std::path::Path::new(&raw);
let result = safe_path(p);
assert!(
!result.contains('\x1b'),
"raw ESC must be absent from safe_path output"
);
assert!(
result.contains("\\u001B"),
"ESC must be escaped to \\u001B; got: {result:?}"
);
}
#[test]
fn safe_path_passes_clean_path_unchanged() {
let p = std::path::Path::new("dir/normal.mds");
assert_eq!(safe_path(p), "dir/normal.mds");
}
#[test]
fn neutralize_source_removes_c0_del_c1_preserving_byte_length() {
let raw = "a\x00b\x7fc\u{0085}d\ne\tf";
let out = neutralize_source_for_render(raw);
assert_eq!(out.len(), raw.len(), "byte length preserved");
assert!(!out.contains('\x00'), "NUL removed");
assert!(!out.contains('\x7f'), "DEL removed");
assert!(!out.contains('\u{0085}'), "C1 NEL removed");
assert!(out.contains('\n'), "LF preserved");
assert!(out.contains('\t'), "TAB preserved");
}
#[test]
fn neutralize_source_caret_alignment_with_span_after_control_char() {
use miette::{GraphicalReportHandler, GraphicalTheme, NamedSource, SourceSpan};
let raw = "a\x1bbc";
let clean = neutralize_source_for_render(raw);
assert_eq!(clean.len(), raw.len(), "byte length invariant");
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("test")]
struct SpanErr {
#[source_code]
src: NamedSource<String>,
#[label("here")]
span: SourceSpan,
}
let report = miette::Report::new(SpanErr {
src: NamedSource::new("test.mds", clean.into_owned()),
span: (2, 1).into(), });
let mut buf = String::new();
GraphicalReportHandler::new_themed(GraphicalTheme::unicode_nocolor())
.render_report(&mut buf, report.as_ref())
.expect("render must not panic after neutralization");
assert!(buf.contains('b'), "caret points at b");
assert!(!buf.contains('\x1b'), "no raw ESC in rendered output");
}
#[test]
fn colour_path_miette_sgr_survives_hostile_osc_is_removed() {
use miette::{GraphicalReportHandler, GraphicalTheme, NamedSource, SourceSpan};
let hostile_char = '\u{009D}'; let raw = format!("good{}text", hostile_char);
let clean = neutralize_source_for_render(&raw);
assert_eq!(clean.len(), raw.len(), "byte length preserved");
assert!(
!clean.contains(hostile_char),
"C1 OSC neutralised in source"
);
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("colour test")]
struct ColourErr {
#[source_code]
src: NamedSource<String>,
#[label("here")]
span: SourceSpan,
}
let src_len = clean.len();
let report = miette::Report::new(ColourErr {
src: NamedSource::new("colour.mds", clean.into_owned()),
span: (0, src_len).into(),
});
let mut coloured = String::new();
GraphicalReportHandler::new_themed(GraphicalTheme::unicode())
.render_report(&mut coloured, report.as_ref())
.expect("render must not panic");
assert!(
coloured.contains('\x1b'),
"miette SGR codes present in coloured output"
);
assert!(
!coloured.contains(hostile_char),
"hostile C1 absent from rendered output"
);
}
fn render_nocolor(report: &miette::Report) -> String {
use miette::{GraphicalReportHandler, GraphicalTheme};
let mut buf = String::new();
GraphicalReportHandler::new_themed(GraphicalTheme::unicode_nocolor())
.render_report(&mut buf, report.as_ref())
.expect("render must not panic");
buf
}
#[test]
fn sanitize_report_escapes_message_and_help() {
let hostile_name = format!("bad{}[31mNAME", '\u{1b}');
let report = sanitize_report(miette::Report::new(mds::MdsError::UndefinedVariable {
name: hostile_name,
span: None,
src: None,
}));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("undefined variable"),
"non-vacuity: expected the undefined-variable message; got: {rendered:?}"
);
assert!(
rendered.contains("help:"),
"non-vacuity: expected a help line; got: {rendered:?}"
);
assert!(
!rendered.contains('\u{1b}'),
"raw ESC must not survive into the rendered frame; got: {rendered:?}"
);
assert!(
rendered.matches("\\u001B").count() >= 2,
"ESC must be escaped in the message AND the help text; got: {rendered:?}"
);
}
#[test]
fn sanitize_report_escapes_cli_authored_miette_message() {
let hostile = format!("cannot write fo{}[2Jo.mds", '\u{1b}');
let report = sanitize_report(miette::miette!("{hostile}"));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("cannot write"),
"non-vacuity: expected the miette!() message; got: {rendered:?}"
);
assert!(
!rendered.contains('\u{1b}'),
"raw ESC must not survive a miette!() report; got: {rendered:?}"
);
assert!(
rendered.contains("\\u001B"),
"ESC must be escaped to the \\u001B literal; got: {rendered:?}"
);
}
#[test]
fn sanitize_report_escapes_bidi_override_in_message() {
let hostile = format!("alias{}reversed", '\u{202e}');
let report = sanitize_report(miette::miette!("{hostile}"));
let rendered = render_nocolor(&report);
assert!(
!rendered.contains('\u{202e}'),
"raw U+202E must not survive; got: {rendered:?}"
);
assert!(
rendered.contains("\\u202E"),
"U+202E must be escaped to the \\u202E literal; got: {rendered:?}"
);
}
#[test]
fn sanitize_report_preserves_newline_in_message() {
let report = sanitize_report(miette::miette!("line one\nline two"));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("line one"),
"non-vacuity: message must render; got: {rendered:?}"
);
assert!(
!rendered.contains("\\u000A"),
"HUMAN mode must NOT escape newlines; got: {rendered:?}"
);
}
#[test]
fn sanitize_report_escapes_label_text_but_keeps_span() {
let hostile_label = format!("here{}[31m", '\u{1b}');
let diag = miette::MietteDiagnostic::new("outer message")
.with_label(miette::LabeledSpan::at(2..5, hostile_label));
let report =
sanitize_report(miette::Report::new(diag).with_source_code("abcdefgh".to_string()));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("here"),
"non-vacuity: the label must render; got: {rendered:?}"
);
assert!(
!rendered.contains('\u{1b}'),
"raw ESC must not survive in label text; got: {rendered:?}"
);
assert!(
rendered.contains("\\u001B"),
"label ESC must be escaped; got: {rendered:?}"
);
assert!(
rendered.contains("abcdefgh"),
"the labelled source excerpt must still render; got: {rendered:?}"
);
}
#[test]
fn sanitize_report_colour_path_keeps_miette_sgr_and_escapes_hostile_input() {
use miette::{GraphicalReportHandler, GraphicalTheme};
let hostile = format!("hostile{}[31mtext", '\u{1b}');
let report = sanitize_report(miette::miette!("{hostile}"));
let mut coloured = String::new();
GraphicalReportHandler::new_themed(GraphicalTheme::unicode())
.render_report(&mut coloured, report.as_ref())
.expect("render must not panic");
assert!(
coloured.contains('\u{1b}'),
"miette's own SGR codes must survive on the colour path; got: {coloured:?}"
);
assert!(
coloured.contains("\\u001B"),
"hostile ESC must be escaped even on the colour path; got: {coloured:?}"
);
assert_eq!(
coloured.matches("\\u001B").count(),
1,
"exactly one escaped literal (the hostile byte) — more means miette's own \
SGR codes were escaped, which is the PF-014 regression; got: {coloured:?}"
);
}
#[test]
fn sanitize_report_is_inert_on_clean_input() {
let raw = miette::Report::new(mds::MdsError::UndefinedVariable {
name: "user_name".to_string(),
span: None,
src: None,
});
let before = render_nocolor(&raw);
let after = render_nocolor(&sanitize_report(raw));
assert_eq!(
before, after,
"sanitizing must not alter the render of a clean diagnostic"
);
}
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("outer failure")]
struct OuterWithCause {
#[source]
cause: InnerCause,
}
#[derive(Debug, thiserror::Error)]
#[error("inner cause: {0}")]
struct InnerCause(String);
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("parent diagnostic")]
struct ParentWithRelated {
#[related]
related: Vec<RelatedChild>,
}
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("related child: {0}")]
#[diagnostic(help("child help: {0}"))]
struct RelatedChild(String);
fn hostile_fragment() -> String {
format!("bad{}[31m{}{}end", '\u{1b}', '\u{202e}', '\u{061c}')
}
fn assert_aux_text_escaped(rendered: &str, surface: &str) {
for raw in ['\u{1b}', '\u{202e}', '\u{061c}'] {
assert!(
!rendered.contains(raw),
"{surface}: raw U+{:04X} must not survive into the rendered frame; \
got: {rendered:?}",
raw as u32
);
}
for escaped in ["\\u001B", "\\u202E", "\\u061C"] {
assert!(
rendered.contains(escaped),
"{surface}: {escaped} must appear in the rendered frame; got: {rendered:?}"
);
}
}
#[test]
fn sanitize_report_escapes_and_preserves_the_cause_chain() {
let report = sanitize_report(miette::Report::new(OuterWithCause {
cause: InnerCause(hostile_fragment()),
}));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("inner cause"),
"non-vacuity: the cause chain must still render; got: {rendered:?}"
);
assert!(
rendered.contains("outer failure"),
"non-vacuity: the outer message must still render; got: {rendered:?}"
);
assert_aux_text_escaped(&rendered, "cause chain");
}
#[test]
fn sanitize_report_escapes_and_preserves_related_diagnostics() {
let report = sanitize_report(miette::Report::new(ParentWithRelated {
related: vec![RelatedChild(hostile_fragment())],
}));
let rendered = render_nocolor(&report);
assert!(
rendered.contains("parent diagnostic"),
"non-vacuity: the parent message must render; got: {rendered:?}"
);
assert!(
rendered.contains("related child"),
"non-vacuity: the related diagnostic must still render; got: {rendered:?}"
);
assert!(
rendered.contains("child help"),
"non-vacuity: the related diagnostic's help must still render; got: {rendered:?}"
);
assert_aux_text_escaped(&rendered, "related diagnostics");
}
#[test]
fn sanitize_report_bounds_a_cyclic_cause_chain() {
#[derive(Debug)]
struct Cycle;
impl std::fmt::Display for Cycle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("cyclic cause")
}
}
impl std::error::Error for Cycle {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&Cycle)
}
}
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("outer")]
struct Outer(#[source] Cycle);
let wrapped = SanitizedReport::new(miette::Report::new(Outer(Cycle)));
let mut depth = 0usize;
let mut node = wrapped.source.as_ref();
while let Some(n) = node {
depth += 1;
assert!(
depth <= MAX_AUX_DEPTH,
"the cause-chain walk must be bounded by MAX_AUX_DEPTH"
);
node = n.source.as_deref();
}
assert_eq!(
depth, MAX_AUX_DEPTH,
"an infinite chain must be truncated at exactly MAX_AUX_DEPTH"
);
}
#[test]
fn eprint_warning_sanitizes_hostile_control_chars() {
let hostile = format!(
"MAX_SOURCEMAP_SEGMENTS exceeded in imported module 'lib{}[2Jbar.mds'",
'\u{1b}'
);
let result = mds::sanitize_control_chars(&hostile);
assert!(
result.contains("MAX_SOURCEMAP_SEGMENTS"),
"non-vacuity: warning text must be preserved; got: {result:?}"
);
assert!(
result.contains("lib"),
"non-vacuity: filename prefix must be preserved; got: {result:?}"
);
assert!(
!result.contains('\u{1b}'),
"raw ESC must be absent from warning output; hostile = {hostile:?}"
);
assert!(
result.contains("\\u001B"),
"ESC must be escaped to \\u001B literal; got: {result:?}"
);
}
#[test]
fn eprint_warning_clean_string_passes_through_unchanged() {
let clean = "MAX_SOURCEMAP_SEGMENTS exceeded in imported module 'lib.mds'";
let result = mds::sanitize_control_chars(clean);
assert_eq!(
result.as_ref(),
clean,
"clean warning must pass through unchanged; got: {result:?}"
);
}
#[test]
fn eprint_warning_sanitizes_bidi_control_in_warning_text() {
let hostile = format!("warning: module 'lib{}evil.mds'", '\u{202e}');
let result = mds::sanitize_control_chars(&hostile);
assert!(
!result.contains('\u{202e}'),
"raw U+202E must be absent from warning output; got: {result:?}"
);
assert!(
result.contains("\\u202E"),
"U+202E must be escaped to \\u202E literal; got: {result:?}"
);
}
#[test]
fn render_unified_diff_empty_for_identical_input() {
let rendered = render_unified_diff("same\n", "same\n", "label");
assert!(rendered.is_empty());
}
#[test]
fn render_unified_diff_contains_unified_markers_for_changed_input() {
let rendered = render_unified_diff("a\n", "b\n", "label");
assert!(rendered.contains("---"));
assert!(rendered.contains("+++"));
assert!(rendered.contains("-a"));
assert!(rendered.contains("+b"));
}
#[test]
fn colorize_unified_diff_wraps_add_remove_lines_with_ansi_when_requested() {
let unified = "--- a\n+++ b\n@@ -1 +1 @@\n-old\n+new\n";
let colorized = colorize_unified_diff(unified);
assert!(colorized.contains("\x1b[32m+new\x1b[0m"));
assert!(colorized.contains("\x1b[31m-old\x1b[0m"));
assert!(colorized.contains("\x1b[36m--- a\x1b[0m"));
}
#[test]
fn colorize_unified_diff_correctly_colors_content_starting_with_dashes_or_pluses() {
let unified = "--- a\n+++ b\n@@ -1,2 +1,2 @@\n--- dashes content\n+++ plus content\n";
let colorized = colorize_unified_diff(unified);
assert!(colorized.contains("\x1b[31m--- dashes content\x1b[0m"));
assert!(colorized.contains("\x1b[32m+++ plus content\x1b[0m"));
assert!(colorized.contains("\x1b[36m--- a\x1b[0m"));
assert!(colorized.contains("\x1b[36m+++ b\x1b[0m"));
}
fn temp_residue(dir: &Path) -> Vec<String> {
std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(".mds-tmp-"))
.collect()
}
#[test]
fn atomic_write_file_creates_missing_target() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("fresh.md");
assert!(!target.exists(), "precondition: target must be absent");
atomic_write_file(&target, "CREATED", Durability::Fsync)
.expect("writing an absent target must succeed");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "CREATED");
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"no .mds-tmp- residue may survive a successful write; got {residue:?}"
);
}
#[test]
fn atomic_write_file_rename_only_matches_fsync_contract() {
let dir = tempfile::tempdir().unwrap();
let quick = dir.path().join("quick.md");
let synced = dir.path().join("synced.md");
atomic_write_file(&quick, "DERIVED", Durability::RenameOnly).unwrap();
atomic_write_file(&synced, "DERIVED", Durability::Fsync).unwrap();
assert_eq!(std::fs::read_to_string(&quick).unwrap(), "DERIVED");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(
std::fs::metadata(&quick).unwrap().permissions().mode() & 0o777,
std::fs::metadata(&synced).unwrap().permissions().mode() & 0o777,
"RenameOnly must not change the mode a fresh artifact is created with"
);
}
atomic_write_file(&quick, "REBUILT", Durability::RenameOnly).unwrap();
assert_eq!(std::fs::read_to_string(&quick).unwrap(), "REBUILT");
#[cfg(unix)]
{
let real = dir.path().join("real.md");
std::fs::write(&real, "REAL").unwrap();
let link = dir.path().join("link.md");
std::os::unix::fs::symlink(&real, &link).unwrap();
let err = atomic_write_file(&link, "NEW", Durability::RenameOnly)
.expect_err("RenameOnly must still refuse a symlink target");
assert!(
err.to_string().contains("symlink"),
"the refusal must say why; got: {err}"
);
assert_eq!(std::fs::read_to_string(&real).unwrap(), "REAL");
}
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"RenameOnly must leave no .mds-tmp- residue; got {residue:?}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_new_file_mode_matches_std_fs_write() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let ctl = dir.path().join("ctl.md");
atomic_write_file(&out, "X", Durability::Fsync).unwrap();
std::fs::write(&ctl, "X").unwrap();
let mode_out = std::fs::metadata(&out).unwrap().permissions().mode() & 0o777;
let mode_ctl = std::fs::metadata(&ctl).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode_out, mode_ctl,
"new-file mode must match std::fs::write; got 0{mode_out:o} vs control 0{mode_ctl:o}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_existing_mode_0640_preserved() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("src.mds");
std::fs::write(&target, "OLD").unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o640)).unwrap();
atomic_write_file(&target, "NEW", Durability::Fsync).unwrap();
let mode = std::fs::metadata(&target).unwrap().permissions().mode() & 0o7777;
assert_eq!(
mode, 0o640,
"existing mode must be preserved; got 0{mode:o}"
);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
}
#[cfg(unix)]
#[test]
fn atomic_write_file_refuses_live_symlink_target() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real.md");
let link = dir.path().join("link.md");
std::fs::write(&real, "REAL").unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
let err = atomic_write_file(&link, "NEW", Durability::Fsync)
.expect_err("writing through a symlink must be refused")
.to_string();
assert!(
err.contains("symlink"),
"expected a symlink refusal; got {err}"
);
assert_eq!(
std::fs::read_to_string(&real).unwrap(),
"REAL",
"the symlink's target must not be written through"
);
assert!(
std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink(),
"the symlink itself must survive the refusal"
);
atomic_write_file(&real, "NEW", Durability::Fsync)
.expect("writing the real file must succeed");
assert_eq!(std::fs::read_to_string(&real).unwrap(), "NEW");
}
#[cfg(unix)]
#[test]
fn atomic_write_file_refuses_dangling_symlink_target() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.md");
let link = dir.path().join("link.md");
std::os::unix::fs::symlink(&missing, &link).unwrap();
let err = atomic_write_file(&link, "NEW", Durability::Fsync)
.expect_err("writing through a dangling symlink must be refused")
.to_string();
assert!(
err.contains("symlink"),
"expected a symlink refusal; got {err}"
);
assert!(
!missing.exists(),
"the dangling link's target must not be created"
);
assert!(
std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink(),
"the symlink itself must survive the refusal"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_failure_preserves_original_and_leaves_no_temp() {
use std::os::unix::fs::MetadataExt as _;
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let target = sub.join("locked.mds");
std::fs::write(&target, "OLD").unwrap();
let before = std::fs::metadata(&target).unwrap();
let (ino, mtime) = (before.ino(), before.modified().unwrap());
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o555)).unwrap();
let result = atomic_write_file(&target, "NEW", Durability::Fsync);
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
let err = result
.expect_err("a read-only parent directory must fail the write")
.to_string();
assert!(
err.contains("locked.mds"),
"error must name the target; got {err}"
);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "OLD");
let after = std::fs::metadata(&target).unwrap();
assert_eq!(
after.ino(),
ino,
"a failed write must not replace the inode"
);
assert_eq!(
after.modified().unwrap(),
mtime,
"a failed write must not touch the mtime"
);
let residue = temp_residue(&sub);
assert!(
residue.is_empty(),
"failed write left temp residue: {residue:?}"
);
atomic_write_file(&target, "NEW", Durability::Fsync)
.expect("write must succeed once the dir is writable");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
assert_ne!(
std::fs::metadata(&target).unwrap().ino(),
ino,
"replace-by-rename must produce a new inode"
);
}
#[test]
fn atomic_write_file_directory_target_refused_without_residue() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("adir");
std::fs::create_dir(&target).unwrap();
let err = atomic_write_file(&target, "X", Durability::Fsync)
.expect_err("a directory target must not be written")
.to_string();
assert!(
err.contains("adir"),
"error must name the target; got {err}"
);
assert!(target.is_dir(), "the directory must survive the refusal");
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"refused write left temp residue: {residue:?}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_unreadable_parent_is_hard_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("nosearch");
std::fs::create_dir(&p).unwrap();
let probe = p.join("probe");
std::fs::write(&probe, "").unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::metadata(&probe).is_ok() {
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
eprintln!("running as root; cannot exercise EACCES");
return;
}
let result = atomic_write_file(&p.join("x.md"), "X", Durability::Fsync);
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
let err = result
.expect_err("an unstattable target must be a hard error")
.to_string();
assert!(
err.contains("cannot stat"),
"expected a stat error; got {err}"
);
assert!(
err.contains("x.md"),
"error must name the target; got {err}"
);
}
}