mod common;
use common::{mds_bin, spawn_watch_ready, spawn_watch_unsynchronized, StderrTap};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
impl ChildGuard {
fn id(&self) -> u32 {
self.0.id()
}
fn wait_status(&mut self) -> std::process::ExitStatus {
self.0.wait().expect("wait failed")
}
}
fn spawn_ready(cmd: &mut Command) -> (ChildGuard, StderrTap) {
let (child, tap) = spawn_watch_ready(cmd);
(ChildGuard(child), tap)
}
fn spawn_unsynchronized(cmd: &mut Command) -> (ChildGuard, StderrTap) {
let (child, tap) = spawn_watch_unsynchronized(cmd);
(ChildGuard(child), tap)
}
fn wait_for_file_contains(path: &Path, needle: &str, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Ok(content) = std::fs::read_to_string(path) {
if content.contains(needle) {
return true;
}
}
std::thread::sleep(Duration::from_millis(50));
}
false
}
fn wait_for_file_contains_tight(path: &Path, needle: &str, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Ok(content) = std::fs::read_to_string(path) {
if content.contains(needle) {
return true;
}
}
std::thread::sleep(Duration::from_millis(1));
}
false
}
fn wait_for_file_gone(path: &Path, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if !path.exists() {
return true;
}
std::thread::sleep(Duration::from_millis(50));
}
false
}
const TIMEOUT: Duration = Duration::from_secs(2);
const TICK_TIMEOUT: Duration = Duration::from_secs(8);
const STARTUP_WINDOW_TIMEOUT: Duration = Duration::from_secs(5);
#[test]
fn watch_rejects_stdin() {
let output = mds_bin()
.args(["watch", "-"])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with stdin should fail; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("stdin") || stderr.contains("build"),
"error should mention stdin, got: {stderr}"
);
}
#[test]
fn watch_rejects_dir_with_output_flag() {
let dir = tempfile::tempdir().unwrap();
let output = mds_bin()
.args(["watch", dir.path().to_str().unwrap(), "-o", "out.md"])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch dir with -o should fail; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
}
#[test]
fn watch_initial_compile_writes_output() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
let found = wait_for_file_contains(&out, "Hello World!", TIMEOUT);
assert!(found, "initial compile should write output to hello.md");
drop(child);
}
#[test]
fn watch_edit_entry_updates_output() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: Alice\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
"initial compile should produce Hello Alice!"
);
std::fs::write(&src, "---\nname: Bob\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
"after editing, output should contain Hello Bob!"
);
drop(child);
}
#[test]
fn watch_edit_imported_dep_updates_entry() {
let dir = tempfile::tempdir().unwrap();
let helper = dir.path().join("helper.mds");
std::fs::write(
&helper,
"@define greet(name):\nHello {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
let entry = dir.path().join("entry.mds");
std::fs::write(
&entry,
"@import \"./helper.mds\" as h\n\n{{h.greet(\"World\")}}\n",
)
.unwrap();
let out = dir.path().join("entry.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", entry.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should produce Hello World!"
);
std::fs::write(
&helper,
"@define greet(name):\nHi there {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out, "Hi there World!", TIMEOUT),
"editing the imported helper should trigger a rebuild"
);
drop(child);
}
#[test]
fn watch_compile_error_keeps_watcher_alive() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: Alice\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
"initial compile should succeed"
);
std::fs::write(&src, "Hello {{undefined_var_xyz}}!\n").unwrap();
std::thread::sleep(Duration::from_millis(500));
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher should stay alive after compile error"
);
std::fs::write(&src, "---\nname: Charlie\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello Charlie!", TIMEOUT),
"fixing the error should trigger a successful rebuild"
);
drop(child);
}
#[test]
fn watch_dir_mode_compiles_all_on_startup() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.mds"),
"---\nname: A\n---\nFile A: {{name}}\n",
)
.unwrap();
std::fs::write(
dir.path().join("b.mds"),
"---\nname: B\n---\nFile B: {{name}}\n",
)
.unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
"a.md should be compiled on startup"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "File B: B", TIMEOUT),
"b.md should be compiled on startup"
);
std::fs::write(
dir.path().join("a.mds"),
"---\nname: A-edited\n---\nFile A: {{name}}\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A-edited", TIMEOUT),
"editing a.mds should update a.md"
);
let b_content = std::fs::read_to_string(out_dir.join("b.md")).unwrap();
assert!(
b_content.contains("File B: B"),
"b.md should not be affected by edits to a.mds, got: {b_content}"
);
drop(child);
}
#[test]
fn watch_dir_mode_picks_up_new_files() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "---\nname: A\n---\nFile A\n").unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A", TIMEOUT),
"a.md should appear on startup"
);
std::fs::write(
dir.path().join("c.mds"),
"---\nname: C\n---\nNew file {{name}}\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("c.md"), "New file C", TIMEOUT),
"newly created c.mds should be compiled to c.md"
);
drop(child);
}
#[test]
fn watch_dir_mode_deletes_output_on_source_deletion() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "---\nname: A\n---\nFile A\n").unwrap();
std::fs::write(dir.path().join("b.mds"), "---\nname: B\n---\nFile B\n").unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A", TIMEOUT),
"a.md should appear on startup"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "File B", TIMEOUT),
"b.md should appear on startup"
);
std::fs::remove_file(dir.path().join("a.mds")).unwrap();
assert!(
wait_for_file_gone(&out_dir.join("a.md"), TIMEOUT),
"a.md should be removed when a.mds is deleted"
);
assert!(
out_dir.join("b.md").exists(),
"b.md should not be removed when only a.mds was deleted"
);
drop(child);
}
#[test]
fn watch_vars_file_change_triggers_recompile() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: Default\n---\nHello {{name}}!\n").unwrap();
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"name": "Alice"}"#).unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--vars",
vars.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
"initial compile with vars should produce Hello Alice!"
);
std::fs::write(&vars, r#"{"name": "Bob"}"#).unwrap();
assert!(
wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
"editing vars file should trigger recompile with new name"
);
drop(child);
}
#[test]
fn watch_clear_non_tty_no_ansi_escape() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--clear", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should write output"
);
std::fs::write(&src, "---\nname: There\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello There!", TIMEOUT),
"rebuild should occur after editing source"
);
let _ = child.0.kill();
let _ = child.0.wait();
let stderr_bytes = stderr_tap.bytes();
assert!(
!contains_subslice(&stderr_bytes, b"\x1b[2J"),
"ANSI erase-screen (\\x1b[2J) must not be emitted on a non-TTY pipe; \
stderr was: {:?}",
String::from_utf8_lossy(&stderr_bytes)
);
assert!(
!contains_subslice(&stderr_bytes, b"\x1b[3J"),
"ANSI erase-scrollback (\\x1b[3J) must not be emitted on a non-TTY pipe"
);
assert!(
!contains_subslice(&stderr_bytes, b"\x1b["),
"no ANSI CSI escape (\\x1b[) should appear on a non-TTY pipe"
);
}
fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
if needle.is_empty() {
return true;
}
haystack.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn watch_output_flag_writes_to_specified_file() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("custom_output.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
out.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"watch with -o should write to the specified file"
);
assert!(
!dir.path().join("hello.md").exists(),
"default hello.md should not be written when -o overrides"
);
drop(child);
}
#[test]
fn watch_set_vars_applied_on_rebuild() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("tpl.mds");
std::fs::write(&src, "Hello {{name}}!\n").unwrap();
let out = dir.path().join("tpl.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--set",
"name=Alice",
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello Alice!", TIMEOUT),
"--set name=Alice should be applied on initial compile"
);
std::fs::write(&src, "Greetings {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Greetings Alice!", TIMEOUT),
"--set name=Alice should persist across rebuilds"
);
drop(child);
}
#[test]
fn watch_messages_template_produces_json_intrinsically() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("chat.mds");
std::fs::write(&src, "@message user:\nWhat is 2+2?\n@end\n").unwrap();
let out = dir.path().join("chat.json");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
out.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "What is 2+2?", TIMEOUT),
"messages template should write JSON containing the message"
);
let content = std::fs::read_to_string(&out).unwrap();
let parsed: serde_json::Value =
serde_json::from_str(&content).expect("messages output should be valid JSON");
assert!(
parsed.is_array(),
"messages output should be a JSON array, got: {content}"
);
drop(child);
}
#[test]
fn watch_stdout_contains_content_when_o_stdout() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"-q",
])
.stdout(Stdio::piped()),
);
use std::io::Read as _;
let deadline = Instant::now() + TIMEOUT;
let mut buf = String::new();
let mut found = false;
while Instant::now() < deadline {
let mut tmp = [0u8; 256];
if let Some(stdout) = child.0.stdout.as_mut() {
match stdout.read(&mut tmp) {
Ok(0) | Err(_) => {}
Ok(n) => {
buf.push_str(&String::from_utf8_lossy(&tmp[..n]));
if buf.contains("Hello World!") {
found = true;
break;
}
}
}
}
std::thread::sleep(Duration::from_millis(50));
}
assert!(found, "with -o -, compiled output should appear on stdout");
drop(child);
}
#[test]
#[cfg(unix)]
fn watch_ctrl_c_exits_cleanly() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (mut guard, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
let pid = guard.id();
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should succeed before sending SIGINT"
);
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let deadline = Instant::now() + Duration::from_secs(5);
let mut exited = false;
while Instant::now() < deadline {
if guard.0.try_wait().unwrap().is_some() {
exited = true;
break;
}
std::thread::sleep(Duration::from_millis(50));
}
assert!(exited, "process should exit after SIGINT");
let status = guard.wait_status();
assert!(
status.success(),
"exit code should be 0 after Ctrl+C, got: {status:?}"
);
}
#[test]
fn watch_debounce_final_value_wins_after_rapid_edits() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: v0\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "200"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello v0!", TIMEOUT),
"initial compile should produce v0"
);
for i in 1..=10 {
std::fs::write(&src, format!("---\nname: v{i}\n---\nHello {{{{name}}}}!\n")).unwrap();
std::thread::sleep(Duration::from_millis(5));
}
assert!(
wait_for_file_contains(&out, "Hello v10!", TIMEOUT),
"after rapid edits, output should reflect final value"
);
drop(child);
}
#[test]
fn watch_invalid_path_startup_error() {
let output = mds_bin()
.args(["watch", "/nonexistent/path/that/does/not/exist.mds"])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with invalid path should fail"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.is_empty(),
"error message should appear on stderr, got empty"
);
}
#[test]
fn watch_import_removal_stops_tracking_dep() {
let dir = tempfile::tempdir().unwrap();
let helper = dir.path().join("helper.mds");
std::fs::write(
&helper,
"@define greet(name):\nHello {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
let entry = dir.path().join("entry.mds");
std::fs::write(
&entry,
"@import \"./helper.mds\" as h\n\n{{h.greet(\"World\")}}\n",
)
.unwrap();
let out = dir.path().join("entry.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", entry.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should produce Hello World!"
);
std::fs::write(
&helper,
"@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out, "Hi World!", TIMEOUT),
"editing helper while imported should trigger a rebuild"
);
std::fs::write(&entry, "Static content\n").unwrap();
assert!(
wait_for_file_contains(&out, "Static content", TIMEOUT),
"removing @import should rebuild entry with static content"
);
let content_before = std::fs::read_to_string(&out).unwrap();
std::fs::write(
&helper,
"@define greet(name):\nBye {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
std::thread::sleep(Duration::from_millis(500));
let content_after = std::fs::read_to_string(&out).unwrap();
assert_eq!(
content_before, content_after,
"after removing @import, editing helper must NOT change entry output"
);
drop(child);
}
#[test]
fn watch_dir_mode_vars_change_recompiles_all() {
let src_dir = tempfile::tempdir().unwrap();
let out_dir_path = src_dir.path().join("out");
std::fs::create_dir(&out_dir_path).unwrap();
std::fs::write(
src_dir.path().join("a.mds"),
"---\ngreeting: Default\n---\n{{greeting}} from A\n",
)
.unwrap();
std::fs::write(
src_dir.path().join("b.mds"),
"---\ngreeting: Default\n---\n{{greeting}} from B\n",
)
.unwrap();
let vars = src_dir.path().join("vars.json");
std::fs::write(&vars, r#"{"greeting": "Hello"}"#).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src_dir.path().to_str().unwrap(),
"--out-dir",
out_dir_path.to_str().unwrap(),
"--vars",
vars.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir_path.join("a.md"), "Hello from A", TIMEOUT),
"a.md should initially contain 'Hello from A'"
);
assert!(
wait_for_file_contains(&out_dir_path.join("b.md"), "Hello from B", TIMEOUT),
"b.md should initially contain 'Hello from B'"
);
std::fs::write(&vars, r#"{"greeting": "Goodbye"}"#).unwrap();
assert!(
wait_for_file_contains(&out_dir_path.join("a.md"), "Goodbye from A", TIMEOUT),
"a.md should update to 'Goodbye from A' after vars change"
);
assert!(
wait_for_file_contains(&out_dir_path.join("b.md"), "Goodbye from B", TIMEOUT),
"b.md should update to 'Goodbye from B' after vars change"
);
drop(child);
}
#[test]
fn watch_quiet_keeps_errors_visible() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should succeed"
);
std::fs::write(&src, "Hello {{__undefined_xyz__}}!\n").unwrap();
std::thread::sleep(Duration::from_millis(500));
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher must stay alive after a compile error even under -q"
);
let stderr_str = stderr_tap.text();
assert!(
stderr_str.contains("__undefined_xyz__"),
"stderr must carry the compile error naming the undefined variable even under \
-q; got:\n{stderr_str}"
);
std::fs::write(&src, "---\nname: Fixed\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello Fixed!", TIMEOUT),
"after fixing the compile error, watcher should rebuild successfully"
);
drop(child);
}
#[test]
#[cfg(unix)]
fn watch_ctrl_c_prints_stopped_watching() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (mut guard, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
let pid = guard.id();
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should succeed before sending SIGINT"
);
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let deadline = Instant::now() + Duration::from_secs(5);
let mut exited = false;
while Instant::now() < deadline {
if guard.0.try_wait().unwrap().is_some() {
exited = true;
break;
}
std::thread::sleep(Duration::from_millis(50));
}
assert!(exited, "process should exit after SIGINT");
let status = guard.wait_status();
assert!(
status.success(),
"exit code should be 0 after Ctrl+C, got: {status:?}"
);
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
assert!(
stderr_str.contains("Stopped watching."),
"stderr should contain 'Stopped watching.' after Ctrl+C, got: {stderr_str:?}"
);
}
#[test]
fn watch_debounce_single_rebuild_from_burst() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("burst.mds");
std::fs::write(&src, "---\nname: v0\n---\nBurst {{name}}!\n").unwrap();
let out = dir.path().join("burst.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "250"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Burst v0!", TIMEOUT),
"initial compile should produce Burst v0!"
);
for i in 1..=10u32 {
std::fs::write(&src, format!("---\nname: v{i}\n---\nBurst {{{{name}}}}!\n")).unwrap();
std::thread::sleep(Duration::from_millis(5));
}
assert!(
wait_for_file_contains(&out, "Burst v10!", TIMEOUT),
"after burst, output should reflect final value v10"
);
std::thread::sleep(Duration::from_millis(400));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let rebuild_count = stderr_str.matches("Recompiled ").count();
assert!(
rebuild_count >= 1,
"at least one rebuild must have occurred, got 0; stderr: {stderr_str}"
);
assert!(
rebuild_count <= 2,
"debounce should coalesce burst into <= 2 rebuilds, got {rebuild_count}; \
stderr: {stderr_str}"
);
}
#[test]
fn watch_no_arg_auto_detects_single_mds_file() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("only.mds"),
"---\nname: AutoDetect\n---\nAuto {{name}}!\n",
)
.unwrap();
let out = dir.path().join("only.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", "--debounce", "0", "-q"])
.current_dir(dir.path()) .stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Auto AutoDetect!", TIMEOUT),
"auto-detect with single .mds file should compile only.mds"
);
drop(child);
}
#[test]
fn watch_no_arg_fails_with_multiple_mds_files() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "File A\n").unwrap();
std::fs::write(dir.path().join("b.mds"), "File B\n").unwrap();
let output = mds_bin()
.args(["watch"])
.current_dir(dir.path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with multiple .mds files and no arg should exit non-zero"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("multiple") || stderr.contains("ambiguous") || stderr.contains("specify"),
"error should mention multiple files or instruct user to specify; got: {stderr}"
);
}
#[test]
fn watch_startup_no_spurious_recompile() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("nochange.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("nochange.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
out.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should write output"
);
std::thread::sleep(Duration::from_millis(1500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(50));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let compiled_count = stderr_str.matches("Compiled to").count();
assert_eq!(
compiled_count, 1,
"expected exactly 1 'Compiled to' line on startup (no double initial compile); \
got {compiled_count}; stderr was:\n{stderr_str}"
);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 0,
"expected 0 'Recompiled' lines with no edits (spurious startup rebuild); \
got {recompiled_count}; stderr was:\n{stderr_str}"
);
}
#[test]
fn watch_stdout_no_duplicate_write_on_startup() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("stdout_once.mds");
std::fs::write(&src, "UNIQUE_MARKER_XYZ\n").unwrap();
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
])
.stdout(Stdio::piped()),
);
let stdout_handle = child.0.stdout.take().expect("piped stdout");
let stdout_buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
let stdout_buf_clone = stdout_buf.clone();
let _reader_thread = std::thread::spawn(move || {
use std::io::Read as _;
let mut handle = stdout_handle;
let mut tmp = [0u8; 512];
loop {
match handle.read(&mut tmp) {
Ok(0) | Err(_) => break,
Ok(n) => {
stdout_buf_clone
.lock()
.unwrap()
.extend_from_slice(&tmp[..n]);
}
}
}
});
std::thread::sleep(Duration::from_millis(1500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(50));
let stdout_bytes = stdout_buf.lock().unwrap().clone();
let stdout_str = String::from_utf8_lossy(&stdout_bytes);
assert!(
stdout_str.contains("UNIQUE_MARKER_XYZ"),
"compiled output must appear on stdout; got: {stdout_str:?}"
);
let occurrence_count = stdout_str.matches("UNIQUE_MARKER_XYZ").count();
assert_eq!(
occurrence_count, 1,
"compiled content must be written to stdout EXACTLY ONCE on startup \
(no duplicate write from spurious synthetic FS event); \
got {occurrence_count} occurrences; stdout was:\n{stdout_str}"
);
}
#[test]
fn watch_dir_mode_no_spurious_startup_recompile() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.mds"),
"---\nname: A\n---\nFile A: {{name}}\n",
)
.unwrap();
std::fs::write(
dir.path().join("b.mds"),
"---\nname: B\n---\nFile B: {{name}}\n",
)
.unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
"a.md should be compiled on startup"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "File B: B", TIMEOUT),
"b.md should be compiled on startup"
);
std::thread::sleep(Duration::from_millis(1500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(50));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 0,
"expected 0 'Recompiled' lines in dir mode with no edits \
(spurious startup rebuild from synthetic FSEvents); \
got {recompiled_count}; stderr was:\n{stderr_str}"
);
let compiled_count = stderr_str.matches("Compiled to").count();
assert_eq!(
compiled_count, 2,
"expected exactly 2 'Compiled to' lines on dir-mode startup (one per source file); \
got {compiled_count}; stderr was:\n{stderr_str}"
);
}
#[test]
fn watch_single_status_line_per_rebuild() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("status.mds");
std::fs::write(&src, "---\nname: v0\n---\nStatus {{name}}!\n").unwrap();
let out = dir.path().join("status.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"100", ])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Status v0!", TIMEOUT),
"initial compile should produce Status v0!"
);
std::fs::write(&src, "---\nname: v1\n---\nStatus {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Status v1!", TIMEOUT),
"after editing, output should contain Status v1!"
);
std::thread::sleep(Duration::from_millis(500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(50));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 1,
"expected exactly 1 'Recompiled' line for one real edit; \
got {recompiled_count}; stderr was:\n{stderr_str}"
);
let compiled_count = stderr_str.matches("Compiled to").count();
assert_eq!(
compiled_count, 1,
"expected exactly 1 'Compiled to' line total (startup only, no extra from loop rebuild); \
got {compiled_count}; stderr was:\n{stderr_str}"
);
}
#[test]
fn watch_dir_mode_mirrors_subtree_to_out_dir() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::write(sub.join("deep.mds"), "---\nname: D\n---\nDeep {{name}}\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
let mirrored = out_dir.join("sub").join("deep.md");
assert!(
wait_for_file_contains(&mirrored, "Deep D", TIMEOUT),
"startup compile should write mirrored output to out/sub/deep.md"
);
assert!(
!out_dir.join("deep.md").exists(),
"flat stem deep.md must not exist when mirroring is active"
);
drop(child);
}
#[test]
fn watch_dir_mode_no_stem_collision_with_mirroring() {
let dir = tempfile::tempdir().unwrap();
let a_dir = dir.path().join("a");
let b_dir = dir.path().join("b");
std::fs::create_dir_all(&a_dir).unwrap();
std::fs::create_dir_all(&b_dir).unwrap();
std::fs::write(a_dir.join("x.mds"), "From A\n").unwrap();
std::fs::write(b_dir.join("x.mds"), "From B\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a").join("x.md"), "From A", TIMEOUT),
"out/a/x.md should contain 'From A'"
);
assert!(
wait_for_file_contains(&out_dir.join("b").join("x.md"), "From B", TIMEOUT),
"out/b/x.md should contain 'From B'"
);
std::fs::remove_file(a_dir.join("x.mds")).unwrap();
assert!(
wait_for_file_gone(&out_dir.join("a").join("x.md"), TIMEOUT),
"out/a/x.md should be removed when a/x.mds is deleted"
);
assert!(
out_dir.join("b").join("x.md").exists(),
"out/b/x.md must not be affected by deletion of a/x.mds"
);
drop(child);
}
#[test]
fn watch_dir_mode_shared_partial_rebuilds_importers() {
let dir = tempfile::tempdir().unwrap();
let partial = dir.path().join("_shared.mds");
std::fs::write(
&partial,
"@define greet(name):\nHello {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
let a = dir.path().join("a.mds");
let b = dir.path().join("b.mds");
std::fs::write(&a, "@import \"./_shared.mds\" as s\n{{s.greet(\"A\")}}\n").unwrap();
std::fs::write(&b, "@import \"./_shared.mds\" as s\n{{s.greet(\"B\")}}\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "Hello A!", TIMEOUT),
"a.md should contain Hello A! on startup"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "Hello B!", TIMEOUT),
"b.md should contain Hello B! on startup"
);
assert!(
!out_dir.join("_shared.md").exists(),
"_shared.md must not be written for a _-prefixed partial (DD2)"
);
std::fs::write(
&partial,
"@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "Hi A!", TIMEOUT),
"a.md should update after editing the shared partial"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "Hi B!", TIMEOUT),
"b.md should update after editing the shared partial"
);
assert!(
!out_dir.join("_shared.md").exists(),
"_shared.md must not appear after editing the partial"
);
drop(child);
}
#[test]
fn watch_dir_mode_chain_rebuild() {
let dir = tempfile::tempdir().unwrap();
let c = dir.path().join("_c.mds");
std::fs::write(&c, "@define val():\nV1\n@end\n\n@export val\n").unwrap();
let b = dir.path().join("_b.mds");
std::fs::write(
&b,
"@import \"./_c.mds\" as c\n@define val():\n{{c.val()}}\n@end\n\n@export val\n",
)
.unwrap();
let a = dir.path().join("a.mds");
std::fs::write(&a, "@import \"./_b.mds\" as b\n{{b.val()}}\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "V1", TIMEOUT),
"a.md should contain V1 initially"
);
std::fs::write(&c, "@define val():\nV2\n@end\n\n@export val\n").unwrap();
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "V2", TIMEOUT),
"a.md should update to V2 after editing _c.mds (transitive chain)"
);
drop(child);
}
#[test]
fn watch_poll_interval_zero_works() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"--poll-interval 0 should still do the initial compile"
);
std::fs::write(&src, "---\nname: Poll\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello Poll!", TIMEOUT),
"--poll-interval 0: edit should still trigger rebuild via native event"
);
drop(child);
}
#[test]
fn watch_poll_interval_invalid_exits_2() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "Hello!\n").unwrap();
let output = mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--poll-interval",
"notanumber",
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
let code = output.status.code().unwrap_or(-1);
assert_eq!(
code, 2,
"invalid --poll-interval should exit 2 (clap error), got {code}"
);
}
#[test]
fn watch_poll_interval_tiny_clamped() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("hello.mds");
std::fs::write(&src, "Clamped!\n").unwrap();
let out = dir.path().join("hello.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"1",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Clamped!", TIMEOUT),
"--poll-interval 1 (clamped to 50ms) should still work"
);
drop(child);
}
#[test]
fn watch_file_mode_idle_no_recompile_across_ticks() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("idle.mds");
std::fs::write(&src, "---\nname: World\n---\nIdle {{name}}!\n").unwrap();
let out = dir.path().join("idle.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Idle World!", TIMEOUT),
"initial compile should succeed"
);
let mtime_before = std::fs::metadata(&out)
.and_then(|m| m.modified())
.expect("output file must exist after initial compile");
let content_before = std::fs::read_to_string(&out).expect("output file readable");
std::thread::sleep(Duration::from_millis(2500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 0,
"idle single-file watcher must emit 0 Recompiled across ticks; \
got {recompiled_count}; stderr:\n{stderr_str}"
);
let mtime_after = std::fs::metadata(&out)
.and_then(|m| m.modified())
.expect("output file must still exist after idle");
assert_eq!(
mtime_before, mtime_after,
"output file mtime must not advance during idle (spurious recompile would advance it)"
);
assert_eq!(
content_before,
std::fs::read_to_string(&out).unwrap(),
"output file content must be unchanged during idle"
);
}
#[test]
fn watch_dir_mode_idle_no_recompile_across_ticks() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.mds"),
"---\nname: A\n---\nFile A: {{name}}\n",
)
.unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
"initial compile should succeed"
);
let out_a = out_dir.join("a.md");
let mtime_before = std::fs::metadata(&out_a)
.and_then(|m| m.modified())
.expect("a.md must exist after initial compile");
let content_before = std::fs::read_to_string(&out_a).expect("a.md readable");
std::thread::sleep(Duration::from_millis(2500));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 0,
"idle dir-mode watcher must emit 0 Recompiled across ticks; \
got {recompiled_count}; stderr:\n{stderr_str}"
);
let mtime_after = std::fs::metadata(&out_a)
.and_then(|m| m.modified())
.expect("a.md must still exist after idle");
assert_eq!(
mtime_before, mtime_after,
"output file mtime must not advance during idle (spurious recompile would advance it)"
);
assert_eq!(
content_before,
std::fs::read_to_string(&out_a).unwrap(),
"output file content must be unchanged during idle"
);
}
#[test]
fn watch_file_mode_parent_dir_delete_recreate_recovers() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
std::fs::create_dir(&src_dir).unwrap();
let src = src_dir.join("entry.mds");
std::fs::write(&src, "---\nname: Before\n---\nEntry {{name}}\n").unwrap();
let out = src_dir.join("entry.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Entry Before", TIMEOUT),
"initial compile should produce 'Entry Before'"
);
std::fs::remove_dir_all(&src_dir).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&src_dir).unwrap();
std::fs::write(&src, "---\nname: After\n---\nEntry {{name}}\n").unwrap();
assert!(
wait_for_file_contains(&out, "Entry After", TICK_TIMEOUT),
"watcher must self-heal after parent dir delete+recreate and recompile"
);
drop(child);
}
#[test]
fn watch_dir_mode_root_delete_recreate_recovers() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("watched");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("a.mds"), "---\nname: A\n---\nOld A\n").unwrap();
let out_dir = base.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "Old A", TIMEOUT),
"initial compile should produce 'Old A'"
);
std::fs::remove_dir_all(&root).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&root).unwrap();
std::fs::write(
root.join("new.mds"),
"---\nname: N\n---\nNew file {{name}}\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("new.md"), "New file N", TICK_TIMEOUT),
"watcher must recover after root delete+recreate and compile new file"
);
drop(child);
}
#[test]
fn watch_file_mode_entry_deleted_settles_then_recovers() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("entry.mds");
std::fs::write(&src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("entry.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should produce Hello World!"
);
std::fs::remove_file(&src).unwrap();
std::thread::sleep(Duration::from_millis(500));
let count_w1 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("file not found").count() + s.matches("No such file").count()
};
std::thread::sleep(Duration::from_millis(500));
let count_w2 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("file not found").count() + s.matches("No such file").count()
};
assert_eq!(
count_w1, count_w2,
"error count must not grow in a second idle window (not once-per-tick); \
w1={count_w1}, w2={count_w2} — the fix must settle after initial native-event errors"
);
std::fs::write(&src, "---\nname: Recovered\n---\nHello {{name}}!\n").unwrap();
assert!(
wait_for_file_contains(&out, "Hello Recovered!", TIMEOUT),
"watcher must recompile after recreating deleted entry file"
);
std::thread::sleep(Duration::from_millis(200));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let error_event_count =
stderr_str.matches("file not found").count() + stderr_str.matches("No such file").count();
assert!(
error_event_count <= 10,
"total error count across full test must be small (not a per-tick flood); \
got {error_event_count} file-not-found occurrences; stderr:\n{stderr_str}"
);
}
#[test]
fn watch_vars_dir_delete_recreate_rearms() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
let vars_dir = base.path().join("vars_dir");
std::fs::create_dir_all(&src_dir).unwrap();
std::fs::create_dir_all(&vars_dir).unwrap();
let src = src_dir.join("tpl.mds");
std::fs::write(&src, "---\ngreeting: Default\n---\n{{greeting}}\n").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"greeting": "Hello"}"#).unwrap();
let out = src_dir.join("tpl.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello", TIMEOUT),
"initial compile with vars should produce 'Hello'"
);
std::fs::remove_dir_all(&vars_dir).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir_all(&vars_dir).unwrap();
std::thread::sleep(Duration::from_millis(300));
std::fs::write(&vars_file, r#"{"greeting": "Goodbye"}"#).unwrap();
let got = wait_for_file_contains(&out, "Goodbye", TICK_TIMEOUT);
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
assert!(
got,
"watcher must re-arm vars dir watch after delete+recreate and recompile on edit; \
stderr was:\n{stderr_str}"
);
}
#[test]
fn watch_dir_mode_cross_root_partial_edit_rebuilds_importer() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("root");
let shared = base.path().join("shared");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&shared).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
let partial = shared.join("_x.mds");
std::fs::write(
&partial,
"@define greet():\nExternal V1\n@end\n\n@export greet\n",
)
.unwrap();
let importer = root.join("importer.mds");
std::fs::write(
&importer,
"@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n",
)
.unwrap();
let out_dir = base.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("importer.md"), "External V1", TIMEOUT),
"initial compile should produce 'External V1'"
);
assert!(
!out_dir.join("_x.md").exists(),
"_x.md must not be emitted for external partial"
);
assert!(
!shared.join("_x.md").exists(),
"shared/_x.md must not be written"
);
std::fs::write(
&partial,
"@define greet():\nExternal V2\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("importer.md"), "External V2", TIMEOUT),
"editing external partial must rebuild in-root importer"
);
assert!(
!out_dir.join("_x.md").exists(),
"_x.md must not be emitted after partial edit"
);
drop(child);
}
#[test]
fn watch_dir_mode_delete_partial_surfaces_broken_import() {
let dir = tempfile::tempdir().unwrap();
let partial = dir.path().join("_p.mds");
std::fs::write(
&partial,
"@define val():\nPartial V1\n@end\n\n@export val\n",
)
.unwrap();
let importer = dir.path().join("main.mds");
std::fs::write(&importer, "@import \"./_p.mds\" as p\n{{p.val()}}\n").unwrap();
let out_dir = dir.path().join("out");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("main.md"), "Partial V1", TIMEOUT),
"initial compile should produce 'Partial V1'"
);
assert!(
!out_dir.join("_p.md").exists(),
"_p.md must not be written for partial"
);
std::fs::remove_file(&partial).unwrap();
let deadline = std::time::Instant::now() + TIMEOUT;
loop {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
if s.contains("file not found") || s.contains("No such file") {
break;
}
if std::time::Instant::now() >= deadline {
panic!(
"expected a 'file not found' / 'No such file' error after deleting imported \
partial within {:?}; stderr so far:\n{s}",
TIMEOUT
);
}
std::thread::sleep(Duration::from_millis(50));
}
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher must stay alive after partial deletion surfaces broken import"
);
drop(child);
}
#[test]
fn watch_dir_mode_create_missing_partial_heals_importer() {
let dir = tempfile::tempdir().unwrap();
let importer = dir.path().join("main.mds");
std::fs::write(&importer, "@import \"./_missing.mds\" as m\n{{m.val()}}\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
std::thread::sleep(Duration::from_millis(500));
let partial = dir.path().join("_missing.mds");
std::fs::write(&partial, "@define val():\nHealed!\n@end\n\n@export val\n").unwrap();
assert!(
wait_for_file_contains(&out_dir.join("main.md"), "Healed!", TIMEOUT),
"creating the missing partial must heal the erroring importer"
);
drop(child);
}
#[test]
fn watch_dir_mode_dual_role_node_edit_and_delete() {
let dir = tempfile::tempdir().unwrap();
let dual = dir.path().join("dual.mds");
std::fs::write(
&dual,
"@define greet():\nDual V1\n@end\n\n@export greet\n\nStandalone content\n",
)
.unwrap();
let consumer = dir.path().join("consumer.mds");
std::fs::write(&consumer, "@import \"./dual.mds\" as d\n{{d.greet()}}\n").unwrap();
let out_dir = dir.path().join("out");
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("dual.md"), "Standalone content", TIMEOUT),
"dual.md should be compiled as a top-level target"
);
assert!(
wait_for_file_contains(&out_dir.join("consumer.md"), "Dual V1", TIMEOUT),
"consumer.md should be compiled using the import"
);
std::fs::write(
&dual,
"@define greet():\nDual V2 (updated)\n@end\n\n@export greet\n\nStandalone updated content\n",
)
.unwrap();
assert!(
wait_for_file_contains(
&out_dir.join("dual.md"),
"Standalone updated content",
TIMEOUT
),
"editing dual.mds must update dual.md (own output)"
);
assert!(
wait_for_file_contains(&out_dir.join("consumer.md"), "Dual V2 (updated)", TIMEOUT),
"editing dual.mds must rebuild consumer.md (importer)"
);
std::fs::remove_file(&dual).unwrap();
assert!(
wait_for_file_gone(&out_dir.join("dual.md"), TIMEOUT),
"dual.md must be removed when dual.mds is deleted"
);
std::thread::sleep(Duration::from_millis(300));
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher must stay alive after dual-role node deletion"
);
drop(child);
}
#[test]
fn watch_dir_mode_persistent_error_bounded_count() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("a.mds"),
"---\nname: A\n---\nFile A: {{name}}\n",
)
.unwrap();
std::fs::write(dir.path().join("bad.mds"), "Hello {{__undefined_xyz__}}!\n").unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
"a.md should compile despite bad.mds error"
);
std::thread::sleep(Duration::from_millis(500));
let count_w1 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("undefined variable").count()
};
std::thread::sleep(Duration::from_millis(500));
let count_w2 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("undefined variable").count()
};
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher must stay alive with persistent syntax error in bad.mds"
);
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
assert_eq!(
count_w1, count_w2,
"error count must not grow in a second idle window (not once-per-tick); \
w1={count_w1}, w2={count_w2} (applies ADR-021, guards PF-006); \
stderr:\n{stderr_str}"
);
}
#[test]
fn watch_dir_mode_mds_json_config_dir_ancestor_mirrors_output() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("src");
let sub = root.join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("deep.mds"), "Deep content\n").unwrap();
let mds_json = base.path().join("mds.json");
std::fs::write(&mds_json, r#"{"build":{"output_dir":"out"}}"#).unwrap();
let expected_out = base.path().join("out").join("sub").join("deep.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.current_dir(base.path()) .stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&expected_out, "Deep content", TIMEOUT),
"mds.json output_dir from ancestor config_dir should mirror subtree: {:?}",
expected_out
);
drop(child);
}
#[test]
fn watch_dir_mode_rename_removes_stale_output() {
let dir = tempfile::tempdir().unwrap();
let a_dir = dir.path().join("a");
let b_dir = dir.path().join("b");
std::fs::create_dir_all(&a_dir).unwrap();
std::fs::create_dir_all(&b_dir).unwrap();
std::fs::write(a_dir.join("x.mds"), "Content from A\n").unwrap();
let out_dir = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a").join("x.md"), "Content from A", TIMEOUT),
"initial compile should write out/a/x.md"
);
std::fs::rename(a_dir.join("x.mds"), b_dir.join("x.mds")).unwrap();
assert!(
wait_for_file_contains(&out_dir.join("b").join("x.md"), "Content from A", TIMEOUT),
"out/b/x.md should be written after rename"
);
assert!(
wait_for_file_gone(&out_dir.join("a").join("x.md"), TIMEOUT),
"stale out/a/x.md must be removed after rename (no orphan accumulation)"
);
drop(child);
}
#[test]
fn watch_dir_mode_partial_edit_rebuilds_exactly_n_importers() {
let dir = tempfile::tempdir().unwrap();
let partial = dir.path().join("_shared.mds");
std::fs::write(&partial, "@define val():\nV1\n@end\n\n@export val\n").unwrap();
std::fs::write(
dir.path().join("a.mds"),
"@import \"./_shared.mds\" as s\n{{s.val()}} from A\n",
)
.unwrap();
std::fs::write(
dir.path().join("b.mds"),
"@import \"./_shared.mds\" as s\n{{s.val()}} from B\n",
)
.unwrap();
std::fs::write(
dir.path().join("c.mds"),
"@import \"./_shared.mds\" as s\n{{s.val()}} from C\n",
)
.unwrap();
std::fs::write(dir.path().join("independent.mds"), "Independent\n").unwrap();
let out_dir = dir.path().join("out");
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "V1 from A", TIMEOUT),
"a.md should initially contain 'V1 from A'"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "V1 from B", TIMEOUT),
"b.md should initially contain 'V1 from B'"
);
assert!(
wait_for_file_contains(&out_dir.join("c.md"), "V1 from C", TIMEOUT),
"c.md should initially contain 'V1 from C'"
);
assert!(
wait_for_file_contains(&out_dir.join("independent.md"), "Independent", TIMEOUT),
"independent.md should compile on startup"
);
let independent_before = std::fs::read_to_string(out_dir.join("independent.md")).unwrap();
std::fs::write(
&partial,
"@define val():\nV2 updated\n@end\n\n@export val\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "V2 updated from A", TIMEOUT),
"a.md must update after partial edit"
);
assert!(
wait_for_file_contains(&out_dir.join("b.md"), "V2 updated from B", TIMEOUT),
"b.md must update after partial edit"
);
assert!(
wait_for_file_contains(&out_dir.join("c.md"), "V2 updated from C", TIMEOUT),
"c.md must update after partial edit"
);
let independent_after = std::fs::read_to_string(out_dir.join("independent.md")).unwrap();
assert_eq!(
independent_before, independent_after,
"independent.md must not be modified when an unrelated partial is edited"
);
let _ = child.0.kill();
let _ = child.0.wait();
}
#[test]
fn watch_dir_mode_soak_50_edits_bounded_and_clean_exit() {
let dir = tempfile::tempdir().unwrap();
let partial = dir.path().join("_soak.mds");
std::fs::write(&partial, "@define val():\nSoak V0\n@end\n\n@export val\n").unwrap();
let importer = dir.path().join("consumer.mds");
std::fs::write(&importer, "@import \"./_soak.mds\" as s\n{{s.val()}}\n").unwrap();
let out_dir = dir.path().join("out");
let (mut child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"10", "--poll-interval",
"50",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("consumer.md"), "Soak V0", TIMEOUT),
"initial compile should produce 'Soak V0'"
);
for i in 1_u32..=50 {
let padding = " ".repeat(i as usize);
std::fs::write(
&partial,
format!("@define val():\nSoak V{i}{padding}\n@end\n\n@export val\n"),
)
.unwrap();
let expected = format!("Soak V{i}");
assert!(
wait_for_file_contains(&out_dir.join("consumer.md"), &expected, TIMEOUT),
"round {i}: consumer.md must contain '{expected}'"
);
}
let still_running = child.0.try_wait().unwrap().is_none();
assert!(still_running, "watcher must remain alive after 50 edits");
drop(child);
}
#[test]
fn watch_file_mode_parent_dir_deleted_bounded_errors_then_recovers() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
std::fs::create_dir(&src_dir).unwrap();
let src = src_dir.join("tpl.mds");
std::fs::write(&src, "V1-before\n").unwrap();
let out = src_dir.join("tpl.md");
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"150",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "V1-before", TIMEOUT),
"initial compile should produce V1-before"
);
std::fs::remove_dir_all(&src_dir).unwrap();
std::thread::sleep(Duration::from_millis(900));
let count_w1 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("file not found").count() + s.matches("No such file").count()
};
std::thread::sleep(Duration::from_millis(900));
let count_w2 = {
let bytes = stderr_tap.bytes();
let s = String::from_utf8_lossy(&bytes);
s.matches("file not found").count() + s.matches("No such file").count()
};
assert_eq!(
count_w1, count_w2,
"error count must not grow in a second idle window (not once-per-tick); \
w1={count_w1}, w2={count_w2} — the fix must settle after initial native-event errors \
(applies ADR-021, guards PF-006)"
);
std::fs::create_dir(&src_dir).unwrap();
std::fs::write(&src, "V2-recovered\n").unwrap();
assert!(
wait_for_file_contains(&out, "V2-recovered", TICK_TIMEOUT),
"watcher must self-heal after parent dir delete+recreate and recompile with V2 content"
);
let still_alive = child.0.try_wait().unwrap().is_none();
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
assert!(
still_alive,
"watcher must remain alive while parent dir is absent; stderr:\n{stderr_str}"
);
let error_count =
stderr_str.matches("file not found").count() + stderr_str.matches("No such file").count();
assert!(
error_count <= 8,
"total error count across both idle windows must be small (not a per-tick flood); \
got {error_count} occurrences; stderr:\n{stderr_str}"
);
}
#[test]
fn watch_dir_mode_idle_500_files_no_recompile() {
const FILE_COUNT: usize = 500;
let dir = tempfile::tempdir().unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
for i in 1..=FILE_COUNT {
std::fs::write(
dir.path().join(format!("file_{i:04}.mds")),
format!("scale-idle-{i}\n"),
)
.unwrap();
}
let sentinel_out = out_dir.join(format!("file_{FILE_COUNT:04}.md"));
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"50",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&sentinel_out, &format!("scale-idle-{FILE_COUNT}"), TIMEOUT,),
"AC-P5: sentinel file_{FILE_COUNT:04}.md must be written during startup compile \
(all {FILE_COUNT} files compiled before idle window)"
);
let mtime_before = std::fs::metadata(&sentinel_out)
.and_then(|m| m.modified())
.expect("sentinel output must exist after startup");
std::thread::sleep(Duration::from_millis(600));
let _ = child.0.kill();
let _ = child.0.wait();
std::thread::sleep(Duration::from_millis(100));
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
let recompiled_count = stderr_str.matches("Recompiled").count();
assert_eq!(
recompiled_count, 0,
"AC-P5: idle dir-mode watcher over {FILE_COUNT} files must emit 0 Recompiled \
across ≥10 ticks (ADR-021: idle cost is O(1) regardless of tree size); \
got {recompiled_count}; stderr:\n{stderr_str}"
);
let mtime_after = std::fs::metadata(&sentinel_out)
.and_then(|m| m.modified())
.expect("sentinel output must still exist after idle");
assert_eq!(
mtime_before, mtime_after,
"AC-P5: sentinel output mtime must not advance during idle window \
(a spurious recompile would update it)"
);
}
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_entry() {
let dir = tempfile::tempdir().unwrap();
let real_file = dir.path().join("real.mds");
std::fs::write(&real_file, "@message system:\nYou are helpful.\n@end\n").unwrap();
let link_file = dir.path().join("link.mds");
std::os::unix::fs::symlink(&real_file, &link_file).unwrap();
let out = dir.path().join("out.md");
let output = mds_bin()
.args([
"watch",
link_file.to_str().unwrap(),
"-o",
out.to_str().unwrap(),
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with a symlinked entry must fail at startup; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
stderr.contains("symlink") || stderr.contains("not allowed"),
"error must mention symlink restriction; got: {stderr}"
);
assert!(
!out.exists(),
"output file must not be created when entry is rejected at startup"
);
}
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_vars_file() {
let dir = tempfile::tempdir().unwrap();
let entry = dir.path().join("entry.mds");
std::fs::write(&entry, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
let real_vars = dir.path().join("real_vars.json");
std::fs::write(&real_vars, r#"{"name": "World"}"#).unwrap();
let link_vars = dir.path().join("link_vars.json");
std::os::unix::fs::symlink(&real_vars, &link_vars).unwrap();
let out = dir.path().join("out.md");
let output = mds_bin()
.args([
"watch",
entry.to_str().unwrap(),
"--vars",
link_vars.to_str().unwrap(),
"-o",
out.to_str().unwrap(),
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with a symlinked --vars must fail at startup; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
stderr.contains("symlink") || stderr.contains("not allowed"),
"error must mention symlink restriction for vars; got: {stderr}"
);
}
#[test]
#[cfg(unix)]
fn watch_rejects_symlinked_dir_target() {
let dir = tempfile::tempdir().unwrap();
let real_src = dir.path().join("real_src");
std::fs::create_dir(&real_src).unwrap();
std::fs::write(
real_src.join("a.mds"),
"---\nname: A\n---\nFile A: {{name}}\n",
)
.unwrap();
let link_dir = dir.path().join("link_src");
std::os::unix::fs::symlink(&real_src, &link_dir).unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let output = mds_bin()
.args([
"watch",
link_dir.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap();
assert!(
!output.status.success(),
"watch with a symlinked dir target must fail at startup; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(
stderr.contains("symlink") || stderr.contains("not allowed"),
"error must mention symlink restriction; got: {stderr}"
);
assert!(
!out_dir.join("a.md").exists(),
"symlinked dir must never be traversed; a.md must not be created"
);
}
#[test]
#[cfg(unix)]
fn watch_dir_skips_symlinked_source_file() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("a.mds"), "---\nname: A\n---\nFile A: {{name}}\n").unwrap();
let external_dir = dir.path().join("external");
std::fs::create_dir(&external_dir).unwrap();
std::fs::write(
external_dir.join("external.mds"),
"---\nname: Ext\n---\nExternal: {{name}}\n",
)
.unwrap();
let link_mds = src.join("link.mds");
std::os::unix::fs::symlink(external_dir.join("external.mds"), &link_mds).unwrap();
let out_dir = dir.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "File A: A", TIMEOUT),
"a.md (real sibling) should be compiled"
);
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500);
while std::time::Instant::now() < deadline {
assert!(
!out_dir.join("link.md").exists(),
"link.md must not be created — symlinked source files must be skipped"
);
std::thread::sleep(std::time::Duration::from_millis(50));
}
drop(child);
}
#[test]
fn watch_esc_in_initial_compile_error_is_sanitized() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("esc_watch.mds");
std::fs::write(&src, b"@define \x1bfoo:\nhello\n").unwrap();
let (child, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
drop(child);
let stderr_bytes = stderr_tap.bytes();
let stderr_str = String::from_utf8_lossy(&stderr_bytes);
assert!(
stderr_str.contains("syntax error"),
"watch initial-compile-error must render its diagnostic to stderr, otherwise \
the ESC assertion below is vacuous; got:\n{stderr_str}"
);
assert!(
!stderr_bytes.contains(&0x1Bu8),
"raw ESC byte (0x1B) must be sanitized in watch initial-compile-error stderr; \
got (hex first 512): {:02x?}",
&stderr_bytes[..stderr_bytes.len().min(512)]
);
}
#[test]
fn watch_file_mode_edit_during_startup_window_is_not_lost() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("entry.mds");
std::fs::write(&src, "---\nname: Before\n---\nEntry {{name}}\n").unwrap();
let out = dir.path().join("entry.md");
let (child, _tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains_tight(&out, "Entry Before", STARTUP_WINDOW_TIMEOUT),
"startup compile should publish 'Entry Before'"
);
std::fs::write(&src, "---\nname: After\n---\nEntry {{name}}\n").unwrap();
assert!(
wait_for_file_contains(&out, "Entry After", STARTUP_WINDOW_TIMEOUT),
"an edit made immediately after the startup output was published must not be \
lost: with --poll-interval 0 the OS watch is the only detector, so this fails \
if the watch is armed after the output is written (#317)"
);
drop(child);
}
#[test]
fn watch_dir_mode_edit_during_startup_window_is_not_lost() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("root");
let out_dir = base.path().join("out");
std::fs::create_dir(&root).unwrap();
let src = root.join("a.mds");
std::fs::write(&src, "---\nname: Before\n---\nDir {{name}}\n").unwrap();
let out = out_dir.join("a.md");
let (child, _tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains_tight(&out, "Dir Before", STARTUP_WINDOW_TIMEOUT),
"startup compile should publish 'Dir Before'"
);
std::fs::write(&src, "---\nname: After\n---\nDir {{name}}\n").unwrap();
assert!(
wait_for_file_contains(&out, "Dir After", STARTUP_WINDOW_TIMEOUT),
"an edit made immediately after the startup output was published must not be \
lost in dir mode: the recursive root watch must be armed before the tree walk, \
not after the outputs are written (#317)"
);
drop(child);
}
#[test]
fn watch_dir_mode_cross_root_edit_during_startup_window_is_not_lost() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("root");
let shared = base.path().join("shared");
let out_dir = base.path().join("out");
std::fs::create_dir(&root).unwrap();
std::fs::create_dir(&shared).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
let partial = shared.join("_x.mds");
std::fs::write(
&partial,
"@define greet():\nWindow V1\n@end\n\n@export greet\n",
)
.unwrap();
let importer = root.join("importer.mds");
std::fs::write(
&importer,
"@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n",
)
.unwrap();
let out = out_dir.join("importer.md");
let (child, _tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains_tight(&out, "Window V1", STARTUP_WINDOW_TIMEOUT),
"startup compile should publish 'Window V1'"
);
std::fs::write(
&partial,
"@define greet():\nWindow V2\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out, "Window V2", TICK_TIMEOUT),
"an edit to a cross-root dependency during the startup window must be recovered \
by the idle-tick content backstop: its directory cannot be armed before the \
compile discovers it, so no event exists to deliver, and diffing only the \
in-root file list can never see the change (#321)"
);
drop(child);
}
#[test]
fn watch_file_mode_dep_edit_during_startup_window_is_not_lost() {
let base = tempfile::tempdir().unwrap();
let entry_dir = base.path().join("tpl");
let shared = base.path().join("shared");
std::fs::create_dir(&entry_dir).unwrap();
std::fs::create_dir(&shared).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
let partial = shared.join("_x.mds");
std::fs::write(
&partial,
"@define greet():\nDep V1\n@end\n\n@export greet\n",
)
.unwrap();
let entry = entry_dir.join("entry.mds");
std::fs::write(&entry, "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n").unwrap();
let out = entry_dir.join("entry.md");
let (child, _tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
entry.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains_tight(&out, "Dep V1", STARTUP_WINDOW_TIMEOUT),
"startup compile should publish 'Dep V1'"
);
std::fs::write(
&partial,
"@define greet():\nDep V2\n@end\n\n@export greet\n",
)
.unwrap();
assert!(
wait_for_file_contains(&out, "Dep V2", TICK_TIMEOUT),
"an edit to a dependency outside the entry's directory during the startup \
window must be recovered by the idle tick: the dependency's baseline has to \
predate the edit, which it only does if it is captured when the compile \
reports the dep rather than at the end of startup (#321)"
);
drop(child);
}
#[test]
fn watch_dir_mode_idle_tick_fires_under_event_flood() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
let base = tempfile::tempdir().unwrap();
let root = base.path().join("root");
let shared = base.path().join("shared");
let out_dir = base.path().join("out");
std::fs::create_dir(&root).unwrap();
std::fs::create_dir(&shared).unwrap();
std::fs::create_dir(&out_dir).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
let partial = shared.join("_p.mds");
std::fs::write(&partial, "@define hi():\nP\n@end\n\n@export hi\n").unwrap();
std::fs::write(
root.join("a.mds"),
"@import \"../shared/_p.mds\" as p\n{{p.hi()}}\n",
)
.unwrap();
let (child, _tap) = spawn_ready(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"150",
"-q",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "P", TIMEOUT),
"initial compile should produce 'P'"
);
let stop = Arc::new(AtomicBool::new(false));
let flood = {
let stop = Arc::clone(&stop);
let partial = partial.clone();
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let _ = std::fs::read(&partial);
std::thread::sleep(Duration::from_millis(5));
}
})
};
std::fs::remove_dir_all(&root).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("new.mds"), "---\nname: N\n---\nFlood {{name}}\n").unwrap();
let recovered = wait_for_file_contains(&out_dir.join("new.md"), "Flood N", TICK_TIMEOUT);
stop.store(true, Ordering::Relaxed);
flood.join().expect("flood thread panicked");
assert!(
recovered,
"the idle tick must fire while events arrive 30x faster than --poll-interval: \
nothing but the probe's re-arm can observe a root recreated as a new inode, so \
a tick whose deadline restarts on every message loses this change permanently \
rather than late (#319)"
);
drop(child);
}
#[test]
#[cfg(unix)]
fn watch_dir_mode_ctrl_c_during_startup_compile_terminates() {
use std::os::unix::process::ExitStatusExt;
const SOURCES: usize = 1200;
const OBSERVE_AT: usize = 10;
let base = tempfile::tempdir().unwrap();
let root = base.path().join("root");
let out_dir = base.path().join("out");
std::fs::create_dir(&root).unwrap();
for i in 0..SOURCES {
std::fs::write(
root.join(format!("s{i:04}.mds")),
"---\nname: S\n---\nSource {{name}}\n",
)
.unwrap();
}
let count_outputs = |dir: &Path| -> usize {
std::fs::read_dir(dir)
.map(|rd| rd.filter_map(|e| e.ok()).count())
.unwrap_or(0)
};
let (mut guard, _tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null()),
);
let pid = guard.id();
let deadline = Instant::now() + Duration::from_secs(30);
let mut observed = 0usize;
while Instant::now() < deadline {
observed = count_outputs(&out_dir);
if observed >= OBSERVE_AT {
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(
(OBSERVE_AT..SOURCES / 2).contains(&observed),
"test precondition: SIGINT must be sent while the startup compile is in \
flight; saw {observed} of {SOURCES} outputs (want {OBSERVE_AT}..{})",
SOURCES / 2
);
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let signalled_at = Instant::now();
let deadline = Instant::now() + Duration::from_secs(20);
let mut exited = false;
while Instant::now() < deadline {
if guard.0.try_wait().unwrap().is_some() {
exited = true;
break;
}
std::thread::sleep(Duration::from_millis(1));
}
let elapsed = signalled_at.elapsed();
let written = count_outputs(&out_dir);
assert!(
exited,
"process must exit after SIGINT during startup compile"
);
let status = guard.wait_status();
assert_eq!(
status.signal(),
Some(libc::SIGINT),
"SIGINT during the startup compile must terminate the process; instead it \
exited with {status:?} after {elapsed:?}, having written {written} of \
{SOURCES} outputs — the signal was swallowed until the event loop started"
);
assert!(
written < SOURCES / 2,
"after Ctrl+C during startup the watcher must stop writing outputs; it wrote \
{written} of {SOURCES}"
);
}
#[test]
#[cfg(unix)]
fn watch_file_mode_ctrl_c_during_startup_compile_terminates() {
use std::os::unix::process::ExitStatusExt;
const PARTIALS: usize = 400;
let dir = tempfile::tempdir().unwrap();
let mut entry = String::new();
for i in 0..PARTIALS {
let name = format!("_p{i:04}");
std::fs::write(
dir.path().join(format!("{name}.mds")),
format!("@define v{i}():\nP{i}\n@end\n\n@export v{i}\n"),
)
.unwrap();
entry.push_str(&format!("@import \"./{name}.mds\" as p{i}\n"));
}
entry.push_str("done\n");
let src = dir.path().join("entry.mds");
std::fs::write(&src, &entry).unwrap();
let (mut guard, tap) = spawn_unsynchronized(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
let pid = guard.id();
let deadline = Instant::now() + Duration::from_secs(30);
let mut saw_watching = false;
while Instant::now() < deadline {
if tap.text().contains("Watching ") {
saw_watching = true;
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(
saw_watching,
"expected the `Watching …` startup line; stderr:\n{}",
tap.text()
);
assert!(
!dir.path().join("entry.md").exists(),
"test precondition: the startup compile must not have published its output yet"
);
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let deadline = Instant::now() + Duration::from_secs(20);
let mut exited = false;
while Instant::now() < deadline {
if guard.0.try_wait().unwrap().is_some() {
exited = true;
break;
}
std::thread::sleep(Duration::from_millis(1));
}
assert!(
exited,
"process must exit after SIGINT during startup compile"
);
let status = guard.wait_status();
assert_eq!(
status.signal(),
Some(libc::SIGINT),
"SIGINT during the startup compile must terminate the process; instead it \
exited with {status:?} — the signal was swallowed until the event loop started"
);
}
fn count_occurrences(haystack: &str, needle: &str) -> usize {
let mut count = 0;
let mut start = 0;
while let Some(pos) = haystack[start..].find(needle) {
count += 1;
start += pos + needle.len();
}
count
}
const DUP_SET_WARNING: &str =
"warning: variable 'x' is set more than once by --set; the last value wins";
fn wait_for_stderr_contains_str(tap: &StderrTap, needle: &str, timeout: Duration) -> String {
let deadline = Instant::now() + timeout;
loop {
let text = tap.text();
if text.contains(needle) || Instant::now() >= deadline {
return text;
}
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn i8_file_watch_duplicate_set_warns_exactly_once_across_two_edits() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("t.mds");
std::fs::write(&src, "version 1").unwrap();
let out = dir.path().join("t.md");
let (child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--set",
"x=1",
"--set",
"x=2",
])
.stdout(Stdio::null()),
);
let stderr_after_start = wait_for_stderr_contains_str(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
let count_at_start = count_occurrences(&stderr_after_start, DUP_SET_WARNING);
assert_eq!(
count_at_start, 1,
"I8: expected exactly 1 warning at startup, got {}; stderr:\n{}",
count_at_start, stderr_after_start
);
std::fs::write(&src, "version 2").unwrap();
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I8: rebuild after edit 1 must complete"
);
std::fs::write(&src, "version 3").unwrap();
assert!(
wait_for_file_contains(&out, "version 3", TIMEOUT),
"I8: rebuild after edit 2 must complete"
);
let final_stderr = stderr_tap.text();
let final_count = count_occurrences(&final_stderr, DUP_SET_WARNING);
assert_eq!(
final_count, 1,
"I8: after two edits the warning must still appear exactly once; \
got {}; stderr:\n{}",
final_count, final_stderr
);
drop(child);
}
#[test]
fn i9_dir_watch_duplicate_set_warns_exactly_once_at_startup() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("t.mds");
std::fs::write(&src, "version 1").unwrap();
let out = dir.path().join("t.md");
let (child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
dir.path().to_str().unwrap(),
"--debounce",
"0",
"--set",
"x=1",
"--set",
"x=2",
])
.stdout(Stdio::null()),
);
let stderr_startup = wait_for_stderr_contains_str(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
let count_at_startup = count_occurrences(&stderr_startup, DUP_SET_WARNING);
assert_eq!(
count_at_startup, 1,
"I9: dir-watch startup must emit the warning exactly once (guards :2185); \
got {}; stderr:\n{}",
count_at_startup, stderr_startup
);
std::fs::write(&src, "version 2").unwrap();
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I9: rebuild after edit must complete"
);
let stderr_after_edit = stderr_tap.text();
let count_after_edit = count_occurrences(&stderr_after_edit, DUP_SET_WARNING);
assert_eq!(
count_after_edit, 1,
"I9: after one rebuild, warning must still appear exactly once (guards :1914); \
got {}; stderr:\n{}",
count_after_edit, stderr_after_edit
);
drop(child);
}