use std::borrow::Cow;
use std::ffi::OsStr;
use std::io::{IsTerminal, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use miette::Result;
use crate::build::{OutputKind, ProjectConfig};
use crate::write::{DirIdentity, NotRemoved, Removal};
macro_rules! ewriteln {
() => {
$crate::output::write_stderr_fmt(::std::format_args!("\n"))
};
($($arg:tt)+) => {
$crate::output::write_stderr_fmt(::std::format_args!(
"{}\n",
::std::format_args!($($arg)+)
))
};
}
pub(crate) use ewriteln;
pub(crate) struct OutputState {
bits: AtomicU8,
clear_asked: AtomicBool,
}
impl OutputState {
const STDERR_CLOSED: u8 = 1 << 0;
const IO_FAILED: u8 = 1 << 1;
const STDOUT_CLOSED: u8 = 1 << 2;
const STDOUT_FAILED: u8 = 1 << 3;
const WATCH_LIVE: u8 = 1 << 4;
const PANICKED: u8 = 1 << 5;
const RESOURCE_LIMITED: u8 = 1 << 6;
const INTERNAL_FAILED: u8 = 1 << 7;
pub(crate) const fn new() -> Self {
Self {
bits: AtomicU8::new(0),
clear_asked: AtomicBool::new(false),
}
}
fn set(&self, bit: u8) -> bool {
self.bits.fetch_or(bit, Ordering::AcqRel) & bit == 0
}
fn clear(&self, bit: u8) {
self.bits.fetch_and(!bit, Ordering::AcqRel);
}
fn has(&self, bit: u8) -> bool {
self.bits.load(Ordering::Acquire) & bit != 0
}
pub(crate) fn note_stderr_closed(&self) {
self.set(Self::STDERR_CLOSED);
}
pub(crate) fn note_io_failure(&self) {
self.set(Self::IO_FAILED);
}
pub(crate) fn note_stdout_closed(&self) {
self.set(Self::STDOUT_CLOSED);
}
pub(crate) fn note_stdout_failure(&self) -> bool {
self.set(Self::STDOUT_FAILED)
}
pub(crate) fn note_stdout_written(&self) {
self.clear(Self::STDOUT_FAILED);
}
pub(crate) fn stderr_closed(&self) -> bool {
self.has(Self::STDERR_CLOSED)
}
pub(crate) fn io_failed(&self) -> bool {
self.has(Self::IO_FAILED)
}
pub(crate) fn stdout_closed(&self) -> bool {
self.has(Self::STDOUT_CLOSED)
}
pub(crate) fn note_watch_live(&self) {
self.set(Self::WATCH_LIVE);
}
pub(crate) fn note_panicked(&self) {
self.set(Self::PANICKED);
}
pub(crate) fn panicked(&self) -> bool {
self.has(Self::PANICKED)
}
pub(crate) fn note_resource_limited(&self) {
self.set(Self::RESOURCE_LIMITED);
}
pub(crate) fn resource_limited(&self) -> bool {
self.has(Self::RESOURCE_LIMITED)
}
fn note_internal_failed(&self) {
self.set(Self::INTERNAL_FAILED);
}
fn internal_failed(&self) -> bool {
self.has(Self::INTERNAL_FAILED)
}
pub(crate) fn ask_clear(&self) {
self.clear_asked.store(true, Ordering::Release);
}
pub(crate) fn cancel_clear(&self) {
self.clear_asked.store(false, Ordering::Release);
}
fn take_clear(&self) -> bool {
self.clear_asked.swap(false, Ordering::AcqRel)
}
#[cfg(test)]
pub(crate) fn clear_is_asked(&self) -> bool {
self.clear_asked.load(Ordering::Acquire)
}
pub(crate) fn exit_policy(&self) -> ExitPolicy {
if self.has(Self::WATCH_LIVE) {
ExitPolicy::WatchSession
} else {
ExitPolicy::Batch
}
}
}
static OUTPUT_STATE: OutputState = OutputState::new();
pub(crate) fn note_io_failure() {
OUTPUT_STATE.note_io_failure();
}
pub(crate) fn note_watch_session_live() {
OUTPUT_STATE.note_watch_live();
}
const CLEAR_SEQUENCE: &str = "\x1b[2J\x1b[3J\x1b[H";
pub(crate) fn ask_clear() {
if stderr_is_a_terminal() {
OUTPUT_STATE.ask_clear();
}
}
pub(crate) fn cancel_clear() {
OUTPUT_STATE.cancel_clear();
}
fn stderr_is_a_terminal() -> bool {
#[cfg(test)]
if child_process::on_a_terminal() {
return true;
}
std::io::stderr().is_terminal()
}
pub(crate) fn eprint_io_failure(e: mds::MdsError) {
note_io_failure();
eprint_error(miette::Report::new(e));
}
pub(crate) fn eprint_file_failure(report: miette::Report) {
note_file_failure(&OUTPUT_STATE, &report);
eprint_error(report);
}
fn note_file_failure(state: &OutputState, report: &miette::Report) {
match crate::build::exit_code(report) {
IO_FAILURE_EXIT => state.note_io_failure(),
RESOURCE_LIMIT_EXIT => state.note_resource_limited(),
PANIC_EXIT => state.note_internal_failed(),
_ => {}
}
}
pub(crate) fn write_stderr_fmt(args: std::fmt::Arguments<'_>) {
write_stderr_to(&OUTPUT_STATE, &mut std::io::stderr().lock(), args);
}
fn write_stderr_to<W: std::io::Write + ?Sized>(
state: &OutputState,
sink: &mut W,
args: std::fmt::Arguments<'_>,
) {
if state.stderr_closed() {
return;
}
let mut text = String::new();
let _ = std::fmt::Write::write_fmt(&mut text, args);
if !text.is_empty() && state.take_clear() {
text.insert_str(0, CLEAR_SEQUENCE);
}
write_stderr_text(state, sink, &text);
}
fn write_pending_clear_to<W: std::io::Write + ?Sized>(state: &OutputState, sink: &mut W) {
if !state.stderr_closed() && state.take_clear() {
write_stderr_text(state, sink, CLEAR_SEQUENCE);
}
}
fn write_stderr_text<W: std::io::Write + ?Sized>(state: &OutputState, sink: &mut W, text: &str) {
match sink.write_all(text.as_bytes()).and_then(|()| sink.flush()) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => state.note_stderr_closed(),
Err(_) => state.note_io_failure(),
}
}
#[must_use]
#[derive(Debug)]
pub(crate) enum StdoutOutcome {
Written,
Closed,
Failed(std::io::Error),
FailedAgain,
}
impl StdoutOutcome {
pub(crate) fn into_batch_result(self) -> std::result::Result<(), mds::MdsError> {
match self {
Self::Written | Self::Closed | Self::FailedAgain => Ok(()),
Self::Failed(e) => Err(stdout_failure(&e)),
}
}
}
pub(crate) fn stdout_failure(e: &std::io::Error) -> mds::MdsError {
mds::MdsError::Io {
message: format!("cannot write to stdout: {}", safe_inline(io_cause(e))),
}
}
pub(crate) fn write_stdout(bytes: &[u8]) -> StdoutOutcome {
if !bytes.is_empty() && !OUTPUT_STATE.stdout_closed() {
write_pending_clear_to(&OUTPUT_STATE, &mut std::io::stderr().lock());
}
write_stdout_to(&OUTPUT_STATE, &mut std::io::stdout().lock(), bytes)
}
fn write_stdout_to<W: std::io::Write + ?Sized>(
state: &OutputState,
sink: &mut W,
bytes: &[u8],
) -> StdoutOutcome {
if state.stdout_closed() {
return StdoutOutcome::Closed;
}
match sink.write_all(bytes).and_then(|()| sink.flush()) {
Ok(()) => {
if !bytes.is_empty() {
state.note_stdout_written();
}
StdoutOutcome::Written
}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {
state.note_stdout_closed();
StdoutOutcome::Closed
}
Err(e) => {
if state.note_stdout_failure() {
StdoutOutcome::Failed(e)
} else {
StdoutOutcome::FailedAgain
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ExitPolicy {
Batch,
WatchSession,
}
const IO_FAILURE_EXIT: i32 = 2;
const RESOURCE_LIMIT_EXIT: i32 = 3;
#[must_use]
pub(crate) fn final_exit_code(verdict: i32, state: &OutputState, policy: ExitPolicy) -> i32 {
if state.panicked() {
return PANIC_EXIT;
}
match policy {
ExitPolicy::Batch if state.internal_failed() => PANIC_EXIT,
ExitPolicy::Batch => {
let after_io = if state.io_failed() {
verdict.max(IO_FAILURE_EXIT)
} else {
verdict
};
if state.resource_limited() {
after_io.max(RESOURCE_LIMIT_EXIT)
} else {
after_io
}
}
ExitPolicy::WatchSession => verdict,
}
}
pub(crate) fn exit(verdict: i32) -> ! {
std::process::exit(final_exit_code(
verdict,
&OUTPUT_STATE,
OUTPUT_STATE.exit_policy(),
))
}
const ICE_TEXT: &str = concat!(
"mds: internal compiler error\n",
"note: this is a bug in mds; please report it at ",
env!("CARGO_PKG_REPOSITORY"),
"/issues\n",
);
pub(crate) const PANIC_EXIT: i32 = 101;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BacktraceStyle {
Short,
Full,
}
impl BacktraceStyle {
fn from_env(value: Option<&OsStr>) -> Option<Self> {
match value {
None => None,
Some(value) if value == OsStr::new("0") => None,
Some(value) if value == OsStr::new("full") => Some(Self::Full),
Some(_) => Some(Self::Short),
}
}
}
thread_local! {
static CATCHING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static UNWINDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn install_panic_hook() {
let backtrace = BacktraceStyle::from_env(std::env::var_os("RUST_BACKTRACE").as_deref());
std::panic::set_hook(Box::new(move |info| on_panic(backtrace, info)));
}
fn on_panic(backtrace: Option<BacktraceStyle>, info: &std::panic::PanicHookInfo<'_>) {
OUTPUT_STATE.note_panicked();
OUTPUT_STATE.cancel_clear();
let mut stderr = std::io::stderr();
let _ = stderr.write_all(ICE_TEXT.as_bytes());
if let Some(style) = backtrace {
write_backtrace(&mut stderr, style);
}
#[cfg(feature = "debug-panics")]
write_panic_detail(&mut stderr, info);
#[cfg(not(feature = "debug-panics"))]
let _ = info;
if !unwinds_to_a_catch() {
exit_after_panic();
}
}
fn unwinds_to_a_catch() -> bool {
let catching = CATCHING.with(std::cell::Cell::get);
let already_unwinding = UNWINDING.with(|unwinding| unwinding.replace(true));
catching && !already_unwinding
}
fn exit_after_panic() -> ! {
std::process::exit(PANIC_EXIT)
}
#[derive(Debug)]
pub(crate) struct Panicked;
pub(crate) fn catch_panic<T>(
f: impl FnOnce() -> T + std::panic::UnwindSafe,
) -> std::result::Result<T, Panicked> {
let outer = CATCHING.with(|catching| catching.replace(true));
let caught = std::panic::catch_unwind(f);
CATCHING.with(|catching| catching.set(outer));
caught.map_err(|payload| {
dispose_payload(payload);
UNWINDING.with(|unwinding| unwinding.set(false));
Panicked
})
}
pub(crate) fn catch_compile<T>(
label: &Path,
compile: impl FnOnce() -> T + std::panic::UnwindSafe,
) -> std::result::Result<T, Panicked> {
catch_panic(move || {
panic_on_compile(label);
compile()
})
}
#[derive(Debug, PartialEq, Eq)]
enum Disposal {
Dropped,
Forgotten,
}
fn dispose_payload(payload: Box<dyn std::any::Any + Send>) -> Disposal {
if payload.is::<String>() || payload.is::<&'static str>() {
drop(payload);
Disposal::Dropped
} else {
std::mem::forget(payload);
Disposal::Forgotten
}
}
fn write_backtrace<W: std::io::Write + ?Sized>(sink: &mut W, style: BacktraceStyle) {
let backtrace = std::backtrace::Backtrace::force_capture();
let mut text = String::from("stack backtrace:\n");
let _ = match style {
BacktraceStyle::Short => std::fmt::Write::write_fmt(&mut text, format_args!("{backtrace}")),
BacktraceStyle::Full => {
std::fmt::Write::write_fmt(&mut text, format_args!("{backtrace:#}"))
}
};
let _ = sink.write_all(escape_each_line(&text).as_bytes());
}
fn escape_each_line(text: &str) -> String {
let mut escaped = String::with_capacity(text.len());
for line in text.split_terminator('\n') {
escaped.push_str(&mds::sanitize_control_chars_wire(line));
escaped.push('\n');
}
escaped
}
#[cfg(feature = "debug-panics")]
fn write_panic_detail<W: std::io::Write + ?Sized>(
sink: &mut W,
info: &std::panic::PanicHookInfo<'_>,
) {
let payload = info.payload();
let message = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str))
.unwrap_or("(a panic payload that is not text)");
let mut text = String::new();
let _ = std::fmt::Write::write_fmt(&mut text, format_args!("panic: {message}\n"));
if let Some(location) = info.location() {
let _ = std::fmt::Write::write_fmt(&mut text, format_args!(" at {location}\n"));
}
let _ = sink.write_all(escape_each_line(&text).as_bytes());
}
#[cfg(debug_assertions)]
mod panic_trigger {
use std::path::Path;
const VARIABLE: &str = "MDS_TEST_PANIC";
pub(super) const SENTINEL: &str = "mds-test-panic-payload";
fn requested() -> Option<String> {
std::env::var_os(VARIABLE).and_then(|value| value.into_string().ok())
}
pub(crate) fn panic_on_request() {
match requested().as_deref() {
Some("main") => std::panic::panic_any(payload()),
Some("thread") => {
let _ = std::thread::spawn(|| std::panic::panic_any(payload())).join();
}
_ => {}
}
}
pub(crate) fn panic_on_compile(label: &Path) {
let Some(stem) = label.file_stem().and_then(std::ffi::OsStr::to_str) else {
return;
};
if requested()
.as_deref()
.and_then(|value| value.strip_prefix("compile:"))
== Some(stem)
{
std::panic::panic_any(payload());
}
}
pub(crate) fn panic_in_handler(handler: &str) {
if requested().as_deref() == Some(handler) {
std::panic::panic_any(payload());
}
}
pub(super) fn payload() -> String {
let esc = char::from(0x1b);
let here = std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir());
format!("{SENTINEL} {esc}[2J {}", here.display())
}
}
#[cfg(debug_assertions)]
use panic_trigger::panic_on_compile;
#[cfg(debug_assertions)]
pub(crate) use panic_trigger::{panic_in_handler, panic_on_request};
#[cfg(not(debug_assertions))]
pub(crate) fn panic_on_request() {}
#[cfg(not(debug_assertions))]
fn panic_on_compile(_label: &Path) {}
#[cfg(not(debug_assertions))]
pub(crate) fn panic_in_handler(_handler: &str) {}
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(),
})
}
pub(crate) fn current_dir() -> std::result::Result<PathBuf, mds::MdsError> {
std::env::current_dir().map_err(|e| mds::MdsError::Io {
message: format!(
"cannot determine current directory: {}",
safe_inline(io_cause(&e))
),
})
}
pub(crate) fn reject_forbidden_output_path(
what: &str,
value: &OsStr,
) -> std::result::Result<(), mds::MdsError> {
mds::reject_forbidden_path(what, Path::new(value), &value.to_string_lossy())
}
pub(crate) fn reject_non_utf8_output_path<'a>(
what: &str,
value: &'a OsStr,
) -> std::result::Result<&'a str, mds::MdsError> {
value.to_str().ok_or_else(|| mds::MdsError::Io {
message: format!(
"{what} is not valid UTF-8: \"{}\"",
mds::escape_path_for_message(&value.to_string_lossy())
),
})
}
pub(crate) fn reject_forbidden_resolved_output_path(
what: &str,
path: &Path,
typed: &OsStr,
) -> std::result::Result<(), mds::MdsError> {
let Some(resolved) = resolve_existing_prefix(path)? else {
return Ok(());
};
mds::reject_forbidden_path(
&format!("{what} resolved path"),
&resolved,
&typed.to_string_lossy(),
)
}
fn resolve_existing_prefix(path: &Path) -> std::result::Result<Option<PathBuf>, mds::MdsError> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
current_dir()?.join(path)
};
Ok(absolute.ancestors().find_map(|a| a.canonicalize().ok()))
}
pub(crate) fn reject_output_dir_escape(output_dir: &str) -> std::result::Result<(), mds::MdsError> {
use std::path::Component;
let mut components = Path::new(output_dir).components();
if components
.clone()
.any(|c| matches!(c, Component::RootDir | Component::Prefix(_)))
{
return Err(mds::MdsError::Io {
message: format!(
"mds.json output_dir '{}' must be a relative path",
mds::escape_path_for_message(output_dir)
),
});
}
if components.any(|c| c == Component::ParentDir) {
return Err(mds::MdsError::Io {
message: format!(
"mds.json output_dir '{}' must not contain '..' components",
mds::escape_path_for_message(output_dir)
),
});
}
Ok(())
}
#[derive(Debug, Clone)]
pub(crate) enum OutputBase {
Dir {
canonical: PathBuf,
shown: PathBuf,
below_anchor: usize,
},
NextToSource,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WriteTarget {
pub(crate) path: PathBuf,
pub(crate) shown: PathBuf,
below_anchor: usize,
checked_anchor: Option<DirIdentity>,
}
impl WriteTarget {
pub(crate) fn as_typed(path: PathBuf) -> Self {
Self::new(path.clone(), path)
}
pub(crate) fn new(path: PathBuf, shown: PathBuf) -> Self {
Self {
path,
shown,
below_anchor: 1,
checked_anchor: None,
}
}
pub(crate) fn below(anchor: &Path, shown_anchor: &Path, rel: &Path) -> Self {
Self {
path: anchor.join(rel),
shown: shown_anchor.join(rel),
below_anchor: rel
.components()
.filter(|c| *c != std::path::Component::CurDir)
.count(),
checked_anchor: None,
}
}
pub(crate) fn below_out_dir(
dir: &Path,
shown_dir: &Path,
dir_below_anchor: usize,
rel: &Path,
) -> Self {
let mut target = Self::below(dir, shown_dir, rel);
target.below_anchor += dir_below_anchor;
target
}
pub(crate) fn walked_below(root: RootPaths<'_>, file: &Path) -> Self {
match file.strip_prefix(root.walked) {
Ok(rel) => Self::below(root.walked, root.typed, rel),
Err(_) => Self::as_typed(file.to_path_buf()),
}
}
pub(crate) fn below_anchor(&self) -> usize {
self.below_anchor
}
pub(crate) fn below_checked_anchor(
&self,
dir: &Path,
missing: usize,
identity: DirIdentity,
) -> Self {
let above = self
.path
.components()
.count()
.saturating_sub(self.below_anchor);
Self {
path: dir.join(self.path.components().skip(above).collect::<PathBuf>()),
shown: self.shown.clone(),
below_anchor: self.below_anchor + missing,
checked_anchor: Some(identity),
}
}
pub(crate) fn checked_anchor(&self) -> Option<DirIdentity> {
self.checked_anchor
}
pub(crate) fn sibling(&self, edit: impl Fn(&Path) -> PathBuf) -> Self {
Self {
path: edit(&self.path),
shown: edit(&self.shown),
below_anchor: self.below_anchor,
checked_anchor: self.checked_anchor,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct RootPaths<'a> {
pub(crate) typed: &'a Path,
pub(crate) walked: &'a Path,
}
impl<'a> RootPaths<'a> {
pub(crate) fn as_typed(dir: &'a Path) -> Self {
Self {
typed: dir,
walked: dir,
}
}
pub(crate) fn shown_below(self, source: &Path) -> PathBuf {
self.typed_below(source)
.unwrap_or_else(|| source.to_path_buf())
}
pub(crate) fn typed_below(self, path: &Path) -> Option<PathBuf> {
let below = path.strip_prefix(self.walked).ok()?;
Some(if below.as_os_str().is_empty() {
self.typed.to_path_buf()
} else {
self.typed.join(below)
})
}
}
pub(crate) fn canonicalize_out_dir(
out_dir: Option<&PathBuf>,
) -> std::result::Result<Option<PathBuf>, mds::MdsError> {
let Some(d) = out_dir else {
return Ok(None);
};
let abs = if d.is_absolute() {
d.clone()
} else {
current_dir()?.join(d)
};
Ok(Some(abs.canonicalize().unwrap_or(abs)))
}
pub(crate) fn resolve_output_base(
out_dir: Option<&PathBuf>,
config: &Option<ProjectConfig>,
) -> Result<OutputBase> {
if let (Some(typed), Some(canonical)) = (out_dir, canonicalize_out_dir(out_dir)?) {
return Ok(OutputBase::Dir {
canonical,
shown: typed.clone(),
below_anchor: 0,
});
}
if let Some(ProjectConfig {
config,
dir,
shown_dir,
}) = config
{
if let Some(ref output_dir) = config.build.output_dir {
reject_output_dir_escape(output_dir)?;
return Ok(OutputBase::Dir {
canonical: dir.join(output_dir),
shown: shown_dir.join(output_dir),
below_anchor: Path::new(output_dir)
.components()
.filter(|c| matches!(c, std::path::Component::Normal(_)))
.count(),
});
}
}
Ok(OutputBase::NextToSource)
}
pub(crate) fn output_path_for(
source: &Path,
root: RootPaths<'_>,
base: &OutputBase,
ext: &str,
) -> WriteTarget {
match base {
OutputBase::Dir {
canonical,
shown,
below_anchor,
} => {
let (rel, flattened) = mirrored_output(source, root.walked, ext);
let target = WriteTarget::below_out_dir(canonical, shown, *below_anchor, &rel);
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.walked),
safe_path(&target.shown)
));
}
target
}
OutputBase::NextToSource => {
output_stem_for(source, root, base).sibling(|stem| stem.with_extension(ext))
}
}
}
fn mirrored_output(source: &Path, root: &Path, ext: &str) -> (PathBuf, bool) {
let mirrored = mirror_stem(source, root);
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(Path::new("")).join(&name);
if out
.components()
.all(|c| matches!(c, std::path::Component::Normal(_)))
{
return (out, flattened);
}
debug_assert!(
false,
"output_path_for: output {out:?} is not below the out-dir"
);
flat_output(source, ext)
}
fn flat_output(source: &Path, ext: &str) -> (PathBuf, bool) {
let mut flat_name = source
.file_stem()
.unwrap_or_else(|| OsStr::new("output"))
.to_os_string();
flat_name.push(".");
flat_name.push(ext);
(PathBuf::from(flat_name), true)
}
pub(crate) struct WalkResult {
pub files: Vec<PathBuf>,
metadata: std::collections::HashMap<PathBuf, std::fs::Metadata>,
pub excluded_by_default: usize,
}
pub(crate) fn collect_mds_files_detailed(
root: &Path,
max_depth: usize,
exclude_prefix: Option<&Path>,
) -> WalkResult {
let mut walk = WalkResult {
files: Vec::new(),
metadata: std::collections::HashMap::new(),
excluded_by_default: 0,
};
collect_mds_files_inner(root, 0, max_depth, exclude_prefix, &mut walk);
pause_after_walk();
walk
}
pub(crate) fn walked_pin(
walk: &WalkResult,
file: &Path,
typed_dir: &Path,
canonical_dir: &Path,
) -> std::result::Result<mds::EntryPin, mds::MdsError> {
let invalid = || mds::MdsError::Io {
message: format!(
"cannot read {}: missing or invalid walk metadata",
safe_path(file)
),
};
let relative = file.strip_prefix(typed_dir).map_err(|_| invalid())?;
let metadata = walk.metadata.get(file).ok_or_else(invalid)?;
Ok(mds::EntryPin::key(canonical_dir.join(relative)).with_walked(metadata))
}
#[cfg(debug_assertions)]
mod walk_pause_trigger {
use super::*;
use crate::write::{atomic_write_file, Durability, Parents};
const VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_WALK";
const POLL: std::time::Duration = std::time::Duration::from_millis(5);
const MAX_POLLS: u32 = 2_000;
pub(crate) fn pause_after_walk() {
let Some(go) = std::env::var_os(VARIABLE).map(PathBuf::from) else {
return;
};
let mut paused = go.clone().into_os_string();
paused.push(".paused");
if atomic_write_file(
&WriteTarget::as_typed(PathBuf::from(paused)),
"",
Durability::RenameOnly,
Parents::Existing,
)
.is_err()
{
return;
}
for _ in 0..MAX_POLLS {
if go.exists() {
return;
}
std::thread::sleep(POLL);
}
}
}
#[cfg(debug_assertions)]
use walk_pause_trigger::pause_after_walk;
#[cfg(not(debug_assertions))]
pub(crate) fn pause_after_walk() {}
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 by_name(read_dir: std::fs::ReadDir) -> Vec<std::fs::DirEntry> {
let mut entries: Vec<_> = read_dir.flatten().collect();
entries.sort_by_cached_key(std::fs::DirEntry::file_name);
entries
}
fn collect_mds_files_inner(
dir: &Path,
depth: usize,
max_depth: usize,
exclude_prefix: Option<&Path>,
results: &mut WalkResult,
) {
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 by_name(read_dir) {
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,
&mut results.excluded_by_default,
);
continue;
}
}
collect_mds_files_inner(&path, depth + 1, max_depth, exclude_prefix, results);
} else if file_type.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds") {
let Ok(metadata) = entry.metadata() else {
continue;
};
if !metadata.is_file() {
continue;
}
results.metadata.insert(path.clone(), metadata);
results.files.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 stale_output(written: &WriteTarget, kind: OutputKind) -> WriteTarget {
written.sibling(|path| path.with_extension(kind.stale_extension()))
}
pub(crate) fn probe_and_remove_stale(
written: &WriteTarget,
kind: OutputKind,
quiet: bool,
) -> std::result::Result<(), mds::MdsError> {
let stale = stale_output(written, kind);
match kind {
OutputKind::Markdown => remove_stale_messages(&stale, quiet),
OutputKind::Messages => {
if !quiet && std::fs::symlink_metadata(&stale.path).is_ok() {
eprint_warning(&format!(
"warning: kept stale output {}: mds never removes a Markdown file",
safe_path(&stale.shown)
));
}
Ok(())
}
}
}
fn remove_stale_messages(
stale: &WriteTarget,
quiet: bool,
) -> std::result::Result<(), mds::MdsError> {
let proof = |file: &mut std::fs::File| {
let size = file.metadata()?.len();
holds_messages_output(file, size, mds::MAX_FILE_SIZE)
};
let not_removed = match crate::write::remove_proven(stale, proof) {
Ok(Removal::Removed | Removal::Missing) => return Ok(()),
Ok(Removal::Kept) | Err(NotRemoved::NotAFile | NotRemoved::Link) => {
if !quiet {
eprint_warning(&format!(
"warning: kept stale output {}: not proven to be written by mds",
safe_path(&stale.shown)
));
}
return Ok(());
}
Err(not_removed) => not_removed,
};
Err(stale_removal_error(
"stale output",
&stale.shown,
¬_removed,
))
}
pub(crate) fn stale_removal_error(
noun: &str,
shown: &Path,
not_removed: &NotRemoved,
) -> mds::MdsError {
let what = match not_removed {
NotRemoved::Unreadable(_) => "cannot read",
_ => "could not remove",
};
mds::MdsError::Io {
message: format!(
"{what} {noun} {}: {}",
safe_path(shown),
not_removed.cause()
),
}
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct WrittenMessage {
role: String,
content: String,
}
fn holds_messages_output(
reader: &mut impl std::io::Read,
size: u64,
cap: u64,
) -> std::io::Result<bool> {
if size > cap {
return Ok(false);
}
let bytes = mds::read_at_most(reader, cap.saturating_add(1), size)?;
if bytes.len() as u64 > cap {
return Ok(false);
}
let Ok(messages) = serde_json::from_slice::<Vec<WrittenMessage>>(&bytes) else {
return Ok(false);
};
Ok(crate::build::messages_json(&messages).is_ok_and(|written| written.as_bytes() == bytes))
}
#[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) -> MirroredStem {
match source.strip_prefix(root) {
Ok(rel) => {
let stem = rel.file_stem().unwrap_or(rel.as_os_str()).to_os_string();
MirroredStem::Mirrored(rel.parent().unwrap_or(Path::new("")).join(stem))
}
Err(_) => {
let stem = source.file_stem().unwrap_or_else(|| OsStr::new("output"));
MirroredStem::Flattened(PathBuf::from(stem))
}
}
}
pub(crate) fn output_base_no_ext(source: &Path, root: &Path, base: &OutputBase) -> PathBuf {
match base {
OutputBase::Dir { canonical, .. } => canonical.join(mirror_stem(source, root).into_path()),
OutputBase::NextToSource => {
source.with_extension("")
}
}
}
pub(crate) fn output_stem_for(
source: &Path,
root: RootPaths<'_>,
base: &OutputBase,
) -> WriteTarget {
match base {
OutputBase::Dir {
canonical,
shown,
below_anchor,
} => WriteTarget::below_out_dir(
canonical,
shown,
*below_anchor,
&mirror_stem(source, root.walked).into_path(),
),
OutputBase::NextToSource => {
WriteTarget::walked_below(root, source).sibling(|source| source.with_extension(""))
}
}
}
pub(crate) use mds::neutralize_source_for_render;
struct SanitizedReport {
inner: miette::Report,
message: String,
code: Option<String>,
help: Option<String>,
url: 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>>,
}
const UNFORMATTABLE: &str = "(this text could not be formatted)";
fn display_text<T: std::fmt::Display + ?Sized>(d: &T) -> Option<String> {
let mut text = String::new();
std::fmt::Write::write_fmt(&mut text, format_args!("{d}")).ok()?;
Some(text)
}
fn escape_display(d: Option<Box<dyn std::fmt::Display + '_>>) -> Option<String> {
d.and_then(|v| display_text(&*v))
.map(|text| mds::sanitize_control_chars(&text).into_owned())
}
fn escape_message<T: std::fmt::Display + ?Sized>(d: &T) -> String {
display_text(d).map_or_else(
|| UNFORMATTABLE.to_owned(),
|text| mds::sanitize_control_chars(&text).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: escape_message(d),
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: escape_message(e),
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 = escape_message(&inner);
let code = escape_display(inner.code());
let help = escape_display(inner.help());
let url = escape_display(inner.url());
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,
code,
help,
url,
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>> {
boxed_str(self.code.as_deref())
}
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>> {
boxed_str(self.url.as_deref())
}
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);
let mut rendered = String::new();
match std::fmt::Write::write_fmt(&mut rendered, format_args!("{report:?}")) {
Ok(()) => rendered,
Err(std::fmt::Error) => plain_text_fallback(report.as_ref()),
}
}
fn plain_text_fallback(d: &dyn miette::Diagnostic) -> String {
let mut out = String::new();
if let Some(code) = d.code().and_then(|c| display_text(&*c)) {
out.push_str(&mds::sanitize_control_chars_wire(&code));
out.push_str("\n\n");
}
push_frame_block(&mut out, " \u{00d7} ", &escape_message(d));
if let Some(help) = escape_display(d.help()) {
push_frame_block(&mut out, " help: ", &help);
}
out
}
fn push_frame_block(out: &mut String, lead: &str, text: &str) {
out.push_str(lead);
out.push_str(&text.replace('\n', "\n \u{2502} "));
out.push('\n');
}
pub(crate) fn eprint_error(report: miette::Report) {
ewriteln!("{}", render_error_sanitized(report));
}
pub(crate) fn eprint_warning(w: &str) {
ewriteln!("{}", 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_file_display(&mds::display_native_path(p).display().to_string())
}
pub(crate) fn safe_file_display(name: &str) -> String {
mds::escape_path_for_message(name).into_owned()
}
pub(crate) fn safe_inline(value: impl std::fmt::Display) -> String {
mds::sanitize_control_chars_wire(&value.to_string()).into_owned()
}
const WATCHER_ERROR: &str = "file watcher error";
pub(crate) fn io_cause(e: &std::io::Error) -> String {
match e.get_ref() {
None => e.to_string(),
Some(_) => e.kind().to_string(),
}
}
pub(crate) fn notify_cause(e: ¬ify::Error) -> String {
use notify::ErrorKind;
match &e.kind {
ErrorKind::Io(io) => io_cause(io),
ErrorKind::Generic(text) if !text.contains(['/', '\\']) => text.clone(),
ErrorKind::Generic(_) => WATCHER_ERROR.to_owned(),
ErrorKind::PathNotFound => notify::Error::path_not_found().to_string(),
ErrorKind::WatchNotFound => notify::Error::watch_not_found().to_string(),
ErrorKind::InvalidConfig(config) => notify::Error::invalid_config(config).to_string(),
ErrorKind::MaxFilesWatch => notify::Error::new(ErrorKind::MaxFilesWatch).to_string(),
}
}
#[cfg(test)]
pub(crate) mod child_process {
const CHILD: &str = "MDS_UNIT_TEST_CHILD";
pub(crate) fn run(name: &str) -> std::process::Output {
let binary = std::env::current_exe().expect("the test binary's path");
std::process::Command::new(binary)
.args([name, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, name)
.env_remove("RUST_BACKTRACE")
.output()
.expect("the child runs")
}
pub(crate) fn is_child(name: &str) -> bool {
std::env::var_os(CHILD).is_some_and(|value| value == name)
}
const TERMINAL: &str = "MDS_UNIT_TEST_TERMINAL";
pub(crate) fn run_on_a_terminal(name: &str) -> std::process::Output {
let binary = std::env::current_exe().expect("the test binary's path");
std::process::Command::new(binary)
.args([name, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, name)
.env(TERMINAL, "1")
.env_remove("RUST_BACKTRACE")
.output()
.expect("the child runs")
}
pub(crate) fn on_a_terminal() -> bool {
std::env::var_os(CHILD).is_some() && std::env::var_os(TERMINAL).is_some()
}
pub(crate) fn clear_is_asked() -> bool {
super::OUTPUT_STATE.clear_is_asked()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn walked_pin_reports_missing_metadata_without_a_panic() {
let file = Path::new("src").join("a.mds");
let walk = WalkResult {
files: vec![file.clone()],
metadata: std::collections::HashMap::new(),
excluded_by_default: 0,
};
let error = walked_pin(&walk, &file, Path::new("src"), Path::new("canonical")).unwrap_err();
assert!(matches!(error, mds::MdsError::Io { .. }));
assert_eq!(
error.to_string(),
format!(
"cannot read {}: missing or invalid walk metadata",
safe_path(&file)
)
);
let dir = tempfile::tempdir().unwrap();
let source = dir.path().join("a.mds");
std::fs::write(&source, "Hello\n").unwrap();
let mut complete = walk;
complete
.metadata
.insert(file.clone(), std::fs::symlink_metadata(source).unwrap());
assert!(walked_pin(&complete, &file, Path::new("src"), dir.path()).is_ok());
assert!(walked_pin(&complete, &file, Path::new("other"), dir.path()).is_err());
}
fn out_base() -> OutputBase {
OutputBase::Dir {
canonical: PathBuf::from("/out"),
shown: PathBuf::from("out"),
below_anchor: 0,
}
}
fn target(anchor: &str, shown_anchor: &str, rel: &str) -> WriteTarget {
WriteTarget::below(Path::new(anchor), Path::new(shown_anchor), Path::new(rel))
}
#[test]
fn an_output_is_written_below_the_canonical_out_dir_and_named_below_the_typed_one() {
let source = Path::new("/root/sub/page.mds");
let root = Path::new("/root");
let out = output_path_for(source, RootPaths::as_typed(root), &out_base(), "md");
assert_eq!(out, target("/out", "out", "sub/page.md"));
assert_eq!(
out.sibling(crate::build::map_path_for),
target("/out", "out", "sub/page.md.map")
);
assert_eq!(
output_path_for(
Path::new("src/sub/page.mds"),
RootPaths::as_typed(Path::new("src")),
&OutputBase::NextToSource,
"md"
),
target("src", "src", "sub/page.md")
);
}
const HI: &str = "[\n {\n \"role\": \"user\",\n \"content\": \"Hi\"\n }\n]\n";
fn compiled_messages(dir: &Path, source: &str) -> String {
let path = dir.join("chat.mds");
std::fs::write(&path, source).unwrap();
let compiled =
crate::build::compile_to_content(&path, None, true, mds::CompileOptions::default())
.unwrap();
assert_eq!(compiled.kind, OutputKind::Messages, "{source:?}");
compiled.content
}
fn proven(bytes: &[u8], cap: u64) -> bool {
holds_messages_output(&mut &bytes[..], bytes.len() as u64, cap).unwrap()
}
#[test]
fn a_messages_output_is_proven_only_by_the_bytes_mds_writes() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(
compiled_messages(dir.path(), "@message user:\nHi\n@end\n"),
HI
);
let escaped = compiled_messages(
dir.path(),
"@message system:\nSay \"hi\"\tthen go\n@end\n@message user:\nCaf\u{e9} \u{2014} 1 < 2\n@end\n",
);
let none = compiled_messages(dir.path(), "@message user:\n \n@end\n");
assert_eq!(none, "[]\n", "mds writes an empty messages output");
for (name, output) in [
("HI", HI),
("escaped", escaped.as_str()),
("none", none.as_str()),
] {
assert!(
proven(output.as_bytes(), mds::MAX_FILE_SIZE),
"control: {name} {output:?}"
);
}
let backslash = '\\';
let not_written_by_mds: Vec<(&str, Vec<u8>)> = vec![
(
"compact",
b"[{\"role\":\"user\",\"content\":\"Hi\"}]\n".to_vec(),
),
("no final newline", HI.trim_end_matches('\n').into()),
("CRLF", HI.replace('\n', "\r\n").into()),
(
"a byte-order mark",
[&b"\xEF\xBB\xBF"[..], HI.as_bytes()].concat(),
),
(
"another escape",
HI.replace("\"Hi\"", &format!("\"H{backslash}u0069\""))
.into(),
),
(
"a field more",
HI.replace("\"Hi\"\n", "\"Hi\",\n \"name\": \"x\"\n")
.into(),
),
(
"a field fewer",
HI.replace(",\n \"content\": \"Hi\"", "").into(),
),
(
"fields in another order",
b"[\n {\n \"content\": \"Hi\",\n \"role\": \"user\"\n }\n]\n".to_vec(),
),
("content not a string", HI.replace("\"Hi\"", "1").into()),
(
"an object",
b"{\n \"role\": \"user\",\n \"content\": \"Hi\"\n}\n".to_vec(),
),
("strings", b"[\n \"Hi\"\n]\n".to_vec()),
("null", b"null\n".to_vec()),
("empty", Vec::new()),
("a raw control character", HI.replace("Hi", "H\u{1}").into()),
];
for (name, bytes) in not_written_by_mds {
assert!(!proven(&bytes, mds::MAX_FILE_SIZE), "{name}: {bytes:?}");
}
let mut not_utf8 = HI.as_bytes().to_vec();
let at = HI.find("Hi").unwrap() + 1;
not_utf8[at] = 0xFF;
assert!(!proven(¬_utf8, mds::MAX_FILE_SIZE), "not UTF-8");
let size = HI.len() as u64;
assert!(
proven(HI.as_bytes(), size),
"control: a file of exactly the cap"
);
assert!(!proven(HI.as_bytes(), size - 1), "one byte over the cap");
assert!(
!holds_messages_output(&mut HI.as_bytes(), size + 1, size).unwrap(),
"a size over the cap"
);
assert!(
!holds_messages_output(&mut HI.as_bytes(), 1, size - 1).unwrap(),
"a reader holding more than the cap whatever its size said"
);
}
#[cfg(unix)]
#[test]
fn a_stale_output_is_never_removed_through_a_symlink_below_its_anchor() {
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir_all(anchor.join("real")).unwrap();
std::fs::create_dir(dir.path().join("victim")).unwrap();
std::os::unix::fs::symlink("../victim", anchor.join("sub")).unwrap();
let victim = dir.path().join("victim/x.json");
std::fs::write(&victim, HI).unwrap();
let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md"));
let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
assert_eq!(
std::fs::read_to_string(&victim).ok().as_deref(),
Some(HI),
"nothing is removed through the symlink"
);
match result {
Err(mds::MdsError::Io { message }) => assert_eq!(
message,
"could not remove stale output out/sub/x.json: \
refusing to follow a symlink at out/sub"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
let real = anchor.join("real/x.json");
std::fs::write(&real, HI).unwrap();
let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("real/x.md"));
assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
assert!(!real.exists(), "control: the stale output is removed");
}
#[cfg(unix)]
#[test]
fn a_proven_stale_output_that_cannot_be_removed_is_an_io_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir(&anchor).unwrap();
let stale = anchor.join("x.json");
std::fs::write(&stale, HI).unwrap();
let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
let mode = |mode| std::fs::set_permissions(&anchor, std::fs::Permissions::from_mode(mode));
mode(0o555).unwrap();
if std::fs::write(anchor.join(".probe"), "").is_ok() {
mode(0o755).unwrap();
ewriteln!("skipped: out is writable at mode 0o555 (running as root?)");
return;
}
let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
mode(0o755).unwrap();
match result {
Err(mds::MdsError::Io { message }) => assert_eq!(
message,
format!(
"could not remove stale output out/x.json: {}",
std::io::Error::from(rustix::io::Errno::ACCESS)
)
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert_eq!(std::fs::read_to_string(&stale).ok().as_deref(), Some(HI));
assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
assert!(!stale.exists(), "control: the stale output is removed");
}
#[cfg(windows)]
#[test]
fn a_proven_stale_output_held_open_on_windows_is_an_io_error() {
use std::os::windows::fs::OpenOptionsExt as _;
const FILE_SHARE_READ: u32 = 0x1;
const ERROR_SHARING_VIOLATION: i32 = 32;
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir(&anchor).unwrap();
let stale = anchor.join("x.json");
std::fs::write(&stale, HI).unwrap();
let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
let held = std::fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.open(&stale)
.unwrap();
let result = probe_and_remove_stale(&written, OutputKind::Markdown, true);
drop(held);
match result {
Err(mds::MdsError::Io { message }) => assert_eq!(
message,
format!(
"could not remove stale output {}: {}",
Path::new("out").join("x.json").display(),
std::io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)
)
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert_eq!(std::fs::read_to_string(&stale).ok().as_deref(), Some(HI));
assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
assert!(!stale.exists(), "control: the stale output is removed");
}
#[test]
fn a_stale_json_that_is_not_utf8_or_over_the_read_cap_is_kept() {
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir(&anchor).unwrap();
let stale = anchor.join("x.json");
let written = WriteTarget::below(&anchor, Path::new("out"), Path::new("x.md"));
let kept_or_removed = |bytes: &[u8]| {
std::fs::write(&stale, bytes).unwrap();
assert!(probe_and_remove_stale(&written, OutputKind::Markdown, true).is_ok());
if stale.exists() {
"kept"
} else {
"removed"
}
};
let mut not_utf8 = HI.as_bytes().to_vec();
not_utf8[HI.find("Hi").unwrap() + 1] = 0xFF;
assert_eq!(kept_or_removed(¬_utf8), "kept", "not UTF-8");
assert_eq!(kept_or_removed(HI.as_bytes()), "removed", "control: {HI:?}");
let output = |len: usize| {
let message = WrittenMessage {
role: "user".to_owned(),
content: "a".repeat(len),
};
crate::build::messages_json(&[message]).unwrap()
};
let cap = usize::try_from(mds::MAX_FILE_SIZE).unwrap();
let frame = output(0).len();
let over = output(cap + 1 - frame);
assert_eq!(over.len(), cap + 1, "one byte over the cap");
assert_eq!(kept_or_removed(over.as_bytes()), "kept", "over the cap");
let at_cap = output(cap - frame);
assert_eq!(at_cap.len(), cap, "exactly the cap");
assert_eq!(
kept_or_removed(at_cap.as_bytes()),
"removed",
"control: exactly the cap"
);
}
#[test]
fn an_output_next_to_its_source_is_named_below_the_root_as_typed() {
let root = RootPaths {
typed: Path::new("src"),
walked: Path::new("/root"),
};
let source = Path::new("/root/sub/page.mds");
let next_to = OutputBase::NextToSource;
assert_eq!(
output_path_for(source, root, &next_to, "md"),
target("/root", "src", "sub/page.md")
);
assert_eq!(
output_stem_for(source, root, &next_to),
target("/root", "src", "sub/page")
);
assert_eq!(
output_path_for(source, root, &out_base(), "json"),
target("/out", "out", "sub/page.json")
);
assert_eq!(
output_stem_for(source, root, &out_base()),
target("/out", "out", "sub/page")
);
assert_eq!(
output_stem_for(Path::new("/other/page.mds"), root, &next_to),
WriteTarget::as_typed(PathBuf::from("/other/page"))
);
}
#[test]
fn the_out_dir_is_shown_as_typed_and_resolved_absolute() {
let typed = PathBuf::from("out");
match resolve_output_base(Some(&typed), &None).expect("a relative out-dir resolves") {
OutputBase::Dir {
canonical,
shown,
below_anchor,
} => {
assert!(canonical.is_absolute(), "canonical: {canonical:?}");
assert!(canonical.ends_with("out"), "canonical: {canonical:?}");
assert_eq!(shown, typed);
assert_eq!(below_anchor, 0);
}
other => panic!("want Dir; got {other:?}"),
}
let config = Some(ProjectConfig {
config: crate::build::MdsConfig {
build: crate::build::BuildConfig {
output_dir: Some("dist".to_string()),
..Default::default()
},
..Default::default()
},
dir: PathBuf::from("/project"),
shown_dir: PathBuf::from("src/.."),
});
match resolve_output_base(None, &config).expect("a config output_dir resolves") {
OutputBase::Dir {
canonical,
shown,
below_anchor,
} => {
assert_eq!(canonical, Path::new("/project").join("dist"));
assert_eq!(shown, Path::new("src/..").join("dist"));
assert_eq!(below_anchor, 1);
}
other => panic!("want Dir; got {other:?}"),
}
}
#[test]
fn a_build_output_dir_lies_below_the_config_directory() {
let config = |output_dir: &str| {
Some(ProjectConfig {
config: crate::build::MdsConfig {
build: crate::build::BuildConfig {
output_dir: Some(output_dir.to_string()),
..Default::default()
},
..Default::default()
},
dir: PathBuf::from("/project"),
shown_dir: PathBuf::from("."),
})
};
let root = PathBuf::from("/project/src");
let source = root.join("sub").join("a.mds");
for (output_dir, rel) in [("dist", "dist/sub/a.md"), ("./a/b", "a/b/sub/a.md")] {
let base = resolve_output_base(None, &config(output_dir)).expect("relative");
assert_eq!(
output_path_for(&source, RootPaths::as_typed(&root), &base, "md"),
target("/project", ".", rel),
"{output_dir:?}"
);
}
let absolute = std::env::temp_dir().join("dist");
let refused = resolve_output_base(None, &config(absolute.to_str().unwrap()))
.expect_err("an absolute output_dir is refused")
.to_string();
assert!(refused.contains("must be a relative path"), "{refused}");
}
#[test]
fn output_path_for_json_extension_dir_mode() {
let source = PathBuf::from("/root/src/chat.mds");
let root = PathBuf::from("/root");
let base = out_base();
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "json");
assert_eq!(result, target("/out", "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 = out_base();
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert_eq!(result, target("/out", "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, RootPaths::as_typed(&root), &base, "md");
assert_eq!(result, target("/root", "/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, RootPaths::as_typed(&root), &base, "json");
assert_eq!(result, target("/root", "/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 = out_base();
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert!(
result.path.starts_with("/out"),
"output must be inside /out; got {result:?}"
);
assert_eq!(result, target("/out", "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")),
MirroredStem::Flattened(PathBuf::from("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")),
MirroredStem::Mirrored(PathBuf::from("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 = out_base();
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, RootPaths::as_typed(root), &base, "md"),
target("/out", "out", "output.md"),
"the write oracle must not join an absolute stem"
);
}
#[test]
fn the_flat_fallback_of_a_mirror_is_flagged_flattened() {
assert_eq!(
flat_output(Path::new("/root/../x/a.mds"), "md"),
(PathBuf::from("a.md"), true)
);
assert_eq!(
flat_output(Path::new("/"), "json"),
(PathBuf::from("output.json"), true),
"a stem-less source keeps a relative name"
);
}
#[cfg(not(debug_assertions))]
#[test]
fn a_mirror_that_leaves_the_out_dir_is_written_flat_and_reported() {
assert_eq!(
mirrored_output(Path::new("/root/../x/a.mds"), Path::new("/root"), "md"),
(PathBuf::from("a.md"), true),
"the flat name is returned with the flag that makes the caller warn"
);
}
#[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");
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}"
);
for header in ["fn output_base_no_ext(", "fn output_stem_for("] {
let probe = fn_body(SRC, header)
.unwrap_or_else(|| panic!("non-vacuity: {header} must be present in this file"));
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 collect_mds_files_visits_each_directory_by_name() {
let dir = tempfile::tempdir().unwrap();
for name in ["z.mds", "m/b.mds", "m/a.mds", "a.mds"] {
let path = dir.path().join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "x\n").unwrap();
}
let names: Vec<_> = collect_mds_files(dir.path(), 64, None)
.iter()
.map(|path| path.strip_prefix(dir.path()).unwrap().to_path_buf())
.collect();
let want: Vec<PathBuf> = ["a.mds", "m/a.mds", "m/b.mds", "z.mds"]
.iter()
.map(PathBuf::from)
.collect();
assert_eq!(names, want);
}
#[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 = out_base();
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 safe_path_escapes_every_forbidden_char_tab_included() {
for ch in ['\t', '\n', '\x1b', '\u{202E}'] {
let raw = format!("out{ch}dir/in.md");
let got = safe_path(std::path::Path::new(&raw));
assert!(!got.contains(ch), "U+{:04X}: {got:?}", u32::from(ch));
assert_eq!(
got,
format!("out\\u{:04X}dir/in.md", u32::from(ch)),
"U+{:04X}",
u32::from(ch)
);
}
}
#[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"));
}
const SENTINEL_DIR: &str = "sentinel-cause-dir";
fn sentinel(dir: &tempfile::TempDir) -> PathBuf {
dir.path().join(SENTINEL_DIR).join("leaf")
}
#[test]
fn io_cause_drops_the_path_an_error_carries() {
let dir = tempfile::tempdir().unwrap();
let sentinel = sentinel(&dir);
let needle = SENTINEL_DIR;
let tempfile = tempfile::Builder::new()
.tempfile_in(sentinel.parent().unwrap())
.expect_err("no temporary file below a directory that does not exist");
assert!(
tempfile.to_string().contains(needle),
"control: tempfile's text names the path: {tempfile}"
);
let cause = io_cause(&tempfile);
assert!(!cause.contains(needle), "{cause}");
assert!(!cause.contains("at path"), "{cause}");
assert_eq!(cause, tempfile.kind().to_string(), "its kind's text");
let custom = std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!("denied: {}", sentinel.display()),
);
assert!(custom.to_string().contains(needle), "control: {custom}");
assert_eq!(io_cause(&custom), "permission denied");
let os = std::fs::File::open(&sentinel).expect_err("the sentinel does not exist");
assert!(os.raw_os_error().is_some(), "control: an OS error: {os:?}");
assert_eq!(io_cause(&os), os.to_string());
assert!(io_cause(&os).contains("(os error "), "{}", io_cause(&os));
let kind = std::io::Error::from(std::io::ErrorKind::NotFound);
assert_eq!(io_cause(&kind), std::io::ErrorKind::NotFound.to_string());
}
#[test]
fn notify_cause_drops_the_paths_a_watcher_error_lists() {
let dir = tempfile::tempdir().unwrap();
let sentinel = sentinel(&dir);
let needle = SENTINEL_DIR;
let listing = |e: notify::Error| e.add_path(sentinel.clone());
let os = std::fs::File::open(&sentinel).expect_err("the sentinel does not exist");
let os_text = os.to_string();
let config = notify::Config::default();
let cases = [
(
listing(notify::Error::path_not_found()),
"No path was found.".to_owned(),
),
(
listing(notify::Error::watch_not_found()),
"No watch was found.".to_owned(),
),
(
listing(notify::Error::invalid_config(&config)),
format!("Invalid configuration: {config:?}"),
),
(
listing(notify::Error::new(notify::ErrorKind::MaxFilesWatch)),
"OS file watch limit reached.".to_owned(),
),
(listing(notify::Error::io(os)), os_text),
(
listing(notify::Error::generic(
"Input watch path is neither a file nor a directory.",
)),
"Input watch path is neither a file nor a directory.".to_owned(),
),
(
listing(notify::Error::generic(&format!(
"Expected ack for {sentinel:?}"
))),
WATCHER_ERROR.to_owned(),
),
(
listing(notify::Error::io(std::io::Error::other(format!(
"IO error for operation on {}",
sentinel.display()
)))),
std::io::ErrorKind::Other.to_string(),
),
];
for (error, expected) in cases {
let shown = error.to_string();
assert!(shown.contains(needle), "control: {shown}");
let cause = notify_cause(&error);
assert!(!cause.contains(needle), "{cause}");
assert!(!cause.contains(" about "), "{cause}");
assert_eq!(cause, expected, "the cause of {shown:?}");
}
let raw = format!("bad{}word", '\x1b');
let cause = notify_cause(¬ify::Error::generic(&raw));
assert_eq!(cause, raw, "the cause is the backend's text");
let shown = safe_inline(&cause);
assert!(!shown.contains('\x1b'), "{shown:?}");
assert!(
shown.starts_with("bad") && shown.ends_with("word"),
"{shown:?}"
);
}
fn escaped_esc() -> String {
format!("{}u001B", '\\')
}
struct Unformattable;
impl std::fmt::Display for Unformattable {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Err(std::fmt::Error)
}
}
#[derive(Debug)]
struct FailsNarrowReads(String);
impl miette::SourceCode for FailsNarrowReads {
fn read_span<'a>(
&'a self,
span: &miette::SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> std::result::Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError>
{
if context_lines_before == 0 && context_lines_after == 0 {
return Err(miette::MietteError::OutOfBounds);
}
miette::SourceCode::read_span(&self.0, span, context_lines_before, context_lines_after)
}
}
#[derive(Debug)]
struct UnformattableCause;
impl std::fmt::Display for UnformattableCause {
fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Err(std::fmt::Error)
}
}
impl std::error::Error for UnformattableCause {}
#[derive(Debug, Default)]
struct Probe {
message: String,
message_fails: bool,
code_fails: bool,
help_fails: bool,
cause: Option<UnformattableCause>,
source: Option<FailsNarrowReads>,
}
impl std::fmt::Display for Probe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.message_fails {
return Err(std::fmt::Error);
}
f.write_str(&self.message)
}
}
impl std::error::Error for Probe {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause
.as_ref()
.map(|c| c as &(dyn std::error::Error + 'static))
}
}
impl miette::Diagnostic for Probe {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
if self.code_fails {
Some(Box::new(Unformattable))
} else {
Some(Box::new("mds::probe"))
}
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
if self.help_fails {
Some(Box::new(Unformattable))
} else {
Some(Box::new("probe help"))
}
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
self.source.as_ref().map(|s| s as &dyn miette::SourceCode)
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
self.source.as_ref()?;
Some(Box::new(std::iter::once(
miette::LabeledSpan::new_primary_with_span(Some("here".to_string()), (0, 5)),
)))
}
}
#[test]
fn a_report_whose_message_cannot_be_formatted_renders_a_placeholder() {
let rendered = render_error_sanitized(miette::Report::new(Probe {
message_fails: true,
..Probe::default()
}));
assert!(
rendered.contains("mds::probe") && rendered.contains("probe help"),
"the rest of the frame must render; got {rendered:?}"
);
assert!(
rendered.contains("could not be formatted"),
"the message's place must say it could not be formatted; got {rendered:?}"
);
}
#[test]
fn a_report_whose_code_help_or_cause_cannot_be_formatted_keeps_its_message() {
let rendered = render_error_sanitized(miette::Report::new(Probe {
message: format!("cannot write fo{}[2Jo.mds", '\x1b'),
code_fails: true,
help_fails: true,
cause: Some(UnformattableCause),
..Probe::default()
}));
assert!(
rendered.contains("cannot write fo") && rendered.contains(&escaped_esc()),
"the message must render, with ESC escaped; got {rendered:?}"
);
assert!(
!rendered.contains('\x1b'),
"no raw ESC may reach the rendered text; got {rendered:?}"
);
assert!(
rendered.contains("could not be formatted"),
"the unformattable cause must leave a placeholder, not vanish; got {rendered:?}"
);
}
#[test]
fn a_render_failure_falls_back_to_escaped_plain_text() {
let rendered = render_error_sanitized(miette::Report::new(Probe {
message: format!("cannot write fo{}[2Jo.mds\nsecond line", '\x1b'),
source: Some(FailsNarrowReads("Hello world\n".to_string())),
..Probe::default()
}));
let esc = escaped_esc();
let want = format!(
"mds::probe\n\n \u{00d7} cannot write fo{esc}[2Jo.mds\n \u{2502} second line\n help: probe help\n"
);
assert_eq!(
rendered, want,
"a failed render must fall back to the plain-text form, escaped"
);
}
#[derive(Clone, Copy)]
enum OnWrite {
Accept,
Fail(std::io::ErrorKind),
Zero,
}
struct Sink {
on_write: OnWrite,
flush_fails: Option<std::io::ErrorKind>,
writes: usize,
bytes: Vec<u8>,
}
impl Sink {
fn new(on_write: OnWrite) -> Self {
Self {
on_write,
flush_fails: None,
writes: 0,
bytes: Vec::new(),
}
}
fn failing_flush(kind: std::io::ErrorKind) -> Self {
Self {
flush_fails: Some(kind),
..Self::new(OnWrite::Accept)
}
}
}
impl std::io::Write for Sink {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.writes += 1;
match self.on_write {
OnWrite::Accept => {
self.bytes.extend_from_slice(buf);
Ok(buf.len())
}
OnWrite::Fail(kind) => Err(std::io::Error::from(kind)),
OnWrite::Zero => Ok(0),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self.flush_fails {
Some(kind) => Err(std::io::Error::from(kind)),
None => Ok(()),
}
}
}
#[test]
fn stderr_writer_writes_the_whole_text_and_records_nothing() {
let state = OutputState::new();
let mut sink = Sink::new(OnWrite::Accept);
write_stderr_to(&state, &mut sink, format_args!("OK: {}\n", "x.mds"));
assert_eq!(sink.bytes, b"OK: x.mds\n");
assert_eq!(sink.writes, 1, "the rendered text goes out in one write");
assert!(!state.stderr_closed() && !state.io_failed());
}
#[test]
fn stderr_writer_treats_a_closed_pipe_as_sticky_and_drops_later_writes() {
let state = OutputState::new();
let mut closed = Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe));
write_stderr_to(&state, &mut closed, format_args!("first\n"));
assert!(state.stderr_closed(), "a closed pipe must be recorded");
assert!(!state.io_failed(), "a closed pipe is not an I/O failure");
let mut later = Sink::new(OnWrite::Accept);
write_stderr_to(&state, &mut later, format_args!("second\n"));
assert_eq!(
later.writes, 0,
"every write after the pipe closed must be dropped"
);
}
#[test]
fn stderr_writer_records_any_other_failure_and_keeps_writing() {
let state = OutputState::new();
let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
write_stderr_to(&state, &mut full, format_args!("first\n"));
assert!(state.io_failed(), "a non-pipe failure must be recorded");
assert!(!state.stderr_closed(), "a full disk is not a closed pipe");
let mut later = Sink::new(OnWrite::Accept);
write_stderr_to(&state, &mut later, format_args!("second\n"));
assert_eq!(
later.bytes, b"second\n",
"an I/O failure must not stop later writes"
);
assert!(state.io_failed(), "the failure stays recorded");
}
#[test]
fn stderr_writer_counts_a_short_write_and_a_failed_flush() {
let short = OutputState::new();
write_stderr_to(&short, &mut Sink::new(OnWrite::Zero), format_args!("x\n"));
assert!(short.io_failed() && !short.stderr_closed());
let flush_full = OutputState::new();
let mut sink = Sink::failing_flush(std::io::ErrorKind::StorageFull);
write_stderr_to(&flush_full, &mut sink, format_args!("x\n"));
assert!(flush_full.io_failed() && !flush_full.stderr_closed());
let flush_closed = OutputState::new();
let mut sink = Sink::failing_flush(std::io::ErrorKind::BrokenPipe);
write_stderr_to(&flush_closed, &mut sink, format_args!("x\n"));
assert!(flush_closed.stderr_closed() && !flush_closed.io_failed());
}
#[test]
fn stderr_writer_survives_a_display_that_fails() {
let state = OutputState::new();
let mut sink = Sink::new(OnWrite::Accept);
write_stderr_to(
&state,
&mut sink,
format_args!("before {} after\n", Unformattable),
);
assert_eq!(
sink.bytes, b"before ",
"the text ends where the Display failed"
);
assert!(
!state.stderr_closed() && !state.io_failed(),
"a formatting bug is not an output failure"
);
}
#[test]
fn an_asked_clear_goes_before_the_first_printed_byte_once() {
let state = OutputState::new();
state.ask_clear();
let mut sink = Sink::new(OnWrite::Accept);
write_stderr_to(&state, &mut sink, format_args!(""));
assert!(sink.bytes.is_empty(), "an empty text makes no clear");
assert!(state.clear_is_asked(), "an empty text keeps the request");
write_stderr_to(&state, &mut sink, format_args!("warning: w\n"));
write_stderr_to(&state, &mut sink, format_args!("Recompiled\n"));
let expected = format!("{CLEAR_SEQUENCE}warning: w\nRecompiled\n");
assert_eq!(sink.bytes, expected.as_bytes());
assert_eq!(sink.writes, 2, "the clear and its line go out in one write");
assert!(!state.clear_is_asked());
}
#[test]
fn no_clear_is_written_unless_one_is_asked_and_stderr_is_open() {
let unasked = OutputState::new();
let mut sink = Sink::new(OnWrite::Accept);
write_stderr_to(&unasked, &mut sink, format_args!("x\n"));
assert_eq!(sink.bytes, b"x\n");
let cancelled = OutputState::new();
cancelled.ask_clear();
cancelled.cancel_clear();
let mut sink = Sink::new(OnWrite::Accept);
write_stderr_to(&cancelled, &mut sink, format_args!("x\n"));
assert_eq!(sink.bytes, b"x\n");
let closed = OutputState::new();
closed.note_stderr_closed();
closed.ask_clear();
let mut sink = Sink::new(OnWrite::Accept);
write_pending_clear_to(&closed, &mut sink);
assert_eq!(sink.writes, 0, "a closed stderr gets no clear");
}
#[test]
fn a_pending_clear_is_made_on_its_own_before_stdout_output() {
let state = OutputState::new();
state.ask_clear();
let mut sink = Sink::new(OnWrite::Accept);
write_pending_clear_to(&state, &mut sink);
write_pending_clear_to(&state, &mut sink);
assert_eq!(sink.bytes, CLEAR_SEQUENCE.as_bytes());
assert_eq!(sink.writes, 1);
}
#[test]
fn write_stdout_is_written_only_when_the_write_and_the_flush_succeed() {
let state = OutputState::new();
let mut ok = Sink::new(OnWrite::Accept);
assert!(matches!(
write_stdout_to(&state, &mut ok, b"compiled\n"),
StdoutOutcome::Written
));
assert_eq!(ok.bytes, b"compiled\n");
assert!(
!state.stdout_closed() && !state.io_failed(),
"a write that succeeds records nothing"
);
let cases = [
(
"write hits a closed pipe",
Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe)),
None,
),
(
"flush hits a closed pipe",
Sink::failing_flush(std::io::ErrorKind::BrokenPipe),
None,
),
(
"write fails",
Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull)),
Some(std::io::ErrorKind::StorageFull),
),
(
"write is short",
Sink::new(OnWrite::Zero),
Some(std::io::ErrorKind::WriteZero),
),
(
"flush fails",
Sink::failing_flush(std::io::ErrorKind::StorageFull),
Some(std::io::ErrorKind::StorageFull),
),
];
for (what, mut sink, failed_kind) in cases {
let outcome = write_stdout_to(&OutputState::new(), &mut sink, b"compiled\n");
match (failed_kind, &outcome) {
(None, StdoutOutcome::Closed) => {}
(Some(want), StdoutOutcome::Failed(e)) if e.kind() == want => {}
_ => panic!("{what}: want Closed or Failed({failed_kind:?}); got {outcome:?}"),
}
}
}
#[test]
fn write_stdout_writes_nothing_once_stdout_is_closed() {
let state = OutputState::new();
let mut closed = Sink::new(OnWrite::Fail(std::io::ErrorKind::BrokenPipe));
let first = write_stdout_to(&state, &mut closed, b"first\n");
assert!(state.stdout_closed(), "a closed stdout must be recorded");
assert!(!state.io_failed(), "a closed pipe is not an I/O failure");
let second = write_stdout_to(&state, &mut closed, b"second\n");
let mut later = Sink::new(OnWrite::Accept);
let third = write_stdout_to(&state, &mut later, b"third\n");
assert_eq!(
(closed.writes, later.writes),
(1, 0),
"no write may follow a closed pipe; outcomes {first:?}, {second:?}, {third:?}"
);
assert!(
matches!(
(&first, &second, &third),
(
StdoutOutcome::Closed,
StdoutOutcome::Closed,
StdoutOutcome::Closed
)
),
"got {first:?}, {second:?}, {third:?}"
);
}
#[test]
fn write_stdout_reports_only_the_first_other_failure() {
let state = OutputState::new();
let _ = write_stdout_to(&state, &mut Sink::new(OnWrite::Accept), b"ok\n");
let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
let first = write_stdout_to(&state, &mut full, b"first\n");
let second = write_stdout_to(&state, &mut full, b"second\n");
assert!(
matches!(&first, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
"the first failure is reported; got {first:?}"
);
assert!(
!matches!(second, StdoutOutcome::Failed(_)),
"a second failure must not be reported again; got {second:?}"
);
assert_eq!(full.writes, 2, "a write after a failure is still attempted");
assert!(
second.into_batch_result().is_ok(),
"a batch run does not report a repeated failure"
);
let mut ok = Sink::new(OnWrite::Accept);
let third = write_stdout_to(&state, &mut ok, b"third\n");
assert!(
matches!(third, StdoutOutcome::Written) && ok.bytes == b"third\n",
"a write that succeeds after a failure is written; got {third:?}"
);
assert!(
!state.stdout_closed() && !state.io_failed(),
"the writer records only the stdout failure; the caller's report records the \
I/O failure for the exit code"
);
}
#[test]
fn write_stdout_reports_a_new_failure_after_stdout_recovers() {
let state = OutputState::new();
let mut full = Sink::new(OnWrite::Fail(std::io::ErrorKind::StorageFull));
let first = write_stdout_to(&state, &mut full, b"one\n");
assert!(
matches!(&first, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
"the first failure is reported; got {first:?}"
);
state.note_io_failure();
let repeat = write_stdout_to(&state, &mut full, b"two\n");
assert!(
matches!(repeat, StdoutOutcome::FailedAgain),
"a repeat before stdout recovers is not reported; got {repeat:?}"
);
let mut empty = Sink::new(OnWrite::Accept);
let nothing = write_stdout_to(&state, &mut empty, b"");
assert!(matches!(nothing, StdoutOutcome::Written), "got {nothing:?}");
let still = write_stdout_to(&state, &mut full, b"three\n");
assert!(
matches!(still, StdoutOutcome::FailedAgain),
"a write of no bytes does not show that stdout recovered; got {still:?}"
);
let mut ok = Sink::new(OnWrite::Accept);
let recovered = write_stdout_to(&state, &mut ok, b"four\n");
assert!(
matches!(recovered, StdoutOutcome::Written) && ok.bytes == b"four\n",
"stdout recovers; got {recovered:?}"
);
let again = write_stdout_to(&state, &mut full, b"five\n");
assert!(
matches!(&again, StdoutOutcome::Failed(e) if e.kind() == std::io::ErrorKind::StorageFull),
"a failure after stdout recovered is a new one, reported again; got {again:?}"
);
let repeat_again = write_stdout_to(&state, &mut full, b"six\n");
assert!(
matches!(repeat_again, StdoutOutcome::FailedAgain),
"the new failure's repeat is not reported; got {repeat_again:?}"
);
assert_eq!(full.writes, 5, "every write is attempted");
assert!(
state.io_failed() && !state.stdout_closed(),
"the recovery clears neither the recorded I/O failure nor anything else"
);
assert_eq!(
final_exit_code(0, &state, ExitPolicy::Batch),
IO_FAILURE_EXIT,
"a batch run that lost a stdout write still exits 2 after stdout recovered"
);
}
#[test]
fn a_batch_run_ignores_a_closed_stdout_and_reports_any_other_failure() {
assert!(StdoutOutcome::Written.into_batch_result().is_ok());
assert!(StdoutOutcome::Closed.into_batch_result().is_ok());
assert!(
StdoutOutcome::FailedAgain.into_batch_result().is_ok(),
"a repeated failure was already reported"
);
let failed = StdoutOutcome::Failed(std::io::Error::new(
std::io::ErrorKind::StorageFull,
"no space left",
))
.into_batch_result();
match failed {
Err(mds::MdsError::Io { message }) => {
assert_eq!(
message,
format!(
"cannot write to stdout: {}",
std::io::ErrorKind::StorageFull
),
"the error's kind, not the text it carries (#390)"
);
}
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
}
#[test]
fn final_exit_code_table() {
struct Case {
verdict: i32,
closed: bool,
failed: bool,
policy: ExitPolicy,
want: i32,
}
const fn case(
verdict: i32,
closed: bool,
failed: bool,
policy: ExitPolicy,
want: i32,
) -> Case {
Case {
verdict,
closed,
failed,
policy,
want,
}
}
use ExitPolicy::{Batch, WatchSession};
let cases = [
case(0, false, false, Batch, 0),
case(1, false, false, Batch, 1),
case(2, false, false, Batch, 2),
case(3, false, false, Batch, 3),
case(101, false, false, Batch, 101),
case(0, true, false, Batch, 0),
case(1, true, false, Batch, 1),
case(3, true, false, Batch, 3),
case(0, false, true, Batch, 2),
case(1, false, true, Batch, 2),
case(2, false, true, Batch, 2),
case(3, false, true, Batch, 3),
case(101, false, true, Batch, 101),
case(0, true, true, Batch, 2),
case(1, true, true, Batch, 2),
case(0, false, false, WatchSession, 0),
case(1, false, false, WatchSession, 1),
case(0, true, false, WatchSession, 0),
case(0, false, true, WatchSession, 0),
case(1, false, true, WatchSession, 1),
case(3, false, true, WatchSession, 3),
case(0, true, true, WatchSession, 0),
];
for c in cases {
let state = OutputState::new();
if c.closed {
state.note_stderr_closed();
}
if c.failed {
state.note_io_failure();
}
assert_eq!(
final_exit_code(c.verdict, &state, c.policy),
c.want,
"verdict {} closed={} failed={} {:?}",
c.verdict,
c.closed,
c.failed,
c.policy
);
}
let report = miette::Report::new(mds::MdsError::Internal);
for (verdict, policy, want) in [(1, Batch, 101), (0, WatchSession, 0), (1, WatchSession, 1)]
{
let state = OutputState::new();
state.note_io_failure();
state.note_resource_limited();
note_file_failure(&state, &report);
assert!(!state.panicked());
assert_eq!(final_exit_code(verdict, &state, policy), want, "{policy:?}");
}
}
#[test]
fn the_session_rule_applies_only_once_a_watch_session_is_live() {
let state = OutputState::new();
assert_eq!(
state.exit_policy(),
ExitPolicy::Batch,
"a fresh run is a batch"
);
state.note_io_failure();
assert_eq!(
final_exit_code(0, &state, state.exit_policy()),
2,
"before a session goes live, an output failure lifts the exit code"
);
state.note_watch_live();
assert_eq!(state.exit_policy(), ExitPolicy::WatchSession);
assert_eq!(
final_exit_code(0, &state, state.exit_policy()),
0,
"a live session keeps its verdict, the failure recorded before it included"
);
state.note_io_failure();
state.note_watch_live();
assert_eq!(
final_exit_code(1, &state, state.exit_policy()),
1,
"going live is sticky, and a failure recorded after it changes nothing"
);
}
#[test]
fn a_resource_limited_file_lifts_a_batch_run_to_3() {
use ExitPolicy::{Batch, WatchSession};
let cases = [
(0, false, Batch, 0, 3),
(1, false, Batch, 1, 3),
(2, false, Batch, 2, 3),
(3, false, Batch, 3, 3),
(1, true, Batch, 2, 3),
(2, true, Batch, 2, 3),
(101, false, Batch, 101, 101),
(0, false, WatchSession, 0, 0),
(1, true, WatchSession, 1, 1),
];
for (verdict, io_failed, policy, without, with) in cases {
let state = OutputState::new();
if io_failed {
state.note_io_failure();
}
assert_eq!(
final_exit_code(verdict, &state, policy),
without,
"control: verdict {verdict} io_failed={io_failed} {policy:?} without a limit"
);
state.note_resource_limited();
assert!(state.resource_limited());
assert_eq!(
final_exit_code(verdict, &state, policy),
with,
"verdict {verdict} io_failed={io_failed} {policy:?} with a limit"
);
}
let state = OutputState::new();
state.note_resource_limited();
state.note_panicked();
assert_eq!(
final_exit_code(1, &state, Batch),
101,
"a panic still wins over a resource limit"
);
}
#[test]
fn a_file_failure_is_recorded_by_the_class_of_its_exit_code() {
use mds::MdsError;
let cases = [
(
miette::Report::new(MdsError::Io {
message: "cannot read a.mds".to_owned(),
}),
true,
false,
),
(
miette::Report::new(MdsError::not_mds_file("a.txt")),
true,
false,
),
(
miette::Report::new(MdsError::ResourceLimit {
message: "module has more than 256 @block declarations".to_owned(),
}),
false,
true,
),
(
miette::Report::new(MdsError::YamlError {
message: "bad frontmatter".to_owned(),
}),
false,
false,
),
(miette::miette!("an error with no code"), false, false),
];
for (report, io_failed, resource_limited) in cases {
let state = OutputState::new();
note_file_failure(&state, &report);
assert_eq!(
(state.io_failed(), state.resource_limited()),
(io_failed, resource_limited),
"{report}"
);
}
}
#[test]
fn a_panic_exits_101_whatever_else_was_recorded() {
use ExitPolicy::{Batch, WatchSession};
let cases = [
(0, false, false, Batch),
(1, false, false, Batch),
(2, false, true, Batch),
(3, false, true, Batch),
(0, true, false, Batch),
(0, false, false, WatchSession),
(1, true, true, WatchSession),
(3, false, true, WatchSession),
];
for (verdict, closed, failed, policy) in cases {
let state = OutputState::new();
if closed {
state.note_stderr_closed();
}
if failed {
state.note_io_failure();
}
assert!(
final_exit_code(verdict, &state, policy) < 101,
"control: verdict {verdict} closed={closed} failed={failed} {policy:?} \
exits below 101 until a panic is recorded"
);
state.note_panicked();
assert!(state.panicked());
assert_eq!(
final_exit_code(verdict, &state, policy),
101,
"verdict {verdict} closed={closed} failed={failed} {policy:?}"
);
}
}
#[test]
fn rust_backtrace_picks_the_backtrace_a_panic_prints() {
let cases = [
(None, None),
(Some("0"), None),
(Some("1"), Some(BacktraceStyle::Short)),
(Some("full"), Some(BacktraceStyle::Full)),
(Some(""), Some(BacktraceStyle::Short)),
(Some("short"), Some(BacktraceStyle::Short)),
];
for (value, want) in cases {
assert_eq!(
BacktraceStyle::from_env(value.map(OsStr::new)),
want,
"RUST_BACKTRACE={value:?}"
);
}
}
#[test]
fn the_internal_compiler_error_text_names_the_issue_tracker() {
let lines: Vec<&str> = ICE_TEXT.lines().collect();
assert_eq!(lines.len(), 2, "{ICE_TEXT:?}");
assert!(ICE_TEXT.ends_with('\n'), "{ICE_TEXT:?}");
assert_eq!(lines[0], "mds: internal compiler error");
let tracker = concat!(env!("CARGO_PKG_REPOSITORY"), "/issues");
assert!(
tracker.starts_with("https://github.com/") && tracker.len() > 26,
"the manifest names a GitHub repository: {tracker}"
);
assert!(lines[1].ends_with(tracker), "{ICE_TEXT:?}");
assert!(
ICE_TEXT.chars().all(|c| c == '\n' || !c.is_control()),
"{ICE_TEXT:?}"
);
}
#[test]
fn a_backtrace_is_escaped_line_by_line() {
let esc = char::from(0x1b);
let cr = char::from(0x0d);
let rlo = char::from_u32(0x202E).expect("U+202E");
let code = |c: char| format!("{}u{:04X}", '\\', u32::from(c));
let text = format!("frame {esc}[2J\n\tat {rlo}file.rs{cr}\nlast");
assert_eq!(
escape_each_line(&text),
format!(
"frame {}[2J\n\tat {}file.rs{}\nlast\n",
code(esc),
code(rlo),
code(cr)
)
);
assert_eq!(escape_each_line("a\nb\n"), "a\nb\n");
}
#[test]
fn write_backtrace_writes_escaped_frames_and_ignores_a_failed_write() {
for style in [BacktraceStyle::Short, BacktraceStyle::Full] {
let mut sink = Sink::new(OnWrite::Accept);
write_backtrace(&mut sink, style);
let text = String::from_utf8(sink.bytes).expect("a backtrace is UTF-8");
assert!(text.starts_with("stack backtrace:\n"), "{style:?}: {text}");
assert!(
text.contains("write_backtrace"),
"{style:?}: the frames include the writer's own; {text}"
);
assert!(
text.split_terminator('\n')
.all(|line| mds::sanitize_control_chars_wire(line) == line),
"{style:?}: every line is escaped; {text}"
);
assert_eq!(sink.writes, 1, "{style:?}: one write");
for kind in [
std::io::ErrorKind::BrokenPipe,
std::io::ErrorKind::StorageFull,
] {
let mut failing = Sink::new(OnWrite::Fail(kind));
write_backtrace(&mut failing, style);
assert_eq!(
failing.writes, 1,
"{style:?}: a failed write is not retried"
);
}
}
}
#[cfg(debug_assertions)]
#[test]
fn the_trigger_s_payload_carries_a_sentinel_an_esc_and_an_absolute_path() {
let payload = panic_trigger::payload();
let here = std::env::current_dir().expect("the working directory");
assert!(here.is_absolute(), "{here:?}");
assert!(payload.contains(panic_trigger::SENTINEL), "{payload:?}");
assert!(payload.contains(char::from(0x1b)), "{payload:?}");
assert!(payload.contains(&here.display().to_string()), "{payload:?}");
}
fn streams(child: &std::process::Output) -> (String, String) {
(
String::from_utf8_lossy(&child.stdout).into_owned(),
String::from_utf8_lossy(&child.stderr).into_owned(),
)
}
#[test]
fn a_caught_panic_is_reported_once_and_the_run_goes_on() {
const NAME: &str = "output::tests::a_caught_panic_is_reported_once_and_the_run_goes_on";
if child_process::is_child(NAME) {
install_panic_hook();
let first = catch_panic(|| {
panic!("first");
});
let second = catch_panic(|| {
panic!("second");
});
if first.is_err() && second.is_err() {
let _ = write_stdout(b"after both catches\n");
}
exit(0);
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert_eq!(
child.status.code(),
Some(101),
"a run that caught a panic exits 101; stdout:\n{report}\nstderr:\n{shown}"
);
assert!(
report.contains("after both catches") && !report.contains("test result"),
"both panics were caught and the run went on to the exit; stdout:\n{report}"
);
assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
}
#[test]
fn a_panic_report_cancels_the_pending_clear() {
const NAME: &str = "output::tests::a_panic_report_cancels_the_pending_clear";
if child_process::is_child(NAME) {
install_panic_hook();
OUTPUT_STATE.ask_clear();
let caught = catch_panic(|| {
panic!("while a clear is asked for");
});
assert!(caught.is_err(), "the panic unwound to the catch");
assert!(
!OUTPUT_STATE.clear_is_asked(),
"the report took the request"
);
ewriteln!("after the report");
OUTPUT_STATE.ask_clear();
ewriteln!("control");
exit(0);
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert_eq!(
shown,
format!("{ICE_TEXT}after the report\n{CLEAR_SEQUENCE}control\n"),
"no clear before the report or after it; the control's clear comes before its line"
);
assert_eq!(
child.status.code(),
Some(101),
"a run that caught a panic exits 101; stdout:\n{report}\nstderr:\n{shown}"
);
}
#[test]
fn a_panic_nothing_catches_ends_the_run_at_once_with_101() {
const NAME: &str = "output::tests::a_panic_nothing_catches_ends_the_run_at_once_with_101";
if child_process::is_child(NAME) {
install_panic_hook();
panic!("uncaught");
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert_eq!(
child.status.code(),
Some(101),
"stdout:\n{report}\nstderr:\n{shown}"
);
assert!(
!report.contains("test result"),
"the process ended at the panic, before the harness could report it; \
stdout:\n{report}"
);
assert_eq!(shown, ICE_TEXT, "the text, once");
}
#[test]
fn a_panic_while_unwinding_ends_the_run_with_101_not_an_abort() {
const NAME: &str =
"output::tests::a_panic_while_unwinding_ends_the_run_with_101_not_an_abort";
struct PanicsWhenDropped;
impl Drop for PanicsWhenDropped {
fn drop(&mut self) {
panic!("second");
}
}
if child_process::is_child(NAME) {
install_panic_hook();
let _ = catch_panic(|| {
let _armed = PanicsWhenDropped;
panic!("first");
});
let _ = write_stdout(b"the run went on\n");
exit(0);
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert_eq!(
child.status.code(),
Some(101),
"exit 101, not an abort (a signal: None); stdout:\n{report}\nstderr:\n{shown}"
);
assert!(
!report.contains("the run went on") && !report.contains("test result"),
"the process ended at the second panic; stdout:\n{report}"
);
assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
}
#[test]
fn a_panic_is_recorded_before_the_hook_writes() {
const NAME: &str = "output::tests::a_panic_is_recorded_before_the_hook_writes";
const POLLS: u32 = 500;
const POLL: std::time::Duration = std::time::Duration::from_millis(10);
if child_process::is_child(NAME) {
install_panic_hook();
let _held = std::io::stderr().lock();
let _helper = std::thread::spawn(|| panic!("helper"));
for _ in 0..POLLS {
if OUTPUT_STATE.panicked() {
break;
}
std::thread::sleep(POLL);
}
let _ = write_stdout(b"at the funnel\n");
exit(0);
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert!(
report.contains("at the funnel") && !report.contains("test result"),
"control: the child ended at the funnel; stdout:\n{report}"
);
assert_eq!(
shown, "",
"control: the hook's write waited on the held lock until the process ended"
);
assert_eq!(
child.status.code(),
Some(101),
"a panic whose hook cannot write still makes the run exit 101; stdout:\n{report}"
);
}
#[test]
fn a_panic_into_a_function_that_cannot_unwind_ends_the_run_with_101_not_an_abort() {
const NAME: &str = "output::tests::\
a_panic_into_a_function_that_cannot_unwind_ends_the_run_with_101_not_an_abort";
extern "C" fn cannot_unwind() {
panic!("first");
}
if child_process::is_child(NAME) {
install_panic_hook();
let _ = catch_panic(|| cannot_unwind());
let _ = write_stdout(b"the run went on\n");
exit(0);
}
let child = child_process::run(NAME);
let (report, shown) = streams(&child);
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert_eq!(
child.status.code(),
Some(101),
"exit 101, not an abort (a signal: None); stdout:\n{report}\nstderr:\n{shown}"
);
assert!(
!report.contains("the run went on") && !report.contains("test result"),
"the process ended at the second panic; stdout:\n{report}"
);
assert_eq!(shown, ICE_TEXT.repeat(2), "one text per panic");
}
#[test]
fn a_caught_payload_is_dropped_only_when_that_runs_no_code_of_its_own() {
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
struct CountsDrops(Arc<AtomicUsize>);
impl Drop for CountsDrops {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
assert_eq!(
dispose_payload(Box::new(String::from("a formatted message"))),
Disposal::Dropped,
"a `String` message is dropped"
);
assert_eq!(
dispose_payload(Box::new("a literal message")),
Disposal::Dropped,
"a `&'static str` message is dropped"
);
let drops = Arc::new(AtomicUsize::new(0));
drop(CountsDrops(Arc::clone(&drops)));
assert_eq!(
drops.load(Ordering::SeqCst),
1,
"control: the counting payload's destructor runs when it is dropped"
);
assert_eq!(
dispose_payload(Box::new(CountsDrops(Arc::clone(&drops)))),
Disposal::Forgotten,
"any other payload is forgotten"
);
assert_eq!(
drops.load(Ordering::SeqCst),
1,
"a forgotten payload's destructor never runs"
);
}
#[cfg(unix)]
const GONE_CWD_CHILD: &str = "MDS_OUTPUT_GONE_CWD_CHILD";
#[cfg(unix)]
#[test]
fn a_working_directory_that_is_gone_fails_closed_in_core_s_words() {
const NAME: &str =
"output::tests::a_working_directory_that_is_gone_fails_closed_in_core_s_words";
if std::env::var_os(GONE_CWD_CHILD).is_some_and(|value| value == NAME) {
let dir = tempfile::tempdir().expect("a temp dir");
let gone = dir.path().join("gone");
std::fs::create_dir(&gone).expect("create the working directory");
std::env::set_current_dir(&gone).expect("move into it");
std::fs::remove_dir(&gone).expect("remove it");
let ours = current_dir().expect_err("no working directory to determine");
let core = mds::check_str_with("Hello!\n", None, None)
.expect_err("core needs the working directory as the base");
assert!(
matches!(
(&ours, &core),
(mds::MdsError::Io { .. }, mds::MdsError::Io { .. })
),
"both mds::io: {ours:?} / {core:?}"
);
assert_eq!(ours.to_string(), core.to_string(), "core's words exactly");
assert!(
ours.to_string()
.starts_with("cannot determine current directory: "),
"{ours}"
);
let refused = canonicalize_out_dir(Some(&PathBuf::from("out")))
.expect_err("a relative out-dir has no directory to resolve against");
assert_eq!(refused.to_string(), ours.to_string());
let absolute = dir.path().join("out");
assert_eq!(
canonicalize_out_dir(Some(&absolute)).expect("an absolute out-dir resolves"),
Some(absolute.clone()),
"control: an absolute out-dir needs no working directory"
);
assert_eq!(canonicalize_out_dir(None).expect("no out-dir"), None);
let refused = resolve_output_base(Some(&PathBuf::from("out")), &None)
.expect_err("a relative out-dir is refused, not resolved");
assert_eq!(refused.to_string(), ours.to_string());
assert!(
matches!(
refused.downcast_ref::<mds::MdsError>(),
Some(mds::MdsError::Io { .. })
),
"mds::io: {refused:?}"
);
match resolve_output_base(Some(&absolute), &None).expect("an absolute out-dir") {
OutputBase::Dir {
canonical, shown, ..
} => {
assert_eq!(canonical, absolute, "control: resolved without one");
assert_eq!(shown, absolute, "control: shown as typed");
}
other => panic!("control: want Dir; got {other:?}"),
}
return;
}
assert_eq!(
current_dir().expect("the working directory exists"),
std::env::current_dir().expect("the working directory exists"),
"control: where it exists, it is the working directory"
);
let binary = std::env::current_exe().expect("the test binary's path");
let child = std::process::Command::new(binary)
.args([NAME, "--exact", "--nocapture", "--test-threads=1"])
.env(GONE_CWD_CHILD, NAME)
.output()
.expect("the child runs");
let report = String::from_utf8_lossy(&child.stdout);
assert!(
child.status.success() && report.contains("1 passed"),
"the child ran the test and it passed; stdout:\n{report}\nstderr:\n{}",
String::from_utf8_lossy(&child.stderr)
);
}
}