use std::borrow::Cow;
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 {
let no_ext = output_base_no_ext(source, root, base);
match base {
OutputBase::Dir(d) => {
let mut name = no_ext
.file_name()
.unwrap_or(source.as_os_str())
.to_os_string();
name.push(".");
name.push(ext);
let out = no_ext.parent().unwrap_or(d.as_path()).join(&name);
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(source.as_os_str())
.to_os_string();
n.push(".");
n.push(ext);
n
};
d.join(flat_name)
}
}
OutputBase::NextToSource => no_ext.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) {
Ok(r) => r,
Err(_) => return false, };
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 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)
));
}
}
}
}
pub(crate) fn output_base_no_ext(source: &Path, root: &Path, base: &OutputBase) -> PathBuf {
match base {
OutputBase::Dir(d) => {
let rel = match source.strip_prefix(root) {
Ok(r) => r.to_path_buf(),
Err(_) => {
let stem = source.file_stem().unwrap_or(source.as_os_str());
return d.join(stem);
}
};
let stem = rel.file_stem().unwrap_or(rel.as_os_str()).to_os_string();
d.join(rel.parent().unwrap_or(Path::new(""))).join(stem)
}
OutputBase::NextToSource => {
source.with_extension("")
}
}
}
pub(crate) fn atomic_write_file(path: &Path, content: &str) -> Result<()> {
use mds::{effective_parent, NativeFs};
NativeFs::check_symlink(path)
.map_err(|e| miette::miette!("cannot write {}: {e}", path.display()))?;
let parent = effective_parent(path);
#[cfg(unix)]
let original_mode: Option<u32> = {
use std::os::unix::fs::PermissionsExt as _;
match std::fs::metadata(path) {
Ok(m) => Some(m.permissions().mode()),
Err(e) => {
eprint_error(miette::miette!(
"cannot get metadata for {}: {e}",
path.display()
));
None
}
}
};
let mut tmp = tempfile::Builder::new()
.prefix(".mds-tmp-")
.suffix(".tmp")
.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()))?;
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"));
}
#[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 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"));
}
}