mod common;
use common::{make_symlink, mds_bin};
use std::fs;
use std::path::Path;
fn create_plain_mds(dir: &Path, name: &str) {
fs::write(dir.join(name), "Hello, world!\n").unwrap();
}
fn create_messages_mds(dir: &Path, name: &str) {
fs::write(
dir.join(name),
"@message system:\nYou are a helpful assistant.\n@end\n@message user:\nHello!\n@end\n",
)
.unwrap();
}
fn create_bad_mds(dir: &Path, name: &str) {
fs::write(dir.join(name), "{{undefined_var_xyz}}\n").unwrap();
}
fn build_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("build")
.arg(dir)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
#[cfg(unix)]
fn build_file(path: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("build")
.arg(path)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
fn check_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("check")
.arg(dir)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
#[test]
#[cfg(unix)]
fn dir_build_refuses_a_file_replaced_after_walk() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "page.mds");
create_plain_mds(src.path(), "good.mds");
let output = common::run_after_walk(
mds_bin()
.arg("build")
.arg(src.path())
.arg("--source-map")
.arg("--out-dir")
.arg(out.path()),
|| {
fs::rename(src.path().join("page.mds"), src.path().join("saved.txt")).unwrap();
fs::write(src.path().join("page.mds"), "Replacement\n").unwrap();
},
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains("mds::io") && stderr.contains("file changed"),
"{stderr}"
);
assert!(stderr.contains("1 built, 1 failed"), "{stderr}");
assert!(!out.path().join("page.md").exists());
assert!(!out.path().join("page.md.map").exists());
assert_eq!(
fs::read_to_string(out.path().join("good.md")).unwrap(),
"Hello, world!\n"
);
}
#[test]
fn dir_build_refuses_a_parent_redirected_after_walk() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
let sub = src.path().join("sub");
let moved = src.path().join("moved");
fs::create_dir(&sub).unwrap();
create_plain_mds(&sub, "page.mds");
if !make_symlink(&sub, &src.path().join("probe")) {
return;
}
let output = common::run_after_walk(
mds_bin()
.arg("build")
.arg(src.path())
.arg("--out-dir")
.arg(out.path()),
|| {
fs::rename(&sub, &moved).unwrap();
assert!(make_symlink(&moved, &sub));
},
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains("mds::io") && stderr.contains("file changed"),
"{stderr}"
);
assert!(stderr.contains("0 built, 1 failed"), "{stderr}");
assert!(!out.path().join("sub/page.md").exists());
assert!(!out.path().join("moved/page.md").exists());
}
#[test]
fn dir_build_accepts_an_unchanged_tree_after_walk() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
fs::create_dir(src.path().join("sub")).unwrap();
create_plain_mds(&src.path().join("sub"), "page.mds");
let output = common::run_after_walk(
mds_bin()
.arg("build")
.arg(src.path())
.arg("--out-dir")
.arg(out.path()),
|| {},
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "{stderr}");
assert!(stderr.contains("1 built, 0 failed"), "{stderr}");
assert_eq!(
fs::read_to_string(out.path().join("sub/page.md")).unwrap(),
"Hello, world!\n"
);
}
#[test]
fn dir_build_subtree_mirror_intrinsic_ext() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
fs::create_dir(src.path().join("sub")).unwrap();
create_plain_mds(src.path(), "plain.mds");
create_messages_mds(&src.path().join("sub"), "messages.mds");
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
output.status.success(),
"dir build should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let plain_out = out.path().join("plain.md");
assert!(
plain_out.exists(),
"expected out/plain.md to be created; out dir: {:?}",
fs::read_dir(out.path()).map(|rd| rd
.filter_map(|e| e.ok().map(|e| e.path()))
.collect::<Vec<_>>())
);
let plain_content = fs::read_to_string(&plain_out).unwrap();
assert!(
plain_content.contains("Hello"),
"plain.md should contain rendered content; got: {plain_content:?}"
);
let msg_out = out.path().join("sub").join("messages.json");
assert!(
msg_out.exists(),
"expected out/sub/messages.json to be created"
);
let msg_content = fs::read_to_string(&msg_out).unwrap();
let parsed: serde_json::Value =
serde_json::from_str(&msg_content).expect("messages.json should be valid JSON");
assert!(parsed.is_array(), "messages.json should be a JSON array");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("built"),
"stderr should contain build summary; got: {stderr}"
);
}
#[test]
fn dir_build_partials_produce_no_output() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_partial.mds");
create_plain_mds(src.path(), "main.mds");
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
output.status.success(),
"dir build should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let partial_out = out.path().join("_partial.md");
assert!(
!partial_out.exists(),
"_partial.md must not be created (partials are skipped)"
);
let main_out = out.path().join("main.md");
assert!(main_out.exists(), "main.md should be created");
}
#[test]
fn dir_build_continue_on_error_summary_nonzero() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "good.mds");
create_bad_mds(src.path(), "bad.mds");
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
!output.status.success(),
"dir build with a failing file must exit non-zero"
);
let good_out = out.path().join("good.md");
assert!(
good_out.exists(),
"good.md should still be created despite bad.mds failing"
);
let bad_out = out.path().join("bad.md");
assert!(
!bad_out.exists(),
"bad.md must not be created when compilation fails"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("built") && stderr.contains("failed"),
"stderr must contain a build summary with 'built' and 'failed'; got: {stderr}"
);
assert!(
stderr.contains("1 built") && stderr.contains("1 failed"),
"stderr must show '1 built, 1 failed'; got: {stderr}"
);
}
#[test]
fn dir_build_bare_writes_next_to_source() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "page.mds");
create_messages_mds(src.path(), "chat.mds");
let output = build_dir(src.path(), &[]);
assert!(
output.status.success(),
"bare dir build should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let page_out = src.path().join("page.md");
assert!(page_out.exists(), "page.md should appear next to page.mds");
let chat_out = src.path().join("chat.json");
assert!(
chat_out.exists(),
"chat.json should appear next to chat.mds"
);
let _ = fs::remove_file(&page_out);
let _ = fs::remove_file(&chat_out);
}
#[test]
fn dir_build_symlinked_file_skipped() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
let real_file = src.path().join("real.mds");
fs::write(&real_file, "Real content.\n").unwrap();
let link_file = src.path().join("link.mds");
if !make_symlink(&real_file, &link_file) {
return;
}
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
output.status.success(),
"build should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let link_out = out.path().join("link.md");
assert!(
!link_out.exists(),
"symlinked .mds file must not produce output"
);
let real_out = out.path().join("real.md");
assert!(real_out.exists(), "real.md should be created from real.mds");
}
#[test]
fn dir_build_symlinked_subdir_skipped() {
let real_dir = tempfile::tempdir().unwrap();
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
fs::write(real_dir.path().join("child.mds"), "Child.\n").unwrap();
let link_dir = src.path().join("linked_sub");
if !make_symlink(real_dir.path(), &link_dir) {
return;
}
create_plain_mds(src.path(), "root.mds");
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
output.status.success(),
"build should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let child_out = out.path().join("linked_sub").join("child.md");
assert!(
!child_out.exists(),
"symlinked subdirectory must not be traversed"
);
}
#[test]
fn dir_build_symlinked_entry_root_rejected() {
let real_dir = tempfile::tempdir().unwrap();
create_plain_mds(real_dir.path(), "page.mds");
let link_dir = tempfile::tempdir().unwrap();
let link_path = link_dir.path().join("linked");
if !make_symlink(real_dir.path(), &link_path) {
return;
}
let output = build_dir(&link_path, &[]);
assert!(
!output.status.success(),
"build on a symlinked entry root must fail"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("symlink") || stderr.contains("directory"),
"error must mention symlink; got: {stderr}"
);
}
#[test]
fn dir_build_oversized_file_fails_others_succeed() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "good.mds");
let big_content = "x".repeat(10 * 1024 * 1024 + 1);
fs::write(src.path().join("big.mds"), &big_content).unwrap();
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
!output.status.success(),
"dir build with an oversized file must exit non-zero"
);
let good_out = out.path().join("good.md");
assert!(
good_out.exists(),
"good.md should still be created despite the oversized file"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("failed"),
"stderr must mention failure in summary; got: {stderr}"
);
}
fn resource_limited_source() -> String {
(0..257)
.map(|i| format!("@block block_{i}:\n@end\n"))
.collect()
}
fn oversized_source() -> String {
"x".repeat(10 * 1024 * 1024 + 1)
}
struct FailingSources {
limited: String,
template_error: &'static str,
}
fn assert_a_directory_run_exits_3_for_a_resource_limited_file(
subcommand: &str,
run_dir: fn(&Path, &[&str]) -> std::process::Output,
failing: &FailingSources,
) {
let limited = tempfile::tempdir().unwrap();
fs::write(limited.path().join("limited.mds"), &failing.limited).unwrap();
let alone = mds_bin()
.arg(subcommand)
.arg(limited.path().join("limited.mds"))
.output()
.unwrap();
assert_eq!(
alone.status.code(),
Some(3),
"control: the limited file alone must exit 3; stderr: {}",
String::from_utf8_lossy(&alone.stderr)
);
let template_error = tempfile::tempdir().unwrap();
create_plain_mds(template_error.path(), "good.mds");
fs::write(
template_error.path().join("bad.mds"),
failing.template_error,
)
.unwrap();
let control = run_dir(template_error.path(), &[]);
assert_eq!(
control.status.code(),
Some(1),
"control: a template error alone must exit 1; stderr: {}",
String::from_utf8_lossy(&control.stderr)
);
for (label, with_template_error, extra) in [
("beside a good file", false, &[][..]),
("beside a template error", true, &[][..]),
("under --quiet", false, &["--quiet"][..]),
] {
let dir = tempfile::tempdir().unwrap();
create_plain_mds(dir.path(), "good.mds");
fs::write(dir.path().join("limited.mds"), &failing.limited).unwrap();
if with_template_error {
fs::write(dir.path().join("bad.mds"), failing.template_error).unwrap();
}
let output = run_dir(dir.path(), extra);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(3),
"`mds {subcommand} <dir>` with a resource-limited file {label} must exit 3; \
stderr: {stderr}"
);
assert!(
stderr.contains("resource limit exceeded"),
"the limit is reported, {label}; stderr: {stderr}"
);
}
}
#[test]
fn dir_build_with_a_resource_limited_file_exits_3() {
assert_a_directory_run_exits_3_for_a_resource_limited_file(
"build",
build_dir,
&FailingSources {
limited: resource_limited_source(),
template_error: "{{undefined_var_xyz}}\n",
},
);
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "good.mds");
fs::write(src.path().join("limited.mds"), resource_limited_source()).unwrap();
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
out.path().join("good.md").is_file() && !out.path().join("limited.md").exists(),
"the good file is built and the limited one is not; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 1 failed"),
"the summary is unchanged; stderr: {stderr}"
);
}
#[test]
fn dir_check_with_a_resource_limited_file_exits_3() {
assert_a_directory_run_exits_3_for_a_resource_limited_file(
"check",
check_dir,
&FailingSources {
limited: resource_limited_source(),
template_error: "{{undefined_var_xyz}}\n",
},
);
}
#[test]
fn dir_fmt_with_a_resource_limited_file_exits_3() {
assert_a_directory_run_exits_3_for_a_resource_limited_file(
"fmt",
fmt_dir,
&FailingSources {
limited: oversized_source(),
template_error: "```\nunclosed fence\n",
},
);
}
#[test]
fn dir_check_validates_tree_exits_zero_on_all_ok() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "page.mds");
create_messages_mds(src.path(), "chat.mds");
let output = check_dir(src.path(), &[]);
assert!(
output.status.success(),
"check on a valid tree should succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("passed"),
"stderr should contain check summary; got: {stderr}"
);
}
#[test]
fn dir_check_continues_on_error_nonzero_exit() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "good.mds");
create_bad_mds(src.path(), "bad.mds");
let output = check_dir(src.path(), &[]);
assert!(
!output.status.success(),
"check with a failing file must exit non-zero"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("passed") || stderr.contains("failed"),
"stderr must contain check summary; got: {stderr}"
);
}
#[test]
fn dir_check_empty_dir_exits_one() {
let src = tempfile::tempdir().unwrap();
let output = check_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"check on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("no .mds files found in"),
"stderr must carry the empty-tree diagnostic; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was checked"),
"stderr must say nothing was checked; got: {stderr:?}"
);
}
#[test]
fn dir_check_empty_dir_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let output = check_dir(src.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"check --quiet on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
!stderr.is_empty(),
"stderr must not be empty under --quiet on an empty tree"
);
assert!(
stderr.contains("no .mds files found in"),
"empty-tree diagnostic must appear under --quiet; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was checked"),
"stderr must say nothing was checked under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_check_partials_only_exits_one() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_only.mds");
let output = check_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"check on a partials-only dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("nothing was checked"),
"stderr must say nothing was checked; got: {stderr:?}"
);
assert!(
stderr.contains("all are _-prefixed partials"),
"stderr must say all are _-prefixed partials; got: {stderr:?}"
);
create_plain_mds(src.path(), "real.mds");
let output2 = check_dir(src.path(), &[]);
let stderr2 = String::from_utf8_lossy(&output2.stderr);
assert_eq!(
output2.status.code(),
Some(0),
"check with a real file present must succeed; stderr: {stderr2}"
);
assert!(
stderr2.contains("1 passed, 0 failed"),
"stderr must show the check summary; got: {stderr2:?}"
);
}
#[test]
fn dir_check_missing_root_exits_two() {
let src = tempfile::tempdir().unwrap();
let missing = src.path().join("nope");
let output = check_dir(&missing, &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(2),
"check on a missing path must exit 2; stderr: {stderr}"
);
assert!(
!stderr.contains("no .mds files found in"),
"a missing path must NOT produce the empty-tree diagnostic; got: {stderr:?}"
);
}
#[test]
fn dir_check_mixed_content_file_nonzero() {
let src = tempfile::tempdir().unwrap();
fs::write(
src.path().join("mixed.mds"),
"Some text before.\n@message user:\nHello!\n@end\n",
)
.unwrap();
let output = check_dir(src.path(), &[]);
assert!(
!output.status.success(),
"check on a mixed-content file must exit non-zero"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("mixed") || stderr.contains("failed"),
"error must mention mixed content or failure; got: {stderr}"
);
}
const MESSAGES: &str = "@message user:\nHi\n@end\n";
const MESSAGES_OUTPUT: &str = "[\n {\n \"role\": \"user\",\n \"content\": \"Hi\"\n }\n]\n";
const MARKDOWN: &str = "Plain\n";
const HAND_WRITTEN_JSON: &str = "{\"hand\":\"written\",\"not\":\"mds output\"}";
fn build_src_into_out(root: &Path, extra: &[&str]) -> std::process::Output {
mds_bin()
.current_dir(root)
.args(["build", "src", "--out-dir", "out"])
.args(extra)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
fn put(root: &Path, rel: &str, contents: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, contents).unwrap();
}
fn read(root: &Path, rel: &str) -> Option<String> {
fs::read_to_string(root.join(rel)).ok()
}
fn kept_lines(output: &std::process::Output) -> Vec<String> {
let mut lines: Vec<String> = String::from_utf8_lossy(&output.stderr)
.lines()
.filter(|line| line.starts_with("warning: kept "))
.map(str::to_owned)
.collect();
lines.sort();
lines
}
fn sorted(mut lines: Vec<String>) -> Vec<String> {
lines.sort();
lines
}
fn kept_json(name: &str) -> String {
format!(
"warning: kept stale output {}: not proven to be written by mds",
Path::new("out").join(name).display()
)
}
fn kept_markdown(name: &str) -> String {
format!(
"warning: kept stale output {}: mds never removes a Markdown file",
Path::new("out").join(name).display()
)
}
#[test]
fn dir_build_out_dir_removes_a_stale_json_only_when_it_is_exactly_what_mds_wrote() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/x.mds", MARKDOWN);
put(root, "src/y.mds", MESSAGES);
put(root, "src/z.mds", MARKDOWN);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
assert_eq!(
read(root, "out/y.json").as_deref(),
Some(MESSAGES_OUTPUT),
"what mds writes for a messages template"
);
put(root, "src/y.mds", MARKDOWN);
put(root, "out/x.json", HAND_WRITTEN_JSON);
let reformatted = "[{\"role\":\"user\",\"content\":\"Hi\"}]\n";
put(root, "out/z.json", reformatted);
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(0), "stderr: {stderr}");
assert_eq!(
read(root, "out/x.json").as_deref(),
Some(HAND_WRITTEN_JSON),
"the hand-written x.json survives; stderr: {stderr}"
);
assert_eq!(
read(root, "out/z.json").as_deref(),
Some(reformatted),
"the same messages formatted another way survive; stderr: {stderr}"
);
assert_eq!(
read(root, "out/y.json"),
None,
"control: the stale y.json mds wrote is removed; stderr: {stderr}"
);
assert_eq!(read(root, "out/y.md").as_deref(), Some(MARKDOWN));
assert_eq!(
kept_lines(&second),
sorted(vec![kept_json("x.json"), kept_json("z.json")]),
"stderr: {stderr}"
);
}
#[test]
fn dir_build_out_dir_keeps_a_stale_markdown_output_with_a_warning() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/page.mds", MARKDOWN);
put(root, "src/j.mds", MESSAGES);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
assert_eq!(read(root, "out/page.md").as_deref(), Some(MARKDOWN));
put(root, "src/page.mds", MESSAGES);
put(root, "src/j.mds", MARKDOWN);
put(root, "src/d.mds", MESSAGES);
put(root, "out/d.md/keep", "keep\n");
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(0), "stderr: {stderr}");
assert_eq!(
read(root, "out/page.md").as_deref(),
Some(MARKDOWN),
"the stale page.md is kept; stderr: {stderr}"
);
assert_eq!(
read(root, "out/page.json").as_deref(),
Some(MESSAGES_OUTPUT)
);
assert_eq!(
read(root, "out/d.md/keep").as_deref(),
Some("keep\n"),
"nothing under the stale d.md is touched"
);
assert_eq!(read(root, "out/d.json").as_deref(), Some(MESSAGES_OUTPUT));
assert_eq!(
read(root, "out/j.json"),
None,
"control: the stale j.json mds wrote is removed; stderr: {stderr}"
);
assert_eq!(
kept_lines(&second),
sorted(vec![kept_markdown("d.md"), kept_markdown("page.md")]),
"stderr: {stderr}"
);
let quiet = build_src_into_out(root, &["--quiet"]);
assert_eq!(
(quiet.status.code(), String::from_utf8_lossy(&quiet.stderr)),
(Some(0), "".into()),
"--quiet keeps them without a word"
);
assert_eq!(read(root, "out/page.md").as_deref(), Some(MARKDOWN));
}
#[test]
fn dir_build_out_dir_looks_for_the_stale_output_beside_the_output_it_wrote() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/a.mds", MESSAGES);
put(root, "src/a.z.mds", MESSAGES);
put(root, "src/b.mds", MARKDOWN);
put(root, "src/b.z.mds", MARKDOWN);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
create_bad_mds(&root.join("src"), "a.mds");
create_bad_mds(&root.join("src"), "b.mds");
put(root, "src/a.z.mds", MARKDOWN);
put(root, "src/b.z.mds", MESSAGES);
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(1), "stderr: {stderr}");
assert_eq!(
read(root, "out/a.json").as_deref(),
Some(MESSAGES_OUTPUT),
"a.mds's output survives a.z.mds's change of kind; stderr: {stderr}"
);
assert_eq!(
read(root, "out/b.md").as_deref(),
Some(MARKDOWN),
"b.mds's output survives b.z.mds's change of kind; stderr: {stderr}"
);
assert_eq!(
read(root, "out/a.z.json"),
None,
"control: a.z.mds's own stale JSON is removed; stderr: {stderr}"
);
assert_eq!(read(root, "out/a.z.md").as_deref(), Some(MARKDOWN));
assert_eq!(read(root, "out/b.z.json").as_deref(), Some(MESSAGES_OUTPUT));
assert_eq!(read(root, "out/b.z.md").as_deref(), Some(MARKDOWN));
assert_eq!(
kept_lines(&second),
vec![kept_markdown("b.z.md")],
"stderr: {stderr}"
);
}
#[test]
fn dir_build_out_dir_keeps_what_is_not_a_regular_file_at_a_stale_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/k.mds", MESSAGES);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
put(root, "src/k.mds", MARKDOWN);
for name in ["d", "l", "m"] {
put(root, &format!("src/{name}.mds"), MARKDOWN);
}
put(root, "elsewhere.json", MESSAGES_OUTPUT);
if !make_symlink(&root.join("elsewhere.json"), &root.join("out/l.json")) {
return;
}
assert!(make_symlink(
&root.join("missing.json"),
&root.join("out/m.json")
));
put(root, "out/d.json/keep", "keep\n");
#[cfg_attr(not(unix), allow(unused_mut))]
let mut want = vec![
kept_json("d.json"),
kept_json("l.json"),
kept_json("m.json"),
];
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt as _;
put(root, "src/f.mds", MARKDOWN);
let fifo = root.join("out/f.json");
let name = std::ffi::CString::new(fifo.as_os_str().as_bytes()).expect("no NUL in it");
assert_eq!(
unsafe { libc::mkfifo(name.as_ptr(), 0o644) },
0,
"make a FIFO"
);
want.push(kept_json("f.json"));
}
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(0), "stderr: {stderr}");
for link in ["out/l.json", "out/m.json"] {
assert!(
fs::symlink_metadata(root.join(link)).is_ok_and(|meta| meta.file_type().is_symlink()),
"the symlink {link} is kept; stderr: {stderr}"
);
}
assert_eq!(
read(root, "elsewhere.json").as_deref(),
Some(MESSAGES_OUTPUT)
);
assert_eq!(read(root, "out/d.json/keep").as_deref(), Some("keep\n"));
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt as _;
assert!(
fs::symlink_metadata(root.join("out/f.json"))
.is_ok_and(|meta| meta.file_type().is_fifo()),
"the FIFO is kept; stderr: {stderr}"
);
}
assert_eq!(
read(root, "out/k.json"),
None,
"control: the stale k.json mds wrote is removed; stderr: {stderr}"
);
assert_eq!(kept_lines(&second), sorted(want), "stderr: {stderr}");
}
#[test]
fn dir_build_out_dir_partial_removes_nothing() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/q.mds", MESSAGES);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
put(root, "src/q.mds", MARKDOWN);
put(root, "src/_p.mds", MESSAGES);
put(root, "out/_p.json", MESSAGES_OUTPUT);
put(root, "out/_p.md", "P\n");
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(0), "stderr: {stderr}");
assert_eq!(read(root, "out/_p.json").as_deref(), Some(MESSAGES_OUTPUT));
assert_eq!(read(root, "out/_p.md").as_deref(), Some("P\n"));
assert_eq!(
read(root, "out/q.json"),
None,
"control: the stale q.json mds wrote is removed; stderr: {stderr}"
);
assert_eq!(
kept_lines(&second),
Vec::<String>::new(),
"stderr: {stderr}"
);
}
#[cfg(unix)]
#[test]
fn dir_build_out_dir_a_stale_name_too_long_for_the_file_system_is_no_file() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let (long, fits) = ("y".repeat(251), "z".repeat(250));
put(root, &format!("src/{long}.mds"), MARKDOWN);
put(root, &format!("src/{fits}.mds"), MESSAGES);
let first = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&first.stderr);
assert_eq!(first.status.code(), Some(0), "stderr: {stderr}");
assert_eq!(
read(root, &format!("out/{long}.md")).as_deref(),
Some(MARKDOWN),
"stderr: {stderr}"
);
assert_eq!(
read(root, &format!("out/{fits}.json")).as_deref(),
Some(MESSAGES_OUTPUT),
"control: the first build writes the messages output; stderr: {stderr}"
);
put(root, &format!("src/{fits}.mds"), MARKDOWN);
let second = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&second.stderr);
assert_eq!(second.status.code(), Some(0), "stderr: {stderr}");
assert_eq!(
read(root, &format!("out/{fits}.json")),
None,
"control: the stale .json mds wrote is removed; stderr: {stderr}"
);
assert_eq!(
kept_lines(&second),
Vec::<String>::new(),
"stderr: {stderr}"
);
}
fn compiled_to(output: &std::process::Output) -> Vec<String> {
String::from_utf8_lossy(&output.stderr)
.lines()
.filter_map(|line| line.strip_prefix("Compiled to "))
.map(str::to_owned)
.collect()
}
#[test]
fn a_build_beside_its_sources_never_removes_an_output_it_wrote_this_run() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/p/a.mds", MESSAGES);
put(root, "src/p/a.b.mds", MARKDOWN);
put(root, "src/q/a.mds", MARKDOWN);
put(root, "src/q/a.b.mds", MESSAGES);
let beside = mds_bin()
.current_dir(root)
.args(["build", "src"])
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&beside.stderr);
assert_eq!(beside.status.code(), Some(0), "stderr: {stderr}");
let compiled = compiled_to(&beside);
assert_eq!(compiled.len(), 4, "one output per source; stderr: {stderr}");
for shown in &compiled {
assert!(
root.join(shown).is_file(),
"{shown}, which this run wrote, is still there; stderr: {stderr}"
);
}
for shown in &compiled {
assert!(
!kept_lines(&beside)
.iter()
.any(|line| line.contains(&format!(" {shown}: "))),
"no warning names {shown}, which this run wrote; stderr: {stderr}"
);
}
for json in ["src/p/a.json", "src/q/a.json"] {
assert_eq!(
read(root, json).as_deref(),
Some(MESSAGES_OUTPUT),
"{json}; stderr: {stderr}"
);
}
for md in ["src/p/a.md", "src/q/a.md"] {
assert_eq!(
read(root, md).as_deref(),
Some(MARKDOWN),
"{md}; stderr: {stderr}"
);
}
put(root, "src/x.mds", MARKDOWN);
put(root, "out/x.json", MESSAGES_OUTPUT);
let into_out = build_src_into_out(root, &[]);
let stderr = String::from_utf8_lossy(&into_out.stderr);
assert_eq!(into_out.status.code(), Some(0), "stderr: {stderr}");
for rel in [
"out/p/a.json",
"out/p/a.b.md",
"out/q/a.md",
"out/q/a.b.json",
] {
assert!(root.join(rel).is_file(), "control: {rel}; stderr: {stderr}");
}
assert_eq!(
read(root, "out/x.json"),
None,
"control: the stale x.json mds wrote is removed; stderr: {stderr}"
);
}
#[test]
fn dir_build_empty_dir_exits_one() {
let src = tempfile::tempdir().unwrap();
let output = build_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"build on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("no .mds files found in"),
"stderr must carry the empty-tree diagnostic; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was built"),
"stderr must say nothing was built; got: {stderr:?}"
);
}
#[test]
fn dir_build_empty_dir_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let output = build_dir(src.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"build --quiet on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
!stderr.is_empty(),
"stderr must not be empty under --quiet on an empty tree"
);
assert!(
stderr.contains("no .mds files found in"),
"empty-tree diagnostic must appear under --quiet; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was built"),
"stderr must say nothing was built under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_build_partials_only_exits_one() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_only.mds");
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"build on a partials-only dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("1 .mds file(s) found in"),
"stderr must carry the partials-only count diagnostic; got: {stderr:?}"
);
assert!(
stderr.contains("all are _-prefixed partials"),
"stderr must say all are _-prefixed partials; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was built"),
"stderr must say nothing was built; got: {stderr:?}"
);
assert!(
!out.path().join("_only.md").exists(),
"a partial must never produce output"
);
create_plain_mds(src.path(), "real.mds");
let output2 = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert_eq!(
output2.status.code(),
Some(0),
"build with a real file present must succeed; stderr: {}",
String::from_utf8_lossy(&output2.stderr)
);
assert!(
out.path().join("real.md").exists(),
"real.md should be created"
);
assert!(
!out.path().join("_only.md").exists(),
"_only.md must not be created (partials are skipped)"
);
}
#[test]
fn dir_build_partials_only_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_only.mds");
let output = build_dir(src.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"build --quiet on a partials-only dir must exit 1; stderr: {stderr}"
);
assert!(
!stderr.is_empty(),
"stderr must not be empty under --quiet on a partials-only tree"
);
assert!(
stderr.contains("nothing was built"),
"stderr must say nothing was built under --quiet; got: {stderr:?}"
);
}
fn lint_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("lint")
.arg(dir)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
fn fmt_dir(dir: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("fmt")
.arg(dir)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
#[test]
fn dir_build_all_excluded_exits_nonzero() {
let src = tempfile::tempdir().unwrap();
let hidden = src.path().join(".github");
fs::create_dir_all(hidden.join("prompts")).unwrap();
fs::write(hidden.join("prompts").join("system.mds"), "Hello!\n").unwrap();
let output = build_dir(src.path(), &[]);
assert!(
!output.status.success(),
"build with all candidates in excluded dirs must exit non-zero; exit: {:?}; stderr: {}",
output.status.code(),
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"stderr must mention excluded directories; got: {stderr}"
);
assert!(
stderr.contains('1'),
"stderr must carry the skip count (1 file excluded); got: {stderr}"
);
}
#[test]
fn dir_build_all_excluded_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let nm = src.path().join("node_modules");
fs::create_dir(&nm).unwrap();
fs::write(nm.join("lib.mds"), "Hello!\n").unwrap();
fs::write(nm.join("other.mds"), "World!\n").unwrap();
let output = build_dir(src.path(), &["--quiet"]);
assert!(
!output.status.success(),
"build with all candidates excluded must exit non-zero even under --quiet"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.is_empty(),
"stderr must not be empty under --quiet when all candidates are excluded"
);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"all-excluded diagnostic must appear under --quiet; got: {stderr}"
);
assert!(
stderr.contains('2'),
"stderr must report 2 skipped files; got: {stderr}"
);
}
#[test]
fn dir_build_genuinely_empty_exits_one_without_excluded_diagnostic() {
let src = tempfile::tempdir().unwrap();
let output = build_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"genuinely empty dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("no .mds files found in"),
"empty-dir message must be the empty-tree diagnostic; got: {stderr:?}"
);
assert!(
!stderr.contains("excluded"),
"empty-dir must NOT show the excluded diagnostic; got: {stderr:?}"
);
let control = tempfile::tempdir().unwrap();
let hidden = control.path().join(".github");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("x.mds"), "Hello!\n").unwrap();
let control_out = build_dir(control.path(), &[]);
let control_stderr = String::from_utf8_lossy(&control_out.stderr);
assert_eq!(
control_out.status.code(),
Some(1),
"positive control: the all-excluded case also exits 1; stderr: {control_stderr}"
);
assert!(
control_stderr.contains("excluded"),
"positive control: the all-excluded case must carry the excluded diagnostic; \
got: {control_stderr:?}"
);
assert!(
!control_stderr.contains("no .mds files found in"),
"positive control: the all-excluded case must NOT carry the empty-tree \
diagnostic; got: {control_stderr:?}"
);
}
#[test]
fn dir_build_mixed_excluded_and_normal_processes_normal() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "normal.mds");
let hidden = src.path().join(".prompts");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("excluded.mds"), "Hello!\n").unwrap();
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
assert!(
output.status.success(),
"build with mixed excluded+normal files must succeed; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
out.path().join("normal.md").exists(),
"normal.md must be built"
);
assert!(
!out.path().join(".prompts").join("excluded.md").exists(),
"excluded.md must not be built"
);
}
#[test]
fn dir_check_all_excluded_exits_nonzero() {
let src = tempfile::tempdir().unwrap();
let hidden = src.path().join(".claude");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("prompt.mds"), "Hello!\n").unwrap();
let output = check_dir(src.path(), &[]);
assert!(
!output.status.success(),
"check with all candidates in excluded dirs must exit non-zero; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"stderr must mention excluded directories; got: {stderr}"
);
assert!(
stderr.contains('1'),
"stderr must carry the skip count; got: {stderr}"
);
}
#[test]
fn dir_check_all_excluded_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let hidden = src.path().join(".cursor");
fs::create_dir_all(hidden.join("rules")).unwrap();
fs::write(hidden.join("rules").join("rule.mds"), "Hello!\n").unwrap();
let output = check_dir(src.path(), &["--quiet"]);
assert!(
!output.status.success(),
"check with all candidates excluded must exit non-zero even under --quiet"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
"all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_lint_all_excluded_exits_nonzero() {
let src = tempfile::tempdir().unwrap();
let nm = src.path().join("node_modules");
fs::create_dir(&nm).unwrap();
fs::write(nm.join("template.mds"), "Hello!\n").unwrap();
let output = lint_dir(src.path(), &[]);
assert!(
!output.status.success(),
"lint with all candidates in excluded dirs must exit non-zero; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"stderr must mention excluded directories; got: {stderr}"
);
}
#[test]
fn dir_lint_all_excluded_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let hidden = src.path().join(".github");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("workflow.mds"), "Hello!\n").unwrap();
let output = lint_dir(src.path(), &["--quiet"]);
assert!(
!output.status.success(),
"lint with all candidates excluded must exit non-zero even under --quiet"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
"all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_fmt_all_excluded_exits_nonzero() {
let src = tempfile::tempdir().unwrap();
let hidden = src.path().join(".prompts");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("system.mds"), "Hello!\n").unwrap();
let output = fmt_dir(src.path(), &[]);
assert!(
!output.status.success(),
"fmt with all candidates in excluded dirs must exit non-zero; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"stderr must mention excluded directories; got: {stderr}"
);
}
#[test]
fn dir_fmt_all_excluded_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let nm = src.path().join("node_modules");
fs::create_dir(&nm).unwrap();
fs::write(nm.join("component.mds"), "Hello!\n").unwrap();
let output = fmt_dir(src.path(), &["--quiet"]);
assert!(
!output.status.success(),
"fmt with all candidates excluded must exit non-zero even under --quiet"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!stderr.is_empty() && (stderr.contains("excluded") || stderr.contains("default-excluded")),
"all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_fmt_empty_dir_exits_one() {
let src = tempfile::tempdir().unwrap();
let output = fmt_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"fmt on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("no .mds files found in"),
"stderr must carry the empty-tree diagnostic; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was formatted"),
"stderr must say nothing was formatted; got: {stderr:?}"
);
}
#[test]
fn dir_fmt_empty_dir_quiet_still_emits_diagnostic() {
let src = tempfile::tempdir().unwrap();
let output = fmt_dir(src.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"fmt --quiet on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
!stderr.is_empty(),
"stderr must not be empty under --quiet on an empty tree"
);
assert!(
stderr.contains("no .mds files found in"),
"empty-tree diagnostic must appear under --quiet; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was formatted"),
"stderr must say nothing was formatted under --quiet; got: {stderr:?}"
);
}
#[test]
fn dir_fmt_empty_dir_check_flag_exits_one() {
let src = tempfile::tempdir().unwrap();
let output = fmt_dir(src.path(), &["--check"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(1),
"fmt --check on an empty dir must exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("no .mds files found in"),
"stderr must carry the empty-tree diagnostic under --check; got: {stderr:?}"
);
assert!(
stderr.contains("nothing was formatted"),
"stderr must say nothing was formatted under --check; got: {stderr:?}"
);
}
#[test]
fn dir_fmt_partials_only_still_formats() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_only.mds");
let output = fmt_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(0),
"fmt on a partials-only dir must still succeed; stderr: {stderr}"
);
assert!(
stderr.contains("1 unchanged"),
"stderr must show the fmt summary; got: {stderr:?}"
);
assert!(
!stderr.contains("nothing was formatted"),
"fmt must not treat a partials-only tree as nothing-to-do; got: {stderr:?}"
);
}
#[test]
fn dir_lint_partials_only_still_lints() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "_only.mds");
let output = lint_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(0),
"lint on a partials-only dir must still succeed; stderr: {stderr}"
);
assert!(
stderr.contains("1 clean"),
"stderr must show the lint summary; got: {stderr:?}"
);
assert!(
!stderr.contains("nothing was linted"),
"lint must not treat a partials-only tree as nothing-to-do; got: {stderr:?}"
);
}
#[test]
fn dir_build_quiet_suppresses_summary_on_success() {
let src1 = tempfile::tempdir().unwrap();
create_plain_mds(src1.path(), "a.mds");
create_plain_mds(src1.path(), "b.mds");
let quiet_out = build_dir(src1.path(), &["--quiet"]);
assert_eq!(
quiet_out.status.code(),
Some(0),
"quiet build over an all-success tree must exit 0; stderr: {}",
String::from_utf8_lossy(&quiet_out.stderr)
);
let quiet_stderr = String::from_utf8_lossy(&quiet_out.stderr);
assert!(
quiet_stderr.is_empty(),
"AC-Q01: --quiet build with no failures must produce empty stderr; got: {quiet_stderr:?}"
);
let src2 = tempfile::tempdir().unwrap();
create_plain_mds(src2.path(), "a.mds");
create_plain_mds(src2.path(), "b.mds");
let control_out = build_dir(src2.path(), &[]);
let control_stderr = String::from_utf8_lossy(&control_out.stderr);
assert!(
control_stderr.contains("2 built"),
"positive control: non-quiet run must print '2 built' so the quiet absence assertion \
is non-vacuous; got: {control_stderr:?}"
);
}
#[test]
fn dir_build_quiet_still_prints_summary_on_failure() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "good.mds");
create_bad_mds(src.path(), "bad.mds");
let output = build_dir(src.path(), &["--quiet"]);
assert_eq!(
output.status.code(),
Some(1),
"quiet build with a failing file must exit 1; stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("1 built"),
"AC-Q02: --quiet build with failures must print summary so non-zero exit is explained; \
got: {stderr:?}"
);
assert!(
stderr.contains("1 failed"),
"AC-Q02: summary must include '1 failed'; got: {stderr:?}"
);
}
#[test]
fn dir_build_quiet_works_in_pre_subcommand_position() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "a.mds");
create_plain_mds(src.path(), "b.mds");
let post = build_dir(src.path(), &["--quiet"]);
let pre = mds_bin()
.arg("--quiet")
.arg("build")
.arg(src.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
assert_eq!(
pre.status.code(),
post.status.code(),
"pre-subcommand --quiet must produce the same exit code as post-subcommand --quiet"
);
assert_eq!(
pre.stderr, post.stderr,
"pre-subcommand --quiet must produce the same stderr as post-subcommand --quiet"
);
assert!(
post.stderr.is_empty(),
"AC-Q30 anchor: an all-success tree under --quiet must produce empty stderr in \
BOTH orderings, not merely equal stderr; got: {}",
String::from_utf8_lossy(&post.stderr)
);
let control_src = tempfile::tempdir().unwrap();
create_plain_mds(control_src.path(), "a.mds");
create_plain_mds(control_src.path(), "b.mds");
let control = build_dir(control_src.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("2 built, 0 failed"),
"positive control: the same tree without --quiet must print '2 built, 0 failed'; got: {}",
String::from_utf8_lossy(&control.stderr)
);
}
fn create_defs_only_mds(dir: &Path, name: &str) {
fs::write(
dir.join(name),
"@define greet(name):\n Hi {{name}}\n@end\n\n@export greet\n",
)
.unwrap();
}
#[test]
fn d5_dir_build_summary_reports_empty_outputs() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "a.mds");
create_defs_only_mds(src.path(), "lib.mds");
let output = build_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"both files compile successfully; stderr: {stderr}"
);
let lib_out = src.path().join("lib.md");
assert_eq!(
fs::metadata(&lib_out).map(|m| m.len()).ok(),
Some(0),
"fixture invariant: lib.md must be a zero-byte output"
);
assert!(
stderr.contains("2 built (1 empty), 0 failed"),
"R5: summary must count zero-byte outputs; got: {stderr}"
);
}
#[test]
fn d5_dir_build_summary_omits_empty_clause_when_none() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "a.mds");
let output = build_dir(src.path(), &[]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("1 built, 0 failed"),
"summary keeps its historical form when no output is empty; got: {stderr}"
);
assert!(
!stderr.contains("empty"),
"R5: the empty clause must be ABSENT when every output has content \
(no golden churn); got: {stderr}"
);
}
#[test]
fn d5_dir_build_quiet_gate_unchanged_with_empty_outputs() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "a.mds");
create_defs_only_mds(src.path(), "lib.mds");
let output = build_dir(src.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "all-success run; stderr: {stderr}");
assert!(
!stderr.contains("built"),
"R5: --quiet must still suppress the summary on an all-success run even \
when empty outputs exist (gate unchanged); got: {stderr}"
);
}
fn temp_residue_recursive(dir: &Path) -> Vec<String> {
let mut found = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = fs::read_dir(&d) else { continue };
for entry in rd.flatten() {
let p = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with(".mds-tmp-") {
found.push(p.display().to_string());
}
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
stack.push(p);
}
}
}
found
}
#[test]
fn dir_build_out_dir_source_map_no_temp_residue() {
let src = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
for name in ["one.mds", "two.mds", "three.mds"] {
create_plain_mds(src.path(), name);
}
let output = build_dir(
src.path(),
&["--out-dir", out.path().to_str().unwrap(), "--source-map"],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"dir build with --source-map must succeed; stderr: {stderr}"
);
for stem in ["one", "two", "three"] {
let md = out.path().join(format!("{stem}.md"));
let map = out.path().join(format!("{stem}.md.map"));
assert!(md.is_file(), "{stem}.md must be written");
assert!(map.is_file(), "{stem}.md.map sidecar must be written");
}
let residue = temp_residue_recursive(out.path());
assert!(
residue.is_empty(),
"a successful dir build must leave no temp file; found: {residue:?}"
);
}
#[cfg(unix)]
#[test]
fn dir_build_write_failure_preserves_existing_outputs() {
use std::os::unix::fs::PermissionsExt as _;
let src = tempfile::tempdir().unwrap();
let root = tempfile::tempdir().unwrap();
let out = root.path().join("out");
fs::create_dir(&out).unwrap();
create_plain_mds(src.path(), "a.mds");
create_plain_mds(src.path(), "b.mds");
fs::write(out.join("a.md"), "OLD").unwrap();
fs::write(out.join("b.md"), "OLD").unwrap();
fs::set_permissions(&out, fs::Permissions::from_mode(0o555)).unwrap();
let output = build_dir(src.path(), &["--out-dir", out.to_str().unwrap()]);
let _ = fs::set_permissions(&out, fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(2),
"a dir build into a read-only output dir is an I/O failure, exit 2 (#157); \
stderr: {stderr}"
);
assert!(
stderr.contains("0 built, 2 failed"),
"the summary must report both failures; got: {stderr}"
);
assert!(
stderr.matches("mds::io").count() == 2,
"each failure must be reported as mds::io on stderr; got: {stderr}"
);
assert!(
stderr.contains("a.md"),
"the per-file error must name the artifact; got: {stderr}"
);
assert_eq!(
fs::read_to_string(out.join("a.md")).unwrap(),
"OLD",
"a.md must survive the failed write"
);
assert_eq!(
fs::read_to_string(out.join("b.md")).unwrap(),
"OLD",
"b.md must survive the failed write"
);
let residue = temp_residue_recursive(&out);
assert!(
residue.is_empty(),
"a failed dir build must leave no temp file; found: {residue:?}"
);
}
#[test]
fn dir_build_source_map_sidecar_symlink_target_rejected() {
let src = tempfile::tempdir().unwrap();
let root = tempfile::tempdir().unwrap();
let out = root.path().join("out");
fs::create_dir(&out).unwrap();
create_plain_mds(src.path(), "page.mds");
let real = root.path().join("real.map");
fs::write(&real, "OLD").unwrap();
if !make_symlink(&real, &out.join("page.md.map")) {
return;
}
let output = build_dir(
src.path(),
&["--out-dir", out.to_str().unwrap(), "--source-map"],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(2),
"a symlinked sidecar is a failed write, exit 2 (#157); stderr: {stderr}"
);
assert!(
out.join("page.md").is_file(),
"the compiled artifact is written before the sidecar and must survive"
);
assert!(
stderr.contains("symlink"),
"the refusal must say why; got: {stderr}"
);
assert!(
stderr.contains("1 failed"),
"the summary must report exactly one failure; got: {stderr}"
);
assert_eq!(
fs::read_to_string(&real).unwrap(),
"OLD",
"the symlink target must not be written through"
);
}
#[cfg(unix)]
#[test]
fn dir_build_with_a_template_error_and_a_failed_mkdir_exits_2() {
use std::os::unix::fs::PermissionsExt as _;
let src = tempfile::tempdir().unwrap();
create_bad_mds(src.path(), "a.mds");
create_plain_mds(src.path(), "c.mds");
fs::create_dir_all(src.path().join("sub/deep")).unwrap();
create_plain_mds(&src.path().join("sub/deep"), "b.mds");
let root = tempfile::tempdir().unwrap();
let out = root.path().join("out");
let control = build_dir(src.path(), &["--out-dir", out.to_str().unwrap()]);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert_eq!(
control.status.code(),
Some(1),
"control: a template error alone must exit 1; stderr: {control_stderr}"
);
assert!(
out.join("sub/deep/b.md").is_file() && out.join("c.md").is_file(),
"control: the files that compile must be built; stderr: {control_stderr}"
);
let root = tempfile::tempdir().unwrap();
let out = root.path().join("out");
let blocked = out.join("sub");
fs::create_dir_all(&blocked).unwrap();
fs::set_permissions(&blocked, fs::Permissions::from_mode(0o555)).unwrap();
if fs::create_dir(blocked.join("probe")).is_ok() {
let _ = fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755));
eprintln!("skipped: a directory can be created at mode 0o555 (running as root?)");
return;
}
let output = build_dir(src.path(), &["--out-dir", out.to_str().unwrap()]);
let _ = fs::set_permissions(&blocked, fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(2),
"a template error plus a failed mkdir must exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("mds::io") && stderr.contains("cannot write"),
"the mkdir failure must be reported as mds::io; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 2 failed"),
"the summary must count the template error and the mkdir failure; stderr: {stderr}"
);
assert!(
out.join("c.md").is_file(),
"the file whose directory exists must still be built"
);
}
#[cfg(unix)]
#[test]
fn dir_build_stale_json_that_cannot_be_read_exits_2() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/x.mds", MARKDOWN);
put(root, "out/x.json", MESSAGES_OUTPUT);
let control = build_src_into_out(root, &[]);
assert_eq!(
control.status.code(),
Some(0),
"control: stderr: {}",
String::from_utf8_lossy(&control.stderr)
);
assert_eq!(
read(root, "out/x.json"),
None,
"control: the stale x.json is removed"
);
put(root, "out/x.json", MESSAGES_OUTPUT);
let stale = root.join("out/x.json");
fs::set_permissions(&stale, fs::Permissions::from_mode(0o000)).unwrap();
if fs::read(&stale).is_ok() {
fs::set_permissions(&stale, fs::Permissions::from_mode(0o644)).unwrap();
eprintln!("skipped: x.json is readable at mode 0o000 (running as root?)");
return;
}
let output = build_src_into_out(root, &[]);
fs::set_permissions(&stale, fs::Permissions::from_mode(0o644)).unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
let squash = |text: &str| text.split_whitespace().collect::<String>();
let error = format!(
"cannot read stale output {}: {}",
Path::new("out").join("x.json").display(),
std::io::Error::from_raw_os_error(libc::EACCES)
);
assert!(
stderr.contains("mds::io") && squash(&stderr).contains(&squash(&error)),
"{error:?} as mds::io; stderr: {stderr}"
);
assert_eq!(
read(root, "out/x.md").as_deref(),
Some(MARKDOWN),
"the output itself is still written"
);
assert_eq!(
read(root, "out/x.json").as_deref(),
Some(MESSAGES_OUTPUT),
"the stale x.json is left"
);
}
#[cfg(windows)]
#[test]
fn dir_build_stale_json_that_cannot_be_removed_exits_2_on_windows() {
use std::os::windows::fs::OpenOptionsExt as _;
const FILE_SHARE_READ: u32 = 0x1;
const ERROR_SHARING_VIOLATION: i32 = 32;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
put(root, "src/x.mds", MESSAGES);
let first = build_src_into_out(root, &[]);
assert_eq!(
first.status.code(),
Some(0),
"stderr: {}",
String::from_utf8_lossy(&first.stderr)
);
assert_eq!(read(root, "out/x.json").as_deref(), Some(MESSAGES_OUTPUT));
put(root, "src/x.mds", MARKDOWN);
let held = fs::OpenOptions::new()
.read(true)
.share_mode(FILE_SHARE_READ)
.open(root.join("out").join("x.json"))
.unwrap();
let output = build_src_into_out(root, &[]);
drop(held);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
let squash = |text: &str| -> String {
text.chars()
.filter(|c| !c.is_whitespace() && *c != '\u{2502}')
.collect()
};
let error = format!(
"could not remove stale output {}: {}",
Path::new("out").join("x.json").display(),
std::io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)
);
assert!(
stderr.contains("mds::io") && squash(&stderr).contains(&squash(&error)),
"{error:?} as mds::io; stderr: {stderr}"
);
assert_eq!(
read(root, "out/x.md").as_deref(),
Some(MARKDOWN),
"the output itself is still written"
);
assert_eq!(
read(root, "out/x.json").as_deref(),
Some(MESSAGES_OUTPUT),
"the stale x.json is left"
);
let control = build_src_into_out(root, &[]);
assert_eq!(
control.status.code(),
Some(0),
"control: stderr: {}",
String::from_utf8_lossy(&control.stderr)
);
assert_eq!(
read(root, "out/x.json"),
None,
"control: the stale x.json is removed"
);
}
#[cfg(unix)]
#[test]
fn build_non_utf8_path_exits_2_and_writes_no_map() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let control = tempfile::tempdir().unwrap();
create_plain_mds(control.path(), "ok.mds");
let control_out = build_file(&control.path().join("ok.mds"), &["--source-map"]);
let control_stderr = String::from_utf8_lossy(&control_out.stderr);
assert_eq!(
control_out.status.code(),
Some(0),
"control: a normally named source must build; stderr: {control_stderr}"
);
let map_path = control.path().join("ok.md.map");
assert!(
map_path.is_file(),
"control: --source-map must write a sidecar, or the hostile arm's \
'no .map' assertion proves nothing"
);
let map: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&map_path).unwrap()).expect("sidecar is JSON");
let sources: Vec<&str> = map["sources"]
.as_array()
.expect("sources must be an array")
.iter()
.filter_map(|s| s.as_str())
.collect();
assert_eq!(
sources,
vec!["ok.mds"],
"control: the sidecar must name the source it was built from"
);
let dir = tempfile::tempdir().unwrap();
let raw: Vec<u8> = vec![0xff, 0xfe, b'.', b'm', b'd', b's'];
let hostile = dir.path().join(OsString::from_vec(raw));
if fs::write(&hostile, "Hello, world!\n").is_err() {
#[cfg(not(target_os = "macos"))]
panic!(
"build_non_utf8_path_exits_2_and_writes_no_map: a non-UTF-8 filename was \
rejected by the filesystem — unexpected on this platform"
);
#[cfg(target_os = "macos")]
return;
}
let output = build_file(&hostile, &["--source-map"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(2),
"#217: a path that cannot be named must be an I/O failure; stderr: {stderr}"
);
assert!(
stderr.contains("not valid UTF-8"),
"the diagnostic must say why; got: {stderr}"
);
let names: Vec<String> = fs::read_dir(dir.path())
.unwrap()
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(
names.len(),
1,
"neither an output nor a sidecar may be written for a rejected path; got {names:?}"
);
}
#[test]
fn dir_build_symlinked_ancestor_root_mirrors_without_warning() {
let tmp = tempfile::tempdir().unwrap();
let real_src = tmp.path().join("real").join("src");
fs::create_dir_all(real_src.join("sub")).unwrap();
create_plain_mds(&real_src, "a.mds");
create_plain_mds(&real_src.join("sub"), "b.mds");
if !make_symlink(&tmp.path().join("real"), &tmp.path().join("link")) {
return;
}
let out = tempfile::tempdir().unwrap();
let output = build_dir(
&tmp.path().join("link").join("src"),
&["--out-dir", out.path().to_str().unwrap()],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(0),
"a root under a symlinked ancestor must build; stderr: {stderr}"
);
assert!(
out.path().join("a.md").is_file(),
"top-level source must mirror into the out-dir; stderr: {stderr}"
);
assert!(
out.path().join("sub").join("b.md").is_file(),
"the subtree must be preserved, not flattened; stderr: {stderr}"
);
assert!(
stderr.contains("2 built, 0 failed"),
"control needle: the real summary must be present, or the negative assertion \
below would pass on empty stderr; got: {stderr}"
);
assert!(
!stderr.contains("is outside the build root"),
"a mirrored build must not report the out-of-root flatten; got: {stderr}"
);
}
#[test]
fn dir_build_dotdot_root_mirrors_without_warning() {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir_all(tmp.path().join("sub")).unwrap();
let src = tmp.path().join("src");
fs::create_dir_all(src.join("nested")).unwrap();
create_plain_mds(&src, "a.mds");
create_plain_mds(&src.join("nested"), "b.mds");
let out = tempfile::tempdir().unwrap();
let output = build_dir(
&tmp.path().join("sub").join("..").join("src"),
&["--out-dir", out.path().to_str().unwrap()],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(0),
"a root with a '..' component must build; stderr: {stderr}"
);
assert!(
out.path().join("a.md").is_file(),
"top-level source must mirror into the out-dir; stderr: {stderr}"
);
assert!(
out.path().join("nested").join("b.md").is_file(),
"the subtree must be preserved, not flattened; stderr: {stderr}"
);
assert!(
stderr.contains("2 built, 0 failed"),
"control needle: the real summary must be present, or the negative assertion \
below would pass on empty stderr; got: {stderr}"
);
assert!(
!stderr.contains("is outside the build root"),
"a mirrored build must not report the out-of-root flatten; got: {stderr}"
);
}
#[cfg(windows)]
#[test]
fn dir_build_out_dir_status_line_has_no_verbatim_prefix_on_windows() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "plain.mds");
let out = tempfile::tempdir().unwrap();
assert!(
out.path()
.canonicalize()
.unwrap()
.to_string_lossy()
.starts_with(r"\\?\"),
"test assumption: canonicalize must yield a verbatim path on Windows"
);
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"dir build should succeed; stderr: {stderr}"
);
let expected_line = format!("Compiled to {}\n", out.path().join("plain.md").display());
assert!(
stderr.contains(&expected_line),
"expected the out-dir as typed, {expected_line:?}; got: {stderr}"
);
assert!(
!stdout.contains(r"\\?\"),
"stdout must not contain the Windows verbatim prefix; got: {stdout}"
);
assert!(
!stderr.contains(r"\\?\"),
"stderr must not contain the Windows verbatim prefix; got: {stderr}"
);
}
#[test]
fn dir_build_out_dir_status_line_names_the_out_dir_as_typed() {
let src = tempfile::tempdir().unwrap();
create_plain_mds(src.path(), "plain.mds");
let out = tempfile::tempdir().unwrap();
let output = build_dir(src.path(), &["--out-dir", out.path().to_str().unwrap()]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success(),
"dir build should succeed; stderr: {stderr}"
);
let typed = out.path().join("plain.md");
let expected_line = format!("Compiled to {}\n", typed.display());
assert!(
stderr.contains(&expected_line),
"expected the out-dir as typed, {expected_line:?}; got: {stderr}"
);
let canonical = out.path().canonicalize().unwrap().join("plain.md");
if canonical != typed {
assert!(
!stderr.contains(&format!("Compiled to {}", canonical.display())),
"never the canonical out-dir {canonical:?}; got: {stderr}"
);
}
}
const MODULE: &str = "---\ntype: mds\nname: X\n---\nHi {{name}}\n";
fn build_in(dir: &Path, args: &[&str]) -> (Option<i32>, String) {
let out = mds_bin()
.current_dir(dir)
.arg("build")
.args(args)
.stdin(std::process::Stdio::null())
.output()
.unwrap();
(
out.status.code(),
String::from_utf8_lossy(&out.stderr).into_owned(),
)
}
fn refuses(stderr: &str, shown: &Path, cause: &str) -> bool {
let squash = |text: &str| -> String {
text.chars()
.filter(|c| !c.is_whitespace() && *c != '\u{2502}')
.collect()
};
stderr.contains("mds::io")
&& squash(stderr).contains(&squash(&format!(
"cannot write {}: {cause}",
shown.display()
)))
}
#[test]
fn dir_build_never_writes_over_an_mds_module() {
for out_dir in [None, Some("out")] {
let label = format!("out-dir {out_dir:?}");
let base = tempfile::tempdir().unwrap();
let src = base.path().join("src");
fs::create_dir(&src).unwrap();
fs::write(src.join("a.mds"), "Hello A\n").unwrap();
fs::write(src.join("b.mds"), "Hello B\n").unwrap();
let outputs = match out_dir {
Some(out) => base.path().join(out),
None => src.clone(),
};
fs::create_dir_all(&outputs).unwrap();
fs::write(outputs.join("a.md"), MODULE).unwrap();
fs::write(outputs.join("b.md"), "old b\n").unwrap();
let shown = Path::new(out_dir.unwrap_or("src"));
let mut args = vec!["src"];
args.extend(out_dir.iter().flat_map(|out| ["--out-dir", out]));
let (code, stderr) = build_in(base.path(), &args);
assert_eq!(code, Some(2), "{label}: stderr: {stderr}");
assert!(
refuses(
&stderr,
&shown.join("a.md"),
"refusing to replace an MDS module"
),
"{label}: the module is refused by name; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(outputs.join("a.md")).unwrap(),
MODULE,
"{label}: the module is kept; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(outputs.join("b.md")).unwrap(),
"Hello B\n",
"{label}: control: the plain b.md is written over; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 1 failed"),
"{label}: the build goes on with the other source; stderr: {stderr}"
);
}
}
#[test]
fn dir_build_writes_a_module_output_over_a_module_but_never_over_its_import() {
const LIB: &str = "---\ntype: mds\n---\nShared\n";
let base = tempfile::tempdir().unwrap();
let src = base.path().join("src");
fs::create_dir(&src).unwrap();
fs::write(
base.path().join("v.json"),
r#"{"fm":"---\ntype: mds\n---"}"#,
)
.unwrap();
fs::write(src.join("gen.mds"), "{{fm}}\nBody\n").unwrap();
fs::write(src.join("gen.md"), MODULE).unwrap();
fs::write(
src.join("lib.mds"),
"@import \"./lib.md\" as l\n{{fm}}\nLib\n",
)
.unwrap();
fs::write(src.join("lib.md"), LIB).unwrap();
let (code, stderr) = build_in(base.path(), &["src", "--vars", "v.json"]);
assert_eq!(code, Some(2), "stderr: {stderr}");
assert_eq!(
fs::read_to_string(src.join("gen.md")).unwrap(),
"---\ntype: mds\n---\nBody\n",
"a module output replaces the module; stderr: {stderr}"
);
assert!(
refuses(
&stderr,
&Path::new("src").join("lib.md"),
"refusing to replace a file this run reads"
),
"the imported module is refused by name; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(src.join("lib.md")).unwrap(),
LIB,
"the imported module is left as it was; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 1 failed"),
"the build goes on with the other source; stderr: {stderr}"
);
}
#[test]
fn dir_build_regenerates_a_module_another_source_imports() {
let base = tempfile::tempdir().unwrap();
let src = base.path().join("src");
fs::create_dir(&src).unwrap();
fs::write(
base.path().join("v.json"),
r#"{"fm":"---\ntype: mds\n---"}"#,
)
.unwrap();
fs::write(src.join("gen.mds"), "{{fm}}\nGenerated\n").unwrap();
fs::write(src.join("gen.md"), MODULE).unwrap();
fs::write(src.join("user.mds"), "@import \"./gen.md\" as g\nUser\n").unwrap();
let (code, report) = build_in(base.path(), &["src", "--vars", "v.json"]);
assert!(
!report.contains("refusing to replace a file this run reads"),
"another source's import does not refuse the generator's write: {report}"
);
assert_eq!(code, Some(0), "report: {report}");
assert_eq!(
fs::read_to_string(src.join("gen.md")).unwrap(),
"---\ntype: mds\n---\nGenerated\n",
"the generator replaces the hand-written module; report: {report}"
);
assert_eq!(
fs::read_to_string(src.join("user.md")).unwrap(),
"User\n",
"the consumer writes its output; report: {report}"
);
}
#[test]
fn dir_build_never_writes_over_a_nested_mds_json() {
let fixture = |nested: Option<&str>| {
let base = tempfile::tempdir().unwrap();
let sub = base.path().join("sub");
fs::create_dir(&sub).unwrap();
fs::write(base.path().join("mds.json"), "{}\n").unwrap();
fs::write(sub.join("mds.mds"), "@message user:\nSub\n@end\n").unwrap();
fs::write(base.path().join("doc.mds"), "Doc\n").unwrap();
if let Some(nested) = nested {
fs::write(sub.join("mds.json"), nested).unwrap();
}
base
};
let shown = Path::new(".").join("sub").join("mds.json");
for nested in ["{\"build\":{}}\n", "{ not json\n"] {
let base = fixture(Some(nested));
let (code, stderr) = build_in(base.path(), &["."]);
assert_eq!(code, Some(2), "{nested:?}: stderr: {stderr}");
assert!(
refuses(&stderr, &shown, "refusing to replace a file this run reads"),
"{nested:?}: the nested mds.json is refused by name; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(base.path().join("sub").join("mds.json")).unwrap(),
nested,
"{nested:?}: the nested mds.json is left as it was; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(base.path().join("doc.md")).unwrap(),
"Doc\n",
"{nested:?}: the build goes on with doc.mds; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 1 failed") && !stderr.contains("invalid mds.json"),
"{nested:?}: one failure, and the nested mds.json is not read; stderr: {stderr}"
);
}
let base = fixture(Some("{\"build\":{}}\n"));
let (code, stderr) = build_in(base.path(), &["sub/mds.mds"]);
assert_eq!(code, Some(2), "file mode: stderr: {stderr}");
assert!(
refuses(
&stderr,
&Path::new("sub").join("mds.json"),
"refusing to replace a file this run reads"
),
"file mode refuses it the same way; stderr: {stderr}"
);
let base = fixture(None);
let (code, stderr) = build_in(base.path(), &["."]);
assert_eq!(code, Some(0), "control: stderr: {stderr}");
assert!(
fs::read_to_string(base.path().join("sub").join("mds.json"))
.unwrap()
.contains("Sub"),
"control: with no nested mds.json, the output is written; stderr: {stderr}"
);
}
#[test]
fn dir_build_never_writes_over_a_file_it_reads() {
const VARS: &str = "{\"name\": \"Dean\"}\n";
const CONFIG: &str = "{\"build\":{\"source_map\":false}}\n";
let legs: [(&str, &[&str]); 2] = [
("src", &["--vars", "src/chat.json"]),
(".", &["--out-dir", ".", "--vars", "chat.json"]),
];
for (outputs, extra) in legs {
let base = tempfile::tempdir().unwrap();
let src = base.path().join("src");
fs::create_dir(&src).unwrap();
fs::write(src.join("chat.mds"), "@message user:\nHi {{name}}\n@end\n").unwrap();
fs::write(src.join("mds.mds"), "@message user:\nHello\n@end\n").unwrap();
fs::write(src.join("b.mds"), "Hello B\n").unwrap();
let at = base.path().join(outputs);
fs::write(at.join("chat.json"), VARS).unwrap();
fs::write(at.join("mds.json"), CONFIG).unwrap();
let shown = Path::new(outputs);
let mut args = vec!["src"];
args.extend(extra);
let (code, stderr) = build_in(base.path(), &args);
assert_eq!(code, Some(2), "{args:?}: stderr: {stderr}");
for (name, was) in [("chat.json", VARS), ("mds.json", CONFIG)] {
assert!(
refuses(
&stderr,
&shown.join(name),
"refusing to replace a file this run reads"
),
"{args:?}: {name} is refused by name; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(at.join(name)).unwrap(),
was,
"{args:?}: {name} is left as it was; stderr: {stderr}"
);
}
assert_eq!(
fs::read_to_string(at.join("b.md")).unwrap(),
"Hello B\n",
"{args:?}: control: b.md is written; stderr: {stderr}"
);
assert!(
stderr.contains("1 built, 2 failed"),
"{args:?}: the build goes on with the other source; stderr: {stderr}"
);
}
}