mod common;
use common::{
closed_pipe, count_occurrences, dup_vars_file_warning, make_symlink, mds_bin,
most_debounce_windows, poll_tap_until, record_run_flag, remove_symlink, spawn_watch_ready,
spawn_watch_ready_at, spawn_watch_ready_stderr_untapped, spawn_watch_unsynchronized,
tap_reader, wait_for_tap, wait_for_tap_count, write_atomic, ChildGuard, RunFlag, StderrTap,
StdoutTap, WriteCadence, ORDER_MARKER_LINE, ORDER_MARKER_SOURCE,
};
#[cfg(unix)]
use common::{default_sigint, full_file, limit_file_growth};
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
fn spawn_ready(cmd: &mut Command) -> (ChildGuard, StderrTap) {
let (child, tap, stdout_tap) = spawn_watch_ready(cmd);
assert!(
stdout_tap.is_none(),
"this spawn piped stdout; use spawn_ready_piped_stdout so the drained stdout \
is handed back instead of discarded"
);
(ChildGuard(child), tap)
}
fn spawn_ready_piped_stdout(cmd: &mut Command) -> (ChildGuard, StderrTap, StdoutTap) {
let (child, tap, stdout_tap) = spawn_watch_ready(cmd);
let stdout_tap = stdout_tap.expect("caller must set .stdout(Stdio::piped())");
(ChildGuard(child), tap, stdout_tap)
}
fn spawn_unsynchronized(cmd: &mut Command) -> (ChildGuard, StderrTap) {
let (child, tap, stdout_tap) = spawn_watch_unsynchronized(cmd);
assert!(
stdout_tap.is_none(),
"this spawn piped stdout, and the harness has already drained it — the tap \
would be discarded here; use spawn_unsynchronized_piped_stdout instead"
);
(ChildGuard(child), tap)
}
fn spawn_unsynchronized_piped_stdout(cmd: &mut Command) -> (ChildGuard, StderrTap, StdoutTap) {
let (child, tap, stdout_tap) = spawn_watch_unsynchronized(cmd);
let stdout_tap = stdout_tap.expect("caller must set .stdout(Stdio::piped())");
(ChildGuard(child), tap, stdout_tap)
}
#[track_caller]
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
}
#[track_caller]
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 squash(s: &str) -> String {
s.chars()
.filter(|c| !c.is_whitespace() && *c != '\u{2502}')
.collect()
}
#[track_caller]
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);
const SELF_TEST_TIMEOUT: Duration = Duration::from_millis(60);
fn tap_of(text: &str) -> StderrTap {
tap_reader(std::io::Cursor::new(text.as_bytes().to_vec()))
}
fn panic_message_of<T>(f: impl FnOnce() -> T) -> String {
let payload = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(_) => panic!("expected a panic, but the call returned"),
Err(payload) => payload,
};
payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string()))
.expect("panic payload is a string")
}
#[test]
fn wait_for_tap_panics_at_the_caller_naming_what_it_saw() {
let tap = tap_of("alpha\nbeta\n");
assert_eq!(
wait_for_tap(&tap, "beta", TIMEOUT),
"alpha\nbeta\n",
"control: a needle that is there returns the whole text"
);
let call_line = std::cell::Cell::new(0);
let message = panic_message_of(|| {
call_line.set(line!() + 1);
wait_for_tap(&tap, "gamma", SELF_TEST_TIMEOUT)
});
let caller = format!("{}:{}:", file!(), call_line.get());
assert!(
message.contains(&caller),
"the message must name the caller {caller}; got:\n{message}"
);
assert!(
message.contains("\"gamma\"") && message.contains("alpha\nbeta\n"),
"the message must name the needle and what the tap held; got:\n{message}"
);
}
#[test]
fn wait_for_tap_count_panics_at_the_caller_naming_the_count_it_saw() {
let tap = tap_of("Recompiled a\nRecompiled b\n");
let _ = wait_for_tap_count(&tap, "Recompiled ", 2, TIMEOUT);
let call_line = std::cell::Cell::new(0);
let message = panic_message_of(|| {
call_line.set(line!() + 1);
wait_for_tap_count(&tap, "Recompiled ", 3, SELF_TEST_TIMEOUT)
});
let caller = format!("{}:{}:", file!(), call_line.get());
assert!(
message.contains(&caller),
"the message must name the caller {caller}; got:\n{message}"
);
assert!(
message.contains("at least 3 occurrences") && message.contains("saw 2"),
"the message must name the count wanted and the count seen; got:\n{message}"
);
}
#[test]
fn poll_tap_until_reports_a_timeout_as_data() {
let tap = tap_of("alpha\n");
assert_eq!(
poll_tap_until(&tap, TIMEOUT, |text| text.contains("alpha")),
Ok("alpha\n".to_string())
);
assert_eq!(
poll_tap_until(&tap, SELF_TEST_TIMEOUT, |text| text.contains("omega")),
Err("alpha\n".to_string())
);
}
#[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_type_mds_markdown_entry_compiles() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.md");
std::fs::write(&src, "---\ntype: mds\nname: World\n---\nHello {{name}}!\n").unwrap();
let out = dir.path().join("out.md");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md", "-o", "out.md", "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"a type: mds .md entry compiles at startup"
);
write_atomic(&src, "---\ntype: mds\nname: Again\n---\nHello {{name}}!\n");
assert!(
wait_for_file_contains(&out, "Hello Again!", TIMEOUT),
"and is rebuilt on an edit"
);
drop(child);
}
#[test]
fn watch_rebuild_names_the_entry_as_typed() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("sub")).unwrap();
let src = dir.path().join("page.md");
std::fs::write(&src, "---\ntype: mds\n---\nHello!\n").unwrap();
let out = dir.path().join("out.md");
let typed = "./sub/../page.md";
let (child, stderr_tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", typed, "-o", "out.md", "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello!", TIMEOUT),
"control: the typed path compiles at startup"
);
write_atomic(&src, "Hello again!\n");
let stderr = wait_for_tap(&stderr_tap, &format!("not an MDS file: {typed}"), TIMEOUT);
let canonical = src.canonicalize().unwrap();
assert!(
!squash(&stderr).contains(&squash(&format!(
"not an MDS file: {}",
canonical.display()
))),
"never by its canonical absolute path; stderr: {stderr}"
);
drop(child);
}
#[test]
fn watch_entry_through_a_retargeted_directory_is_refused() {
let dir = tempfile::tempdir().unwrap();
for (name, text) in [("a", "Hello A\n"), ("b", "Hello B\n")] {
std::fs::create_dir(dir.path().join(name)).unwrap();
std::fs::write(dir.path().join(name).join("page.mds"), text).unwrap();
}
let link = dir.path().join("link");
if !make_symlink(Path::new("a"), &link) {
return;
}
let watched = dir.path().join("a").join("page.mds");
let out = dir.path().join("out.md");
let typed = Path::new("link").join("page.mds");
let (child, stderr_tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.arg("watch")
.arg(&typed)
.args(["-o", "out.md", "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(wait_for_file_contains(&out, "Hello A", TIMEOUT), "startup");
write_atomic(&watched, "Hello A1\n");
assert!(
wait_for_file_contains(&out, "Hello A1", TIMEOUT),
"control: an edit rebuilds through the link"
);
remove_symlink(&link);
assert!(
make_symlink(Path::new("b"), &link),
"retarget the link to b"
);
write_atomic(&watched, "Hello A2\n");
let stderr = wait_for_tap(&stderr_tap, "watched entry now resolves", TIMEOUT);
assert!(
squash(&stderr).contains(&squash(&format!(
"mds::io × watched entry now resolves to a different file: \"{}\"; \
restart mds watch to follow it",
typed.display()
))),
"the rebuild is refused, naming the entry as typed; stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&out).unwrap(),
"Hello A1\n",
"nothing is written from the retargeted file"
);
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!"
);
write_atomic(&src, "---\nname: Bob\n---\nHello {{name}}!\n");
assert!(
wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
"after editing, output should contain Hello Bob!"
);
drop(child);
}
#[test]
fn watch_replaces_an_output_another_program_holds_open() {
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),
"control: the startup compile writes the output; stderr: {}",
stderr_tap.text()
);
let held = std::fs::File::open(&out).unwrap();
write_atomic(&src, "---\nname: Bob\n---\nHello {{name}}!\n");
assert!(
wait_for_file_contains(&out, "Hello Bob!", TIMEOUT),
"the rebuild must replace the output held open; stderr: {}",
stderr_tap.text()
);
drop(held);
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!"
);
write_atomic(
&helper,
"@define greet(name):\nHi there {{name}}!\n@end\n\n@export greet\n",
);
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"
);
write_atomic(&src, "Hello {{undefined_var_xyz}}!\n");
wait_for_tap(&stderr_tap, "undefined_var_xyz", TIMEOUT);
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher should stay alive after compile error"
);
write_atomic(&src, "---\nname: Charlie\n---\nHello {{name}}!\n");
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"
);
write_atomic(
&dir.path().join("a.mds"),
"---\nname: A-edited\n---\nFile A: {{name}}\n",
);
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"
);
write_atomic(
&dir.path().join("c.mds"),
"---\nname: C\n---\nNew file {{name}}\n",
);
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_empty_root_starts_and_picks_up_new_file() {
let dir = tempfile::tempdir().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()),
);
write_atomic(
&dir.path().join("c.mds"),
"---\nname: C\n---\nNew file {{name}}\n",
);
assert!(
wait_for_file_contains(&out_dir.join("c.md"), "New file C", TIMEOUT),
"a file created under an initially empty watch root should be compiled"
);
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!"
);
write_atomic(&vars, r#"{"name": "Bob"}"#);
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"
);
write_atomic(&src, "---\nname: There\n---\nHello {{name}}!\n");
assert!(
wait_for_file_contains(&out, "Hello There!", TIMEOUT),
"rebuild should occur after editing source"
);
let stderr_bytes = stderr_tap.finish(&mut child);
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"
);
write_atomic(&src, "Greetings {{name}}!\n");
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(), "--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 (child, _stderr_tap, stdout_tap) = spawn_ready_piped_stdout(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"-q",
])
.stdout(Stdio::piped()),
);
let deadline = Instant::now() + TIMEOUT;
let mut found = false;
while Instant::now() < deadline {
if stdout_tap.text().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 {
write_atomic(&src, format!("---\nname: v{i}\n---\nHello {{{{name}}}}!\n"));
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();
std::fs::write(dir.path().join("empty.mds"), "").unwrap();
let include_warning = "@include of 'e' produced empty output";
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 (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
entry.to_str().unwrap(),
"--debounce",
"100",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello World!", TIMEOUT),
"initial compile should produce Hello World!"
);
write_atomic(
&helper,
"@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
);
assert!(
wait_for_file_contains(&out, "Hi World!", TIMEOUT),
"editing helper while imported should trigger a rebuild"
);
write_atomic(
&entry,
"@import \"./empty.mds\" as e\n@include e\nStatic content\n",
);
assert!(
wait_for_file_contains(&out, "Static content", TIMEOUT),
"removing @import should rebuild entry with static content"
);
const STEP_2_COMPILES: usize = 1;
wait_for_tap_count(&stderr_tap, include_warning, STEP_2_COMPILES, TIMEOUT);
let content_before = std::fs::read_to_string(&out).unwrap();
write_atomic(
&helper,
"@define greet(name):\nBye {{name}}!\n@end\n\n@export greet\n",
);
std::thread::sleep(Duration::from_millis(500));
assert_eq!(
std::fs::read_to_string(&out).unwrap(),
content_before,
"after removing @import, editing helper must NOT change entry output"
);
write_atomic(&entry, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, include_warning),
STEP_2_COMPILES,
"after removing @import, editing helper must NOT rebuild the entry; \
stderr:\n{stderr}"
);
}
#[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'"
);
write_atomic(&vars, r#"{"greeting": "Goodbye"}"#);
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_dir_mode_compiles_a_source_created_with_a_vars_change() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("src");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("a.mds"), "A {{v}}\n").unwrap();
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let out = dir.path().join("out");
let (child, _stderr_tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.arg("--vars")
.arg(&vars)
.args(["--debounce", "300", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"a.md is written at startup"
);
std::fs::write(root.join("new.mds"), "New {{v}}\n").unwrap();
write_atomic(&vars, r#"{"v": "two"}"#);
assert!(
wait_for_file_contains(&out.join("a.md"), "A two", TIMEOUT),
"positive control: the vars edit recompiles the known source"
);
assert!(
wait_for_file_contains(&out.join("new.md"), "New two", TIMEOUT),
"the source created with the vars edit is compiled; new.md: {:?}",
std::fs::read_to_string(out.join("new.md")).ok()
);
drop(child);
}
#[test]
fn watch_dir_mode_compiles_a_source_created_while_the_vars_file_is_broken() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("src");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("a.mds"), "A {{v}}\n").unwrap();
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let out = dir.path().join("out");
let (child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.arg("--vars")
.arg(&vars)
.args(["--debounce", "100", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"a.md is written at startup"
);
write_atomic(&vars, r#"{"v": "#);
wait_for_tap_count(&tap, "mds::invalid_vars", 1, TIMEOUT);
std::fs::write(root.join("new.mds"), "New {{v}}\n").unwrap();
wait_for_tap_count(&tap, "mds::invalid_vars", 2, TIMEOUT);
write_atomic(&vars, r#"{"v": "two"}"#);
assert!(
wait_for_file_contains(&out.join("a.md"), "A two", TIMEOUT),
"positive control: the vars fix recompiles the known source"
);
assert!(
wait_for_file_contains(&out.join("new.md"), "New two", TIMEOUT),
"the source created while the vars file was broken is compiled; new.md: {:?}",
std::fs::read_to_string(out.join("new.md")).ok()
);
drop(child);
}
#[test]
fn watch_dir_mode_recompiles_a_failed_source_on_a_vars_change() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("src");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("a.mds"), "A {{v}}\n").unwrap();
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let out = dir.path().join("out");
let (child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.arg("--vars")
.arg(&vars)
.args(["--debounce", "100", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"a.md is written at startup"
);
write_atomic(&root.join("new.mds"), "Hello {{x}}\n");
wait_for_tap_count(&tap, "undefined variable 'x'", 1, TIMEOUT);
write_atomic(&vars, r#"{"v": "two", "x": "World"}"#);
assert!(
wait_for_file_contains(&out.join("a.md"), "A two", TIMEOUT),
"positive control: the vars edit recompiles the known source"
);
assert!(
wait_for_file_contains(&out.join("new.md"), "Hello World", TIMEOUT),
"the source whose compile failed is recompiled by the vars edit; new.md: {:?}",
std::fs::read_to_string(out.join("new.md")).ok()
);
drop(child);
}
#[test]
fn watch_dir_mode_tick_rebuilds_an_md_module_s_importer_and_never_the_module() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("src");
let notes = root.join("notes");
std::fs::create_dir_all(¬es).unwrap();
std::fs::write(
root.join("a.mds"),
"@import \"./notes/inc.md\" as inc\nA.\n@include inc\n",
)
.unwrap();
let module = notes.join("inc.md");
std::fs::write(&module, "---\ntype: mds\n---\nIncluded one\n").unwrap();
let out = dir.path().join("out");
let (child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.args(["--debounce", "0", "--poll-interval", "100", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "Included one", TIMEOUT),
"a.md is written at startup; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "settle");
write_atomic(&module, "---\ntype: mds\n---\nIncluded two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "Included two", TICK_TIMEOUT),
"positive control: the source that includes the module is rebuilt; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "after_edit");
let module_out = out.join("notes").join("inc.md");
assert!(
!module_out.exists(),
"the module is never compiled as a source; {} holds {:?}; stderr: {}",
module_out.display(),
std::fs::read_to_string(&module_out).ok(),
tap.text()
);
drop(child);
}
#[test]
fn watch_dir_mode_event_rebuilds_the_importer_of_an_md_module_below_or_outside_the_root() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("src");
let notes = root.join("notes");
let shared = base.path().join("shared");
std::fs::create_dir_all(¬es).unwrap();
std::fs::create_dir_all(&shared).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
std::fs::write(
root.join("a.mds"),
"@import \"./notes/inc.md\" as inc\n@import \"../shared/ext.md\" as ext\n\
A.\n@include inc\n@include ext\n",
)
.unwrap();
let inside = notes.join("inc.md");
let outside = shared.join("ext.md");
std::fs::write(&inside, "---\ntype: mds\n---\nInside one\n").unwrap();
std::fs::write(&outside, "---\ntype: mds\n---\nOutside one\n").unwrap();
let out = base.path().join("out");
let (child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.args(["--debounce", "0", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "Outside one", TIMEOUT),
"a.md is written at startup; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "settle");
write_atomic(&inside, "---\ntype: mds\n---\nInside two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "Inside two", TIMEOUT),
"the module below the root: its edit rebuilds the source that includes it; \
stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "inside");
write_atomic(&outside, "---\ntype: mds\n---\nOutside two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "Outside two", TIMEOUT),
"the module outside the root: its edit rebuilds the source that includes it; \
stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "outside");
for module_out in [
out.join("notes").join("inc.md"),
out.join("inc.md"),
out.join("ext.md"),
] {
assert!(
!module_out.exists(),
"a module is never compiled as a source; {} holds {:?}; stderr: {}",
module_out.display(),
std::fs::read_to_string(&module_out).ok(),
tap.text()
);
}
drop(child);
}
#[test]
fn watch_dir_mode_never_compiles_an_md_dependency_outside_the_root_as_an_entry() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("src");
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();
std::fs::write(
root.join("a.mds"),
"@import \"../shared/m.md\" as m\nA.\n@include m\n",
)
.unwrap();
let other = root.join("b.mds");
std::fs::write(&other, "B one\n").unwrap();
let module = shared.join("m.md");
std::fs::write(&module, "---\ntype: mds\n---\nModule one\n").unwrap();
let out = base.path().join("out");
let (mut child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&root)
.arg("--out-dir")
.arg(&out)
.args(["--debounce", "0", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "Module one", TIMEOUT),
"a.md is written at startup; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "settle");
write_atomic(&module, "No frontmatter now\n");
settle_queued_events(&tap, &root.join("barrier.mds"), "broken");
write_atomic(&other, "B two\n");
assert!(
wait_for_file_contains(&out.join("b.md"), "B two", TIMEOUT),
"control: a rebuild with a change runs; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "after_b_two");
write_atomic(&other, "B three\n");
assert!(
wait_for_file_contains(&out.join("b.md"), "B three", TIMEOUT),
"control: a second rebuild with a change runs; stderr: {}",
tap.text()
);
write_atomic(&module, "---\ntype: mds\n---\nModule two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "Module two", TIMEOUT),
"the edit that makes the module one again rebuilds the source; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &root.join("barrier.mds"), "end");
let stderr_text = tap.finish_text(&mut child);
let squashed = squash(&stderr_text);
let refusals = count_occurrences(&squashed, &squash("not an MDS file:"));
let through_import = count_occurrences(&squashed, &squash("not an MDS file: ../shared/m.md"));
assert!(
through_import >= 1,
"control: the import of the plain `.md` is refused; stderr: {stderr_text}"
);
assert_eq!(
refusals - through_import,
0,
"the module is refused through its importer only, never compiled as an entry; \
stderr: {stderr_text}"
);
}
#[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"
);
write_atomic(&src, "Hello {{__undefined_xyz__}}!\n");
wait_for_tap(&stderr_tap, "__undefined_xyz__", TIMEOUT);
let still_running = child.0.try_wait().unwrap().is_none();
assert!(
still_running,
"watcher must stay alive after a compile error even under -q"
);
write_atomic(&src, "---\nname: Fixed\n---\nHello {{name}}!\n");
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:?}"
);
let stderr_str = stderr_tap.finish_text(&mut guard);
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() {
const TEST: &str = "watch_debounce_single_rebuild_from_burst";
const WINDOW: Duration = Duration::from_millis(250);
const CAP: Duration = Duration::from_millis(2_500);
const ALLOWANCE: usize = 1;
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!"
);
let mut cadence = WriteCadence::with_capacity(12);
for i in 1..=12u32 {
cadence.time(|| {
std::fs::write(&src, format!("---\nname: v{i}\n---\nBurst {{{{name}}}}!\n")).unwrap();
});
std::thread::sleep(Duration::from_millis(30));
}
let span = cadence.span();
assert!(
span > WINDOW,
"the burst must outlast the 250ms window; span was {span:?}"
);
assert!(
wait_for_file_contains(&out, "Burst v12!", TIMEOUT),
"the burst's final state must be published"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = stderr_tap.finish_text(&mut child);
let rebuilds = count_occurrences(&stderr, "Recompiled ");
let pauses = cadence.pauses(WINDOW / 2);
let most = most_debounce_windows(&cadence, WINDOW, CAP) + ALLOWANCE;
let flag = if pauses == 0 {
RunFlag::Conclusive
} else {
RunFlag::Inconclusive
};
let judged = match flag {
RunFlag::Conclusive => "exactly 1 required".to_string(),
RunFlag::Inconclusive => format!(
"exactly 1 not judged: {pauses} gap(s) of {:?} or more allow at most {most}",
WINDOW / 2
),
};
record_run_flag(
TEST,
flag,
&format!("{rebuilds} rebuild(s), {judged}; {cadence}"),
);
assert!(
rebuilds >= 1,
"the burst's final state was published, so at least one `Recompiled` line; got \
{rebuilds}; stderr was:\n{stderr}"
);
if flag == RunFlag::Conclusive {
assert_eq!(
rebuilds,
1,
"a {span:?} burst with no gap of {:?} or more ({cadence}) must coalesce into \
exactly one rebuild under a 250ms quiet period; stderr was:\n{stderr}",
WINDOW / 2
);
} else {
assert!(
rebuilds <= most,
"a {span:?} burst with {pauses} gap(s) of {:?} or more ({cadence}) allows at \
most {most} rebuilds under a 250ms quiet period; got {rebuilds}; stderr \
was:\n{stderr}",
WINDOW / 2
);
}
assert_eq!(
count_occurrences(&stderr, "Compiled to"),
1,
"the startup compile is the only 'Compiled to' line; stderr was:\n{stderr}"
);
assert_eq!(
std::fs::read_to_string(&out).unwrap(),
"---\nname: v12\n---\nBurst v12!\n",
"the last rebuild must compile the FINAL state of the burst, not an \
intermediate one; stderr was:\n{stderr}"
);
}
#[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));
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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, stdout_tap) = spawn_ready_piped_stdout(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
])
.stdout(Stdio::piped()),
);
std::thread::sleep(Duration::from_millis(1500));
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stdout_str = stdout_tap.finish_text(&mut child);
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));
write_atomic(&dir.path().join("a.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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));
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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)"
);
write_atomic(
&partial,
"@define greet(name):\nHi {{name}}!\n@end\n\n@export greet\n",
);
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"
);
write_atomic(&c, "@define val():\nV2\n@end\n\n@export val\n");
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"
);
write_atomic(&src, "---\nname: Poll\n---\nHello {{name}}!\n");
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));
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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));
write_atomic(&dir.path().join("a.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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();
write_atomic(&src, "---\nname: After\n---\nEntry {{name}}\n");
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();
write_atomic(
&root.join("new.mds"),
"---\nname: N\n---\nNew file {{name}}\n",
);
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);
}
#[cfg(unix)]
#[test]
fn watch_file_mode_relative_paths_recover_after_the_working_directory_is_recreated() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
std::fs::create_dir(&src_dir).unwrap();
std::fs::write(src_dir.join("entry.mds"), "Entry {{name}}\n").unwrap();
std::fs::write(src_dir.join("vars.json"), r#"{"name": "Before"}"#).unwrap();
let out = base.path().join("out.md");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(&src_dir)
.args([
"watch",
"entry.mds",
"--vars",
"vars.json",
"-o",
"../out.md",
])
.args(["--debounce", "0", "--poll-interval", "100", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Entry Before", TIMEOUT),
"startup compile; stderr: {}",
tap.text()
);
std::fs::remove_dir_all(&src_dir).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&src_dir).unwrap();
write_atomic(&src_dir.join("vars.json"), r#"{"name": "After"}"#);
write_atomic(&src_dir.join("entry.mds"), "Recreated {{name}}\n");
assert!(
wait_for_file_contains(&out, "Recreated After", TICK_TIMEOUT),
"the watcher moves back into the recreated working directory and reads the entry \
and the vars file through it; stderr: {}",
tap.text()
);
drop(child);
}
#[cfg(unix)]
#[test]
fn watch_dot_recovers_after_the_working_directory_is_recreated() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("watched");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("a.mds"), "Old {{n}}\n").unwrap();
std::fs::write(root.join("vars.json"), r#"{"n": "A"}"#).unwrap();
let out_dir = base.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(&root)
.args(["watch", ".", "--vars", "vars.json", "--out-dir"])
.arg(&out_dir)
.args(["--debounce", "0", "--poll-interval", "100", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "Old A", TIMEOUT),
"startup compile; stderr: {}",
tap.text()
);
std::fs::remove_dir_all(&root).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&root).unwrap();
write_atomic(&root.join("vars.json"), r#"{"n": "N"}"#);
write_atomic(&root.join("new.mds"), "New file {{n}}\n");
assert!(
wait_for_file_contains(&out_dir.join("new.md"), "New file N", TICK_TIMEOUT),
"the watcher moves back into the recreated working directory and compiles the \
new file through `.`; stderr: {}",
tap.text()
);
drop(child);
}
#[cfg(unix)]
#[test]
fn watch_does_not_follow_a_working_directory_recreated_as_a_symlink() {
let base = tempfile::tempdir().unwrap();
let entry = base.path().join("entry.mds");
std::fs::write(&entry, "Entry\n").unwrap();
let proj = base.path().join("proj");
let other = base.path().join("other");
std::fs::create_dir(&proj).unwrap();
std::fs::create_dir(&other).unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(&proj)
.arg("watch")
.arg(&entry)
.args(["-o", "out.md", "--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&proj.join("out.md"), "Entry", TIMEOUT),
"control: the startup compile writes out.md; stderr: {}",
tap.text()
);
std::fs::remove_dir_all(&proj).unwrap();
assert!(
make_symlink(Path::new("other"), &proj),
"recreate the working directory as a link"
);
write_atomic(&entry, "Edited\n");
let stderr = wait_for_tap(&tap, "out.md: ", TIMEOUT);
assert!(
!other.join("out.md").exists(),
"nothing is written through the link; stderr: {stderr}"
);
drop(child);
}
const DELETION_REPORTS: std::ops::RangeInclusive<usize> = 1..=2;
#[track_caller]
fn not_found_before_the_recovery(stderr: &str) -> usize {
let at = stderr
.find("Recompiled ")
.unwrap_or_else(|| panic!("the recovery's `Recompiled` line; stderr:\n{stderr}"));
let before = &stderr[..at];
count_occurrences(before, "file not found") + count_occurrences(before, "No such file")
}
#[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",
"100",
"--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();
wait_for_tap(&stderr_tap, "file not found", TIMEOUT);
std::thread::sleep(Duration::from_millis(600));
write_atomic(&src, "---\nname: Recovered\n---\nHello {{name}}!\n");
assert!(
wait_for_file_contains(&out, "Hello Recovered!", TIMEOUT),
"watcher must recompile after recreating deleted entry file"
);
wait_for_tap(&stderr_tap, "Recompiled ", TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
let reports = not_found_before_the_recovery(&stderr_str);
assert!(
DELETION_REPORTS.contains(&reports),
"the deletion is reported {DELETION_REPORTS:?} times, not once per idle tick; got \
{reports} file-not-found reports before the recovery; 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));
write_atomic(&vars_file, r#"{"greeting": "Goodbye"}"#);
let got = wait_for_file_contains(&out, "Goodbye", TICK_TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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"
);
write_atomic(
&partial,
"@define greet():\nExternal V2\n@end\n\n@export greet\n",
);
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()),
);
wait_for_tap(&stderr_tap, "mds::file_not_found", TIMEOUT);
let partial = dir.path().join("_missing.mds");
write_atomic(&partial, "@define val():\nHealed!\n@end\n\n@export val\n");
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"
);
write_atomic(
&dual,
"@define greet():\nDual V2 (updated)\n@end\n\n@export greet\n\nStandalone updated content\n",
);
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",
"100",
"--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"
);
wait_for_tap(&stderr_tap, "undefined variable", TIMEOUT);
write_atomic(&dir.path().join("zz.mds"), "Marker\n");
let marked = wait_for_tap(&stderr_tap, "zz.md (0 deps)", TIMEOUT);
let count_w1 = count_occurrences(&marked, "undefined variable");
std::thread::sleep(Duration::from_millis(500));
let count_w2 = count_occurrences(&stderr_tap.text(), "undefined variable");
write_atomic(
&dir.path().join("bad.mds"),
"Hello again {{__undefined_xyz__}}!\n",
);
wait_for_tap_count(&stderr_tap, "undefined variable", count_w2 + 1, TIMEOUT);
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 stderr_str = stderr_tap.finish_text(&mut child);
assert_eq!(
count_w1, count_w2,
"error count must not grow over an idle window after the marker (not \
once-per-tick); at the marker {count_w1}, after the window {count_w2} (reconcile \
rule; no once-per-tick re-firing); 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();
write_atomic(
&partial,
"@define val():\nV2 updated\n@end\n\n@export val\n",
);
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);
write_atomic(
&partial,
format!("@define val():\nSoak V{i}{padding}\n@end\n\n@export val\n"),
);
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",
"100",
"--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();
let deleted = poll_tap_until(&stderr_tap, TIMEOUT, |text| {
text.contains("file not found") || text.contains("No such file")
});
assert!(
deleted.is_ok(),
"the deletion is reported; stderr: {deleted:?}"
);
std::thread::sleep(Duration::from_millis(900));
std::fs::create_dir(&src_dir).unwrap();
write_atomic(&src, "V2-recovered\n");
assert!(
wait_for_file_contains(&out, "V2-recovered", TICK_TIMEOUT),
"watcher must self-heal after parent dir delete+recreate and recompile with V2 content"
);
wait_for_tap(&stderr_tap, "Recompiled ", TIMEOUT);
let still_alive = child.0.try_wait().unwrap().is_none();
let stderr_str = stderr_tap.finish_text(&mut child);
assert!(
still_alive,
"watcher must remain alive while parent dir is absent; stderr:\n{stderr_str}"
);
let reports = not_found_before_the_recovery(&stderr_str);
assert!(
DELETION_REPORTS.contains(&reports),
"the deletion is reported {DELETION_REPORTS:?} times, not once per idle tick; got \
{reports} file-not-found reports before the recovery; 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));
write_atomic(&dir.path().join("file_0001.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_str = stderr_tap.finish_text(&mut child);
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 (reconcile rule: 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]
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");
if !make_symlink(&real_file, &link_file) {
return;
}
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]
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");
if !make_symlink(&real_vars, &link_vars) {
return;
}
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]
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");
if !make_symlink(&real_src, &link_dir) {
return;
}
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]
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");
if !make_symlink(&external_dir.join("external.mds"), &link_mds) {
return;
}
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 (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
let stderr_bytes = stderr_tap.finish(&mut child);
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'"
);
write_atomic(&src, "---\nname: After\n---\nEntry {{name}}\n");
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'"
);
write_atomic(&src, "---\nname: After\n---\nDir {{name}}\n");
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'"
);
write_atomic(
&partial,
"@define greet():\nWindow V2\n@end\n\n@export greet\n",
);
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_dir_mode_vars_truncated_during_startup_is_held_until_written() {
use std::io::Write as _;
const HOLD: Duration = Duration::from_millis(500);
const DEADLINE: Duration = Duration::from_secs(1);
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 vars = base.path().join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let src = root.join("t.mds");
std::fs::write(&src, "Vars {{v}}\n").unwrap();
let out = out_dir.join("t.md");
let (mut child, tap) = spawn_unsynchronized(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--vars",
vars.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains_tight(&out, "Vars one", STARTUP_WINDOW_TIMEOUT),
"startup compile should publish 'Vars one'"
);
let started = Instant::now();
let mut held = std::fs::File::create(&vars).unwrap();
std::thread::sleep(HOLD);
held.write_all(br#"{"v": "two"}"#).unwrap();
let held_for = started.elapsed();
drop(held);
assert!(
wait_for_file_contains(&out, "Vars two", STARTUP_WINDOW_TIMEOUT),
"the content written to the vars file is compiled; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert!(
count_occurrences(&stderr, "mds::") > 0,
"positive control: the order marker's diagnostic is counted; stderr: {stderr}"
);
if held_for >= DEADLINE {
eprintln!(
"the vars file was held for {held_for:?}, past the {DEADLINE:?} deadline (the \
test thread was descheduled); the watcher may report it, so nothing is checked"
);
return;
}
let head = &stderr[..stderr.find(ORDER_MARKER_LINE).unwrap()];
let before = head.rfind("mds::").map_or(head, |code| &head[..code]);
assert_eq!(
count_occurrences(before, "mds::"),
0,
"the vars file truncated during startup is held, not reported as invalid, until \
it is written; stderr: {stderr}"
);
}
#[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'"
);
write_atomic(
&partial,
"@define greet():\nDep V2\n@end\n\n@export greet\n",
);
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();
write_atomic(&root.join("new.mds"), "---\nname: N\n---\nFlood {{name}}\n");
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 cmd = mds_bin();
cmd.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
"-q",
])
.stdout(Stdio::null());
default_sigint(&mut cmd);
let (mut guard, _tap) = spawn_unsynchronized(&mut cmd);
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 cmd = mds_bin();
cmd.args(["watch", src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null());
default_sigint(&mut cmd);
let (mut guard, tap) = spawn_unsynchronized(&mut cmd);
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"
);
}
#[track_caller]
fn wait_bounded(guard: &mut ChildGuard, timeout: Duration, what: &str) -> std::process::ExitStatus {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Some(status) = guard.0.try_wait().expect("try_wait failed") {
return status;
}
std::thread::sleep(Duration::from_millis(1));
}
panic!("{what}: the process did not exit within {timeout:?} of the signal");
}
#[test]
#[cfg(unix)]
fn watch_readiness_handshake_makes_ctrl_c_exit_deterministic() {
use std::os::unix::process::ExitStatusExt;
const N: usize = 20;
const PARTIALS: usize = 400;
let slow_dir = tempfile::tempdir().unwrap();
let mut entry = String::new();
for i in 0..PARTIALS {
let name = format!("_p{i:04}");
std::fs::write(
slow_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 slow_src = slow_dir.path().join("entry.mds");
std::fs::write(&slow_src, &entry).unwrap();
let fast_dir = tempfile::tempdir().unwrap();
let fast_src = fast_dir.path().join("hello.mds");
std::fs::write(&fast_src, "---\nname: World\n---\nHello {{name}}!\n").unwrap();
for iteration in 0..N {
let mut cmd = mds_bin();
cmd.args(["watch", slow_src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null());
default_sigint(&mut cmd);
let (mut guard, tap) = spawn_unsynchronized(&mut cmd);
let pid = guard.id();
let deadline = Instant::now() + STARTUP_WINDOW_TIMEOUT;
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,
"control arm, iteration {iteration}: expected the `Watching …` startup \
line before signalling; stderr:\n{}",
tap.text()
);
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let status = wait_bounded(
&mut guard,
Duration::from_secs(20),
"control arm (SIGINT before the handler is installed)",
);
assert_eq!(
status.signal(),
Some(libc::SIGINT),
"control arm, iteration {iteration}: SIGINT delivered before \
`ctrlc::set_handler` runs must terminate the process. A clean exit here \
means the signal no longer lands in the pre-handler window, and the \
treatment arm below then proves nothing; got {status:?}"
);
assert!(
!status.success(),
"control arm, iteration {iteration}: death by signal is not a success \
status; got {status:?}"
);
let (mut guard, tap) = spawn_ready(
mds_bin()
.args(["watch", fast_src.to_str().unwrap(), "--debounce", "0"])
.stdout(Stdio::null()),
);
let pid = guard.id();
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGINT);
}
let status = wait_bounded(
&mut guard,
Duration::from_secs(5),
"treatment arm (SIGINT after the readiness handshake)",
);
assert!(
status.success(),
"treatment arm, iteration {iteration}: after the readiness handshake the \
ctrl-c handler provably exists (`set_handler` precedes \
`emit_ready_marker` in `live::go_live`), so SIGINT must exit 0; got \
{status:?}; stderr:\n{}",
tap.text()
);
let stderr = tap.finish_text(&mut guard);
assert!(
stderr.contains("Stopped watching."),
"treatment arm, iteration {iteration}: a clean SIGINT exit must also print \
`Stopped watching.`; stderr:\n{stderr}"
);
}
}
#[test]
#[cfg(unix)]
fn default_sigint_gives_a_child_sigint_s_default_action_though_it_would_inherit_it_ignored() {
use std::os::unix::process::{CommandExt as _, ExitStatusExt as _};
let interrupted = |reset: bool| -> std::process::ExitStatus {
let mut cmd = mds_bin();
cmd.args(["fmt", "-"])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null());
unsafe {
cmd.pre_exec(|| {
if libc::signal(libc::SIGINT, libc::SIG_IGN) == libc::SIG_ERR {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
if reset {
default_sigint(&mut cmd);
}
let mut child = ChildGuard(cmd.spawn().expect("spawn mds fmt -"));
let pid = libc::pid_t::try_from(child.id()).expect("a pid fits pid_t");
let sent = unsafe { libc::kill(pid, libc::SIGINT) };
assert_eq!(sent, 0, "send SIGINT to mds fmt -");
drop(child.0.stdin.take());
wait_bounded(&mut child, Duration::from_secs(5), "mds fmt -")
};
let ignored = interrupted(false);
assert_eq!(
ignored.signal(),
None,
"control: a child that inherits SIGINT ignored survives it; got {ignored:?}"
);
let reset = interrupted(true);
assert_eq!(
reset.signal(),
Some(libc::SIGINT),
"default_sigint gives the child SIGINT's default action; got {reset:?}"
);
}
const DUP_SET_WARNING: &str =
"warning: variable 'x' is set more than once by --set; the last value wins";
#[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 (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--debounce",
"0",
"--set",
"x=1",
"--set",
"x=2",
])
.stdout(Stdio::null()),
);
wait_for_tap(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I8: rebuild after edit 1 must complete"
);
write_atomic(&src, "version 3");
assert!(
wait_for_file_contains(&out, "version 3", TIMEOUT),
"I8: rebuild after edit 2 must complete"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let final_stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&final_stderr, "Recompiled "),
2,
"I8: control: both edits rebuilt; stderr:\n{final_stderr}"
);
assert_eq!(
count_occurrences(&final_stderr, DUP_SET_WARNING),
1,
"I8: after two edits the warning must still appear exactly once; \
stderr:\n{final_stderr}"
);
}
#[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 (mut 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()),
);
wait_for_tap(&stderr_tap, DUP_SET_WARNING, TIMEOUT);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I9: rebuild after edit must complete"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let final_stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&final_stderr, "Recompiled "),
1,
"I9: control: the edit rebuilt; stderr:\n{final_stderr}"
);
assert_eq!(
count_occurrences(&final_stderr, DUP_SET_WARNING),
1,
"I9: the warning must appear exactly once — at startup, and not again on \
the rebuild; stderr:\n{final_stderr}"
);
}
#[test]
fn i16_file_watch_vars_file_duplicate_warns_at_startup_and_on_every_rebuild() {
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("t.mds");
std::fs::write(&src, "version 1").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"x": 1, "x": 2}"#).unwrap();
let out = src_dir.join("t.md");
let expected = dup_vars_file_warning("x", &vars_file);
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
let stderr_after_start = wait_for_tap(&stderr_tap, "Compiled to", TIMEOUT);
assert_eq!(
count_occurrences(&stderr_after_start, &expected),
1,
"I16: expected exactly 1 warning at startup; stderr:\n{stderr_after_start}"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I16: rebuild after edit 1 must complete"
);
let after_edit_1 = wait_for_tap_count(&stderr_tap, "Recompiled ", 1, TIMEOUT);
assert_eq!(
count_occurrences(&after_edit_1, &expected),
2,
"I16: one rebuild must re-report the vars-file duplicate; stderr:\n{after_edit_1}"
);
write_atomic(&src, "version 3");
assert!(
wait_for_file_contains(&out, "version 3", TIMEOUT),
"I16: rebuild after edit 2 must complete"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let after_edit_2 = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&after_edit_2, "Recompiled "),
2,
"I16: control: both edits rebuilt; stderr:\n{after_edit_2}"
);
assert_eq!(
count_occurrences(&after_edit_2, &expected),
3,
"I16: a second rebuild must report the duplicate again; stderr:\n{after_edit_2}"
);
}
#[test]
fn i17_dir_watch_vars_file_duplicate_warns_once_per_rebuild() {
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("t.mds");
std::fs::write(&src, "version 1").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"x": 1, "x": 2}"#).unwrap();
let out = src_dir.join("t.md");
let expected = dup_vars_file_warning("x", &vars_file);
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src_dir.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
let stderr_startup = wait_for_tap_count(&stderr_tap, &expected, 1, TIMEOUT);
assert_eq!(
count_occurrences(&stderr_startup, &expected),
1,
"I17: dir-watch startup must emit the vars-file warning exactly once; \
stderr:\n{stderr_startup}"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I17: rebuild after edit must complete"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr_after_edit = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr_after_edit, "Recompiled "),
1,
"I17: control: the edit rebuilt; stderr:\n{stderr_after_edit}"
);
assert_eq!(
count_occurrences(&stderr_after_edit, &expected),
2,
"I17: startup and the one rebuild warn exactly once each (guards a \
double-emit at startup, and between liveness_probe_dir and \
handle_fs_event_dir); stderr:\n{stderr_after_edit}"
);
}
#[test]
fn i18_duplicate_introduced_mid_session_is_reported_on_the_next_rebuild() {
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("t.mds");
std::fs::write(&src, "version 1").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"x": 1}"#).unwrap();
let out = src_dir.join("t.md");
let expected = dup_vars_file_warning("x", &vars_file);
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"I18: startup compile must complete"
);
let startup_stderr = wait_for_tap(&stderr_tap, "Compiled to", TIMEOUT);
assert_eq!(
count_occurrences(&startup_stderr, &expected),
0,
"I18: a clean vars file must not warn at startup; stderr:\n{startup_stderr}"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I18: first rebuild must complete"
);
let clean_rebuild_stderr = wait_for_tap_count(&stderr_tap, "Recompiled ", 1, TIMEOUT);
assert_eq!(
count_occurrences(&clean_rebuild_stderr, &expected),
0,
"I18: the first rebuild must still not warn (vars file is still clean); \
stderr:\n{clean_rebuild_stderr}"
);
write_atomic(&vars_file, r#"{"x": 1, "x": 2}"#);
write_atomic(&src, "version 3");
assert!(
wait_for_file_contains(&out, "version 3", TIMEOUT),
"I18: rebuild after introducing the duplicate must complete"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let final_stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&final_stderr, "Recompiled "),
2,
"I18: control: the clean edit and the `version 3` edit rebuilt; \
stderr:\n{final_stderr}"
);
assert_eq!(
count_occurrences(&final_stderr, &expected),
1,
"I18: the duplicate introduced mid-session must be reported on the next \
rebuild, naming the key; stderr:\n{final_stderr}"
);
}
#[test]
fn i19_dir_watch_liveness_self_heal_rebuild_warns_about_vars_file_duplicate() {
let base = tempfile::tempdir().unwrap();
let root = base.path().join("watched");
let vars_dir = base.path().join("vars_dir");
std::fs::create_dir(&root).unwrap();
std::fs::create_dir(&vars_dir).unwrap();
std::fs::write(root.join("a.mds"), "---\nname: A\n---\nOld A\n").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"x": 1, "x": 2}"#).unwrap();
let out_dir = base.path().join("out");
std::fs::create_dir(&out_dir).unwrap();
let expected = dup_vars_file_warning("x", &vars_file);
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
root.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
"--poll-interval",
"100",
])
.stdout(Stdio::null()),
);
let startup_stderr = wait_for_tap_count(&stderr_tap, &expected, 1, TIMEOUT);
assert_eq!(
count_occurrences(&startup_stderr, &expected),
1,
"I19: dir-watch startup must warn exactly once; stderr:\n{startup_stderr}"
);
assert!(
wait_for_file_contains(&out_dir.join("a.md"), "Old A", TIMEOUT),
"I19: 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();
write_atomic(
&root.join("new.mds"),
"---\nname: N\n---\nNew file {{name}}\n",
);
assert!(
wait_for_file_contains(&out_dir.join("new.md"), "New file N", TICK_TIMEOUT),
"I19: watcher must self-heal after root delete+recreate and recompile"
);
write_atomic(&root.join("new.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TICK_TIMEOUT);
let final_stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&final_stderr, &expected),
2,
"I19: the liveness self-heal rebuild must warn about the vars-file \
duplicate too, not only at startup; stderr:\n{final_stderr}"
);
}
#[test]
fn i20_watch_quiet_suppresses_vars_file_duplicate_warning_on_every_rebuild() {
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("t.mds");
std::fs::write(&src, "version 1").unwrap();
let vars_file = vars_dir.join("vars.json");
std::fs::write(&vars_file, r#"{"x": 1, "x": 2}"#).unwrap();
let out = src_dir.join("t.md");
let expected = dup_vars_file_warning("x", &vars_file);
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"--vars",
vars_file.to_str().unwrap(),
"--debounce",
"0",
"--quiet",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"I20: startup compile must complete even under --quiet"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"I20: rebuild after edit must complete even under --quiet"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = stderr_tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, &expected),
0,
"I20: --quiet must suppress the vars-file duplicate warning at startup and on \
rebuild; stderr:\n{stderr}"
);
}
#[test]
fn watch_file_mode_rename_into_place_triggers_rebuild() {
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"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"file mode: startup compile must complete"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"file mode: a rename-into-place edit must trigger a rebuild"
);
wait_for_tap(&stderr_tap, "Recompiled", TIMEOUT);
drop(child);
}
#[test]
fn watch_dir_mode_rename_into_place_triggers_rebuild() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
let out_dir = base.path().join("out");
std::fs::create_dir_all(&src_dir).unwrap();
std::fs::create_dir_all(&out_dir).unwrap();
let src = src_dir.join("t.mds");
std::fs::write(&src, "version 1").unwrap();
let out = out_dir.join("t.md");
let (child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src_dir.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"dir mode: startup compile must complete"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"dir mode: a rename-into-place edit must trigger a rebuild"
);
wait_for_tap(&stderr_tap, "Recompiled", TIMEOUT);
drop(child);
}
#[test]
fn watch_dir_mode_write_atomic_temp_file_is_never_compiled() {
let base = tempfile::tempdir().unwrap();
let src_dir = base.path().join("src");
let out_dir = base.path().join("out");
std::fs::create_dir_all(&src_dir).unwrap();
std::fs::create_dir_all(&out_dir).unwrap();
let src = src_dir.join("t.mds");
std::fs::write(&src, "version 1").unwrap();
let (mut child, stderr_tap) = spawn_ready(
mds_bin()
.args([
"watch",
src_dir.to_str().unwrap(),
"--out-dir",
out_dir.to_str().unwrap(),
"--debounce",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out_dir.join("t.md"), "version 1", TIMEOUT),
"temp file: startup compile must complete"
);
write_atomic(&src, "version 2");
assert!(
wait_for_file_contains(&out_dir.join("t.md"), "version 2", TIMEOUT),
"temp file: the atomic edit must rebuild t.md"
);
write_atomic(&src_dir.join("u.mds"), "brand new");
assert!(
wait_for_file_contains(&out_dir.join("u.md"), "brand new", TIMEOUT),
"R3 (positive control): a real source created by a rename must be compiled"
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&stderr_tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = stderr_tap.finish_text(&mut child);
for dir in [&out_dir, &src_dir] {
for entry in std::fs::read_dir(dir).unwrap() {
let name = entry.unwrap().file_name().to_string_lossy().into_owned();
assert!(
!name.contains(".tmp-"),
"temp file: no file derived from a write_atomic temp name may survive in {}; \
found {name}",
dir.display()
);
}
}
assert!(
!stderr.contains(".tmp-"),
"temp file: no status line may mention a write_atomic temp file; stderr:\n{stderr}"
);
}
const CASE_PROBE_LINE: &str = "undefined variable 'probe'";
fn case_insensitive_volume(dir: &Path) -> bool {
std::fs::write(dir.join("probe"), "").unwrap();
dir.join("PROBE").exists()
}
fn stored_names(dir: &Path) -> Vec<String> {
std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect()
}
#[track_caller]
fn rename_case_only(from: &Path, to: &Path) {
std::fs::rename(from, to).unwrap();
let names = stored_names(from.parent().unwrap());
let stored = |p: &Path| {
let name = p.file_name().unwrap().to_string_lossy();
names.iter().any(|n| *n == name)
};
assert!(
stored(to) && !stored(from),
"the rename must change the stored name: {names:?}"
);
}
#[test]
fn watch_file_mode_edit_after_a_case_only_rename_of_the_entry_rebuilds() {
let dir = tempfile::tempdir().unwrap();
let entry = dir.path().join("Main.mds");
let other_case = dir.path().join("main.mds");
let part = dir.path().join("part.mds");
let out = dir.path().join("Main.md");
let case_insensitive = case_insensitive_volume(dir.path());
if case_insensitive {
std::fs::write(&part, "part one\n").unwrap();
std::fs::write(
&entry,
"@import \"./part.mds\" as p\nversion 1\n@include p\n",
)
.unwrap();
} else {
std::fs::write(&entry, "Main {{probe}}\n").unwrap();
std::fs::write(&other_case, "main one\n").unwrap();
}
let (mut child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&entry)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
if case_insensitive {
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"the startup compile writes Main.md; stderr: {}",
tap.text()
);
rename_case_only(&entry, &other_case);
eprintln!(
"arm: case-insensitive volume; Main.mds now resolves to {}",
entry.canonicalize().unwrap().display()
);
settle_queued_events(&tap, &part, "renamed");
write_atomic(&other_case, "version 2\n");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"an edit after a case-only rename of the entry must rebuild through its \
event; Main.md: {:?}; stderr: {}",
std::fs::read_to_string(&out).ok(),
tap.text()
);
write_atomic(&other_case, "version 3\n");
assert!(
wait_for_file_contains(&out, "version 3", TIMEOUT),
"each later edit rebuilds too; stderr: {}",
tap.text()
);
write_atomic(&other_case, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert!(
!stderr.contains("now resolves to a different"),
"a case-only rename of the entry is not a move; stderr:\n{stderr}"
);
} else {
eprintln!("arm: case-sensitive volume");
wait_for_tap(&tap, CASE_PROBE_LINE, TIMEOUT);
assert_eq!(
std::fs::read_to_string(&other_case).unwrap(),
"main one\n",
"Main.mds and main.mds must be two files on this volume"
);
write_atomic(&other_case, "main two\n");
std::thread::sleep(Duration::from_millis(500));
write_atomic(&entry, "version 2\n");
assert!(
wait_for_file_contains(&out, "version 2", TIMEOUT),
"positive control: an edit of the entry rebuilds; stderr: {}",
tap.text()
);
write_atomic(&entry, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, CASE_PROBE_LINE),
1,
"only the startup compile reads the probe: an edit of main.mds must not \
rebuild Main.mds; stderr:\n{stderr}"
);
assert_eq!(
count_occurrences(&stderr, "Recompiled"),
1,
"the edit of Main.mds gives exactly one rebuild; stderr:\n{stderr}"
);
}
}
#[test]
fn watch_file_mode_edit_after_a_case_only_rename_of_the_vars_file_rebuilds() {
let dir = tempfile::tempdir().unwrap();
let entry = dir.path().join("t.mds");
let vars = dir.path().join("Vars.json");
let other_case = dir.path().join("vars.json");
let out = dir.path().join("t.md");
let case_insensitive = case_insensitive_volume(dir.path());
if case_insensitive {
std::fs::write(&entry, "V {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
} else {
std::fs::write(&entry, "V {{probe}}\n").unwrap();
std::fs::write(&vars, "{}").unwrap();
std::fs::write(&other_case, r#"{"probe": "other one"}"#).unwrap();
}
let (mut child, tap) = spawn_ready(
mds_bin()
.arg("watch")
.arg(&entry)
.arg("--vars")
.arg(&vars)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
if case_insensitive {
assert!(
wait_for_file_contains(&out, "V one", TIMEOUT),
"the startup compile writes t.md; stderr: {}",
tap.text()
);
rename_case_only(&vars, &other_case);
eprintln!(
"arm: case-insensitive volume; Vars.json now resolves to {}",
vars.canonicalize().unwrap().display()
);
settle_queued_events(&tap, &entry, "renamed");
write_atomic(&entry, "W {{v}}\n");
assert!(
wait_for_file_contains(&out, "W one", TIMEOUT),
"the entry rebuilds after the barrier; stderr: {}",
tap.text()
);
write_atomic(&other_case, r#"{"v": "two"}"#);
assert!(
wait_for_file_contains(&out, "W two", TIMEOUT),
"an edit after a case-only rename of the vars file must rebuild through its \
event; t.md: {:?}; stderr: {}",
std::fs::read_to_string(&out).ok(),
tap.text()
);
drop(child);
} else {
eprintln!("arm: case-sensitive volume");
wait_for_tap(&tap, CASE_PROBE_LINE, TIMEOUT);
assert_eq!(
std::fs::read_to_string(&vars).unwrap(),
"{}",
"Vars.json and vars.json must be two files on this volume"
);
write_atomic(&other_case, r#"{"probe": "other two"}"#);
std::thread::sleep(Duration::from_millis(500));
write_atomic(&vars, r#"{"probe": "two"}"#);
assert!(
wait_for_file_contains(&out, "V two", TIMEOUT),
"positive control: an edit of the vars file rebuilds; stderr: {}",
tap.text()
);
write_atomic(&entry, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, CASE_PROBE_LINE),
1,
"only the startup compile reads the probe: an edit of vars.json must not \
rebuild t.mds; stderr:\n{stderr}"
);
assert_eq!(
count_occurrences(&stderr, "Recompiled"),
1,
"the edit of Vars.json gives exactly one rebuild; stderr:\n{stderr}"
);
}
}
#[test]
fn stderr_tap_finish_captures_every_line_the_child_wrote() {
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!("drain-{i}\n"),
)
.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()),
);
let stderr = stderr_tap.finish_text(&mut child);
let announced = count_occurrences(&stderr, "Compiled to");
assert_eq!(
announced, FILE_COUNT,
"the tap must return every `Compiled to` line the child wrote; got {announced} \
of {FILE_COUNT}"
);
}
#[test]
fn watch_ready_with_large_piped_stdout_does_not_deadlock() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("big.mds");
let body: String = std::iter::repeat_n("x".repeat(63) + "\n", 8192).collect();
assert!(
body.len() > 256 * 1024,
"fixture must exceed several pipe buffers; got {} bytes",
body.len()
);
std::fs::write(&src, &body).unwrap();
let (mut child, _stderr_tap, stdout_tap) = spawn_ready_piped_stdout(
mds_bin()
.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"-q",
])
.stdout(Stdio::piped()),
);
let stdout = stdout_tap.finish(&mut child);
assert!(
stdout.len() >= body.len(),
"the whole startup output must reach stdout; got {} bytes of {}",
stdout.len(),
body.len()
);
}
#[test]
fn a_symlink_at_the_readiness_file_s_temporary_path_does_not_redirect_it() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Page\n").unwrap();
let victim = dir.path().join("victim.txt");
std::fs::write(&victim, "VICTIM\n").unwrap();
let marker = dir.path().join("ready");
if !make_symlink(&victim, &dir.path().join("ready.tmp")) {
return;
}
let (child, _tap, _) = spawn_watch_ready_at(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--debounce", "0", "-q"])
.stdout(Stdio::null()),
&marker,
);
let _child = ChildGuard(child);
assert_eq!(
std::fs::read_to_string(&victim).unwrap(),
"VICTIM\n",
"the file the planted link points to keeps its bytes"
);
assert!(
std::fs::symlink_metadata(&marker)
.unwrap()
.file_type()
.is_file(),
"the marker is a file of its own, not the planted link"
);
}
#[test]
fn watch_dot_forms_watch_the_canonical_directory() {
let dir = tempfile::tempdir().unwrap();
let proj = dir.path().join("proj");
std::fs::create_dir_all(proj.join("sub")).unwrap();
std::fs::write(proj.join("p.mds"), "P\n").unwrap();
std::fs::write(proj.join("sub").join("s.mds"), "S\n").unwrap();
let canonical = proj.canonicalize().unwrap();
for (i, (cwd, typed)) in [
(proj.clone(), "."),
(proj.clone(), "./"),
(proj.join("sub"), ".."),
(proj.clone(), "sub/.."),
]
.into_iter()
.enumerate()
{
let label = format!("(in {}) mds watch {typed}", cwd.display());
let out = dir.path().join(format!("out{i}"));
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(&cwd)
.args(["watch", typed, "--out-dir", out.to_str().unwrap()])
.args(["--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("p.md"), "P", TIMEOUT),
"{label}: p.mds compiles at startup; stderr: {}",
tap.text()
);
assert!(
wait_for_file_contains(&out.join("sub").join("s.md"), "S", TIMEOUT),
"{label}: sub/s.mds compiles at startup; stderr: {}",
tap.text()
);
let stderr = wait_for_tap(&tap, "Watching directory ", TIMEOUT);
let banner = stderr
.lines()
.find_map(|l| l.strip_prefix("Watching directory "))
.unwrap_or_else(|| panic!("{label}: no banner; stderr: {stderr}"));
assert_eq!(
banner, typed,
"{label}: the banner names the directory as typed"
);
assert!(
!stderr.contains(&format!("Watching directory {}", canonical.display())),
"{label}: never by the canonical directory; stderr: {stderr}"
);
let edited = format!("P{i}");
write_atomic(&proj.join("p.mds"), format!("{edited}\n"));
assert!(
wait_for_file_contains(&out.join("p.md"), &edited, TIMEOUT),
"{label}: an edit rebuilds; stderr: {}",
tap.text()
);
drop(child);
}
}
#[test]
fn watch_dir_through_a_retargeted_link_is_refused() {
let rows = std::iter::once((Path::new("link").join("a"), "one", "two"))
.chain(cfg!(unix).then(|| (Path::new("link").join(".."), "one/a/x", "two/a/y")));
for (typed, first, then) in rows {
let dir = tempfile::tempdir().unwrap();
for (name, below, text) in [("one", "x", "Hello A\n"), ("two", "y", "Hello B\n")] {
let root = dir.path().join(name).join("a");
std::fs::create_dir_all(root.join(below)).unwrap();
std::fs::write(root.join("p.mds"), text).unwrap();
}
let link = dir.path().join("link");
if !make_symlink(Path::new(first), &link) {
return;
}
let watched = dir.path().join("one").join("a").join("p.mds");
let out = dir.path().join("out").join("p.md");
let shown = typed.display();
let (child, stderr_tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.arg("watch")
.arg(&typed)
.args(["--out-dir", "out", "--debounce", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello A", TIMEOUT),
"{shown}: startup"
);
write_atomic(&watched, "Hello A1\n");
assert!(
wait_for_file_contains(&out, "Hello A1", TIMEOUT),
"{shown}: control: an edit rebuilds through the link"
);
remove_symlink(&link);
assert!(
make_symlink(Path::new(then), &link),
"{shown}: retarget the link to {then}"
);
write_atomic(&watched, "Hello A2\n");
let stderr = wait_for_tap(&stderr_tap, "watched directory now resolves", TIMEOUT);
assert!(
squash(&stderr).contains(&squash(&format!(
"mds::io × watched directory now resolves to a different directory: \
\"{shown}\"; restart mds watch to follow it"
))),
"{shown}: the rebuild is refused, naming the directory as typed; stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&out).unwrap(),
"Hello A1\n",
"{shown}: nothing is written from the retargeted directory"
);
drop(child);
}
}
#[test]
fn watch_dir_source_under_a_subdirectory_swapped_for_a_link_is_refused() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("root");
std::fs::create_dir_all(root.join("sub")).unwrap();
std::fs::write(root.join("top.mds"), "Top {{v}}\n").unwrap();
std::fs::write(root.join("sub").join("x.mds"), "Inside {{v}}\n").unwrap();
let outside = dir.path().join("outside");
std::fs::create_dir(&outside).unwrap();
std::fs::write(outside.join("x.mds"), "Outside {{v}}\n").unwrap();
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": "1"}"#).unwrap();
let out = dir.path().join("out");
let x_out = out.join("sub").join("x.md");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "root", "--out-dir", "out", "--vars", "vars.json"])
.args(["--debounce", "0", "--poll-interval", "0", "-q"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&x_out, "Inside 1", TIMEOUT),
"startup; stderr: {}",
tap.text()
);
write_atomic(&root.join("sub").join("x.mds"), "Inside {{v}} again\n");
assert!(
wait_for_file_contains(&x_out, "Inside 1 again", TIMEOUT),
"control: an edit under the unchanged subdirectory rebuilds; stderr: {}",
tap.text()
);
std::fs::rename(root.join("sub"), dir.path().join("sub.old")).unwrap();
if !make_symlink(&outside, &root.join("sub")) {
return;
}
write_atomic(&vars, r#"{"v": "2"}"#);
assert!(
wait_for_file_contains(&out.join("top.md"), "Top 2", TIMEOUT),
"control: the vars edit rebuilds every known source; stderr: {}",
tap.text()
);
let stderr = wait_for_tap(&tap, "watched file now resolves", TIMEOUT);
let walked = Path::new("root").join("sub").join("x.mds");
assert!(
squash(&stderr).contains(&squash(&format!(
"mds::io × watched file now resolves to a different file: \"{}\"; \
restart mds watch to follow it",
walked.display()
))),
"the rebuild is refused, naming the source as walked; stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&x_out).unwrap(),
"Inside 1 again\n",
"nothing is written from outside the tree; stderr: {stderr}"
);
drop(child);
}
const WATCH_HELP_EXAMPLES: [(&str, &str); 10] = [
(
"mds watch template.mds",
"watch_initial_compile_writes_output",
),
(
"mds watch chat.mds",
"watch_messages_template_produces_json_intrinsically",
),
(
"mds watch template.mds -o out.md",
"watch_output_flag_writes_to_specified_file",
),
(
"mds watch template.mds -o -",
"watch_stdout_contains_content_when_o_stdout",
),
(
"mds watch .",
"watch_help_example_dot_watches_the_working_directory",
),
(
"mds watch src/ --out-dir dist",
"watch_help_example_src_out_dir_dist_mirrors_the_subtree",
),
(
"mds watch template.mds --vars v.json",
"watch_vars_file_change_triggers_recompile",
),
(
"mds watch template.mds --clear",
"watch_clear_non_tty_no_ansi_escape",
),
(
"mds watch src/ --poll-interval 500",
"watch_help_example_src_poll_interval_500_self_heals",
),
(
"mds watch src/ --poll-interval 0",
"watch_help_example_src_poll_interval_0_rebuilds_on_native_events",
),
];
fn test_attribute(name: &str) -> Option<bool> {
const SOURCE: &str = include_str!("cli_watch.rs");
let at = SOURCE.find(&format!("\nfn {name}() {{"))?;
let before = &SOURCE[..at];
let preamble = &before[before.rfind("\n}\n").map_or(0, |i| i + 3)..];
Some(preamble.lines().any(|l| l.trim() == "#[test]"))
}
fn not_a_test() {}
#[test]
fn watch_help_examples_each_have_a_named_test() {
let output = mds_bin().args(["watch", "--help"]).output().unwrap();
assert!(output.status.success(), "mds watch --help exits 0");
let help = String::from_utf8(output.stdout).unwrap();
let (_, examples) = help
.split_once("Examples:")
.unwrap_or_else(|| panic!("--help has an Examples section; got: {help}"));
let shown: std::collections::BTreeSet<&str> = examples
.lines()
.map(str::trim)
.filter(|l| l.starts_with("mds watch"))
.map(|l| l.split(" ").next().unwrap_or(l).trim_end())
.collect();
let mapped: std::collections::BTreeSet<&str> =
WATCH_HELP_EXAMPLES.iter().map(|(ex, _)| *ex).collect();
assert_eq!(
shown, mapped,
"every --help example, and only those, is mapped"
);
for (example, test) in WATCH_HELP_EXAMPLES {
assert_eq!(
test_attribute(test),
Some(true),
"{example:?} maps to `{test}`, which is not a #[test] in this file"
);
}
let _: fn() = not_a_test;
assert_eq!(
test_attribute("watch_help_example_that_does_not_exist"),
None
);
assert_eq!(test_attribute("not_a_test"), Some(false));
assert_eq!(
test_attribute("watch_help_examples_each_have_a_named_test"),
Some(true)
);
}
#[test]
fn watch_help_example_dot_watches_the_working_directory() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("template.mds"), "Hello!\n").unwrap();
let out = dir.path().join("template.md");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", ".", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello!", TIMEOUT),
"the startup compile writes template.md; stderr: {}",
tap.text()
);
write_atomic(&dir.path().join("template.mds"), "Hello again!\n");
assert!(
wait_for_file_contains(&out, "Hello again!", TIMEOUT),
"an edit rebuilds; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_help_example_src_out_dir_dist_mirrors_the_subtree() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir_all(src.join("sub")).unwrap();
std::fs::write(src.join("a.mds"), "A\n").unwrap();
std::fs::write(src.join("sub").join("b.mds"), "B\n").unwrap();
let dist = dir.path().join("dist");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "src/", "--out-dir", "dist", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&dist.join("a.md"), "A", TIMEOUT),
"src/a.mds → dist/a.md; stderr: {}",
tap.text()
);
assert!(
wait_for_file_contains(&dist.join("sub").join("b.md"), "B", TIMEOUT),
"src/sub/b.mds → dist/sub/b.md; stderr: {}",
tap.text()
);
assert!(!dist.join("b.md").exists(), "mirrored, not flattened");
write_atomic(&src.join("sub").join("b.mds"), "B2\n");
assert!(
wait_for_file_contains(&dist.join("sub").join("b.md"), "B2", TIMEOUT),
"an edit rebuilds the mirrored output; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_help_example_src_poll_interval_500_self_heals() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("a.mds"), "Old A\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "src/", "--poll-interval", "500", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&src.join("a.md"), "Old A", TIMEOUT),
"startup compile; stderr: {}",
tap.text()
);
std::fs::remove_dir_all(&src).unwrap();
std::thread::sleep(Duration::from_millis(200));
std::fs::create_dir(&src).unwrap();
write_atomic(&src.join("new.mds"), "New file\n");
assert!(
wait_for_file_contains(&src.join("new.md"), "New file", TICK_TIMEOUT),
"the self-heal tick recovers the recreated root; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_help_example_src_poll_interval_0_rebuilds_on_native_events() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("a.mds"), "A\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "src/", "--poll-interval", "0", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&src.join("a.md"), "A", TIMEOUT),
"startup compile; stderr: {}",
tap.text()
);
write_atomic(&src.join("a.mds"), "A2\n");
assert!(
wait_for_file_contains(&src.join("a.md"), "A2", TIMEOUT),
"a native event rebuilds with the self-heal tick off; stderr: {}",
tap.text()
);
drop(child);
}
const TYPE_MDS_PAGE: &str = "---\ntype: mds\nname: X\n---\nHello {{name}}!\n";
fn entry_overwrite_refusal(typed: &str) -> String {
squash(&format!(
"mds::io × output would overwrite the entry file: \"{typed}\"; \
write it elsewhere with -o <file> or --out-dir <dir>"
))
}
fn startup_refusal_exit(
child: &mut ChildGuard,
tap: StderrTap,
label: &str,
) -> (Option<i32>, String) {
let deadline = Instant::now() + Duration::from_secs(10);
let status = loop {
if let Some(status) = child.0.try_wait().unwrap() {
break status;
}
assert!(
Instant::now() < deadline,
"{label}: still running, so it did not refuse; stderr: {}",
tap.text()
);
std::thread::sleep(Duration::from_millis(10));
};
(status.code(), tap.finish_text(child))
}
#[test]
fn watch_refuses_at_startup_to_write_over_the_entry() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.md");
std::fs::write(&src, TYPE_MDS_PAGE).unwrap();
let mut extras: Vec<&[&str]> = vec![
&[],
&["--out-dir", "."],
&["-o", "page.md"],
&["-o", "newdir/../page.md"],
&["--out-dir", "newdir/.."],
];
if dir.path().join("PAGE.md").exists() {
extras.push(&["-o", "newdir/../PAGE.md"]);
}
for extra in extras {
let label = format!("mds watch page.md {}", extra.join(" "));
let (mut child, tap) = spawn_unsynchronized(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md", "--debounce", "0"])
.args(extra)
.stdout(Stdio::null()),
);
let (code, stderr) = startup_refusal_exit(&mut child, tap, &label);
assert_eq!(code, Some(2), "{label}: stderr: {stderr}");
assert!(
squash(&stderr).contains(&entry_overwrite_refusal("page.md")),
"{label}: stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&src).unwrap(),
TYPE_MDS_PAGE,
"{label}: the source is untouched"
);
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
1,
"{label}: nothing is written"
);
}
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md", "--out-dir", "fresh", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(
&dir.path().join("fresh").join("page.md"),
"Hello X!",
TIMEOUT
),
"control: --out-dir fresh is created and written; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_rebuild_never_writes_over_the_entry() {
for extra in [&[][..], &["-o", "newdir/../page.md"]] {
let label = format!("mds watch page.md {}", extra.join(" "));
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.md");
std::fs::write(&src, "---\ntype: mds\n---\nHello {{name\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md", "--debounce", "0"])
.args(extra)
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, TYPE_MDS_PAGE);
let stderr = wait_for_tap(&tap, "output would overwrite the entry file", TIMEOUT);
assert!(
squash(&stderr).contains(&entry_overwrite_refusal("page.md")),
"{label}: the rebuild is refused; stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&src).unwrap(),
TYPE_MDS_PAGE,
"{label}: the fixed source is untouched"
);
assert_eq!(
std::fs::read_dir(dir.path()).unwrap().count(),
1,
"{label}: nothing is written"
);
let mut child = child;
assert!(
child.0.try_wait().unwrap().is_none(),
"{label}: watch keeps running after a refused rebuild"
);
drop(child);
}
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.md");
std::fs::write(&src, "---\ntype: mds\n---\nHello {{name\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md", "--out-dir", "fresh", "--debounce", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
assert!(
!dir.path().join("fresh").exists(),
"control: a failed startup compile creates no directory"
);
write_atomic(&src, TYPE_MDS_PAGE);
assert!(
wait_for_file_contains(
&dir.path().join("fresh").join("page.md"),
"Hello X!",
TIMEOUT
),
"control: the rebuild creates fresh/ and writes it; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_refusal_is_not_preceded_by_the_extension_warning() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("e.mds");
let no_warning = |stderr: &str, label: &str| {
assert!(
!stderr.contains("warning:"),
"{label}: no warning announces a write that is refused; stderr: {stderr}"
);
};
std::fs::write(&src, "E\n").unwrap();
let label = "startup: mds watch e.mds -o e.mds";
let (mut child, tap) = spawn_unsynchronized(
mds_bin()
.current_dir(dir.path())
.args(["watch", "e.mds", "-o", "e.mds", "--debounce", "0"])
.stdout(Stdio::null()),
);
let (code, stderr) = startup_refusal_exit(&mut child, tap, label);
assert_eq!(code, Some(2), "{label}: stderr: {stderr}");
assert!(
squash(&stderr).contains(&entry_overwrite_refusal("e.mds")),
"{label}: stderr: {stderr}"
);
no_warning(&stderr, label);
drop(child);
std::fs::write(&src, "Hello {{name\n").unwrap();
let label = "fallback: mds watch e.mds -o e.mds";
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "e.mds", "-o", "e.mds", "--debounce", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, "E\n");
let stderr = wait_for_tap(&tap, "output would overwrite the entry file", TIMEOUT);
assert!(
squash(&stderr).contains(&entry_overwrite_refusal("e.mds")),
"{label}: the rebuild is refused; stderr: {stderr}"
);
no_warning(&stderr, label);
assert_eq!(std::fs::read_to_string(&src).unwrap(), "E\n", "{label}");
drop(child);
let other = dir.path().join("other.mds");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "e.mds", "-o", "other.mds", "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&other, "E", TIMEOUT),
"control: other.mds is written; stderr: {}",
tap.text()
);
let warning = "warning: output path 'other.mds' has extension '.mds' but compiled output \
is markdown (.md); writing to 'other.mds' anyway";
wait_for_tap(&tap, warning, TIMEOUT);
drop(child);
}
const DOTDOT_OUTPUT_DIR: &str = r#"{"build":{"output_dir":"../x"}}"#;
fn dotdot_output_dir_refusal() -> String {
squash("mds::io × mds.json output_dir '../x' must not contain '..' components")
}
#[test]
fn watch_refuses_at_startup_an_output_route_that_fails() {
let rows = [
("file mode", "page.mds", "Hello one\n", true),
(
"file mode, failed startup compile",
"page.mds",
"Hello {{name\n",
false,
),
("directory mode", ".", "Hello one\n", true),
];
for (mode, input, source, compiles) in rows {
let label = format!("{mode}: mds watch {input}");
let top = tempfile::tempdir().unwrap();
let proj = top.path().join("proj");
std::fs::create_dir(&proj).unwrap();
std::fs::write(proj.join("mds.json"), DOTDOT_OUTPUT_DIR).unwrap();
std::fs::write(proj.join("page.mds"), source).unwrap();
let (mut child, tap, stdout_tap) = spawn_unsynchronized_piped_stdout(
mds_bin()
.current_dir(&proj)
.args(["watch", input, "--debounce", "0"])
.stdout(Stdio::piped()),
);
let (code, stderr) = startup_refusal_exit(&mut child, tap, &label);
let stdout = stdout_tap.finish_text(&mut child);
assert_eq!(code, Some(2), "{label}: stderr: {stderr}");
assert_eq!(
count_occurrences(&squash(&stderr), &dotdot_output_dir_refusal()),
1,
"{label}: the refusal is reported, once; stderr: {stderr}"
);
assert!(
!stderr.contains("Compiled to"),
"{label}: nothing is compiled to a file; stderr: {stderr}"
);
assert!(
!stderr.contains("Recompiled"),
"{label}: no rebuild runs; stderr: {stderr}"
);
assert_eq!(stdout, "", "{label}: nothing is written to stdout");
let mut names: Vec<String> = std::fs::read_dir(&proj)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
assert_eq!(
names,
["mds.json", "page.mds"],
"{label}: nothing is written"
);
assert_eq!(
std::fs::read_dir(top.path()).unwrap().count(),
1,
"{label}: no output directory is created"
);
if compiles {
let build = mds_bin()
.current_dir(&proj)
.args(["build", input])
.output()
.unwrap();
let build_stderr = String::from_utf8_lossy(&build.stderr);
assert_eq!(
build.status.code(),
code,
"{label}: mds build {input} exits as watch does; stderr: {build_stderr}"
);
assert!(
squash(&build_stderr).contains(&dotdot_output_dir_refusal()),
"{label}: mds build {input} gives the same error; stderr: {build_stderr}"
);
} else {
assert!(
stderr.contains("mds::syntax"),
"{label}: the compile error is reported; stderr: {stderr}"
);
}
}
}
#[test]
fn watch_startup_route_refusal_controls() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello {{name\n").unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.mds", "--debounce", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, "Hello fixed\n");
assert!(
wait_for_file_contains(&dir.path().join("page.md"), "Hello fixed", TIMEOUT),
"failed startup compile: the rebuild writes page.md; stderr: {}",
tap.text()
);
assert!(
child.0.try_wait().unwrap().is_none(),
"failed startup compile: watch keeps running"
);
drop(child);
for (flag, value, written) in [
("-o", "out.md", "out.md"),
("--out-dir", "out", "out/page.md"),
] {
let label = format!("mds watch page.mds {flag} {value}");
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("mds.json"), DOTDOT_OUTPUT_DIR).unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let out = dir.path().join(written);
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.mds", flag, value, "--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out, "Hello one", TIMEOUT),
"{label}: startup writes {written}; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello two\n");
assert!(
wait_for_file_contains(&out, "Hello two", TIMEOUT),
"{label}: the rebuild writes {written}; stderr: {}",
tap.text()
);
assert!(
!tap.text().contains("must not contain"),
"{label}: nothing is refused; stderr: {}",
tap.text()
);
assert!(
child.0.try_wait().unwrap().is_none(),
"{label}: watch keeps running"
);
drop(child);
}
let label = "mds watch page.mds -o -";
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("mds.json"), DOTDOT_OUTPUT_DIR).unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let (mut child, tap, stdout_tap) = spawn_ready_piped_stdout(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.mds", "-o", "-", "--debounce", "0"])
.stdout(Stdio::piped()),
);
wait_for_tap(&stdout_tap, "Hello one", TIMEOUT);
write_atomic(&src, "Hello two\n");
wait_for_tap(&stdout_tap, "Hello two", TIMEOUT);
assert!(
!tap.text().contains("must not contain"),
"{label}: nothing is refused; stderr: {}",
tap.text()
);
assert!(
child.0.try_wait().unwrap().is_none(),
"{label}: watch keeps running"
);
assert!(
!dir.path().join("page.md").exists(),
"{label}: nothing is written next to the source"
);
drop(child);
}
#[test]
fn watch_failed_startup_write_keeps_the_compiled_kinds_route() {
let watch = |dir: &Path| {
spawn_ready(
mds_bin()
.current_dir(dir)
.args(["watch", "chat.mds"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
)
};
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("chat.mds");
let json = dir.path().join("chat.json");
let md = dir.path().join("chat.md");
std::fs::write(&src, "@message user:\nWhat is 2+2?\n@end\n").unwrap();
std::fs::create_dir(&json).unwrap();
let shown = Path::new(".").join("chat.json");
let (child, tap) = watch(dir.path());
let startup = wait_for_tap(&tap, "cannot write", TIMEOUT);
assert!(
squash(&startup).contains(&squash(&format!("cannot write {}:", shown.display()))),
"the startup error names the .json output as typed; stderr: {startup}"
);
std::fs::remove_dir(&json).unwrap();
write_atomic(&src, "@message user:\nWhat is 3+3?\n@end\n");
let rebuilt = wait_for_file_contains(&json, "What is 3+3?", TIMEOUT);
let stderr = wait_for_tap(&tap, "Recompiled", TIMEOUT);
assert!(
!md.exists(),
"no Markdown output is ever created; chat.md holds {:?}; stderr: {stderr}",
std::fs::read_to_string(&md).ok()
);
assert!(
squash(&stderr).contains(&squash(&format!("Recompiled {}", shown.display()))),
"the rebuild writes the .json output; stderr: {stderr}"
);
let written = std::fs::read_to_string(&json).unwrap();
let parsed: serde_json::Value =
serde_json::from_str(&written).expect("the .json output is JSON");
assert!(
rebuilt && parsed.is_array() && written.contains("What is 3+3?"),
"chat.json holds the rebuilt messages: {written}"
);
drop(child);
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("chat.mds");
let md = dir.path().join("chat.md");
std::fs::write(&src, "Hello {{name\n").unwrap();
let (child, tap) = watch(dir.path());
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, "Hello fixed\n");
assert!(
wait_for_file_contains(&md, "Hello fixed", TIMEOUT),
"control: after a failed startup compile the rebuild writes chat.md; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_failed_startup_write_keeps_the_compiled_dependencies() {
let dir = tempfile::tempdir().unwrap();
let part = dir.path().join("part.mds");
let src = dir.path().join("page.mds");
let out = dir.path().join("page.md");
std::fs::write(&part, "@define who():\nWorld\n@end\n\n@export who\n").unwrap();
std::fs::write(&src, "@import \"./part.mds\" as p\nHello {{p.who()}}!\n").unwrap();
std::fs::create_dir(&out).unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.mds"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "cannot write", TIMEOUT);
std::fs::remove_dir(&out).unwrap();
write_atomic(&part, "@define who():\nPlanet\n@end\n\n@export who\n");
assert!(
wait_for_file_contains(&out, "Hello Planet!", TIMEOUT),
"an edit to the imported partial rebuilds the entry; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_failed_startup_write_warns_about_the_output_extension_once() {
let warnings = |source: &str| {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("chat.mds"), source).unwrap();
std::fs::create_dir(dir.path().join("out.json")).unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "chat.mds", "-o", "out.json"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let stderr = tap.finish_text(&mut child);
assert!(
squash(&stderr).contains(&squash("cannot write out.json:")),
"the startup write fails; stderr: {stderr}"
);
(
count_occurrences(&squash(&stderr), &squash("has extension '.json'")),
stderr,
)
};
let (count, stderr) = warnings("Hello\n");
assert_eq!(
count, 1,
"a Markdown output named .json is warned about once; stderr: {stderr}"
);
let (count, stderr) = warnings("@message user:\nHi\n@end\n");
assert_eq!(
count, 0,
"a messages output named .json is not warned about; stderr: {stderr}"
);
}
#[test]
fn watch_failed_startup_compile_routes_by_the_kind_it_compiles_to() {
const MESSAGES: &str = "@message user:\nWhat is 3+3?\n@end\n";
const MARKDOWN: &str = "Hello fixed\n";
let session = |args: &[&str], fixed: &str| {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("chat.mds");
std::fs::write(&src, "Hello {{name\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "chat.mds"])
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, fixed);
let stderr = wait_for_tap(&tap, "Recompiled", TIMEOUT);
drop(child);
(dir, stderr)
};
let recompiled = |stderr: &str, shown: &Path| {
squash(stderr).contains(&squash(&format!("Recompiled {}", shown.display())))
};
let (dir, stderr) = session(&[], MESSAGES);
let md = dir.path().join("chat.md");
assert!(
!md.exists(),
"a template fixed into messages never writes chat.md; it holds {:?}; stderr: {stderr}",
std::fs::read_to_string(&md).ok()
);
assert!(
recompiled(&stderr, &Path::new(".").join("chat.json")),
"the rebuild names the .json output as typed; stderr: {stderr}"
);
let written = std::fs::read_to_string(dir.path().join("chat.json")).unwrap();
let parsed: serde_json::Value =
serde_json::from_str(&written).expect("the .json output is JSON");
assert!(
parsed.is_array() && written.contains("What is 3+3?"),
"chat.json holds the messages: {written}"
);
let (dir, stderr) = session(&["--out-dir", "out"], MESSAGES);
assert!(
recompiled(&stderr, &Path::new("out").join("chat.json")),
"under --out-dir the rebuild writes the .json output; stderr: {stderr}"
);
let written = std::fs::read_to_string(dir.path().join("out").join("chat.json")).unwrap();
assert!(
written.contains("What is 3+3?"),
"out/chat.json holds the messages: {written}"
);
let (dir, stderr) = session(&[], MARKDOWN);
assert!(
recompiled(&stderr, &Path::new(".").join("chat.md")),
"control: the rebuild names the .md output; stderr: {stderr}"
);
let written = std::fs::read_to_string(dir.path().join("chat.md")).unwrap();
assert!(
written.contains("Hello fixed"),
"control: chat.md holds the Markdown: {written}"
);
assert!(
!dir.path().join("chat.json").exists(),
"a template fixed into Markdown never writes chat.json; stderr: {stderr}"
);
let (dir, stderr) = session(&["-o", "out.md"], MESSAGES);
assert!(
recompiled(&stderr, Path::new("out.md")),
"control: the rebuild writes the -o output; stderr: {stderr}"
);
let written = std::fs::read_to_string(dir.path().join("out.md")).unwrap();
assert!(
written.contains("What is 3+3?"),
"control: out.md holds the messages: {written}"
);
assert!(
!dir.path().join("chat.json").exists() && !dir.path().join("out.json").exists(),
"control: -o is never routed by the kind; stderr: {stderr}"
);
}
#[test]
fn watch_route_refused_as_the_entry_is_not_kept() {
const MESSAGES: &str = "---\ntype: mds\n---\n@message user:\nWhat is 3+3?\n@end\n";
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.md");
let json = dir.path().join("page.json");
std::fs::write(&src, "---\ntype: mds\n---\nHello {{name\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "page.md"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "mds::syntax", TIMEOUT);
write_atomic(&src, TYPE_MDS_PAGE);
let refused = wait_for_tap(&tap, "output would overwrite the entry file", TIMEOUT);
assert!(
squash(&refused).contains(&entry_overwrite_refusal("page.md")),
"control: the Markdown route is refused; stderr: {refused}"
);
write_atomic(&src, MESSAGES);
let written = wait_for_file_contains(&json, "What is 3+3?", TIMEOUT);
assert!(
written,
"a later compile to messages writes page.json; stderr: {}",
tap.text()
);
let stderr = wait_for_tap(&tap, "Recompiled", TIMEOUT);
assert!(
squash(&stderr).contains(&squash(&format!(
"Recompiled {}",
Path::new(".").join("page.json").display()
))),
"the rebuild names page.json as typed; stderr: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&src).unwrap(),
MESSAGES,
"the entry is untouched"
);
drop(child);
}
#[test]
fn watch_dir_failed_startup_write_is_retried_on_the_next_rebuild() {
let dir = tempfile::tempdir().unwrap();
let d = dir.path().join("d");
std::fs::create_dir(&d).unwrap();
let (a, b) = (d.join("a.mds"), d.join("b.mds"));
let (a_out, b_out) = (d.join("a.md"), d.join("b.md"));
std::fs::write(&a, "Steady a\n").unwrap();
std::fs::write(&b, "Steady b\n").unwrap();
std::fs::create_dir(&a_out).unwrap();
let shown = |name: &str| Path::new("d").join(name);
let recompiled = |stderr: &str, name: &str| {
count_occurrences(
&squash(stderr),
&squash(&format!("Recompiled {}", shown(name).display())),
)
};
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "d"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let startup = wait_for_tap(&tap, "cannot write", TIMEOUT);
assert!(
squash(&startup).contains(&squash(&format!(
"cannot write {}:",
shown("a.md").display()
))),
"the startup write of a.md fails; stderr: {startup}"
);
assert!(
wait_for_file_contains(&b_out, "Steady b", TIMEOUT),
"control: the startup writes b.md; stderr: {startup}"
);
std::fs::remove_dir(&a_out).unwrap();
write_atomic(&a, "Steady a\n");
assert!(
wait_for_file_contains(&a_out, "Steady a", TIMEOUT),
"a save of the unchanged source writes a.md once the obstacle is gone; stderr: {}",
tap.text()
);
write_atomic(&b, "Steady b\n");
write_atomic(&d.join("m.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
recompiled(&stderr, "a.md"),
1,
"a.md is written once; stderr: {stderr}"
);
assert_eq!(
recompiled(&stderr, "b.md"),
0,
"control: a save of the same bytes rewrites nothing; stderr: {stderr}"
);
}
#[test]
fn watch_dir_failed_rebuild_write_keeps_the_compiled_dependencies() {
let base = tempfile::tempdir().unwrap();
let (root, shared) = (base.path().join("root"), base.path().join("shared"));
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():\nShared one\n@end\n\n@export greet\n",
)
.unwrap();
let (a, a_out) = (root.join("a.mds"), root.join("a.md"));
std::fs::write(&a, "Plain a\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "root"])
.args(["--debounce", "0", "--poll-interval", "100"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&a_out, "Plain a", TIMEOUT),
"control: the startup writes a.md; stderr: {}",
tap.text()
);
std::fs::remove_file(&a_out).unwrap();
std::fs::create_dir(&a_out).unwrap();
write_atomic(&a, "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n");
let failed = wait_for_tap(&tap, "cannot write", TIMEOUT);
assert!(
squash(&failed).contains(&squash(&format!(
"cannot write {}:",
Path::new("root").join("a.md").display()
))),
"the rebuild's write of a.md fails; stderr: {failed}"
);
std::fs::remove_dir(&a_out).unwrap();
write_atomic(
&partial,
"@define greet():\nShared, edited\n@end\n\n@export greet\n",
);
assert!(
wait_for_file_contains(&a_out, "Shared, edited", TICK_TIMEOUT),
"an edit to the file the failed rebuild imported rebuilds a.md; stderr: {}",
tap.text()
);
drop(child);
}
#[cfg(debug_assertions)]
#[test]
fn watch_dir_startup_compiles_each_source_once() {
let dir = tempfile::tempdir().unwrap();
let d = dir.path().join("d");
std::fs::create_dir(&d).unwrap();
for name in ["a", "b"] {
std::fs::write(d.join(format!("{name}.mds")), format!("Hello {name}\n")).unwrap();
}
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.env("MDS_TEST_PANIC", "compile:a")
.args(["watch", "d", "--quiet"])
.args(["--debounce", "30000", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let b_md = std::fs::read_to_string(d.join("b.md")).ok();
let stderr = tap.finish_text(&mut child);
assert_eq!(
b_md.as_deref(),
Some("Hello b\n"),
"control: the startup compiles and writes the other source; stderr: {stderr}"
);
assert!(
!d.join("a.md").exists(),
"a compile that panicked writes no output; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, "mds: internal compiler error"),
1,
"the startup compiles a.mds once; stderr: {stderr}"
);
}
const STOPPED_STDOUT_CLOSED: &str = "Stopped watching (stdout closed).\n";
const SESSION_END_TIMEOUT: Duration = Duration::from_secs(10);
#[cfg(unix)]
fn interrupt(guard: &ChildGuard) {
unsafe {
libc::kill(guard.id() as libc::pid_t, libc::SIGINT);
}
}
#[test]
fn watch_to_stdout_whose_reader_is_gone_stops_and_exits_0() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let src = src.to_str().unwrap();
let loud = ["watch", src, "-o", "-", "--debounce", "0"];
let quiet = ["watch", src, "-o", "-", "--debounce", "0", "-q"];
let (mut open, _open_tap, open_stdout) =
spawn_ready_piped_stdout(mds_bin().args(loud).stdout(Stdio::piped()));
wait_for_tap(&open_stdout, "Hello one", TIMEOUT);
assert!(
open.0.try_wait().unwrap().is_none(),
"control: with an open pipe the session keeps watching"
);
drop(open);
let (mut closed, tap) =
spawn_unsynchronized(mds_bin().args(loud).stdout(Stdio::from(closed_pipe())));
let status = wait_bounded(
&mut closed,
SESSION_END_TIMEOUT,
"watch -o - with no reader",
);
let stderr = tap.finish_text(&mut closed);
assert_eq!(
status.code(),
Some(0),
"a gone stdout reader ends the session with exit 0; stderr: {stderr:?}"
);
let lines: Vec<&str> = stderr.lines().collect();
assert!(
lines.len() == 2 && lines[0].starts_with("Watching "),
"the session prints `Watching …` and then exactly the stop line; stderr: {stderr:?}"
);
assert_eq!(
format!("{}\n", lines[1]),
STOPPED_STDOUT_CLOSED,
"the last line names the closed stdout; stderr: {stderr:?}"
);
let (mut quiet_run, quiet_tap) =
spawn_unsynchronized(mds_bin().args(quiet).stdout(Stdio::from(closed_pipe())));
let status = wait_bounded(
&mut quiet_run,
SESSION_END_TIMEOUT,
"watch -o - -q with no reader",
);
let stderr = quiet_tap.finish_text(&mut quiet_run);
assert_eq!(
status.code(),
Some(0),
"--quiet: a gone stdout reader ends the session with exit 0; stderr: {stderr:?}"
);
assert_eq!(
stderr, "",
"--quiet prints nothing when stdout's reader is gone"
);
}
#[test]
fn watch_to_stdout_stops_when_its_reader_goes_away_and_exits_0() {
use std::io::Read as _;
for quiet in [false, true] {
let what = if quiet { "--quiet" } else { "loud" };
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let mut args = vec!["watch", src.to_str().unwrap(), "-o", "-", "--debounce", "0"];
if quiet {
args.push("-q");
}
let (reader, writer) = std::io::pipe().unwrap();
let (mut guard, tap) = spawn_ready(mds_bin().args(&args).stdout(Stdio::from(writer)));
let first_output = b"Hello one\n";
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut reader = reader;
let mut first = vec![0u8; first_output.len()];
let read = reader.read_exact(&mut first).map(|()| first);
let _ = tx.send((read, reader));
});
let (read, reader) = rx
.recv_timeout(TIMEOUT)
.expect("the startup output must reach the pipe");
assert_eq!(
read.expect("read the startup output"),
first_output,
"control ({what}): the session writes its output to stdout"
);
drop(reader);
write_atomic(&src, "Hello two\n");
let status = wait_bounded(
&mut guard,
SESSION_END_TIMEOUT,
&format!("watch -o - ({what}) after its reader went away"),
);
let stderr = tap.finish_text(&mut guard);
assert_eq!(
status.code(),
Some(0),
"{what}: a reader that goes away ends the session with exit 0; stderr: {stderr:?}"
);
if quiet {
assert_eq!(
stderr, "",
"--quiet prints nothing when stdout's reader goes away mid-session"
);
continue;
}
assert!(
stderr.ends_with(STOPPED_STDOUT_CLOSED)
&& count_occurrences(&stderr, STOPPED_STDOUT_CLOSED) == 1,
"the session ends with exactly one stop line; stderr: {stderr:?}"
);
assert!(
stderr.starts_with("Watching ") && !stderr.contains("Recompiled"),
"a write the closed pipe lost is not a rebuild; stderr: {stderr:?}"
);
}
}
#[test]
fn watch_with_stderr_closed_keeps_watching() {
for mode in ["file", "directory"] {
for closed in [false, true] {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let out = dir.path().join("page.md");
let mut cmd = mds_bin();
if mode == "file" {
cmd.args(["watch", src.to_str().unwrap()]);
} else {
cmd.args(["watch", dir.path().to_str().unwrap()]);
}
cmd.args(["--debounce", "0"]).stdout(Stdio::null());
let what = format!(
"{mode} mode, stderr {}",
if closed { "closed" } else { "open" }
);
let (mut guard, tap) = if closed {
cmd.stderr(Stdio::from(closed_pipe()));
let (child, _no_stdout) = spawn_watch_ready_stderr_untapped(&mut cmd);
(ChildGuard(child), None)
} else {
let (guard, tap) = spawn_ready(&mut cmd);
(guard, Some(tap))
};
assert!(
wait_for_file_contains(&out, "Hello one", TIMEOUT),
"{what}: the startup compile writes the output"
);
write_atomic(&src, "Hello two\n");
assert!(
wait_for_file_contains(&out, "Hello two", TIMEOUT),
"{what}: an edit rebuilds the output"
);
if let Some(tap) = &tap {
wait_for_tap(tap, "Recompiled ", TIMEOUT);
assert!(
tap.text().starts_with("Watching "),
"control ({what}): the session writes its status lines to stderr"
);
}
assert!(
guard.0.try_wait().unwrap().is_none(),
"{what}: the session keeps watching"
);
#[cfg(unix)]
{
interrupt(&guard);
let status = wait_bounded(&mut guard, SESSION_END_TIMEOUT, &what);
assert_eq!(status.code(), Some(0), "{what}: Ctrl+C exits 0");
if let Some(tap) = tap {
let stderr = tap.finish_text(&mut guard);
assert!(
stderr.ends_with("Stopped watching.\n"),
"control ({what}): Ctrl+C prints the stop line; stderr: {stderr:?}"
);
}
}
}
}
}
#[cfg(unix)]
#[test]
fn watch_to_a_failing_stdout_reports_once_and_retries_the_same_content() {
const LIMIT: usize = 64;
const FINAL_MARKER_SOURCE: &str = "Final marker {{__final_marker__}}\n";
const FINAL_MARKER_LINE: &str = "undefined variable '__final_marker__'";
let include_warning = "@include of 'e' produced empty output";
let edited = "@import \"./empty.mds\" as e\n@include e\nHello two\n";
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("empty.mds"), "").unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let stdout_dir = tempfile::tempdir().unwrap();
let stdout_path = stdout_dir.path().join("stdout");
let mut cmd = mds_bin();
cmd.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"--poll-interval",
"0",
]);
let stdout_file = full_file(&stdout_path, LIMIT);
let mut stdout_offset = stdout_file.try_clone().unwrap();
cmd.stdout(Stdio::from(stdout_file));
limit_file_growth(&mut cmd, LIMIT as libc::rlim_t);
let (mut guard, tap) = spawn_ready(&mut cmd);
assert_eq!(
std::fs::read(&stdout_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: the vector fails every write, so the startup output never landed"
);
wait_for_tap(&tap, "cannot write to stdout", TIMEOUT);
write_atomic(&src, edited);
wait_for_tap(&tap, include_warning, TIMEOUT);
write_atomic(&src, ORDER_MARKER_SOURCE);
let seen = wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
assert_eq!(
count_occurrences(&seen, "Recompiled"),
0,
"a write stdout lost is not a rebuild; stderr:\n{seen}"
);
assert_eq!(
std::fs::read(&stdout_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: no write reached the file"
);
{
use std::io::Seek as _;
stdout_offset.set_len(0).unwrap();
stdout_offset.seek(std::io::SeekFrom::Start(0)).unwrap();
}
write_atomic(&src, edited);
let retried = poll_tap_until(&tap, TIMEOUT, |text| text.contains("Recompiled <stdout>"));
assert!(
retried.is_ok(),
"a save of the text whose write stdout lost must write it again; stderr:\n{}",
tap.text()
);
assert_eq!(
std::fs::read_to_string(&stdout_path).unwrap(),
"Hello two\n",
"the retried write reached stdout"
);
write_atomic(&src, FINAL_MARKER_SOURCE);
let seen = wait_for_tap(&tap, FINAL_MARKER_LINE, TIMEOUT);
assert_eq!(
count_occurrences(&seen, "cannot write to stdout"),
1,
"a stdout failure is reported once however many writes it fails; stderr:\n{seen}"
);
assert!(
seen.contains("mds::io") && seen.contains("File too large"),
"the report is `mds::io` with the cause; stderr:\n{seen}"
);
assert_eq!(
count_occurrences(&seen, "Recompiled"),
1,
"exactly the retried write is a rebuild; stderr:\n{seen}"
);
interrupt(&guard);
let status = wait_bounded(
&mut guard,
SESSION_END_TIMEOUT,
"Ctrl+C after a stdout failure",
);
assert_eq!(
status.code(),
Some(0),
"a stdout failure during the session does not change the Ctrl+C exit"
);
}
#[test]
fn watch_to_a_failing_stdout_reports_once_and_keeps_watching() {
let include_warning = "@include of 'e' produced empty output";
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("empty.mds"), "").unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let stdout_dir = tempfile::tempdir().unwrap();
let stdout_path = stdout_dir.path().join("stdout");
let mut cmd = mds_bin();
cmd.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"--poll-interval",
"0",
]);
#[cfg(unix)]
let (held, cause) = {
const LIMIT: usize = 64;
cmd.stdout(Stdio::from(full_file(&stdout_path, LIMIT)));
limit_file_growth(&mut cmd, LIMIT as libc::rlim_t);
(vec![b'#'; LIMIT], "File too large (os error 27)")
};
#[cfg(windows)]
let (held, cause) = {
std::fs::write(&stdout_path, "").unwrap();
let read_only = std::fs::File::open(&stdout_path).unwrap();
cmd.stdout(Stdio::from(read_only));
(Vec::<u8>::new(), "(os error 5)")
};
let (mut guard, tap) = spawn_ready(&mut cmd);
wait_for_tap(&tap, "cannot write to stdout", TIMEOUT);
write_atomic(
&src,
"@import \"./empty.mds\" as e\n@include e\nHello two\n",
);
wait_for_tap(&tap, include_warning, TIMEOUT);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
assert!(
guard.0.try_wait().unwrap().is_none(),
"the session keeps watching; stderr:\n{}",
tap.text()
);
let stderr = tap.finish_text(&mut guard);
assert_eq!(
count_occurrences(&stderr, "cannot write to stdout"),
1,
"a stdout failure is reported once however many writes it fails; stderr:\n{stderr}"
);
assert!(
stderr.contains("mds::io") && stderr.contains(cause),
"the report is `mds::io` with the cause, {cause}; stderr:\n{stderr}"
);
assert_eq!(
count_occurrences(&stderr, "Recompiled"),
0,
"a write stdout lost is not a rebuild; stderr:\n{stderr}"
);
assert_eq!(
std::fs::read(&stdout_path).unwrap(),
held,
"precondition: no write reached stdout"
);
}
#[cfg(unix)]
#[test]
fn watch_to_stdout_reports_a_new_failure_after_stdout_recovers() {
const LIMIT: usize = 64;
const FINAL_MARKER_SOURCE: &str = "Final marker {{__final_marker__}}\n";
const FINAL_MARKER_LINE: &str = "undefined variable '__final_marker__'";
let include_warning = "@include of 'e' produced empty output";
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("empty.mds"), "").unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let stdout_dir = tempfile::tempdir().unwrap();
let stdout_path = stdout_dir.path().join("stdout");
let mut cmd = mds_bin();
cmd.args([
"watch",
src.to_str().unwrap(),
"-o",
"-",
"--debounce",
"0",
"--poll-interval",
"0",
]);
let stdout_file = full_file(&stdout_path, LIMIT);
let mut stdout_offset = stdout_file.try_clone().unwrap();
cmd.stdout(Stdio::from(stdout_file));
limit_file_growth(&mut cmd, LIMIT as libc::rlim_t);
let (mut guard, tap) = spawn_ready(&mut cmd);
assert_eq!(
std::fs::read(&stdout_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: the vector fails every write, so the startup output never landed"
);
wait_for_tap(&tap, "cannot write to stdout", TIMEOUT);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
{
use std::io::Seek as _;
stdout_offset.set_len(0).unwrap();
stdout_offset.seek(std::io::SeekFrom::Start(0)).unwrap();
}
write_atomic(&src, "Hello two\n");
let recovered = poll_tap_until(&tap, TIMEOUT, |text| text.contains("Recompiled <stdout>"));
assert!(
recovered.is_ok(),
"precondition: once there is room, a rebuild writes stdout; stderr:\n{}",
tap.text()
);
assert_eq!(
std::fs::read_to_string(&stdout_path).unwrap(),
"Hello two\n",
"precondition: the recovered write reached stdout"
);
{
use std::io::{Seek as _, Write as _};
stdout_offset.set_len(0).unwrap();
stdout_offset.seek(std::io::SeekFrom::Start(0)).unwrap();
stdout_offset.write_all(&[b'#'; LIMIT]).unwrap();
}
write_atomic(&src, "Hello three\n");
wait_for_tap_count(&tap, "cannot write to stdout", 2, TIMEOUT);
write_atomic(
&src,
"@import \"./empty.mds\" as e\n@include e\nHello four\n",
);
wait_for_tap(&tap, include_warning, TIMEOUT);
write_atomic(&src, FINAL_MARKER_SOURCE);
let seen = wait_for_tap(&tap, FINAL_MARKER_LINE, TIMEOUT);
assert_eq!(
count_occurrences(&seen, "cannot write to stdout"),
2,
"one report per failure, however many writes each fails; stderr:\n{seen}"
);
assert_eq!(
count_occurrences(&seen, "Recompiled"),
1,
"only the write that landed is a rebuild; stderr:\n{seen}"
);
assert_eq!(
std::fs::read(&stdout_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: no write after the refill reached the file"
);
interrupt(&guard);
let status = wait_bounded(
&mut guard,
SESSION_END_TIMEOUT,
"Ctrl+C after a second stdout failure",
);
assert_eq!(
status.code(),
Some(0),
"stdout failures during the session do not change the Ctrl+C exit"
);
}
fn a_session_whose_rebuild_write_failed() -> (
ChildGuard,
StderrTap,
std::path::PathBuf,
[tempfile::TempDir; 2],
) {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let out_dir = tempfile::tempdir().unwrap();
let out = out_dir.path().join("page.md");
let (guard, 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 one", TIMEOUT),
"the startup compile writes the output"
);
std::fs::remove_file(&out).unwrap();
std::fs::create_dir(&out).unwrap();
std::fs::write(out.join("keep"), "a directory where the output was\n").unwrap();
write_atomic(&src, "Hello two\n");
let seen = wait_for_tap(&tap, "mds::io", TIMEOUT);
assert!(
!seen.contains("Recompiled"),
"the failed write is reported, not announced; stderr:\n{seen}"
);
(guard, tap, src, [dir, out_dir])
}
#[cfg(unix)]
#[test]
fn watch_exits_0_at_ctrl_c_after_a_rebuild_write_failed() {
let (mut guard, tap, _, _dirs) = a_session_whose_rebuild_write_failed();
interrupt(&guard);
let status = wait_bounded(
&mut guard,
SESSION_END_TIMEOUT,
"Ctrl+C after a failed write",
);
let stderr = tap.finish_text(&mut guard);
assert_eq!(
status.code(),
Some(0),
"a failed rebuild write does not change the Ctrl+C exit; stderr: {stderr:?}"
);
assert!(
stderr.ends_with("Stopped watching.\n"),
"the session ends as any Ctrl+C does; stderr: {stderr:?}"
);
assert!(
!stderr.contains("Recompiled"),
"the failed write is never announced, before the session ends or after the error; \
stderr: {stderr:?}"
);
}
#[test]
fn watch_reports_a_rebuild_write_that_failed_and_keeps_watching() {
let (mut guard, tap, src, _dirs) = a_session_whose_rebuild_write_failed();
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
assert!(
guard.0.try_wait().unwrap().is_none(),
"the session keeps watching; stderr:\n{}",
tap.text()
);
let stderr = tap.finish_text(&mut guard);
assert!(
stderr.contains("mds::io") && !stderr.contains("Recompiled"),
"the failed write is reported, and never announced; stderr: {stderr:?}"
);
}
#[cfg(unix)]
#[test]
fn watch_with_a_failing_stderr_keeps_watching_and_exits_0_at_ctrl_c() {
const LIMIT: usize = 64;
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let stderr_dir = tempfile::tempdir().unwrap();
let args = ["watch", src.to_str().unwrap(), "-o", "-", "--debounce", "0"];
let check_stderr = stderr_dir.path().join("check-stderr");
let mut check = mds_bin();
check
.args(["check", src.to_str().unwrap()])
.stdout(Stdio::null())
.stderr(Stdio::from(full_file(&check_stderr, LIMIT)));
limit_file_growth(&mut check, LIMIT as libc::rlim_t);
let mut check = ChildGuard(check.spawn().unwrap());
let status = wait_bounded(&mut check, SESSION_END_TIMEOUT, "mds check");
assert_eq!(
status.code(),
Some(2),
"control: a stderr that fails other than by a closed pipe lifts `mds check` to 2"
);
let (open, open_tap, open_stdout) =
spawn_ready_piped_stdout(mds_bin().args(args).stdout(Stdio::piped()));
wait_for_tap(&open_stdout, "Hello one", TIMEOUT);
write_atomic(&src, "Hello two\n");
wait_for_tap(&open_stdout, "Hello two", TIMEOUT);
let seen = wait_for_tap(&open_tap, "Recompiled <stdout>", TIMEOUT);
assert!(
seen.starts_with("Watching "),
"control: the session writes its status lines to stderr; stderr: {seen:?}"
);
drop(open);
std::fs::write(&src, "Hello one\n").unwrap();
let stderr_path = stderr_dir.path().join("watch-stderr");
let mut cmd = mds_bin();
cmd.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::from(full_file(&stderr_path, LIMIT)));
limit_file_growth(&mut cmd, LIMIT as libc::rlim_t);
let (child, stdout_tap) = spawn_watch_ready_stderr_untapped(&mut cmd);
let mut guard = ChildGuard(child);
let stdout_tap = stdout_tap.expect("stdout is piped");
wait_for_tap(&stdout_tap, "Hello one", TIMEOUT);
write_atomic(&src, "Hello two\n");
wait_for_tap(&stdout_tap, "Hello two", TIMEOUT);
assert!(
guard.0.try_wait().unwrap().is_none(),
"the session keeps watching with a failing stderr"
);
interrupt(&guard);
let status = wait_bounded(
&mut guard,
SESSION_END_TIMEOUT,
"Ctrl+C with a failing stderr",
);
assert_eq!(
status.code(),
Some(0),
"a failing stderr during the session does not change the Ctrl+C exit"
);
assert_eq!(
std::fs::read(&stderr_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: every stderr write failed"
);
}
#[cfg(unix)]
#[test]
fn watch_that_stops_before_it_is_live_exits_by_the_batch_rule() {
const LIMIT: usize = 64;
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
std::fs::write(&src, "Hello one\n").unwrap();
let args = ["watch", src.to_str().unwrap(), "-o", "-", "--debounce", "0"];
let (mut open, open_tap) =
spawn_unsynchronized(mds_bin().args(args).stdout(Stdio::from(closed_pipe())));
let status = wait_bounded(&mut open, SESSION_END_TIMEOUT, "stderr open");
let stderr = open_tap.finish_text(&mut open);
assert_eq!(
status.code(),
Some(0),
"control: with stderr open, a startup write into a gone reader ends the session \
with exit 0; stderr: {stderr:?}"
);
assert!(
stderr.starts_with("Watching ") && stderr.ends_with(STOPPED_STDOUT_CLOSED),
"control: the session writes its status lines, the stop line last; stderr: {stderr:?}"
);
let stderr_dir = tempfile::tempdir().unwrap();
let stderr_path = stderr_dir.path().join("watch-stderr");
let mut cmd = mds_bin();
cmd.args(args)
.stdout(Stdio::from(closed_pipe()))
.stderr(Stdio::from(full_file(&stderr_path, LIMIT)));
limit_file_growth(&mut cmd, LIMIT as libc::rlim_t);
let mut failing = ChildGuard(cmd.spawn().unwrap());
let status = wait_bounded(&mut failing, SESSION_END_TIMEOUT, "stderr failing");
assert_eq!(
status.code(),
Some(2),
"a session that stops before it is live exits as a batch run does: a stderr that \
failed other than by a closed pipe lifts its exit code to 2"
);
assert_eq!(
std::fs::read(&stderr_path).unwrap(),
vec![b'#'; LIMIT],
"precondition: every stderr write failed"
);
}
const ENTRY_AND_DIRECTORY: [&[&str]; 2] = [&["watch", "src/a.mds"], &["watch", "src"]];
#[track_caller]
fn one_edit(
base: &Path,
args: &[&str],
edited: &Path,
text: &str,
(before, after): (&str, &str),
) -> String {
let output = base.join("src").join("a.md");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let startup = std::fs::read_to_string(&output).unwrap_or_default();
assert!(
startup.contains(before),
"{args:?}: control: the startup output holds {before:?}; it held {startup:?}"
);
write_atomic(edited, text);
wait_for_tap(&tap, "Recompiled ", TIMEOUT);
let rebuilt = std::fs::read_to_string(&output).unwrap_or_default();
assert!(
rebuilt.contains(after) && !rebuilt.contains(before),
"{args:?}: the rebuild wrote what the edit made; the output held {rebuilt:?}"
);
write_atomic(&base.join("src").join("a.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
tap.finish_text(&mut child)
}
#[track_caller]
fn assert_one_rebuild(args: &[&str], stderr: &str) {
assert_eq!(
count_occurrences(stderr, "Recompiled "),
1,
"{args:?}: one edit, one rebuild; stderr: {stderr}"
);
}
#[test]
fn watch_rebuilds_once_when_a_dependency_behind_a_symlinked_directory_changes() {
for args in ENTRY_AND_DIRECTORY {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::write(base.join(".mdsroot"), "").unwrap();
std::fs::create_dir_all(base.join("src")).unwrap();
std::fs::create_dir_all(base.join("real-lib")).unwrap();
std::fs::write(base.join("real-lib/x.mds"), "X one\n").unwrap();
if !make_symlink(&base.join("real-lib"), &base.join("src").join("lib-link")) {
return;
}
std::fs::write(
base.join("src/a.mds"),
"@import \"./lib-link/x.mds\" as x\n@include x\n",
)
.unwrap();
let edited = base.join("real-lib/x.mds");
let stderr = one_edit(base, args, &edited, "X two\n", ("X one", "X two"));
assert_one_rebuild(args, &stderr);
}
}
#[test]
fn watch_rebuilds_once_when_an_imported_partial_changes() {
for args in ENTRY_AND_DIRECTORY {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::create_dir_all(base.join("src")).unwrap();
std::fs::write(base.join("src/_part.mds"), "P one\n").unwrap();
std::fs::write(
base.join("src/a.mds"),
"@import \"./_part.mds\" as p\n@include p\n",
)
.unwrap();
let edited = base.join("src").join("_part.mds");
let stderr = one_edit(base, args, &edited, "P two\n", ("P one", "P two"));
assert_one_rebuild(args, &stderr);
assert!(
!base.join("src").join("_part.md").exists(),
"{args:?}: a partial has no output of its own"
);
}
}
#[test]
fn watch_rebuilds_once_when_the_vars_file_changes() {
for args in ENTRY_AND_DIRECTORY {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::create_dir_all(base.join("src")).unwrap();
std::fs::write(base.join("src/a.mds"), "Hello {{name}}\n").unwrap();
std::fs::write(base.join("vars.json"), r#"{"name": "one"}"#).unwrap();
let args = [args, &["--vars", "vars.json"][..]].concat();
let edited = base.join("vars.json");
let stderr = one_edit(
base,
&args,
&edited,
r#"{"name": "two"}"#,
("Hello one", "Hello two"),
);
assert_one_rebuild(&args, &stderr);
}
}
#[test]
fn watch_rebuilds_once_when_a_dependency_outside_the_directory_changes() {
for args in ENTRY_AND_DIRECTORY {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::write(base.join(".mdsroot"), "").unwrap();
std::fs::create_dir_all(base.join("src")).unwrap();
std::fs::create_dir_all(base.join("shared")).unwrap();
std::fs::write(base.join("shared/y.mds"), "Y one\n").unwrap();
std::fs::write(
base.join("src/a.mds"),
"@import \"../shared/y.mds\" as y\n@include y\n",
)
.unwrap();
let edited = base.join("shared").join("y.mds");
let stderr = one_edit(base, args, &edited, "Y two\n", ("Y one", "Y two"));
assert_one_rebuild(args, &stderr);
assert!(
!base.join("shared").join("y.md").exists(),
"{args:?}: a dependency outside the directory has no output"
);
}
}
#[test]
fn watch_arms_the_directory_of_a_dependency_a_rebuild_first_imports() {
for args in ENTRY_AND_DIRECTORY {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::write(base.join(".mdsroot"), "").unwrap();
std::fs::create_dir_all(base.join("src")).unwrap();
std::fs::create_dir_all(base.join("shared")).unwrap();
std::fs::write(base.join("shared/y.mds"), "Y one\n").unwrap();
std::fs::write(base.join("src/a.mds"), "A alone\n").unwrap();
let (entry, output) = (
base.join("src").join("a.mds"),
base.join("src").join("a.md"),
);
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&output, "A alone", TIMEOUT),
"{args:?}: control: the startup writes src/a.md; stderr: {}",
tap.text()
);
write_atomic(&entry, "@import \"../shared/y.mds\" as y\n@include y\n");
assert!(
wait_for_file_contains(&output, "Y one", TIMEOUT),
"{args:?}: control: the edit that adds the import rebuilds; stderr: {}",
tap.text()
);
write_atomic(
&entry,
"@import \"../shared/y.mds\" as y\n@include y\nBarrier\n",
);
assert!(
wait_for_file_contains(&output, "Barrier", TIMEOUT),
"{args:?}: control: the barrier edit rebuilds; stderr: {}",
tap.text()
);
write_atomic(&base.join("shared").join("y.mds"), "Y two\n");
assert!(
wait_for_file_contains(&output, "Y two", TIMEOUT),
"{args:?}: an edit to a dependency a rebuild first imported rebuilds its \
importer with native events only; stderr: {}",
tap.text()
);
write_atomic(&entry, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, "Recompiled "),
3,
"{args:?}: three edits that change the output, three rebuilds; stderr: {stderr}"
);
}
}
#[test]
fn watch_arms_the_directory_of_a_dependency_a_refused_rebuild_imports() {
let import = "@import \"../shared/y.mds\" as y\n@include y\n";
let module_refusal = squash(&format!(
"cannot write {}: refusing to replace an MDS module",
Path::new("src").join("a.md").display()
));
let sessions = [
(
"directory mode",
".",
&["watch", "src"][..],
"A alone\n",
"refusing to replace an MDS module",
module_refusal,
),
(
"file mode",
"src",
&["watch", "a.mds", "-o", "a.mds"][..],
"Hello {{name\n",
"mds::syntax",
entry_overwrite_refusal("a.mds"),
),
];
for (mode, cwd, args, startup, reported, refusal) in sessions {
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::write(base.join(".mdsroot"), "").unwrap();
let (src, shared) = (base.join("src"), base.join("shared"));
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&shared).unwrap();
std::fs::write(shared.join("y.mds"), "Y one\n").unwrap();
let entry = src.join("a.mds");
std::fs::write(&entry, startup).unwrap();
std::fs::write(src.join("a.md"), MODULE).unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.join(cwd))
.args(args)
.args(["--debounce", "100", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let refused = |stderr: &str| count_occurrences(&squash(stderr), &refusal);
let refused_after = |n: usize, what: &str| {
let seen = poll_tap_until(&tap, TIMEOUT, |seen| refused(seen) > n);
assert!(
seen.is_ok(),
"{mode}: {what} is refused; stderr: {}",
tap.text()
);
refused(&tap.text())
};
let seen = refused(&wait_for_tap(&tap, reported, TIMEOUT));
write_atomic(&entry, import);
let seen = refused_after(seen, "the edit that adds the import");
let mut barrier = None;
for attempt in 1..=3 {
let text = format!("{import}Barrier {attempt}\n");
write_atomic(&entry, &text);
if poll_tap_until(&tap, TIMEOUT, |now| refused(now) > seen).is_ok() {
barrier = Some(text);
break;
}
}
let barrier = barrier.unwrap_or_else(|| {
panic!(
"{mode}: no save of the barrier edit is refused; stderr: {}",
tap.text()
)
});
let seen = refused(&tap.text());
write_atomic(&shared.join("y.mds"), "Y two\n");
refused_after(
seen,
"with native events only, an edit to the dependency a refused rebuild imported",
);
assert_eq!(
text_of(&src.join("a.md")).as_deref(),
Some(MODULE),
"{mode}: the module is kept; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&entry),
Some(barrier),
"{mode}: the entry is kept; stderr: {}",
tap.text()
);
assert!(
child.0.try_wait().unwrap().is_none(),
"{mode}: watch keeps running after refused rebuilds; stderr: {}",
tap.text()
);
drop(child);
}
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "linux"),
ignore = "only inotify refuses to watch a directory the user cannot read"
)]
#[test]
fn watch_retries_a_dependency_directory_whose_startup_watch_failed() {
use std::os::unix::fs::PermissionsExt;
if unsafe { libc::geteuid() } == 0 {
eprintln!("skipped: running as root, whom no directory permission refuses");
return;
}
let base = tempfile::tempdir().unwrap();
let base = base.path();
std::fs::write(base.join(".mdsroot"), "").unwrap();
std::fs::create_dir_all(base.join("src")).unwrap();
let shared = base.join("shared");
std::fs::create_dir_all(&shared).unwrap();
std::fs::write(shared.join("y.mds"), "Y one\n").unwrap();
let import = "@import \"../shared/y.mds\" as y\n@include y\n";
let (entry, output) = (
base.join("src").join("a.mds"),
base.join("src").join("a.md"),
);
std::fs::write(&entry, import).unwrap();
let refused = format!(
"warning: failed to watch external dep dir {}: ",
shared.canonicalize().unwrap().display()
);
std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o100)).unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(["watch", "src", "--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o755)).unwrap();
wait_for_tap(&tap, &refused, TIMEOUT);
assert!(
wait_for_file_contains(&output, "Y one", TIMEOUT),
"control: the startup compile read the dependency; stderr: {}",
tap.text()
);
write_atomic(&entry, format!("{import}Barrier\n"));
assert!(
wait_for_file_contains(&output, "Barrier", TIMEOUT),
"control: the barrier edit rebuilds; stderr: {}",
tap.text()
);
write_atomic(&shared.join("y.mds"), "Y two\n");
assert!(
wait_for_file_contains(&output, "Y two", TIMEOUT),
"an edit to a dependency whose directory could not be watched at startup, and now \
can, rebuilds its importer with native events only; stderr: {}",
tap.text()
);
write_atomic(&entry, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, &refused),
1,
"the startup's refusal only — the retry arms the directory; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, "Recompiled "),
2,
"two edits that change the output, two rebuilds; stderr: {stderr}"
);
}
const OUT_DIR_SESSIONS: [(&[&str], bool); 4] = [
(&["watch", "src/a.mds", "--out-dir", "out"], false),
(&["watch", "src", "--out-dir", "out"], false),
(&["watch", "src/a.mds"], true),
(&["watch", "src"], true),
];
fn out_dir_session_base(config: bool) -> tempfile::TempDir {
let base = tempfile::tempdir().unwrap();
let src = base.path().join("src");
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("a.mds"), "A one\n").unwrap();
std::fs::write(src.join("b.mds"), "B one\n").unwrap();
if config {
std::fs::write(
base.path().join("mds.json"),
r#"{"build":{"output_dir":"out"}}"#,
)
.unwrap();
}
base
}
fn names_in(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
fn make_real_dir(dir: &Path) {
match std::fs::create_dir(dir) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let kind = std::fs::symlink_metadata(dir)
.unwrap_or_else(|e| panic!("look at {}: {e}", dir.display()))
.file_type();
assert!(
kind.is_dir(),
"{} is already there, and is not a real directory: {kind:?}",
dir.display()
);
}
Err(e) => panic!("create {}: {e}", dir.display()),
}
}
fn out_dir_moved_refusal(shown: &Path) -> String {
squash(&format!(
"mds::io × cannot write {}: the output directory now resolves to a different \
directory; restart mds watch to follow it",
shown.display()
))
}
fn recompiled_below_out(stderr: &str, config: bool, name: &str) -> usize {
let out = if config {
Path::new("src").join("..").join("out")
} else {
Path::new("out").to_path_buf()
};
count_occurrences(
&squash(stderr),
&squash(&format!("Recompiled {} (", out.join(name).display())),
)
}
fn settle_queued_events(tap: &StderrTap, source: &Path, name: &str) {
write_atomic(source, format!("Barrier {{{{__{name}__}}}}\n"));
wait_for_tap(tap, &format!("undefined variable '__{name}__'"), TIMEOUT);
}
#[test]
fn watch_recreates_a_deleted_out_dir_and_writes_its_outputs_again() {
for (args, config) in OUT_DIR_SESSIONS {
let base = out_dir_session_base(config);
let base = base.path();
let (src, out) = (base.join("src"), base.join("out"));
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"{args:?}: control: the startup writes out/a.md; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &src.join("a.mds"), "first_barrier");
std::fs::remove_dir_all(&out).unwrap();
write_atomic(&src.join("a.mds"), "A two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "A two", TIMEOUT),
"{args:?}: an edit after the out-dir was deleted recreates it and writes \
there; stderr: {}",
tap.text()
);
let (saved, text, output) = if args[1] == "src" {
(src.join("b.mds"), "B one\n", out.join("b.md"))
} else {
settle_queued_events(&tap, &src.join("a.mds"), "second_barrier");
std::fs::remove_dir_all(&out).unwrap();
(src.join("a.mds"), "A two\n", out.join("a.md"))
};
write_atomic(&saved, text);
assert!(
wait_for_file_contains(&output, text.trim_end(), TIMEOUT),
"{args:?}: a save of unchanged bytes writes {} into the recreated out-dir; \
stderr: {}",
output.display(),
tap.text()
);
write_atomic(&src.join("a.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
let written = |name| recompiled_below_out(&stderr, config, name);
let expected = if args[1] == "src" { [1, 1] } else { [2, 0] };
assert_eq!(
[written("a.md"), written("b.md")],
expected,
"{args:?}: each output was written once into each directory it was missing \
from; stderr: {stderr}"
);
}
}
#[test]
fn watch_writes_into_a_new_directory_made_in_place_of_the_out_dir() {
for (args, config) in OUT_DIR_SESSIONS {
let base = out_dir_session_base(config);
let base = base.path();
let (src, out, moved) = (base.join("src"), base.join("out"), base.join("out.old"));
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"{args:?}: control: the startup writes out/a.md; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &src.join("a.mds"), "first_barrier");
std::fs::rename(&out, &moved).unwrap();
std::fs::create_dir(&out).unwrap();
let mut rebuilds = 0;
if cfg!(unix) {
write_atomic(&src.join("a.mds"), "A one\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"{args:?}: a save of unchanged bytes writes out/a.md into the new \
directory; stderr: {}",
tap.text()
);
rebuilds += 1;
}
write_atomic(&src.join("a.mds"), "A two\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "A two", TIMEOUT),
"{args:?}: an edit writes out/a.md into the new directory; stderr: {}",
tap.text()
);
rebuilds += 1;
assert_eq!(
std::fs::read_to_string(moved.join("a.md")).unwrap(),
"A one\n",
"{args:?}: the directory moved aside keeps its output"
);
write_atomic(&src.join("a.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
recompiled_below_out(&stderr, config, "a.md"),
rebuilds,
"{args:?}: each rebuild of a.mds wrote out/a.md once; stderr: {stderr}"
);
}
}
#[test]
fn watch_refuses_an_out_dir_link_retargeted_mid_session() {
for args in [
&["watch", "src/x.mds", "--out-dir", "lnk"][..],
&["watch", "src", "--out-dir", "lnk"],
] {
let base = tempfile::tempdir().unwrap();
let base = base.path();
for name in ["src", "a", "b"] {
std::fs::create_dir(base.join(name)).unwrap();
}
let source = base.join("src").join("x.mds");
std::fs::write(&source, "X one\n").unwrap();
let (lnk, a_out, b) = (
base.join("lnk"),
base.join("a").join("x.md"),
base.join("b"),
);
if !make_symlink(Path::new("a"), &lnk) {
return;
}
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&a_out, "X one", TIMEOUT),
"{args:?}: control: the startup writes through the link; stderr: {}",
tap.text()
);
remove_symlink(&lnk);
assert!(make_symlink(Path::new("b"), &lnk), "retarget the link to b");
write_atomic(&source, "X two\n");
let refusal = out_dir_moved_refusal(&Path::new("lnk").join("x.md"));
let refused = poll_tap_until(&tap, TIMEOUT, |text| squash(text).contains(&refusal));
assert!(
refused.is_ok(),
"{args:?}: the write is refused, naming the output as typed; stderr: {refused:?}"
);
assert_eq!(
names_in(&b),
Vec::<String>::new(),
"{args:?}: nothing is written to the link's new target"
);
assert_eq!(
std::fs::read_to_string(&a_out).unwrap(),
"X one\n",
"{args:?}: nor to the directory the session started with"
);
remove_symlink(&lnk);
assert!(
make_symlink(Path::new("a"), &lnk),
"lead the link back to a"
);
write_atomic(&source, "X three\n");
assert!(
wait_for_file_contains(&a_out, "X three", TIMEOUT),
"{args:?}: control: through the link led back, the session writes again; \
stderr: {}",
tap.text()
);
assert_eq!(
names_in(&b),
Vec::<String>::new(),
"{args:?}: b stays empty"
);
drop(child);
}
}
#[test]
fn watch_refuses_an_out_dir_replaced_by_a_symlink() {
for (args, config) in OUT_DIR_SESSIONS {
let base = out_dir_session_base(config);
let base = base.path();
let (source, out, victim) = (
base.join("src").join("a.mds"),
base.join("out"),
base.join("victim"),
);
std::fs::create_dir(&victim).unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("a.md"), "A one", TIMEOUT),
"{args:?}: control: the startup writes out/a.md; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &source, "barrier");
std::fs::remove_dir_all(&out).unwrap();
if !make_symlink(Path::new("victim"), &out) {
return;
}
write_atomic(&source, "A two\n");
let refusal = if config {
let link = Path::new("src").join("..").join("out");
squash(&format!(
"mds::io × cannot write {}: refusing to follow a symlink at {}",
link.join("a.md").display(),
link.display()
))
} else {
out_dir_moved_refusal(&Path::new("out").join("a.md"))
};
let refused = poll_tap_until(&tap, TIMEOUT, |text| squash(text).contains(&refusal));
assert!(
refused.is_ok(),
"{args:?}: the write is refused, naming the path as the user knows it; \
stderr: {refused:?}"
);
settle_queued_events(&tap, &source, "refused_barrier");
assert_eq!(
names_in(&victim),
Vec::<String>::new(),
"{args:?}: nothing is written into the directory the link leads to"
);
remove_symlink(&out);
make_real_dir(&out);
write_atomic(&source, "A three\n");
assert!(
wait_for_file_contains(&out.join("a.md"), "A three", TIMEOUT),
"{args:?}: control: a real directory back in place is written into; stderr: {}",
tap.text()
);
assert_eq!(
names_in(&victim),
Vec::<String>::new(),
"{args:?}: victim stays empty"
);
drop(child);
}
}
const MESSAGES_KIND: &str = "@message user:\nWhat is 3+3?\n@end\n";
const HAND_WRITTEN: &str = "hand-written, not mds output\n";
const USER_EDIT: &str = "the user's own edit\n";
const DELETION_BATCHES: [(&str, &[&str], bool); 2] = [
("a deletion alone", &["--debounce", "0"], false),
(
"a deletion with a --vars edit",
&["--vars", "vars.json", "--debounce", "500"],
true,
),
];
fn lines_starting(stderr: &str, prefix: &str) -> Vec<String> {
let mut lines: Vec<String> = stderr
.lines()
.filter(|line| line.starts_with(prefix))
.map(str::to_owned)
.collect();
lines.sort();
lines
}
fn below(dir: &str, name: &str) -> String {
Path::new(dir).join(name).display().to_string()
}
fn text_of(path: &Path) -> Option<String> {
std::fs::read_to_string(path).ok()
}
fn notes_with(files: &[(&str, &str)]) -> tempfile::TempDir {
let base = tempfile::tempdir().unwrap();
let notes = base.path().join("notes");
std::fs::create_dir(¬es).unwrap();
for (name, text) in files {
std::fs::write(notes.join(name), text).unwrap();
}
std::fs::write(base.path().join("vars.json"), r#"{"name": "one"}"#).unwrap();
base
}
#[test]
fn watch_keeps_the_hand_written_siblings_of_a_deleted_source() {
for (label, extra, edit_vars) in DELETION_BATCHES {
let base = notes_with(&[
("todo.mds", "Buy milk\n"),
("todo.json", HAND_WRITTEN),
("msg.mds", MESSAGES_KIND),
("msg.md", HAND_WRITTEN),
("_p.mds", "Partial\n"),
("_p.md", HAND_WRITTEN),
]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--poll-interval", "0"])
.args(extra)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("todo.md"), "Buy milk", TIMEOUT)
&& wait_for_file_contains(¬es.join("msg.json"), "What is 3+3?", TIMEOUT),
"{label}: control: the startup writes todo.md and msg.json; stderr: {}",
tap.text()
);
for name in ["_p.mds", "msg.mds", "todo.mds"] {
std::fs::remove_file(notes.join(name)).unwrap();
}
if edit_vars {
write_atomic(&base.path().join("vars.json"), r#"{"name": "two"}"#);
}
assert!(
wait_for_file_gone(¬es.join("msg.json"), TIMEOUT)
&& wait_for_file_gone(¬es.join("todo.md"), TIMEOUT),
"{label}: control: the outputs the session wrote are removed; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
for name in ["todo.json", "msg.md", "_p.md"] {
assert_eq!(
text_of(¬es.join(name)).as_deref(),
Some(HAND_WRITTEN),
"{label}: the hand-written {name} survives; stderr: {stderr}"
);
}
assert_eq!(
lines_starting(&stderr, "Kept "),
[
format!(
"Kept {}: not written by this session",
below("notes", "msg.md")
),
format!(
"Kept {}: not written by this session",
below("notes", "todo.json")
),
],
"{label}: one notice for each hand-written sibling, none for the partial's; \
stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[
format!("Removed {} (source deleted)", below("notes", "msg.json")),
format!("Removed {} (source deleted)", below("notes", "todo.md")),
],
"{label}: stderr: {stderr}"
);
}
}
#[test]
fn watch_keeps_an_output_edited_since_the_session_wrote_it() {
for (label, extra, edit_vars) in DELETION_BATCHES {
let base = notes_with(&[("edited.mds", "Edited\n"), ("same.mds", "Same\n")]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--poll-interval", "0"])
.args(extra)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("edited.md"), "Edited", TIMEOUT)
&& wait_for_file_contains(¬es.join("same.md"), "Same", TIMEOUT),
"{label}: control: the startup writes both outputs; stderr: {}",
tap.text()
);
std::fs::write(notes.join("edited.md"), USER_EDIT).unwrap();
for name in ["edited.mds", "same.mds"] {
std::fs::remove_file(notes.join(name)).unwrap();
}
if edit_vars {
write_atomic(&base.path().join("vars.json"), r#"{"name": "two"}"#);
}
assert!(
wait_for_file_gone(¬es.join("same.md"), TIMEOUT),
"{label}: control: the output left as written is removed; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("edited.md")).as_deref(),
Some(USER_EDIT),
"{label}: the output the user edited survives; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!(
"Kept {}: changed since it was written",
below("notes", "edited.md")
)],
"{label}: stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[format!(
"Removed {} (source deleted)",
below("notes", "same.md")
)],
"{label}: stderr: {stderr}"
);
}
}
#[test]
fn watch_keeps_with_a_notice_the_outputs_of_a_deleted_source_it_never_wrote() {
for (label, extra, edit_vars) in DELETION_BATCHES {
let base = notes_with(&[
("draft.mds", "Draft {{missing}}\n"),
("draft.md", HAND_WRITTEN),
("draft.json", HAND_WRITTEN),
("ok.mds", "Ok\n"),
]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--poll-interval", "0"])
.args(extra)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("ok.md"), "Ok", TIMEOUT),
"{label}: control: the startup writes ok.md; stderr: {}",
tap.text()
);
for name in ["draft.mds", "ok.mds"] {
std::fs::remove_file(notes.join(name)).unwrap();
}
if edit_vars {
write_atomic(&base.path().join("vars.json"), r#"{"name": "two"}"#);
}
assert!(
wait_for_file_gone(¬es.join("ok.md"), TIMEOUT),
"{label}: control: the output the session wrote is removed; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
for name in ["draft.md", "draft.json"] {
assert_eq!(
text_of(¬es.join(name)).as_deref(),
Some(HAND_WRITTEN),
"{label}: {name}, which the session never wrote, survives; stderr: {stderr}"
);
}
assert_eq!(
lines_starting(&stderr, "Kept "),
[
format!(
"Kept {}: not written by this session",
below("notes", "draft.json")
),
format!(
"Kept {}: not written by this session",
below("notes", "draft.md")
),
],
"{label}: one notice for each file kept; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[format!(
"Removed {} (source deleted)",
below("notes", "ok.md")
)],
"{label}: stderr: {stderr}"
);
}
}
#[test]
fn watch_removes_the_output_a_deleted_source_was_written_to() {
let base = tempfile::tempdir().unwrap();
let (src, shared, out) = (
base.path().join("src"),
base.path().join("shared"),
base.path().join("out"),
);
std::fs::create_dir(&src).unwrap();
std::fs::create_dir(&shared).unwrap();
std::fs::write(base.path().join(".git"), "").unwrap();
std::fs::write(src.join("a.mds"), "A\n").unwrap();
std::fs::write(src.join("a.b.mds"), "A dot B\n").unwrap();
std::fs::write(src.join("x.mds"), "X\n").unwrap();
std::fs::write(
shared.join("x.mds"),
"@define greet():\nShared\n@end\n\n@export greet\n",
)
.unwrap();
std::fs::write(
src.join("importer.mds"),
"@import \"../shared/x.mds\" as x\n{{x.greet()}}\n",
)
.unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "src", "--out-dir", "out"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
for (name, text) in [
("a.md", "A"),
("a.b.md", "A dot B"),
("x.md", "X"),
("importer.md", "Shared"),
] {
assert!(
wait_for_file_contains(&out.join(name), text, TIMEOUT),
"control: the startup writes out/{name}; stderr: {}",
tap.text()
);
}
std::fs::remove_file(src.join("a.b.mds")).unwrap();
std::fs::remove_file(shared.join("x.mds")).unwrap();
let broken = poll_tap_until(&tap, TIMEOUT, |text| {
text.contains("file not found") || text.contains("No such file")
});
assert!(
broken.is_ok(),
"control: the importer recompiles; stderr: {broken:?}"
);
write_atomic(&src.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(&out.join("a.md")).as_deref(),
Some("A\n"),
"out/a.md, written for a.mds, survives the deletion of a.b.mds; stderr: {stderr}"
);
assert_eq!(
text_of(&out.join("x.md")).as_deref(),
Some("X\n"),
"out/x.md, written for src/x.mds, survives the deletion of shared/x.mds; \
stderr: {stderr}"
);
assert!(
!out.join("a.b.md").exists(),
"out/a.b.md, written for a.b.mds, is removed; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[format!(
"Removed {} (source deleted)",
below("out", "a.b.md")
)],
"stderr: {stderr}"
);
}
#[test]
fn watch_removes_the_old_output_of_a_changed_kind_only_when_it_wrote_it() {
let base = tempfile::tempdir().unwrap();
let (src, out) = (base.path().join("src"), base.path().join("out"));
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("a.mds"), "A\n").unwrap();
std::fs::write(src.join("a.b.mds"), "A dot B\n").unwrap();
std::fs::write(src.join("c.mds"), "C\n").unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "src", "--out-dir", "out"])
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
for (name, text) in [("a.md", "A"), ("a.b.md", "A dot B"), ("c.md", "C")] {
assert!(
wait_for_file_contains(&out.join(name), text, TIMEOUT),
"control: the startup writes out/{name}; stderr: {}",
tap.text()
);
}
std::fs::write(out.join("c.md"), USER_EDIT).unwrap();
for name in ["a.b", "c"] {
write_atomic(&src.join(format!("{name}.mds")), MESSAGES_KIND);
assert!(
wait_for_file_contains(&out.join(format!("{name}.json")), "What is 3+3?", TIMEOUT),
"control: {name}.mds edited into messages writes out/{name}.json; stderr: {}",
tap.text()
);
}
write_atomic(&src.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(&out.join("a.md")).as_deref(),
Some("A\n"),
"out/a.md, written for a.mds, survives a.b.mds's change of kind; stderr: {stderr}"
);
assert!(
!out.join("a.b.md").exists(),
"out/a.b.md, written and left as it was, is removed; stderr: {stderr}"
);
assert_eq!(
text_of(&out.join("c.md")).as_deref(),
Some(USER_EDIT),
"out/c.md, which the user edited, survives; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!(
"Kept {}: changed since it was written",
below("out", "c.md")
)],
"stderr: {stderr}"
);
}
#[test]
fn watch_writes_a_file_whose_kind_changed_to_that_kinds_output() {
let session = |args: &[&str]| {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("chat.mds"), "Hello\n").unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args(["watch", "chat.mds"])
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
(dir, child, tap)
};
let (dir, mut child, tap) = session(&[]);
let (src, md, json) = (
dir.path().join("chat.mds"),
dir.path().join("chat.md"),
dir.path().join("chat.json"),
);
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT),
"control: the startup writes chat.md; stderr: {}",
tap.text()
);
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"a template edited into messages writes chat.json; chat.md holds {:?}; stderr: {}",
text_of(&md),
tap.text()
);
assert!(
wait_for_file_gone(&md, TIMEOUT),
"chat.md, written and left as it was, is removed; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello again\n");
assert!(
wait_for_file_contains(&md, "Hello again", TIMEOUT) && wait_for_file_gone(&json, TIMEOUT),
"edited back into Markdown, it writes chat.md and removes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
let shown = |name: &str| Path::new(".").join(name).display().to_string();
let recompiled =
|name: &str| lines_starting(&stderr, &format!("Recompiled {} (", shown(name))).len();
assert_eq!(
(recompiled("chat.json"), recompiled("chat.md")),
(1, 1),
"each rebuild names the output of its own kind; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
Vec::<String>::new(),
"stderr: {stderr}"
);
let (dir, mut child, tap) = session(&[]);
let (src, md) = (dir.path().join("chat.mds"), dir.path().join("chat.md"));
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT),
"control: the startup writes chat.md; stderr: {}",
tap.text()
);
std::fs::write(&md, USER_EDIT).unwrap();
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&dir.path().join("chat.json"), "What is 3+3?", TIMEOUT),
"a template edited into messages writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(&md).as_deref(),
Some(USER_EDIT),
"chat.md, which the user edited, survives; stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!(
"Kept {}: changed since it was written",
shown("chat.md")
)],
"stderr: {stderr}"
);
let (dir, mut child, tap) = session(&["-o", "out.md"]);
let named = dir.path().join("out.md");
assert!(
wait_for_file_contains(&named, "Hello", TIMEOUT),
"control: the startup writes out.md; stderr: {}",
tap.text()
);
write_atomic(&dir.path().join("chat.mds"), MESSAGES_KIND);
assert!(
wait_for_file_contains(&named, "What is 3+3?", TIMEOUT),
"control: -o out.md takes the messages; stderr: {}",
tap.text()
);
write_atomic(&dir.path().join("chat.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
for name in ["chat.json", "chat.md", "out.json"] {
assert!(
!dir.path().join(name).exists(),
"control: -o is never routed by the kind, so {name} is not written; \
stderr: {stderr}"
);
}
assert_eq!(
lines_starting(&stderr, "Kept "),
Vec::<String>::new(),
"control: stderr: {stderr}"
);
}
#[test]
fn watch_quiet_keeps_files_without_a_notice() {
let base = notes_with(&[("todo.mds", "Buy milk\n"), ("todo.json", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args([
"watch",
"notes",
"-q",
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("todo.md"), "Buy milk", TIMEOUT),
"control: the startup writes todo.md; stderr: {}",
tap.text()
);
std::fs::remove_file(notes.join("todo.mds")).unwrap();
assert!(
wait_for_file_gone(¬es.join("todo.md"), TIMEOUT),
"control: the output the session wrote is removed; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("todo.json")).as_deref(),
Some(HAND_WRITTEN),
"the hand-written todo.json survives; stderr: {stderr}"
);
assert!(
!stderr.contains("Kept ") && !stderr.contains("Removed "),
"--quiet prints neither; stderr: {stderr}"
);
let dir = tempfile::tempdir().unwrap();
let (src, md) = (dir.path().join("chat.mds"), dir.path().join("chat.md"));
std::fs::write(&src, "Hello\n").unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args([
"watch",
"chat.mds",
"-q",
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT),
"control: the startup writes chat.md; stderr: {}",
tap.text()
);
std::fs::write(&md, USER_EDIT).unwrap();
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&dir.path().join("chat.json"), "What is 3+3?", TIMEOUT),
"control: a template edited into messages writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(&md).as_deref(),
Some(USER_EDIT),
"chat.md, which the user edited, survives; stderr: {stderr}"
);
assert!(
!stderr.contains("Kept "),
"--quiet prints no notice; stderr: {stderr}"
);
}
#[test]
fn watch_treats_a_source_unlinked_and_created_again_as_an_edit() {
let base = notes_with(&[("todo.mds", "Buy milk\n"), ("todo.json", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args([
"watch",
"notes",
"--debounce",
"300",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("todo.md"), "Buy milk", TIMEOUT),
"control: the startup writes todo.md; stderr: {}",
tap.text()
);
std::fs::remove_file(notes.join("todo.mds")).unwrap();
write_atomic(¬es.join("todo.mds"), "Buy bread\n");
assert!(
wait_for_file_contains(¬es.join("todo.md"), "Buy bread", TIMEOUT),
"control: the source created again is rebuilt; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("todo.json")).as_deref(),
Some(HAND_WRITTEN),
"the hand-written todo.json survives; stderr: {stderr}"
);
assert_eq!(
(
lines_starting(&stderr, "Removed "),
lines_starting(&stderr, "Kept ")
),
(Vec::new(), Vec::new()),
"nothing is removed and no notice printed; stderr: {stderr}"
);
assert_eq!(
lines_starting(
&stderr,
&format!("Recompiled {} (", below("notes", "todo.md"))
)
.len(),
1,
"control: the edit is one rebuild; stderr: {stderr}"
);
}
const OTHER_MESSAGES: &str = "@message user:\nWhat is 4+4?\n@end\n";
const CHAT_SESSIONS: [(&str, &str, &[&str], &str); 2] = [
("file mode", "notes", &["watch", "chat.mds"], "."),
("directory mode", "", &["watch", "notes"], "notes"),
];
#[test]
fn watch_never_writes_over_a_file_it_did_not_write_when_the_kind_changes() {
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[("chat.mds", MESSAGES_KIND), ("chat.md", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let (src, md, json) = (
notes.join("chat.mds"),
notes.join("chat.md"),
notes.join("chat.json"),
);
let shown_md = below(shown_dir, "chat.md");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"{mode}: control: the startup writes chat.json; stderr: {}",
tap.text()
);
let startup_json = text_of(&json);
write_atomic(&src, "Hello\n");
let seen = poll_tap_until(&tap, TIMEOUT, |seen| {
seen.contains(&format!("Recompiled {shown_md} ("))
|| seen.contains(&format!("Kept {shown_md}:"))
});
assert!(
seen.is_ok(),
"{mode}: the edit into Markdown reported nothing; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some(HAND_WRITTEN),
"{mode}: chat.md, which the session did not write, is not overwritten; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&json),
startup_json,
"{mode}: chat.json, the old kind's output, is kept as it was; stderr: {}",
tap.text()
);
write_atomic(&src, OTHER_MESSAGES);
assert!(
wait_for_file_contains(&json, "What is 4+4?", TIMEOUT),
"{mode}: edited back into messages, it writes chat.json; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some(HAND_WRITTEN),
"{mode}: chat.md is still untouched; stderr: {}",
tap.text()
);
std::fs::remove_file(&md).unwrap();
write_atomic(&src, "Hello\n");
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT) && wait_for_file_gone(&json, TIMEOUT),
"{mode}: control: with chat.md gone, the next save writes it and removes \
chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!(
"Kept {shown_md}: not written by this session; not overwritten"
)],
"{mode}: one notice; stderr: {stderr}"
);
let recompiled = |name: &str| {
lines_starting(&stderr, &format!("Recompiled {} (", below(shown_dir, name))).len()
};
assert_eq!(
(recompiled("chat.json"), recompiled("chat.md")),
(1, 1),
"{mode}: one rebuild of each kind is written; stderr: {stderr}"
);
}
}
#[cfg(debug_assertions)]
const READ_PAUSE: &str = "MDS_TEST_PAUSE_AFTER_READ";
#[cfg(debug_assertions)]
#[test]
fn watch_file_vars_duplicate_warning_skips_a_kept_rebuild_that_tells_nothing() {
let base = notes_with(&[("chat.mds", MESSAGES_KIND), ("chat.md", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let (src, vars) = (notes.join("chat.mds"), base.path().join("vars.json"));
std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();
let warning = dup_vars_file_warning("x", &vars);
let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(¬es)
.args(["watch", "chat.mds", "--vars"])
.arg(&vars)
.args(["--debounce", "0", "--poll-interval", "0"])
.env(READ_PAUSE, &go)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("chat.json"), "What is 3+3?", TIMEOUT),
"control: the startup writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello\n");
wait_paused(&paused, &mut child, &tap, "the change of kind");
std::fs::write(&go, "").unwrap();
let kept = format!(
"Kept {}: not written by this session; not overwritten",
below(".", "chat.md")
);
wait_for_tap(&tap, &kept, TIMEOUT);
wait_for_tap_count(&tap, &warning, 2, TIMEOUT);
std::fs::remove_file(&paused).unwrap();
std::fs::remove_file(&go).unwrap();
write_atomic(&src, "Hello\n");
wait_paused(&paused, &mut child, &tap, "the rebuild of the same");
std::fs::write(&go, "").unwrap();
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("chat.md")).as_deref(),
Some(HAND_WRITTEN),
"control: chat.md, which the session did not write, is not overwritten; \
stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
[kept],
"control: the notice is told once; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, &warning),
2,
"the warning is printed at startup and with the notice — not again by the \
rebuild that tells nothing; stderr: {stderr}"
);
}
#[test]
fn watch_file_vars_duplicate_warning_comes_with_a_reported_write_failure() {
let dir = tempfile::tempdir().unwrap();
let (src, out, vars) = (
dir.path().join("t.mds"),
dir.path().join("t.md"),
dir.path().join("vars.json"),
);
std::fs::write(&src, "version 1\n").unwrap();
std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();
let warning = dup_vars_file_warning("x", &vars);
let (mut child, tap) = spawn_ready(
mds_bin()
.args(["watch", src.to_str().unwrap(), "--vars"])
.arg(&vars)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
wait_for_tap(&tap, "Compiled to", TIMEOUT);
std::fs::remove_file(&out).unwrap();
std::fs::create_dir(&out).unwrap();
std::fs::write(out.join("keep"), "a directory where the output was\n").unwrap();
write_atomic(&src, "version 2\n");
wait_for_tap(&tap, "mds::io", TIMEOUT);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
let reports = count_occurrences(&stderr, "mds::io");
assert!(
reports > 0 && !stderr.contains("Recompiled"),
"control: the failed write is reported, and never announced; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, &warning),
1 + reports,
"the warning is printed at startup and with each failed write's report; \
stderr: {stderr}"
);
}
fn a_dir_session_with_duplicate_vars(base: &Path) -> (ChildGuard, StderrTap, String) {
let vars = base.join("vars.json");
std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(base)
.args(["watch", "notes", "--vars"])
.arg(&vars)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
(child, tap, dup_vars_file_warning("x", &vars))
}
#[test]
fn watch_dir_vars_duplicate_warning_comes_once_before_a_batch_s_recompiled_lines() {
let base = notes_with(&[("a.mds", "A {{x}}\n"), ("b.mds", "B {{x}}\n")]);
let notes = base.path().join("notes");
let (mut child, tap, warning) = a_dir_session_with_duplicate_vars(base.path());
let written = |name: &str, text: &str| wait_for_file_contains(¬es.join(name), text, TIMEOUT);
assert!(
written("a.md", "A 2") && written("b.md", "B 2"),
"control: the startup writes both outputs; stderr: {}",
tap.text()
);
settle_queued_events(&tap, ¬es.join("barrier.mds"), "settle");
write_atomic(&base.path().join("vars.json"), r#"{"x": 3, "x": 4}"#);
assert!(
written("a.md", "A 4") && written("b.md", "B 4"),
"control: the vars edit rebuilds both sources; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
count_occurrences(&stderr, "Recompiled "),
2,
"control: one batch rebuilds both sources; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, &warning),
2,
"the warning is printed at startup and once by the batch; stderr: {stderr}"
);
let first_recompiled = stderr.find("Recompiled ").unwrap();
assert_eq!(
count_occurrences(&stderr[..first_recompiled], &warning),
2,
"the batch's warning comes before its first `Recompiled` line; stderr: {stderr}"
);
}
#[cfg(debug_assertions)]
#[test]
fn watch_dir_vars_duplicate_warning_skips_a_kept_rebuild_that_tells_nothing() {
let base = notes_with(&[("chat.mds", MESSAGES_KIND), ("chat.md", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let src = notes.join("chat.mds");
let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));
let vars = base.path().join("vars.json");
std::fs::write(&vars, r#"{"x": 1, "x": 2}"#).unwrap();
let warning = dup_vars_file_warning("x", &vars);
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--vars"])
.arg(&vars)
.args(["--debounce", "0", "--poll-interval", "0"])
.env(BATCH_PAUSE, &go)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("chat.json"), "What is 3+3?", TIMEOUT),
"control: the startup writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello\n");
wait_paused(&paused, &mut child, &tap, "the change of kind");
std::fs::write(&go, "").unwrap();
let kept = format!(
"Kept {}: not written by this session; not overwritten",
below("notes", "chat.md")
);
wait_for_tap(&tap, &kept, TIMEOUT);
wait_for_tap_count(&tap, &warning, 2, TIMEOUT);
std::fs::remove_file(&paused).unwrap();
std::fs::remove_file(&go).unwrap();
write_atomic(&src, "Hello\n");
wait_paused(&paused, &mut child, &tap, "the rebuild of the same");
std::fs::write(&go, "").unwrap();
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("chat.md")).as_deref(),
Some(HAND_WRITTEN),
"control: chat.md, which the session did not write, is not overwritten; \
stderr: {stderr}"
);
let notice = stderr.find(&kept).unwrap();
assert_eq!(
lines_starting(&stderr, "Kept "),
[kept],
"control: the notice is told once; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, &warning),
2,
"the warning is printed at startup and with the notice — not again by the \
rebuild that tells nothing; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr[notice..], &warning),
1,
"the rebuild's warning comes after its notice; stderr: {stderr}"
);
}
#[test]
fn watch_dir_vars_duplicate_warning_comes_with_a_reported_write_failure() {
let base = notes_with(&[("t.mds", "version 1\n")]);
let notes = base.path().join("notes");
let (src, out) = (notes.join("t.mds"), notes.join("t.md"));
let (mut child, tap, warning) = a_dir_session_with_duplicate_vars(base.path());
assert!(
wait_for_file_contains(&out, "version 1", TIMEOUT),
"control: the startup writes t.md; stderr: {}",
tap.text()
);
std::fs::remove_file(&out).unwrap();
std::fs::create_dir(&out).unwrap();
std::fs::write(out.join("keep"), "a directory where the output was\n").unwrap();
write_atomic(&src, "version 2\n");
wait_for_tap(&tap, "mds::io", TIMEOUT);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
let reports = count_occurrences(&stderr, "mds::io");
assert!(
reports > 0 && !stderr.contains("Recompiled"),
"control: the failed write is reported, and never announced; stderr: {stderr}"
);
assert_eq!(
count_occurrences(&stderr, &warning),
1 + reports,
"the warning is printed at startup and with each failed write's report; \
stderr: {stderr}"
);
let first_report = stderr.find("mds::io").unwrap();
assert_eq!(
count_occurrences(&stderr[..first_report], &warning),
2,
"the rebuild's warning comes before its report; stderr: {stderr}"
);
}
#[test]
fn watch_quiet_keeps_a_file_a_change_of_kind_would_overwrite_without_a_notice() {
let base = notes_with(&[
("chat.mds", MESSAGES_KIND),
("chat.md", HAND_WRITTEN),
("talk.mds", MESSAGES_KIND),
]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args([
"watch",
"notes",
"-q",
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
for name in ["chat.json", "talk.json"] {
assert!(
wait_for_file_contains(¬es.join(name), "What is 3+3?", TIMEOUT),
"control: the startup writes {name}; stderr: {}",
tap.text()
);
}
let startup_json = text_of(¬es.join("chat.json"));
write_atomic(¬es.join("chat.mds"), "Hello\n");
write_atomic(¬es.join("talk.mds"), "Hello\n");
assert!(
wait_for_file_contains(¬es.join("talk.md"), "Hello", TIMEOUT)
&& wait_for_file_gone(¬es.join("talk.json"), TIMEOUT),
"control: talk.md is written and talk.json removed; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("chat.md")).as_deref(),
Some(HAND_WRITTEN),
"the hand-written chat.md is not overwritten; stderr: {stderr}"
);
assert_eq!(
text_of(¬es.join("chat.json")),
startup_json,
"chat.json, the old kind's output, is kept as it was; stderr: {stderr}"
);
assert!(
!stderr.contains("Kept "),
"--quiet prints no notice; stderr: {stderr}"
);
}
#[test]
fn watch_removes_an_empty_startup_output_when_the_kind_changes() {
let dir = tempfile::tempdir().unwrap();
let (src, md, json) = (
dir.path().join("chat.mds"),
dir.path().join("chat.md"),
dir.path().join("chat.json"),
);
std::fs::write(&src, "").unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(dir.path())
.args([
"watch",
"chat.mds",
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
assert_eq!(
text_of(&md).as_deref(),
Some(""),
"control: the startup writes an empty chat.md; stderr: {}",
tap.text()
);
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"control: edited into messages, it writes chat.json; stderr: {}",
tap.text()
);
assert!(
wait_for_file_gone(&md, TIMEOUT),
"the empty chat.md the startup wrote is removed; stderr: {}",
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
lines_starting(&stderr, "Kept "),
Vec::<String>::new(),
"stderr: {stderr}"
);
}
#[test]
fn watch_tells_a_kept_file_again_once_its_source_has_changed_in_between() {
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[("chat.mds", MESSAGES_KIND), ("chat.md", HAND_WRITTEN)]);
let notes = base.path().join("notes");
let (src, md, json) = (
notes.join("chat.mds"),
notes.join("chat.md"),
notes.join("chat.json"),
);
let notice = format!(
"Kept {}: not written by this session; not overwritten",
below(shown_dir, "chat.md")
);
let notices = |seen: &str| seen.lines().filter(|line| *line == notice).count();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"{mode}: control: the startup writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello\n");
assert!(
poll_tap_until(&tap, TIMEOUT, |seen| notices(seen) == 1).is_ok(),
"{mode}: control: the first edit into Markdown is told; stderr: {}",
tap.text()
);
write_atomic(&src, MESSAGES_KIND);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
write_atomic(&src, "Hello\n");
assert!(
poll_tap_until(&tap, TIMEOUT, |seen| notices(seen) == 2).is_ok(),
"{mode}: the same edit into Markdown, made again, is told again; stderr: {}",
tap.text()
);
write_atomic(&src, OTHER_MESSAGES);
wait_for_tap(
&tap,
&format!("Recompiled {} (", below(shown_dir, "chat.json")),
TIMEOUT,
);
let stderr = tap.finish_text(&mut child);
assert_eq!(
notices(&stderr),
2,
"{mode}: one notice for each save that kept chat.md; stderr: {stderr}"
);
assert_eq!(
text_of(&md).as_deref(),
Some(HAND_WRITTEN),
"{mode}: chat.md is kept throughout; stderr: {stderr}"
);
}
}
#[test]
fn watch_never_removes_the_output_of_a_source_that_is_still_there() {
let base = notes_with(&[("a.mds", "Plain A\n"), ("a.b.mds", "Plain B\n")]);
let notes = base.path().join("notes");
let (md, shown_md) = (notes.join("a.md"), below("notes", "a.md"));
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&md, "Plain", TIMEOUT),
"control: the startup writes notes/a.md; stderr: {}",
tap.text()
);
write_atomic(¬es.join("a.b.mds"), "Second B\n");
assert!(
wait_for_file_contains(&md, "Second B", TIMEOUT),
"control: a.b.mds's edit writes notes/a.md; stderr: {}",
tap.text()
);
std::fs::remove_file(notes.join("a.mds")).unwrap();
let told = |seen: &str| {
seen.lines().any(|line| {
line.starts_with(&format!("Kept {shown_md}:"))
|| line.starts_with(&format!("Removed {shown_md} "))
})
};
assert!(
poll_tap_until(&tap, TIMEOUT, told).is_ok(),
"the deletion of a.mds reported nothing on notes/a.md; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some("Second B\n"),
"notes/a.md, written for a.b.mds, survives the deletion of a.mds; stderr: {}",
tap.text()
);
std::fs::remove_file(notes.join("a.b.mds")).unwrap();
assert!(
wait_for_file_gone(&md, TIMEOUT),
"control: deleting a.b.mds removes notes/a.md; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!("Kept {shown_md}: not written by this source")],
"stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[format!("Removed {shown_md} (source deleted)")],
"one removal, for a.b.mds; stderr: {stderr}"
);
}
#[test]
fn watch_never_replaces_the_output_of_another_source_when_the_kind_changes() {
let base = notes_with(&[("a.mds", MESSAGES_KIND), ("a.b.mds", "Plain B\n")]);
let notes = base.path().join("notes");
let (json, md) = (notes.join("a.json"), notes.join("a.md"));
let shown_json = below("notes", "a.json");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT)
&& wait_for_file_contains(&md, "Plain B", TIMEOUT),
"control: the startup writes notes/a.json and notes/a.md; stderr: {}",
tap.text()
);
let startup_json = text_of(&json);
write_atomic(¬es.join("a.b.mds"), OTHER_MESSAGES);
let seen = poll_tap_until(&tap, TIMEOUT, |seen| {
seen.contains(&format!("Recompiled {shown_json} ("))
|| seen.contains(&format!("Kept {shown_json}:"))
});
assert!(
seen.is_ok(),
"the edit of a.b.mds into messages reported nothing; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&json),
startup_json,
"notes/a.json, written for a.mds, is not overwritten; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some("Plain B\n"),
"notes/a.md, a.b.mds's old output, is kept as it was; stderr: {}",
tap.text()
);
std::fs::remove_file(&json).unwrap();
write_atomic(¬es.join("a.b.mds"), OTHER_MESSAGES);
assert!(
wait_for_file_contains(&json, "What is 4+4?", TIMEOUT) && wait_for_file_gone(&md, TIMEOUT),
"control: with a.json gone, a.b.mds writes it and removes a.md; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!(
"Kept {shown_json}: not written by this source; not overwritten"
)],
"one notice; stderr: {stderr}"
);
}
#[test]
fn watch_names_a_file_it_wrote_then_the_user_changed_as_changed() {
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[("chat.mds", "Hello\n")]);
let notes = base.path().join("notes");
let (src, md, json) = (
notes.join("chat.mds"),
notes.join("chat.md"),
notes.join("chat.json"),
);
let shown_md = below(shown_dir, "chat.md");
let kept = |seen: &str| {
seen.lines()
.filter(|line| line.starts_with(&format!("Kept {shown_md}:")))
.count()
};
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT),
"{mode}: control: the startup writes chat.md; stderr: {}",
tap.text()
);
std::fs::write(&md, USER_EDIT).unwrap();
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"{mode}: control: edited into messages, it writes chat.json; stderr: {}",
tap.text()
);
write_atomic(&src, "Hello\n");
assert!(
poll_tap_until(&tap, TIMEOUT, |seen| {
kept(seen) >= 2 || seen.contains(&format!("Recompiled {shown_md} ("))
})
.is_ok(),
"{mode}: the edit back into Markdown reported nothing on chat.md; stderr: {}",
tap.text()
);
let directory_mode = shown_dir == "notes";
if directory_mode {
std::fs::remove_file(&src).unwrap();
assert!(
wait_for_file_gone(&json, TIMEOUT),
"{mode}: control: deleting chat.mds removes chat.json; stderr: {}",
tap.text()
);
}
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(&md).as_deref(),
Some(USER_EDIT),
"{mode}: chat.md keeps the user's edit; stderr: {stderr}"
);
let changed = format!("Kept {shown_md}: changed since it was written");
let mut expected = vec![changed.clone(), format!("{changed}; not overwritten")];
if directory_mode {
expected.push(changed);
}
expected.sort();
assert_eq!(
lines_starting(&stderr, "Kept "),
expected,
"{mode}: stderr: {stderr}"
);
}
}
#[test]
fn watch_replaces_its_own_file_once_the_user_restores_it_when_the_kind_changes() {
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[("chat.mds", "Hello\n")]);
let notes = base.path().join("notes");
let (src, md, json) = (
notes.join("chat.mds"),
notes.join("chat.md"),
notes.join("chat.json"),
);
let shown_md = below(shown_dir, "chat.md");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&md, "Hello", TIMEOUT),
"{mode}: control: the startup writes chat.md; stderr: {}",
tap.text()
);
let written = std::fs::read(&md).unwrap();
std::fs::write(&md, USER_EDIT).unwrap();
write_atomic(&src, MESSAGES_KIND);
assert!(
wait_for_file_contains(&json, "What is 3+3?", TIMEOUT),
"{mode}: control: edited into messages, it writes chat.json; stderr: {}",
tap.text()
);
wait_for_tap(
&tap,
&format!("Kept {shown_md}: changed since it was written"),
TIMEOUT,
);
std::fs::write(&md, &written).unwrap();
write_atomic(&src, "Hello again\n");
assert!(
wait_for_file_contains(&md, "Hello again", TIMEOUT)
&& wait_for_file_gone(&json, TIMEOUT),
"{mode}: chat.md, restored to what the session wrote, is replaced and chat.json \
removed; chat.md holds {:?}; stderr: {}",
text_of(&md),
tap.text()
);
write_atomic(&src, ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
lines_starting(&stderr, "Kept "),
[format!("Kept {shown_md}: changed since it was written")],
"{mode}: stderr: {stderr}"
);
}
}
#[cfg(unix)]
const OUT_DIR_PAGE_SESSIONS: [(&str, &[&str]); 2] = [
("file mode", &["watch", "src/page.mds", "--out-dir", "out"]),
("directory mode", &["watch", "src", "--out-dir", "out"]),
];
#[cfg(unix)]
#[test]
fn watch_tells_an_old_kind_output_in_a_remade_out_dir_is_kept() {
for (mode, args) in OUT_DIR_PAGE_SESSIONS {
for remade in [true, false] {
let base = tempfile::tempdir().unwrap();
let (src, out) = (base.path().join("src"), base.path().join("out"));
std::fs::create_dir(&src).unwrap();
std::fs::write(src.join("page.mds"), "Hello\n").unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&out.join("page.md"), "Hello", TIMEOUT),
"{mode}: control: the startup writes out/page.md; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &src.join("page.mds"), "barrier");
if remade {
std::fs::rename(&out, base.path().join("out.old")).unwrap();
std::fs::create_dir(&out).unwrap();
std::fs::write(out.join("page.md"), HAND_WRITTEN).unwrap();
}
write_atomic(&src.join("page.mds"), MESSAGES_KIND);
assert!(
wait_for_file_contains(&out.join("page.json"), "What is 3+3?", TIMEOUT),
"{mode}, remade {remade}: edited into messages, it writes out/page.json; \
stderr: {}",
tap.text()
);
if !remade {
assert!(
wait_for_file_gone(&out.join("page.md"), TIMEOUT),
"{mode}: control: out/page.md, written and left as it was, is removed; \
stderr: {}",
tap.text()
);
}
write_atomic(&src.join("page.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
let expected = if remade {
assert_eq!(
text_of(&out.join("page.md")).as_deref(),
Some(HAND_WRITTEN),
"{mode}: the hand-written out/page.md is kept; stderr: {stderr}"
);
vec![format!(
"Kept {}: not written by this session",
below("out", "page.md")
)]
} else {
Vec::new()
};
assert_eq!(
lines_starting(&stderr, "Kept "),
expected,
"{mode}, remade {remade}: stderr: {stderr}"
);
}
}
}
#[test]
fn watch_quiet_keeps_the_outputs_of_other_sources_and_changed_files_without_a_notice() {
let base = notes_with(&[
("a.mds", MESSAGES_KIND),
("a.b.mds", "Plain B\n"),
("c.mds", "Plain C\n"),
("c.b.mds", "Plain CB\n"),
("chat.mds", "Hello\n"),
("y.mds", "Plain Y\n"),
]);
let notes = base.path().join("notes");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args([
"watch",
"notes",
"-q",
"--debounce",
"0",
"--poll-interval",
"0",
])
.stdout(Stdio::null()),
);
for (name, text) in [
("a.json", "What is 3+3?"),
("a.md", "Plain B"),
("c.md", "Plain C"),
("chat.md", "Hello"),
("y.md", "Plain Y"),
] {
assert!(
wait_for_file_contains(¬es.join(name), text, TIMEOUT),
"control: the startup writes {name}; stderr: {}",
tap.text()
);
}
let startup_json = text_of(¬es.join("a.json"));
write_atomic(¬es.join("c.b.mds"), "Second CB\n");
assert!(
wait_for_file_contains(¬es.join("c.md"), "Second CB", TIMEOUT),
"control: c.b.mds's edit writes c.md; stderr: {}",
tap.text()
);
std::fs::write(notes.join("chat.md"), USER_EDIT).unwrap();
write_atomic(¬es.join("chat.mds"), MESSAGES_KIND);
assert!(
wait_for_file_contains(¬es.join("chat.json"), "What is 3+3?", TIMEOUT),
"control: chat.mds edited into messages writes chat.json; stderr: {}",
tap.text()
);
write_atomic(¬es.join("chat.mds"), "Hello\n");
write_atomic(¬es.join("a.b.mds"), OTHER_MESSAGES);
std::fs::remove_file(notes.join("c.mds")).unwrap();
std::fs::remove_file(notes.join("y.mds")).unwrap();
assert!(
wait_for_file_gone(¬es.join("y.md"), TIMEOUT),
"control: deleting y.mds removes y.md; stderr: {}",
tap.text()
);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert_eq!(
text_of(¬es.join("a.json")),
startup_json,
"a.json, written for a.mds, is not overwritten; stderr: {stderr}"
);
for (name, text) in [
("a.md", "Plain B\n"),
("c.md", "Second CB\n"),
("chat.md", USER_EDIT),
] {
assert_eq!(
text_of(¬es.join(name)).as_deref(),
Some(text),
"{name} is kept; stderr: {stderr}"
);
}
assert!(
!stderr.contains("Kept "),
"--quiet prints no notice; stderr: {stderr}"
);
}
#[test]
fn watch_reports_a_dangling_symlink_at_a_deleted_source_s_output() {
let base = notes_with(&[("x.mds", "Plain X\n"), ("y.mds", "Plain Y\n")]);
let notes = base.path().join("notes");
let target = base.path().join("target.txt");
std::fs::write(&target, HAND_WRITTEN).unwrap();
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
for (name, text) in [("x.md", "Plain X"), ("y.md", "Plain Y")] {
assert!(
wait_for_file_contains(¬es.join(name), text, TIMEOUT),
"control: the startup writes notes/{name}; stderr: {}",
tap.text()
);
}
for (name, to) in [
("x.md", base.path().join("nowhere")),
("y.md", target.clone()),
] {
std::fs::remove_file(notes.join(name)).unwrap();
if !make_symlink(&to, ¬es.join(name)) {
return;
}
}
for name in ["x.mds", "y.mds"] {
std::fs::remove_file(notes.join(name)).unwrap();
}
let warning = |name: &str| {
format!(
"warning: could not remove {}: refusing to remove a symlink",
below("notes", name)
)
};
wait_for_tap(&tap, &warning("y.md"), TIMEOUT);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
let stderr = tap.finish_text(&mut child);
assert!(
stderr.contains(&warning("x.md")),
"the dangling link at notes/x.md is told as a live one is; stderr: {stderr}"
);
for name in ["x.md", "y.md"] {
assert!(
std::fs::symlink_metadata(notes.join(name)).is_ok_and(|meta| meta.is_symlink()),
"the link at notes/{name} is left; stderr: {stderr}"
);
}
assert_eq!(
text_of(&target).as_deref(),
Some(HAND_WRITTEN),
"the live link's target is left as it was; stderr: {stderr}"
);
}
#[cfg(debug_assertions)]
const BATCH_PAUSE: &str = "MDS_TEST_PAUSE_AFTER_BATCH_SPLIT";
#[cfg(debug_assertions)]
#[track_caller]
fn wait_paused(paused: &Path, child: &mut ChildGuard, tap: &StderrTap, label: &str) {
let deadline = Instant::now() + TIMEOUT;
while !paused.exists() {
if let Some(status) = child.0.try_wait().unwrap() {
panic!(
"{label}: setup: the session ended ({status}) before a batch paused; \
stderr: {}",
tap.text()
);
}
assert!(
Instant::now() < deadline,
"{label}: setup: no batch paused; stderr: {}",
tap.text()
);
std::thread::sleep(Duration::from_millis(5));
}
}
#[cfg(debug_assertions)]
#[test]
fn watch_handles_a_source_deleted_during_its_rebuild_as_deleted() {
for (label, extra, edit_vars) in DELETION_BATCHES {
let base = notes_with(&[("edited.mds", "Edited\n"), ("same.mds", "Same\n")]);
let notes = base.path().join("notes");
let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path())
.args(["watch", "notes", "--poll-interval", "0"])
.args(extra)
.env(BATCH_PAUSE, &go)
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("edited.md"), "Edited", TIMEOUT)
&& wait_for_file_contains(¬es.join("same.md"), "Same", TIMEOUT),
"{label}: control: the startup writes both outputs; stderr: {}",
tap.text()
);
std::fs::write(notes.join("edited.md"), USER_EDIT).unwrap();
if edit_vars {
write_atomic(&base.path().join("vars.json"), r#"{"name": "two"}"#);
} else {
write_atomic(¬es.join("edited.mds"), "Edited\n");
write_atomic(¬es.join("same.mds"), "Same\n");
}
wait_paused(&paused, &mut child, &tap, label);
for name in ["edited.mds", "same.mds"] {
std::fs::remove_file(notes.join(name)).unwrap();
}
std::fs::write(&go, "").unwrap();
let kept = format!(
"Kept {}: changed since it was written",
below("notes", "edited.md")
);
let removed = format!("Removed {} (source deleted)", below("notes", "same.md"));
wait_for_tap(&tap, &kept, TIMEOUT);
wait_for_tap(&tap, &removed, TIMEOUT);
write_atomic(¬es.join("zz.mds"), ORDER_MARKER_SOURCE);
wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
assert!(
child.0.try_wait().unwrap().is_none(),
"{label}: the session keeps watching; stderr: {}",
tap.text()
);
#[cfg(unix)]
{
interrupt(&child);
let status = wait_bounded(&mut child, SESSION_END_TIMEOUT, "Ctrl+C");
assert_eq!(
status.code(),
Some(0),
"{label}: Ctrl+C ends the session with exit 0; stderr: {}",
tap.text()
);
}
let stderr = tap.finish_text(&mut child);
assert!(
!stderr.contains("file not found"),
"{label}: a source deleted during its rebuild is no compile error; \
stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Kept "),
[kept],
"{label}: stderr: {stderr}"
);
assert_eq!(
lines_starting(&stderr, "Removed "),
[removed],
"{label}: stderr: {stderr}"
);
assert_eq!(
text_of(¬es.join("edited.md")).as_deref(),
Some(USER_EDIT),
"{label}: the output the user edited survives; stderr: {stderr}"
);
assert!(
!notes.join("same.md").exists(),
"{label}: the output left as written is gone; stderr: {stderr}"
);
}
}
#[cfg(debug_assertions)]
#[test]
fn watch_refuses_a_parent_changed_after_its_path_check() {
for directory_mode in [false, true] {
for change_parent in [false, true] {
let base = tempfile::TempDir::new().unwrap();
let sub = base.path().join("notes").join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("page.mds"), "Original\n").unwrap();
let held = base.path().join("held");
let probe = base.path().join("probe");
if !make_symlink(&sub, &probe) {
return;
}
remove_symlink(&probe);
let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));
let ready = base.path().join("ready");
let entry = Path::new("notes").join("sub").join("page.mds");
let mut command = mds_bin();
command.current_dir(base.path()).arg("watch");
let output = if directory_mode {
command.args(["notes", "--out-dir", "out"]);
base.path().join("out").join("sub").join("page.md")
} else {
command.arg(&entry).args(["-o", "out.md"]);
base.path().join("out.md")
};
let (mut child, tap) = spawn_unsynchronized(
command
.args(["--debounce", "0", "--poll-interval", "0"])
.env("MDS_TEST_READY", &ready)
.env("MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE", &go)
.stdout(Stdio::null()),
);
wait_paused(&paused, &mut child, &tap, "before entry resolution");
if change_parent {
std::fs::rename(&sub, &held).unwrap();
assert!(make_symlink(&held, &sub));
}
std::fs::write(&go, "").unwrap();
wait_paused(&ready, &mut child, &tap, "startup complete");
let stderr = tap.finish_text(&mut child);
if change_parent {
assert!(
stderr.contains("the file changed while it was opened"),
"the compile must refuse the changed parent; stderr: {stderr}"
);
assert!(!output.exists(), "a refused compile writes no output");
} else {
assert_eq!(std::fs::read_to_string(&output).unwrap(), "Original\n");
assert!(!stderr.contains("the file changed while it was opened"));
}
}
}
}
const MODULE: &str = "---\ntype: mds\nname: X\n---\nHi {{name}}\n";
fn refusals(stderr: &str, shown: &str, cause: &str) -> usize {
count_occurrences(
&squash(stderr),
&squash(&format!("cannot write {shown}: {cause}")),
)
}
#[test]
fn watch_never_writes_over_an_mds_module() {
const CAUSE: &str = "refusing to replace an MDS module";
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[("chat.mds", "Hello one\n"), ("chat.md", MODULE)]);
let notes = base.path().join("notes");
let (src, md) = (notes.join("chat.mds"), notes.join("chat.md"));
let shown_md = below(shown_dir, "chat.md");
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let refused_after = |n: usize, what: &str| {
let seen = poll_tap_until(&tap, TIMEOUT, |seen| refusals(seen, &shown_md, CAUSE) > n);
assert!(
seen.is_ok(),
"{mode}: {what} is refused; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some(MODULE),
"{mode}: {what} keeps the module; stderr: {}",
tap.text()
);
refusals(&tap.text(), &shown_md, CAUSE)
};
let seen = refused_after(0, "the startup write");
write_atomic(&src, "Hello two\n");
refused_after(seen, "a rebuild of the same kind");
settle_queued_events(&tap, &src, "module_kept");
std::fs::remove_file(&md).unwrap();
write_atomic(&src, "Hello three\n");
assert!(
wait_for_file_contains(&md, "Hello three", TIMEOUT),
"{mode}: control: with chat.md gone, the next save writes it; stderr: {}",
tap.text()
);
settle_queued_events(&tap, &src, "module_written");
std::fs::write(&md, MODULE).unwrap();
let seen = refusals(&tap.text(), &shown_md, CAUSE);
write_atomic(&src, "Hello four\n");
refused_after(seen, "a rebuild over a module put in place of the output");
std::fs::remove_file(&md).unwrap();
write_atomic(&src, "Hello four\n");
assert!(
wait_for_file_contains(&md, "Hello four", TIMEOUT),
"{mode}: the refused text, saved again, is written; stderr: {}",
tap.text()
);
#[cfg(unix)]
{
interrupt(&child);
let status = wait_bounded(&mut child, SESSION_END_TIMEOUT, "Ctrl+C");
assert_eq!(
status.code(),
Some(0),
"{mode}: refused writes do not change the Ctrl+C exit; stderr: {}",
tap.text()
);
}
let stderr = tap.finish_text(&mut child);
assert!(
stderr.contains("mds::io"),
"{mode}: each refusal is mds::io; stderr: {stderr}"
);
}
}
#[test]
fn watch_rewrites_its_own_output_that_declares_type_mds() {
const CAUSE: &str = "refusing to replace an MDS module";
const GENERATED: &str = "---\ntype: mds\n---\nBody two\n";
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[
("gen.mds", "{{fm}}\nBody one\n"),
("v.json", r#"{"fm":"---\ntype: mds\n---"}"#),
]);
let notes = base.path().join("notes");
let (src, md) = (notes.join("gen.mds"), notes.join("gen.md"));
let shown_md = below(shown_dir, "gen.md");
let vars = below(shown_dir, "v.json");
let mut session: Vec<&str> = args
.iter()
.map(|&arg| if arg == "chat.mds" { "gen.mds" } else { arg })
.collect();
session.extend(["--vars", vars.as_str()]);
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(base.path().join(cwd))
.args(&session)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(&md, "Body one", TIMEOUT),
"{mode}: the startup writes the module gen.md; stderr: {}",
tap.text()
);
write_atomic(&src, "{{fm}}\nBody two\n");
assert!(
wait_for_file_contains(&md, "Body two", TIMEOUT),
"{mode}: the rebuild writes its own module output again; stderr: {}",
tap.text()
);
assert_eq!(text_of(&md).as_deref(), Some(GENERATED), "{mode}");
assert_eq!(
refusals(&tap.text(), &shown_md, CAUSE),
0,
"{mode}: nothing is refused; stderr: {}",
tap.text()
);
write_atomic(&src, "Plain\n");
let seen = poll_tap_until(&tap, TIMEOUT, |seen| refusals(seen, &shown_md, CAUSE) > 0);
assert!(
seen.is_ok(),
"{mode}: control: an output that is no module is refused; stderr: {}",
tap.text()
);
assert_eq!(
text_of(&md).as_deref(),
Some(GENERATED),
"{mode}: control: the module is kept; stderr: {}",
tap.text()
);
write_atomic(&src, "{{fm}}\nBody three\n");
assert!(
wait_for_file_contains(&md, "Body three", TIMEOUT),
"{mode}: a module output again is written; stderr: {}",
tap.text()
);
#[cfg(unix)]
{
interrupt(&child);
let status = wait_bounded(&mut child, SESSION_END_TIMEOUT, "Ctrl+C");
assert_eq!(
status.code(),
Some(0),
"{mode}: a refused write does not change the Ctrl+C exit; stderr: {}",
tap.text()
);
}
drop(tap.finish_text(&mut child));
}
}
struct Guarded<'a> {
source: &'a Path,
edit: &'a str,
shown: String,
file: &'a Path,
was: &'a str,
}
fn assert_never_writes_over(label: &str, cwd: &Path, args: &[&str], guarded: &[Guarded<'_>]) {
const CAUSE: &str = "refusing to replace a file this run reads";
let (mut child, tap) = spawn_ready(
mds_bin()
.current_dir(cwd)
.args(args)
.args(["--debounce", "0", "--poll-interval", "0"])
.stdout(Stdio::null()),
);
let refused_after = |one: &Guarded<'_>, n: usize, what: &str| {
let seen = poll_tap_until(&tap, TIMEOUT, |seen| refusals(seen, &one.shown, CAUSE) > n);
assert!(
seen.is_ok(),
"{label}: {what}: {} is refused; stderr: {}",
one.shown,
tap.text()
);
assert_eq!(
text_of(one.file).as_deref(),
Some(one.was),
"{label}: {what}: {} is left as it was; stderr: {}",
one.shown,
tap.text()
);
};
for one in guarded {
refused_after(one, 0, "the startup write");
}
for one in guarded {
let seen = refusals(&tap.text(), &one.shown, CAUSE);
write_atomic(one.source, one.edit);
refused_after(one, seen, "a rebuild of the same kind");
}
#[cfg(unix)]
{
interrupt(&child);
let status = wait_bounded(&mut child, SESSION_END_TIMEOUT, "Ctrl+C");
assert_eq!(
status.code(),
Some(0),
"{label}: refused writes do not change the Ctrl+C exit; stderr: {}",
tap.text()
);
}
drop(tap.finish_text(&mut child));
}
#[test]
fn watch_never_writes_over_its_vars_file_or_the_mds_json_in_force() {
const VARS: &str = "{\"name\": \"Dean\"}\n";
const CONFIG: &str = "{\"build\":{\"source_map\":false}}\n";
for (mode, cwd, args, shown_dir) in CHAT_SESSIONS {
let base = notes_with(&[
("chat.mds", "@message user:\nHi {{name}}\n@end\n"),
("chat.json", VARS),
("mds.mds", "@message user:\nHello\n@end\n"),
("mds.json", CONFIG),
]);
let notes = base.path().join("notes");
let cwd = base.path().join(cwd);
let vars = below(shown_dir, "chat.json");
let (chat_src, chat_json) = (notes.join("chat.mds"), notes.join("chat.json"));
let (config_src, config) = (notes.join("mds.mds"), notes.join("mds.json"));
let chat = Guarded {
source: &chat_src,
edit: "@message user:\nHi again {{name}}\n@end\n",
shown: below(shown_dir, "chat.json"),
file: &chat_json,
was: VARS,
};
let in_force = Guarded {
source: &config_src,
edit: "@message user:\nHello again\n@end\n",
shown: below(shown_dir, "mds.json"),
file: &config,
was: CONFIG,
};
let mut with_vars = args.to_vec();
with_vars.extend(["--vars", vars.as_str()]);
if args.contains(&"notes") {
assert_never_writes_over(mode, &cwd, &with_vars, &[chat, in_force]);
} else {
assert_never_writes_over(mode, &cwd, &with_vars, &[chat]);
assert_never_writes_over(mode, &cwd, &["watch", "mds.mds"], &[in_force]);
}
}
let base = notes_with(&[("chat.mds", "@message user:\nHi {{name}}\n@end\n")]);
let notes = base.path().join("notes");
std::fs::write(notes.join("chat.json"), VARS).unwrap();
let vars = Path::new("..").join("vars.json");
let (child, tap) = spawn_ready(
mds_bin()
.current_dir(¬es)
.args(["watch", "chat.mds", "--vars"])
.arg(&vars)
.args(["--debounce", "0"])
.stdout(Stdio::null()),
);
assert!(
wait_for_file_contains(¬es.join("chat.json"), "Hi one", TIMEOUT),
"control: chat.json is written; stderr: {}",
tap.text()
);
drop(child);
}
#[test]
fn watch_never_writes_over_the_mds_json_nearest_a_source() {
const CONFIG: &str = "{\"build\":{}}\n";
let base = notes_with(&[("doc.mds", "Doc\n")]);
let sub = base.path().join("notes").join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::write(sub.join("mds.mds"), "@message user:\nSub\n@end\n").unwrap();
std::fs::write(sub.join("mds.json"), CONFIG).unwrap();
let (src, config) = (sub.join("mds.mds"), sub.join("mds.json"));
assert_never_writes_over(
"directory mode",
base.path(),
&["watch", "notes"],
&[Guarded {
source: &src,
edit: "@message user:\nSub again\n@end\n",
shown: below(&below("notes", "sub"), "mds.json"),
file: &config,
was: CONFIG,
}],
);
}
#[test]
fn watch_never_writes_over_a_source_its_entry_imports() {
const VARS: &str = r#"{"fm":"---\ntype: mds\n---"}"#;
const LIB: &str = "---\ntype: mds\n---\nShared\n";
let base = notes_with(&[
("lib.mds", "Shared\n"),
(
"page.mds",
"@import \"./lib.mds\" as l\n{{fm}}\n@include l\nPage\n",
),
("v.json", VARS),
]);
let notes = base.path().join("notes");
let (page, lib) = (notes.join("page.mds"), notes.join("lib.mds"));
assert_never_writes_over(
"file mode",
¬es,
&["watch", "page.mds", "-o", "lib.mds", "--vars", "v.json"],
&[Guarded {
source: &page,
edit: "@import \"./lib.mds\" as l\n{{fm}}\n@include l\nMore\n",
shown: "lib.mds".to_owned(),
file: &lib,
was: "Shared\n",
}],
);
let base = notes_with(&[
("lib.mds", "@import \"./lib.md\" as l\n{{fm}}\nLib\n"),
("lib.md", LIB),
("v.json", VARS),
]);
let notes = base.path().join("notes");
let (src, md) = (notes.join("lib.mds"), notes.join("lib.md"));
let vars = below("notes", "v.json");
assert_never_writes_over(
"directory mode",
base.path(),
&["watch", "notes", "--vars", vars.as_str()],
&[Guarded {
source: &src,
edit: "@import \"./lib.md\" as l\n{{fm}}\nLib again\n",
shown: below("notes", "lib.md"),
file: &md,
was: LIB,
}],
);
}