mod common;
use common::{assert_no_control_chars, fixture, mds_bin};
use std::fs;
use std::path::Path;
fn lint_path(path: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.arg("lint")
.arg(path)
.args(extra_args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
fn lint_stdin(input: &str, extra_args: &[&str]) -> std::process::Output {
use std::io::Write;
let mut child = mds_bin()
.arg("lint")
.args(extra_args)
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(input.as_bytes());
child.wait_with_output().unwrap()
}
#[cfg(unix)]
fn lint_refuses_replacement_after_walk(extra: &[&str]) {
let dir = tempfile::tempdir().unwrap();
let page = dir.path().join("page.mds");
let replacement =
"---\nunused_after_walk: 1\n---\n@if \"x\" == \"x\":\nHello\n@else:\nRemoved\n@end\n";
fs::write(&page, "Original\n").unwrap();
fs::write(dir.path().join("good.mds"), "Good\n").unwrap();
let out = common::run_after_walk(mds_bin().arg("lint").arg(dir.path()).args(extra), || {
fs::rename(&page, dir.path().join("saved.txt")).unwrap();
fs::write(&page, replacement).unwrap();
});
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(out.status.code(), Some(2), "{stderr}\n{stdout}");
assert!(
stderr.contains("1 clean, 0 with warnings, 1 with errors"),
"{stderr}"
);
assert!(!stderr.contains("unused_after_walk"), "{stderr}");
assert!(!stdout.contains("unused_after_walk"), "{stdout}");
assert!(!stdout.contains("--- page.mds"), "{stdout}");
if extra.contains(&"json") {
let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(json["files"].as_array().unwrap().len(), 1, "{json}");
assert_eq!(json["files"][0]["error"]["code"], "mds::io", "{json}");
assert!(
json["files"][0]["error"]["message"]
.as_str()
.unwrap()
.contains("file changed"),
"{json}"
);
} else {
assert!(
stderr.contains("mds::io") && stderr.contains("file changed"),
"{stderr}"
);
assert!(out.stdout.is_empty(), "{stdout}");
}
assert_eq!(fs::read_to_string(page).unwrap(), replacement);
}
#[test]
#[cfg(unix)]
fn dir_lint_refuses_a_file_replaced_after_walk() {
lint_refuses_replacement_after_walk(&[]);
}
#[test]
#[cfg(unix)]
fn dir_lint_json_refuses_a_file_replaced_after_walk() {
lint_refuses_replacement_after_walk(&["--format", "json"]);
}
#[test]
#[cfg(unix)]
fn dir_lint_fix_refuses_a_file_replaced_after_walk() {
lint_refuses_replacement_after_walk(&["--fix", "--format", "json"]);
}
#[test]
#[cfg(unix)]
fn dir_lint_fix_diff_refuses_a_file_replaced_after_walk() {
lint_refuses_replacement_after_walk(&["--fix", "--diff"]);
}
#[test]
fn dir_lint_refuses_a_parent_redirected_after_walk() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
let moved = dir.path().join("moved");
fs::create_dir(&sub).unwrap();
fs::write(
sub.join("page.mds"),
"---\nunused_after_walk: 1\n---\nHello\n",
)
.unwrap();
if !common::make_symlink(&sub, &dir.path().join("probe")) {
return;
}
let out = common::run_after_walk(mds_bin().arg("lint").arg(dir.path()), || {
fs::rename(&sub, &moved).unwrap();
assert!(common::make_symlink(&moved, &sub));
});
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains("mds::io") && stderr.contains("file changed"),
"{stderr}"
);
assert!(
stderr.contains("0 clean, 0 with warnings, 1 with errors"),
"{stderr}"
);
assert!(!stderr.contains("unused_after_walk"), "{stderr}");
assert!(out.stdout.is_empty());
}
#[test]
fn dir_lint_accepts_an_unchanged_tree_after_walk() {
for extra in [
&[][..],
&["--format", "json"][..],
&["--fix", "--format", "json"][..],
] {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join("sub")).unwrap();
fs::write(
dir.path().join("sub/page.mds"),
"---\nunused_after_walk: 1\n---\nHello\n",
)
.unwrap();
let out = common::run_after_walk(mds_bin().arg("lint").arg(dir.path()).args(extra), || {});
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(out.status.code(), Some(1), "{stderr}\n{stdout}");
assert!(
stderr.contains("0 clean, 1 with warnings, 0 with errors"),
"{stderr}"
);
if extra.contains(&"json") {
let json: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(json["files"][0]["file"], "sub/page.mds");
assert_eq!(
json["files"][0]["diagnostics"][0]["rule"], "unused-variable",
"{json}"
);
} else {
assert!(stderr.contains("unused_after_walk"), "{stderr}");
assert!(out.stdout.is_empty());
}
}
}
#[test]
fn clean_file_exits_0_with_empty_stdout() {
let out = lint_path(&fixture("lint_clean.mds"), &[]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"clean file should exit 0; stderr: {stderr}"
);
assert!(
stdout.is_empty(),
"human mode must not write to stdout; got: {stdout}"
);
}
#[test]
fn warn_only_file_exits_1_with_diagnostic_on_stderr() {
let out = lint_path(&fixture("lint_warn_only.mds"), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(
out.status.code(),
Some(1),
"warn-only file should exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("unused-variable"),
"expected unused-variable diagnostic on stderr; got: {stderr}"
);
assert!(
stdout.is_empty(),
"human mode must not write to stdout; got: {stdout}"
);
}
#[test]
fn span_source_context_appears_in_human_render() {
let out = lint_path(&fixture("lint_warn_only.mds"), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("unused_key"),
"expected span context with 'unused_key' source text in miette render; got: {stderr}"
);
assert!(
stderr.contains("lint_warn_only.mds"),
"expected filename reference in miette span render; got: {stderr}"
);
}
#[test]
fn error_file_exits_2_with_error_diagnostic_on_stderr() {
let out = lint_path(&fixture("lint_error.mds"), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(
out.status.code(),
Some(2),
"error-severity finding should exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("duplicate-export"),
"expected duplicate-export error on stderr; got: {stderr}"
);
assert!(
stdout.is_empty(),
"human mode must not write to stdout; got: {stdout}"
);
}
#[test]
fn analysis_gate_failure_exits_2_not_lint_codes() {
let out = lint_path(&fixture("lint_gate_fail.mds"), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"gate failure (file not found) should exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("file not found") || stderr.contains("lint_nonexistent"),
"expected file-not-found error on stderr; got: {stderr}"
);
}
#[test]
fn json_format_clean_file_exits_0_with_json_to_stdout() {
let out = lint_path(&fixture("lint_clean.mds"), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"clean file --format json should exit 0; stderr: {stderr}"
);
let json: serde_json::Value =
serde_json::from_str(&stdout).expect("stdout should be valid JSON");
assert_eq!(json["version"], 1, "version must be 1");
assert!(json["files"].is_array(), "must have files array");
assert!(
stderr.is_empty(),
"JSON mode must not write to stderr when clean; got: {stderr}"
);
}
#[test]
fn json_format_warn_file_exits_1_with_diagnostic_json() {
let out = lint_path(&fixture("lint_warn_only.mds"), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"warn-only --format json should exit 1; stderr: {stderr}"
);
let json: serde_json::Value =
serde_json::from_str(&stdout).expect("stdout should be valid JSON");
assert_eq!(json["version"], 1);
let files = json["files"].as_array().expect("files must be array");
assert!(!files.is_empty(), "files must be non-empty");
let diags = files[0]["diagnostics"].as_array().unwrap();
assert!(!diags.is_empty(), "diagnostics must be non-empty");
assert_eq!(diags[0]["rule"], "unused-variable");
assert_eq!(diags[0]["severity"], "warn");
assert_eq!(diags[0]["fixable"], false);
assert!(
stderr.is_empty(),
"JSON mode must not write diagnostics to stderr; got: {stderr}"
);
}
#[test]
fn json_format_gate_failure_exits_2_with_error_envelope_to_stdout() {
let out = lint_path(&fixture("lint_gate_fail.mds"), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(
out.status.code(),
Some(2),
"gate failure --format json should exit 2"
);
let json: serde_json::Value =
serde_json::from_str(&stdout).expect("stdout should be valid JSON error envelope");
assert_eq!(json["version"], 1);
assert!(
json["error"].is_object(),
"error envelope must have 'error' key"
);
assert!(
!stdout.contains("help:"),
"human rendering must not appear in JSON stdout"
);
}
#[test]
fn fix_applies_auto_fixable_issues_in_place() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_error.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
assert!(
original.contains("@export greet\n@export greet"),
"fixture must have duplicate export"
);
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"--fix should exit 0 after fixing duplicate-export; stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert!(
!after.contains("@export greet\n@export greet"),
"duplicate export should be removed after --fix; got:\n{after}"
);
assert_eq!(
after.matches("@export greet").count(),
1,
"exactly one @export greet should remain; got:\n{after}"
);
}
#[test]
fn fix_check_exits_1_when_fixes_pending_and_never_writes() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_error.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check should exit 1 when fixes are pending; stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_eq!(original, after, "--fix --check must not write to the file");
}
#[test]
fn stdin_mode_report_only_sends_diagnostics_to_stderr() {
let source = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
let out = lint_stdin(source, &[]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"duplicate-export from stdin should exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("duplicate-export"),
"diagnostic must appear on stderr; got: {stderr}"
);
assert!(
stdout.is_empty(),
"stdin report-only mode must not write to stdout; got: {stdout}"
);
}
#[test]
fn stdin_lint_with_root_cwd_succeeds() {
let out = mds_bin()
.arg("lint")
.arg("-")
.current_dir("/")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.and_then(|mut child| {
use std::io::Write;
let _ = child.stdin.take().unwrap().write_all(b"Hello World!\n");
child.wait_with_output()
})
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
out.status.success(),
"lint stdin with cwd=/ should exit 0 for clean input; stderr: {stderr}"
);
}
#[cfg(windows)]
#[test]
fn windows_lint_and_fmt_at_real_drive_root() {
use std::process::Command;
struct SubstGuard(char);
impl Drop for SubstGuard {
fn drop(&mut self) {
let _ = Command::new("subst")
.args([&format!("{}:", self.0), "/D"])
.output();
}
}
let letter = ('A'..='Z')
.rev()
.find(|c| !std::path::Path::new(&format!("{c}:\\")).exists())
.expect("at least one free drive letter must exist");
let dir = tempfile::tempdir().unwrap();
let status = Command::new("subst")
.args([&format!("{letter}:"), dir.path().to_str().unwrap()])
.status()
.expect("subst must be available on Windows");
assert!(status.success(), "subst must succeed to map a drive root");
let _guard = SubstGuard(letter);
let file_path = format!("{letter}:\\root.mds");
std::fs::write(&file_path, "Hello \r\n\r\n\r\nworld\r\n").unwrap();
let lint_output = mds_bin()
.args(["lint", &file_path])
.output()
.expect("run mds lint");
assert!(
lint_output.status.success(),
"lint at a real drive root should succeed; stderr: {}",
String::from_utf8_lossy(&lint_output.stderr)
);
let fmt_output = mds_bin()
.args(["fmt", &file_path])
.output()
.expect("run mds fmt");
assert!(
fmt_output.status.success(),
"fmt at a real drive root should succeed; stderr: {}",
String::from_utf8_lossy(&fmt_output.stderr)
);
let formatted = std::fs::read_to_string(&file_path).unwrap();
assert_eq!(
formatted, "Hello \n\n\nworld\n",
"fmt at a real drive root must apply R1/R2 exactly like anywhere else"
);
}
#[test]
fn stdin_fix_mode_writes_fixed_source_to_stdout() {
let source = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
let out = lint_stdin(source, &["--fix"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"--fix stdin should exit 0 after fixing; stderr: {stderr}"
);
assert!(
stdout.contains("@export greet"),
"fixed source must appear on stdout; got: {stdout}"
);
assert_eq!(
stdout.matches("@export greet").count(),
1,
"exactly one @export should remain in fixed source; got: {stdout}"
);
drop(stderr);
}
#[test]
fn set_var_passes_runtime_variable_to_gate_check() {
let out_no_var = lint_path(&fixture("lint_var_required.mds"), &[]);
assert_eq!(
out_no_var.status.code(),
Some(2),
"missing required_var should exit 2 (gate failure)"
);
let out_with_var = lint_path(
&fixture("lint_var_required.mds"),
&["--set", "required_var=foo"],
);
let stderr = String::from_utf8_lossy(&out_with_var.stderr);
assert_eq!(
out_with_var.status.code(),
Some(1),
"with required_var set, should exit 1 (unused_key warning); stderr: {stderr}"
);
assert!(
stderr.contains("unused-variable"),
"unused_key should be flagged; got: {stderr}"
);
}
#[test]
fn quiet_flag_suppresses_warnings_on_warn_only_file() {
let out = lint_path(&fixture("lint_warn_only.mds"), &["--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(
out.status.code(),
Some(1),
"--quiet warn-only should still exit 1; stderr: {stderr}"
);
assert!(
!stderr.contains("unused-variable"),
"--quiet should suppress warning diagnostic; got: {stderr}"
);
assert!(
stdout.is_empty(),
"stdout must remain empty with --quiet; got: {stdout}"
);
}
#[test]
fn directory_mode_lints_all_files_including_partials() {
let dir = tempfile::tempdir().unwrap();
for name in &["lint_clean.mds", "lint_warn_only.mds", "_lint_partial.mds"] {
fs::copy(fixture(name), dir.path().join(name)).unwrap();
}
let out = lint_path(dir.path(), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"directory with warn-only file should exit 1; stderr: {stderr}"
);
assert!(
stderr.contains("unused-variable"),
"unused-variable warning should appear in directory mode; got: {stderr}"
);
}
#[test]
fn fix_json_stdin_is_usage_error_exit_2() {
let out = lint_stdin("Hello {{name}}!", &["--fix", "--format", "json"]);
assert_eq!(
json_exit(&out),
JsonExit::error(2, "mds::io"),
"--fix --format json stdin must exit 2 with the error document"
);
assert_eq!(error_message(&out).as_deref(), Some(STDIN_FIX_JSON_REFUSAL));
}
#[test]
fn json_format_nonexistent_path_emits_error_envelope() {
let out = lint_path(
Path::new("/nonexistent_mds_lint_test_12345.mds"),
&["--format", "json"],
);
assert_eq!(
out.status.code(),
Some(2),
"--format json + nonexistent path must exit 2"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!("stdout must be valid JSON (error envelope); parse error: {e}; stdout: {stdout}")
});
assert_eq!(
parsed["version"].as_u64(),
Some(1),
"envelope must have version:1; got: {parsed}"
);
let code = parsed["error"]["code"]
.as_str()
.unwrap_or_else(|| panic!("error.code must be a string; got: {parsed}"));
assert_eq!(
code, "mds::file_not_found",
"error code must be mds::file_not_found; got: {code}"
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("mds::file_not_found"),
"JSON mode must not print error to stderr; got stderr: {stderr}"
);
}
#[test]
fn lint_nonexistent_non_mds_reports_file_not_found_not_extension_error() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing_12345.txt");
let out = lint_path(&missing, &[]);
assert_eq!(
out.status.code(),
Some(2),
"non-existent .txt file must exit 2; got: {:?}",
out.status.code()
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("mds::file_not_found") && stderr.contains("file not found"),
"error must be file-not-found (not extension error); got: {stderr:?}"
);
assert!(
!stderr.contains("mds::not_mds") && !stderr.contains("not an MDS file"),
"must NOT report 'not an MDS file' for a non-existent path; got: {stderr:?}"
);
std::fs::write(&missing, "Hello!\n").unwrap();
let out = lint_path(&missing, &[]);
assert_eq!(
out.status.code(),
Some(2),
"control: an existing .txt exits 2"
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("mds::not_mds") && stderr.contains("not an MDS file"),
"control: an existing .txt is mds::not_mds; got: {stderr:?}"
);
}
#[test]
fn lint_nonexistent_non_mds_json_mode_reports_file_not_found() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing_12345.txt");
let envelope_code = |label: &str| {
let out = lint_path(&missing, &["--format", "json"]);
assert_eq!(
out.status.code(),
Some(2),
"{label}: --format json must exit 2"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!("{label}: stdout must be valid JSON (error envelope); parse error: {e}; stdout: {stdout}")
});
parsed["error"]["code"]
.as_str()
.unwrap_or_else(|| panic!("{label}: error.code must be a string; got: {parsed}"))
.to_string()
};
assert_eq!(
envelope_code("missing"),
"mds::file_not_found",
"JSON envelope code must be mds::file_not_found (not mds::not_mds)"
);
std::fs::write(&missing, "Hello!\n").unwrap();
assert_eq!(
envelope_code("control"),
"mds::not_mds",
"control: an existing .txt is mds::not_mds"
);
}
#[test]
fn fix_applied_for_block_spanning_empty_define_and_file_changed() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_block_span_empty.mds");
fs::copy(fixture("lint_block_span_empty.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
assert!(
original.contains("@define empty_fn():"),
"fixture must contain the multi-line empty @define"
);
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("fix rejected"),
"block-spanning empty-block fix must now succeed; got stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(0),
"exit code must be 0 after successful empty-block fix; got stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_ne!(
original, after,
"file must be changed when --fix succeeds for empty-block"
);
assert!(
!after.contains("@define empty_fn():"),
"fixed file must not contain the removed @define; got: {after:?}"
);
}
#[test]
fn fix_removes_an_empty_in_fence_if_and_preserves_the_other_bytes() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("marked.mds");
fs::write(
&target,
"```js +mds\r\n @if 1 == 1: \t\r\n\t@end\r\n keep\r\n```\r\n",
)
.unwrap();
let (json, _) = lint_json(&target, "before fix");
let findings = json_diagnostics(&json, "before fix");
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0]["rule"], "empty-block");
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert_eq!(out.status.code(), Some(0), "{stderr}");
assert!(stderr.contains("Fixed:"), "{stderr}");
assert_eq!(
fs::read(&target).unwrap(),
b"```js +mds\r\n keep\r\n```\r\n"
);
}
#[test]
fn fix_removes_an_indented_empty_if_and_preserves_the_other_bytes() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("indented.mds");
let frontmatter = "---\r\nindented-directives: true\r\n---\r\n";
fs::write(
&target,
format!("{frontmatter} @if 1 == 1: \t\r\n\t@end \t\r\n keep\r\n"),
)
.unwrap();
let (json, _) = lint_json(&target, "before fix");
let findings = json_diagnostics(&json, "before fix");
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0]["rule"], "empty-block");
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert_eq!(out.status.code(), Some(0), "{stderr}");
assert!(stderr.contains("Fixed:"), "{stderr}");
assert_eq!(
fs::read(&target).unwrap(),
format!("{frontmatter} keep\r\n").as_bytes()
);
}
#[test]
fn the_file_key_suppresses_literal_directive_only_outside_plain_fences() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("indented.mds");
let prefix = "---\nindented-directives: true\n---\n @if 1 == 1:\nkeep\n @end\n```txt\n";
let example = " @if demo:\nexample\n";
fs::write(&target, format!("{prefix}{example} @end\n```\n")).unwrap();
let (json, _) = lint_json(&target, "under the file key");
let findings = json_diagnostics(&json, "under the file key");
assert_eq!(findings.len(), 2, "{findings:?}");
for (finding, offset) in findings
.into_iter()
.zip([prefix.len(), prefix.len() + example.len()])
{
assert_eq!(finding["rule"], "literal-directive");
assert_eq!(finding["span"]["offset"], offset);
}
}
#[test]
fn malformed_file_key_reports_a_fixed_message_and_a_safe_source_frame() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("indented.mds");
let esc = char::from(0x1b);
let bidi = char::from_u32(0x202e).unwrap();
let prefix = "---\r\nname: café\r\n";
let line = format!("indented-directives: invalid{esc}{bidi}value");
let message = "syntax error: expected indented-directives: true or indented-directives: false";
fs::write(&path, format!("{prefix}{line}\r\n---\r\n")).unwrap();
let human = lint_path(&path, &[]);
let stderr = String::from_utf8(human.stderr).unwrap();
assert_eq!(human.status.code(), Some(2), "{stderr}");
assert!(stderr.replace("\n │ ", " ").contains(message), "{stderr}");
let safe_value = format!("invalid?{}value", char::REPLACEMENT_CHARACTER);
assert!(stderr.contains(&safe_value), "{stderr:?}");
assert!(!stderr.contains([esc, bidi]), "{stderr:?}");
let json = lint_path(&path, &["--format", "json"]);
let wire = String::from_utf8(json.stdout).unwrap();
assert_eq!(json.status.code(), Some(2), "{wire}");
assert!(!wire.contains([esc, bidi]), "{wire:?}");
let document: serde_json::Value = serde_json::from_str(&wire).unwrap();
let error = &document["error"];
assert_eq!(error["code"], "mds::syntax");
assert_eq!(error["message"], message);
assert_eq!(error["help"], serde_json::Value::Null);
assert_eq!(error["span"]["offset"], prefix.len());
assert_eq!(error["span"]["length"], line.len());
}
#[test]
fn too_many_block_declarations_exits_3_resource_limit() {
const BLOCK_COUNT: usize = 257;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("many_blocks.mds");
let mut content = String::new();
for i in 0..BLOCK_COUNT {
content.push_str(&format!("@block block_{i}:\n@end\n"));
}
fs::write(&target, &content).unwrap();
let out = lint_path(&target, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(3),
"{BLOCK_COUNT} @block declarations must exit 3 (ResourceLimit, MAX_BLOCKS_PER_MODULE); \
stderr: {stderr}"
);
}
#[test]
fn directory_json_files_array_is_deterministically_sorted() {
let dir = tempfile::tempdir().unwrap();
for name in &["lint_dir_c.mds", "lint_dir_b.mds", "lint_dir_a.mds"] {
fs::copy(fixture("lint_warn_only.mds"), dir.path().join(name)).unwrap();
}
let out1 = lint_path(dir.path(), &["--format", "json"]);
let out2 = lint_path(dir.path(), &["--format", "json"]);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
assert_eq!(
out1.status.code(),
Some(1),
"directory with warn-only files must exit 1; stderr: {}",
String::from_utf8_lossy(&out1.stderr)
);
assert_eq!(
stdout1, stdout2,
"directory mode --format json output must be identical across two consecutive runs"
);
let json: serde_json::Value =
serde_json::from_str(&stdout1).expect("stdout must be valid JSON");
let files = json["files"]
.as_array()
.expect("JSON output must have a files array");
assert_eq!(
files.len(),
3,
"all 3 .mds files must appear in the output; got: {files:?}"
);
let paths: Vec<&str> = files
.iter()
.map(|f| {
f["file"]
.as_str()
.expect("each entry must have a file string")
})
.collect();
let mut sorted_paths = paths.clone();
sorted_paths.sort();
assert_eq!(
paths, sorted_paths,
"files[] must be in sorted path order (F1 invariant); got: {paths:?}"
);
}
#[test]
fn fix_applied_for_unreachable_branch_and_file_changed() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_unreachable_branch.mds");
fs::copy(fixture("lint_unreachable_branch.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
assert!(
original.contains("@if \"x\" == \"x\":"),
"fixture must contain the always-true @if condition"
);
assert!(
original.contains("@else:"),
"fixture must contain a later @else branch"
);
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("fix rejected"),
"unreachable-branch fix must now succeed; got stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(0),
"exit code must be 0 after successful unreachable-branch fix; got stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_ne!(original, after, "file must be changed when --fix succeeds");
assert!(
!after.contains("@if"),
"fixed file must not contain the removed @if; got: {after:?}"
);
assert!(
!after.contains("@else"),
"fixed file must not contain the removed @else branch; got: {after:?}"
);
assert!(
after.contains("hello"),
"fixed file must retain the then-body content; got: {after:?}"
);
}
#[test]
fn shadow_variable_info_emits_diagnostic_and_exits_0() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("loop_var_shadow.mds");
fs::copy(fixture("loop_var_shadow.mds"), &target).unwrap();
fs::write(
dir.path().join("mds.json"),
r#"{ "lint": { "rules": { "shadow-variable": "info" } } }"#,
)
.unwrap();
let out = lint_path(&target, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stderr.contains("shadow-variable"),
"shadow-variable Info finding must appear in stderr; got: {stderr}"
);
assert_eq!(
out.status.code(),
Some(0),
"Info-severity shadow-variable must not affect exit code; got stderr: {stderr}"
);
assert!(
stdout.is_empty(),
"human mode must not write to stdout; got: {stdout}"
);
}
#[test]
fn json_format_malformed_config_emits_error_envelope() {
let dir = tempfile::tempdir().unwrap();
let mds_file = dir.path().join("test.mds");
fs::write(&mds_file, "---\nfoo: bar\n---\nHello world").unwrap();
fs::write(dir.path().join("mds.json"), "{ this is not valid json }").unwrap();
let out = lint_path(&mds_file, &["--format", "json"]);
assert_eq!(
out.status.code(),
Some(2),
"--format json + malformed mds.json must exit 2; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"stdout must be valid JSON (error envelope); parse error: {e}; \
stdout: {stdout}; stderr: {stderr}"
)
});
assert_eq!(
parsed["version"].as_u64(),
Some(1),
"envelope must have version:1; got: {parsed}"
);
assert!(
parsed["error"]["code"].is_string(),
"error envelope must have a code field; got: {parsed}"
);
assert!(
!stderr.contains("invalid mds.json"),
"config error must go to stdout in JSON mode, not stderr; got stderr: {stderr}"
);
}
#[test]
fn dir_mode_json_same_basename_files_have_distinct_paths() {
let dir = tempfile::tempdir().unwrap();
for sub in &["sub_a", "sub_b"] {
let subdir = dir.path().join(sub);
fs::create_dir_all(&subdir).unwrap();
fs::copy(fixture("lint_warn_only.mds"), subdir.join("template.mds")).unwrap();
}
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"dir with warn-only files must exit 1; stderr: {stderr}"
);
let json: serde_json::Value = serde_json::from_str(&stdout).expect("stdout must be valid JSON");
let files = json["files"].as_array().expect("must have files[]");
assert_eq!(
files.len(),
2,
"both files must appear in JSON output; got: {files:?}"
);
let paths: Vec<&str> = files
.iter()
.map(|f| {
f["file"]
.as_str()
.expect("each entry must have a file string")
})
.collect();
assert!(
paths.iter().any(|p| p.contains("sub_a")),
"sub_a path must appear in file keys; got: {paths:?}"
);
assert!(
paths.iter().any(|p| p.contains("sub_b")),
"sub_b path must appear in file keys; got: {paths:?}"
);
let mut sorted = paths.clone();
sorted.dedup();
assert_eq!(
sorted.len(),
2,
"file keys must be distinct; got: {paths:?}"
);
}
#[test]
fn dir_fix_json_residuals_keyed_by_relative_path_not_input_mds() {
let dir = tempfile::tempdir().unwrap();
let subdir = dir.path().join("subdir");
fs::create_dir_all(&subdir).unwrap();
let mixed = "---\ngreeting: Hello\nunused_key: not referenced\n---\n\n\
@define greet(name):\n Hello {{name}}!\n@end\n\n\
@export greet\n@export greet\n";
let target = subdir.join("mixed.mds");
fs::write(&target, mixed).unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let json: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
panic!("stdout must be valid JSON; err: {e}; stdout: {stdout}; stderr: {stderr}")
});
assert_eq!(
out.status.code(),
Some(1),
"residual unused-variable must produce exit 1; stderr: {stderr}"
);
let files = json["files"].as_array().expect("must have files[]");
assert!(!files.is_empty(), "files[] must be non-empty after fix");
for entry in files {
let file_key = entry["file"].as_str().unwrap_or("");
assert!(
!file_key.contains("input.mds"),
"file key must NOT be 'input.mds'; got: {file_key}"
);
assert!(
file_key.contains("subdir") || file_key.contains("mixed"),
"file key must reference the actual file; got: {file_key}"
);
}
}
#[test]
fn file_fix_json_residuals_keyed_by_filename_not_input_mds() {
let dir = tempfile::tempdir().unwrap();
let mixed = "---\ngreeting: Hello\nunused_key: not referenced\n---\n\n\
@define greet(name):\n Hello {{name}}!\n@end\n\n\
@export greet\n@export greet\n";
let target = dir.path().join("mixed.mds");
fs::write(&target, mixed).unwrap();
let out = lint_path(&target, &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let json: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_else(|e| {
panic!("stdout must be valid JSON; err: {e}; stdout: {stdout}; stderr: {stderr}")
});
assert_eq!(
out.status.code(),
Some(1),
"residual unused-variable must produce exit 1; stderr: {stderr}"
);
let files = json["files"].as_array().expect("must have files[]");
assert!(!files.is_empty(), "files[] must be non-empty after fix");
for entry in files {
let file_key = entry["file"].as_str().unwrap_or("");
assert!(
!file_key.contains("input.mds"),
"file key must NOT be 'input.mds'; got: {file_key}"
);
assert_eq!(
file_key, "mixed.mds",
"file key must be the real filename basename; got: {file_key}"
);
}
}
#[test]
fn fix_check_coalesced_fix_prints_would_fix() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_overlap_fix.mds");
fs::copy(fixture("lint_overlap_fix.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix"),
"--fix --check must print 'Would fix' when coalescing resolves the overlap; \
got stderr: {stderr}"
);
assert!(
!stderr.contains("fix rejected"),
"--fix --check must NOT print 'fix rejected' after coalescing; got stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_eq!(
original, after,
"--fix --check must never write to the file"
);
}
#[test]
fn fix_check_fixable_prints_would_fix_and_exits_1_file_unchanged() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_error.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix"),
"--fix --check must print 'Would fix' for a fixable file; got stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check must exit 1 when a fix is pending; got stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_eq!(
original, after,
"--fix --check must never write to the file"
);
}
#[test]
fn dir_fix_check_exits_1_when_any_file_fixable_exits_0_when_none() {
let dir1 = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir1.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_clean.mds"), dir1.path().join("b.mds")).unwrap();
let out1 = lint_path(dir1.path(), &["--fix", "--check"]);
let stderr1 = String::from_utf8_lossy(&out1.stderr);
assert_eq!(
out1.status.code(),
Some(1),
"dir with fixable file must exit 1 under --fix --check; stderr: {stderr1}"
);
assert_eq!(
fs::read_to_string(dir1.path().join("a.mds")).unwrap(),
fs::read_to_string(fixture("lint_error.mds")).unwrap(),
"fixable file must not be written by --fix --check"
);
let dir2 = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir2.path().join("c.mds")).unwrap();
let out2 = lint_path(dir2.path(), &["--fix", "--check"]);
let stderr2 = String::from_utf8_lossy(&out2.stderr);
assert_eq!(
out2.status.code(),
Some(0),
"dir with only clean files must exit 0 under --fix --check; stderr: {stderr2}"
);
}
#[test]
fn fix_overlap_coalesced_and_applied() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_overlap.mds");
fs::copy(fixture("lint_overlap.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("fix rejected"),
"--fix on coalesced overlap fixture must NOT print 'fix rejected'; got stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_ne!(
original, after,
"fix must change the file when coalescing resolves the overlap"
);
assert!(
!after.contains("@if"),
"fixed file must not contain the removed @if; got:\n{after}"
);
assert!(
!after.contains("@elseif"),
"fixed file must not contain the removed @elseif; got:\n{after}"
);
assert_eq!(
out.status.code(),
Some(0),
"no residual diagnostics after fix; got stderr: {stderr}"
);
}
#[test]
fn partially_fixed_end_to_end_count_in_summary() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_partial_fix.mds");
fs::copy(fixture("lint_partial_fix.mds"), &target).unwrap();
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("1 of 2"),
"stderr must contain '1 of 2 fixes applied' summary; got: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_eq!(
after.matches("@export greet").count(),
1,
"file must have exactly one @export greet after partial fix; got:\n{after}"
);
assert!(
after.contains("@define empty_fn():"),
"empty @define must still be present after partial fix; got:\n{after}"
);
assert_eq!(
out.status.code(),
Some(1),
"residual empty-block Warn must produce exit 1; got stderr: {stderr}"
);
}
#[test]
fn stdin_lint_diagnostic_includes_code_frame() {
let source = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
let out = lint_stdin(source, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("duplicate-export"),
"diagnostic must appear in stdin report-only mode; got: {stderr}"
);
assert!(
stderr.contains("<stdin>"),
"stdin mode must show '<stdin>' in the code frame; got: {stderr}"
);
assert!(
!stderr.contains("input.mds"),
"stdin human output must not expose the internal VFS key 'input.mds'; got: {stderr}"
);
assert!(
stderr.contains("@export"),
"code frame must include the offending source line '@export greet'; got: {stderr}"
);
}
#[test]
fn stdin_json_wire_file_key_is_stdin_sentinel() {
let source = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
let out = lint_stdin(source, &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let v: serde_json::Value = serde_json::from_str(&stdout).expect("stdout must be valid JSON");
let files = v["files"].as_array().expect("JSON must have 'files' array");
assert!(
!files.is_empty(),
"stdin JSON must have at least one file group (duplicate-export fires); got: {stdout}"
);
for entry in files {
let file_key = entry["file"]
.as_str()
.expect("each file entry must have a 'file' string");
assert_eq!(
file_key, "<stdin>",
"AC-P1-01: JSON files[].file must be '<stdin>' for stdin input, not '{file_key}'"
);
}
assert!(
!stdout.contains("input.mds"),
"AC-P1-27: 'input.mds' must not appear anywhere in CLI stdout for a stdin \
lint; got: {stdout}"
);
}
const OUT_OF_ORDER_FIXTURE: &str =
"@define greet(name):\n Hello {name}!\n@end\n\n@export greet\n@export greet\n";
fn stdin_json_diagnostics(source: &str) -> Vec<serde_json::Value> {
let out = lint_stdin(source, &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let v: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("stdout must be JSON: {e}\n{stdout}"));
let files = v["files"].as_array().expect("JSON must have 'files' array");
assert_eq!(
files.len(),
1,
"stdin lint must emit exactly one file group"
);
files[0]["diagnostics"]
.as_array()
.expect("must have 'diagnostics'")
.clone()
}
#[test]
fn stdin_json_diagnostics_sorted_by_offset() {
let diags = stdin_json_diagnostics(OUT_OF_ORDER_FIXTURE);
let rules: Vec<&str> = diags.iter().filter_map(|d| d["rule"].as_str()).collect();
let offsets: Vec<i64> = diags
.iter()
.filter_map(|d| d["span"]["offset"].as_i64())
.collect();
assert_eq!(
offsets.len(),
diags.len(),
"every diagnostic in this fixture must carry a span; got: {diags:?}"
);
assert!(
offsets.len() >= 2 && offsets[0] != offsets[offsets.len() - 1],
"AC-P1-08 needs at least two diagnostics at DISTINCT offsets to be a real \
check; got rules {rules:?} at offsets {offsets:?}"
);
let mut sorted = offsets.clone();
sorted.sort_unstable();
assert_eq!(
offsets, sorted,
"AC-P1-08: diagnostics must be in ascending byte-offset order; \
got rules {rules:?} at offsets {offsets:?}"
);
let legacy = rules
.iter()
.position(|r| *r == "legacy-interpolation")
.expect("fixture must produce a legacy-interpolation diagnostic");
let dup = rules
.iter()
.position(|r| *r == "duplicate-export")
.expect("fixture must produce a duplicate-export diagnostic");
assert!(
legacy < dup,
"AC-P1-08: emitted order must follow byte offset, not rule-dispatch order \
(duplicate_export is dispatched first but fires later in the file); \
got rules {rules:?} at offsets {offsets:?}"
);
}
#[test]
fn stdin_human_and_json_diagnostic_order_match() {
let json_rules: Vec<String> = stdin_json_diagnostics(OUT_OF_ORDER_FIXTURE)
.iter()
.filter_map(|d| d["rule"].as_str().map(str::to_string))
.collect();
assert!(
json_rules.len() >= 2,
"AC-P1-09 needs at least two diagnostics to compare an ORDER; got {json_rules:?}"
);
let out = lint_stdin(OUT_OF_ORDER_FIXTURE, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
let human_rules: Vec<String> = stderr
.lines()
.filter_map(|line| {
let t = line.trim();
json_rules
.iter()
.find(|r| t == format!("mds::lint::{r}") || t == **r)
.cloned()
})
.collect();
assert_eq!(
human_rules, json_rules,
"AC-P1-09: human and JSON surfaces must agree on diagnostic order.\n\
json: {json_rules:?}\nhuman: {human_rules:?}\nstderr:\n{stderr}"
);
}
#[test]
fn stdin_json_output_is_byte_identical_across_runs() {
let first = lint_stdin(OUT_OF_ORDER_FIXTURE, &["--format", "json"]).stdout;
for run in 2..=5 {
let next = lint_stdin(OUT_OF_ORDER_FIXTURE, &["--format", "json"]).stdout;
assert_eq!(
first,
next,
"AC-P1-11: run {run} differed from run 1.\nrun1: {}\nrun{run}: {}",
String::from_utf8_lossy(&first),
String::from_utf8_lossy(&next)
);
}
}
fn frame_source_identity(rendered: &str) -> Option<String> {
let start = rendered.find('[')?;
let rest = &rendered[start + 1..];
let end = rest.find(']')?;
let inner = &rest[..end];
let mut parts: Vec<&str> = inner.rsplitn(3, ':').collect();
parts.reverse();
(parts.len() == 3 && parts[1].chars().all(|c| c.is_ascii_digit())).then(|| parts[0].to_string())
}
#[test]
fn stdin_analysis_failure_labels_source_as_stdin() {
let source = "@if\nbroken\n";
let human = lint_stdin(source, &[]);
let stderr = String::from_utf8_lossy(&human.stderr);
let identity = frame_source_identity(&stderr).unwrap_or_else(|| {
panic!("expected a miette code frame with a `[label:line:col]` header; got:\n{stderr}")
});
assert_eq!(
identity, "<stdin>",
"AC-P1-07: the analysis-failure frame must name '<stdin>'; got '{identity}'.\n{stderr}"
);
assert_eq!(
human.status.code(),
Some(2),
"an analysis failure must still exit 2; stderr:\n{stderr}"
);
let json = lint_stdin(source, &["--format", "json"]);
let stdout = String::from_utf8_lossy(&json.stdout);
let v: serde_json::Value =
serde_json::from_str(&stdout).expect("analysis-failure JSON must parse");
assert!(
v["error"].is_object(),
"JSON analysis failure must use the error envelope; got: {stdout}"
);
assert!(
v.get("file").is_none() || v["file"].is_null(),
"AC-P1-07: analysis-failure JSON envelope must have NO top-level 'file' key; \
got: {stdout}"
);
assert!(
v.get("files").is_none() || v["files"].is_null(),
"AC-P1-07: analysis-failure JSON envelope must have NO 'files' array; got: {stdout}"
);
let message = v["error"]["message"]
.as_str()
.expect("error.message must be a string");
assert!(
!message.is_empty(),
"AC-P1-07: error.message must not be empty"
);
{
let ctrl_stdout = r#"{"version":1,"error":{"code":"parse_error","message":"<source>:1:1","help":null,"span":null}}"#;
let ctrl_v: serde_json::Value = serde_json::from_str(ctrl_stdout).unwrap();
let ctrl_msg = ctrl_v["error"]["message"]
.as_str()
.expect("control: synthetic envelope must yield a message string");
assert!(
ctrl_msg.contains("<source>"),
"control (ADR-009/PF-013): extraction path v[\"error\"][\"message\"].as_str() \
detects '<source>' in error.message — if this fails the real check below is broken"
);
assert!(
ctrl_stdout.contains("<source>"),
"control (ADR-009/PF-013): raw stdout scan detects '<source>' — \
if this fails the stdout scan below is broken"
);
}
{
let ctrl_stdout = r#"{"version":1,"error":{"code":"io_error","message":"failed to read input.mds","help":null,"span":null}}"#;
let ctrl_v: serde_json::Value = serde_json::from_str(ctrl_stdout).unwrap();
let ctrl_msg = ctrl_v["error"]["message"]
.as_str()
.expect("control: synthetic envelope must yield a message string");
assert!(
ctrl_msg.contains("input.mds"),
"control (ADR-009/PF-013): extraction path v[\"error\"][\"message\"].as_str() \
detects 'input.mds' in error.message — if this fails the real check below is broken"
);
assert!(
ctrl_stdout.contains("input.mds"),
"control (ADR-009/PF-013): raw stdout scan detects 'input.mds' — \
if this fails the stdout scan below is broken"
);
}
assert!(
!message.contains("<source>"),
"AC-P1-07: error.message must not embed '<source>'; got: {message}"
);
assert!(
!message.contains("input.mds"),
"AC-P1-07: error.message must not embed 'input.mds'; got: {message}"
);
assert!(
!stdout.contains("<source>"),
"AC-P1-27: '<source>' must not appear in stdout; got: {stdout}"
);
assert!(
!stdout.contains("input.mds"),
"AC-P1-27: 'input.mds' must not appear in stdout; got: {stdout}"
);
}
#[test]
fn stdin_source_identity_is_uniform_across_subcommands() {
let broken = "@if\nbroken\n";
for subcommand in ["lint", "check", "build"] {
let out = run_mds_stdin(subcommand, broken);
let stderr = String::from_utf8_lossy(&out.stderr);
let identity = frame_source_identity(&stderr).unwrap_or_else(|| {
panic!("`mds {subcommand} -` must render a code frame; got:\n{stderr}")
});
assert_eq!(
identity, "<stdin>",
"AC-P1-04: `mds {subcommand} -` must name the source '<stdin>'; \
got '{identity}'.\n{stderr}"
);
assert!(
!stderr.contains("<source>"),
"AC-P1-04: `mds {subcommand} -` must not emit '<source>'; got:\n{stderr}"
);
}
{
use std::io::Write;
let fmt_source = "@define greet(name): \nHello {{name}}!\n@end\n";
let mut child = mds_bin()
.arg("fmt")
.arg("--check")
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(fmt_source.as_bytes());
let out = child.wait_with_output().unwrap();
let fmt_stderr = String::from_utf8_lossy(&out.stderr);
assert!(
fmt_stderr.contains("Would reformat: <stdin>"),
"AC-P1-04: `mds fmt --check -` must emit 'Would reformat: <stdin>'; \
got:\n{fmt_stderr}"
);
assert!(
!fmt_stderr.contains("input.mds") && !fmt_stderr.contains("<source>"),
"AC-P1-04: `mds fmt --check -` must not emit old source labels; \
got:\n{fmt_stderr}"
);
}
{
let valid_source = "Hello!\n";
let out = run_mds_stdin("check", valid_source);
let check_stderr = String::from_utf8_lossy(&out.stderr);
assert!(
out.status.success(),
"AC-P1-04: `mds check -` must succeed for valid stdin; \
got:\n{check_stderr}"
);
assert!(
check_stderr.contains("OK: <stdin>"),
"AC-P1-04: `mds check -` must emit 'OK: <stdin>' on success; \
got:\n{check_stderr}"
);
assert!(
!check_stderr.contains("input.mds") && !check_stderr.contains("<source>"),
"AC-P1-04: `mds check -` must not emit old source labels; \
got:\n{check_stderr}"
);
}
}
#[test]
fn stdin_import_error_frame_names_imported_file_not_stdin() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let lib = dir.path().join("lib.mds");
fs::write(&lib, "@if\n").unwrap();
let stdin_src = "@import { x } from \"./lib.mds\"\n";
for subcommand in ["lint", "check"] {
let mut child = mds_bin()
.arg(subcommand)
.arg("-")
.current_dir(dir.path())
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(stdin_src.as_bytes());
let out = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
let identity = frame_source_identity(&stderr).unwrap_or_else(|| {
panic!(
"PF-012: `mds {subcommand} -` (stdin importing broken lib.mds) must \
render a miette code frame; got:\n{stderr}"
)
});
assert!(
identity.contains("lib.mds"),
"PF-012: `mds {subcommand} -` frame must name 'lib.mds', not '<stdin>'; \
got '{identity}'.\n{stderr}"
);
assert_ne!(
identity, "<stdin>",
"PF-012: `mds {subcommand} -` must not relabel an imported-file error \
as '<stdin>'; the relabel_stdin_error guard is broken.\n{stderr}"
);
}
}
#[test]
fn json_files_array_is_path_sorted_in_directory_mode() {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join("api")).unwrap();
let dupe = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
for rel in ["b.mds", "api/x.mds", "api-utils.mds"] {
fs::write(dir.path().join(rel), dupe).unwrap();
}
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let v: serde_json::Value = serde_json::from_str(&stdout).expect("stdout must be valid JSON");
let files: Vec<&str> = v["files"]
.as_array()
.expect("JSON must have 'files' array")
.iter()
.filter_map(|f| f["file"].as_str())
.collect();
assert_eq!(
files.len(),
3,
"all three files must report findings; got: {files:?}"
);
let mut sorted = files.clone();
sorted.sort_unstable();
assert_eq!(
files, sorted,
"AC-P1-10: files[] must be in ascending byte-wise path order; got: {files:?}"
);
let single = lint_path(&dir.path().join("b.mds"), &["--format", "json"]);
let single_stdout = String::from_utf8_lossy(&single.stdout);
let sv: serde_json::Value = serde_json::from_str(&single_stdout).unwrap();
assert_eq!(
sv["files"].as_array().map(Vec::len),
Some(1),
"AC-P1-10: single-file mode must emit exactly one files[] entry; got: {single_stdout}"
);
}
#[cfg(unix)]
#[test]
fn directory_json_file_key_escapes_control_bytes_in_paths() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
const BEL: u8 = 0x07;
let dir = tempfile::tempdir().unwrap();
let mut raw = b"be".to_vec();
raw.push(BEL);
raw.extend_from_slice(b"l.mds");
let name = OsString::from_vec(raw.clone());
let target = dir.path().join(&name);
let dupe = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
if fs::write(&target, dupe).is_err() {
panic!(
"directory_json_file_key_escapes_control_bytes_in_paths: \
control-byte filename rejected by filesystem — unexpected on this platform \
(PF-013 / ADR-009)"
);
}
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
fn has_raw_control(s: &str) -> bool {
s.chars().any(|c| c.is_control() && c != '\n' && c != '\t')
}
let raw_path = String::from_utf8_lossy(&raw).into_owned();
assert!(
has_raw_control(&raw_path),
"control arm: the predicate must detect the raw byte when it is present, \
otherwise the assertion below proves nothing (PF-013)"
);
let v: serde_json::Value = serde_json::from_str(&stdout).expect("stdout must be valid JSON");
let file_key = v["files"]
.as_array()
.and_then(|f| f.first())
.and_then(|f| f["file"].as_str())
.unwrap_or_else(|| panic!("expected one files[] entry; got: {stdout}"));
assert!(
!has_raw_control(file_key),
"AC-P1-20: files[].file must not carry a raw control byte; got: {file_key:?}"
);
assert!(
file_key.contains("\\u0007"),
"AC-P1-20: files[].file must carry the escaped literal form of the control \
byte; got: {file_key:?}"
);
}
#[cfg(unix)]
#[test]
fn lint_directory_non_utf8_entry_is_an_io_error_exit_2() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let warn = fs::read_to_string(fixture("lint_warn_only.mds")).unwrap();
let control_dir = tempfile::tempdir().unwrap();
fs::write(control_dir.path().join("ok.mds"), &warn).unwrap();
let control_json = lint_path(control_dir.path(), &["--format", "json"]);
let control_stdout = String::from_utf8_lossy(&control_json.stdout);
assert_eq!(
control_json.status.code(),
Some(1),
"control: a warn-only directory must exit 1, not the hostile arm's 2; \
stdout: {control_stdout}"
);
let cv: serde_json::Value =
serde_json::from_str(&control_stdout).expect("control stdout must be valid JSON");
assert_eq!(
cv["files"]
.as_array()
.and_then(|f| f.first())
.and_then(|f| f["file"].as_str()),
Some("ok.mds"),
"control: the warn-only file must be linted under its in-root key; \
got: {control_stdout}"
);
let control_human = lint_path(control_dir.path(), &[]);
let control_stderr = String::from_utf8_lossy(&control_human.stderr);
assert!(
control_stderr.contains("clean,"),
"control: a real directory summary must contain the exact needle \"clean,\", \
otherwise its absence below proves nothing; got: {control_stderr:?}"
);
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("ok.mds"), &warn).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, &warn).is_err() {
#[cfg(not(target_os = "macos"))]
panic!(
"lint_directory_non_utf8_entry_is_an_io_error_exit_2: a non-UTF-8 filename \
was rejected by the filesystem — unexpected on this platform"
);
#[cfg(target_os = "macos")]
return;
}
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert_eq!(
out.status.code(),
Some(2),
"#217: a directory entry that cannot be named must fail the run with exit 2; \
stdout: {stdout}"
);
let v: serde_json::Value =
serde_json::from_str(&stdout).expect("stdout must be the JSON analysis-failure envelope");
assert_eq!(
v["error"]["code"].as_str(),
Some("mds::io"),
"#217: the envelope must carry the Io error code; got: {stdout}"
);
let message = v["error"]["message"].as_str().unwrap_or("");
assert!(
message.contains("not valid UTF-8"),
"#217: the envelope message must name the condition; got: {message:?}"
);
assert!(
v.get("files").is_none(),
"#217: the analysis-failure envelope must carry no files[] — no file may be \
linted under a lossy key; got: {stdout}"
);
let human = lint_path(dir.path(), &[]);
let stderr = String::from_utf8_lossy(&human.stderr);
assert_eq!(
human.status.code(),
Some(2),
"#217: human mode must fail the run with exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("not valid UTF-8"),
"#217: human mode must report the condition on stderr; got: {stderr:?}"
);
assert!(
!stderr.contains("clean,"),
"#217: the run must abort before the per-file loop, so no directory summary \
may be emitted; got: {stderr:?}"
);
}
fn run_mds_stdin(subcommand: &str, input: &str) -> std::process::Output {
use std::io::Write;
let mut child = mds_bin()
.arg(subcommand)
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(input.as_bytes());
child.wait_with_output().unwrap()
}
#[test]
fn stdin_fix_preview_messages_use_bracketed_sentinel() {
let source = "@define greet(name):\n Hello {name}!\n@end\n";
let out = lint_stdin(source, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix: <stdin>"),
"AC-P1-03: expected 'Would fix: <stdin>'; got:\n{stderr}"
);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check must exit 1 when a fix would apply; stderr:\n{stderr}"
);
assert!(
!stderr.contains("Would fix: stdin"),
"AC-P1-03: the bare `stdin` convention must be gone; got:\n{stderr}"
);
let out = lint_stdin(source, &["--fix", "--diff"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("<stdin>"),
"AC-P1-03: the diff header must reference '<stdin>'; got:\n{stdout}"
);
for line in stdout
.lines()
.filter(|l| l.starts_with("---") || l.starts_with("+++"))
{
assert!(
!line.split_whitespace().any(|w| w == "stdin"),
"AC-P1-03: diff header must not use bare `stdin`; got: {line}"
);
}
}
#[test]
fn stdin_json_clean_source_emits_empty_files_array() {
let out = lint_stdin("Hello World!\n", &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let v: serde_json::Value = serde_json::from_str(&stdout).expect("clean stdin JSON must parse");
assert_eq!(
v["files"],
serde_json::json!([]),
"AC-P1-26: clean stdin must emit files:[] (no file entry); got: {stdout}"
);
assert_eq!(v["truncated"], false, "truncated must be false");
assert_eq!(v["version"], 1, "version must be 1");
assert!(
!stdout.contains("input.mds"),
"AC-P1-26: 'input.mds' must not appear in clean-stdin JSON; got: {stdout}"
);
assert!(
!stdout.contains("<stdin>"),
"AC-P1-26: '<stdin>' must not appear in clean-stdin JSON (files is empty); \
got: {stdout}"
);
assert_eq!(
out.status.code(),
Some(0),
"clean source must exit 0; stdout: {stdout}"
);
}
#[test]
fn stdin_partial_fix_message_uses_bracketed_sentinel() {
let source = "\
@define empty_fn():
@end
@export empty_fn
@define greet(name):
Hello {{name}}!
@end
@export greet
@export greet
";
let out = lint_stdin(source, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Partially fixed: <stdin>"),
"AC-P1-03: 'Partially fixed: <stdin>' must appear in stderr; got:\n{stderr}"
);
assert!(
!stderr.contains("Partially fixed: stdin\n")
&& !stderr.starts_with("Partially fixed: stdin "),
"AC-P1-03: must not use bare 'stdin' in partial-fix message; got:\n{stderr}"
);
}
#[test]
fn auto_detect_hint_names_subcommand_lint_and_fmt() {
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("b.mds")).unwrap();
let out = mds_bin()
.arg("lint")
.current_dir(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("mds lint"),
"auto-detect hint for 'lint' must contain 'mds lint'; got: {stderr}"
);
assert!(
!stderr.contains("mds build"),
"hint must not name a different subcommand; got: {stderr}"
);
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("b.mds")).unwrap();
let out = mds_bin()
.arg("fmt")
.current_dir(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("mds fmt"),
"auto-detect hint for 'fmt' must contain 'mds fmt'; got: {stderr}"
);
assert!(
!stderr.contains("mds build"),
"fmt hint must not name 'mds build'; got: {stderr}"
);
}
}
#[test]
fn dir_fix_check_json_emits_parseable_json_before_exit_1() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("fixable.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--check", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check must exit 1 when fixes are pending; stderr: {stderr}"
);
let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"--fix --check --format json must emit parseable JSON before exiting; \
parse error: {e}; stdout: '{stdout}'"
)
});
assert_eq!(
json["version"], 1,
"envelope must have version:1; got: {json}"
);
assert!(
json["files"].is_array(),
"envelope must have files[]; got: {json}"
);
}
#[test]
fn file_fix_check_json_emits_parseable_json_before_exit_1() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("fixable.mds");
fs::copy(fixture("lint_error.mds"), &file).unwrap();
let out = lint_path(&file, &["--fix", "--check", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"single-file --fix --check must exit 1 when fixes are pending; stderr: {stderr}"
);
let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"single-file --fix --check --format json must emit parseable JSON before exiting; \
parse error: {e}; stdout: '{stdout}'"
)
});
assert_eq!(
json["version"], 1,
"envelope must have version:1; got: {json}"
);
assert!(
json["files"].is_array(),
"envelope must have files[]; got: {json}"
);
}
#[test]
fn stdin_fix_check_exits_1_and_writes_nothing_to_stdout() {
let source = "@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n";
let out = lint_stdin(source, &["--fix", "--check"]);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check stdin must exit 1 when fixes are pending; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.is_empty(),
"--fix --check stdin must not write the fixed source to stdout; got: {stdout}"
);
}
#[test]
fn dir_and_single_file_agree_on_quiet_for_partially_fixed() {
{
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("partial.mds");
fs::copy(fixture("lint_partial_fix.mds"), &target).unwrap();
let out = lint_path(&target, &["--fix", "--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Partially fixed") && !stderr.to_lowercase().contains("partial fix"),
"single-file --fix --quiet must suppress 'Partially fixed'; got: {stderr}"
);
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(
fixture("lint_partial_fix.mds"),
dir.path().join("partial.mds"),
)
.unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json", "--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Partially fixed") && !stderr.to_lowercase().contains("partial fix"),
"dir-mode --fix --format json --quiet must suppress 'Partially fixed'; got: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!("dir-mode --quiet must still emit valid JSON; err: {e}; stdout: {stdout}")
});
}
{
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("partial.mds");
fs::copy(fixture("lint_partial_fix.mds"), &target).unwrap();
let out = lint_path(&target, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Partially fixed"),
"single-file --fix without --quiet must print 'Partially fixed'; got: {stderr}"
);
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(
fixture("lint_partial_fix.mds"),
dir.path().join("partial.mds"),
)
.unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Partially fixed"),
"dir-mode --fix --format json without --quiet must print 'Partially fixed'; got: {stderr}"
);
}
}
#[test]
fn lint_fix_bare_filename_applies_fix() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("dup.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
let original = fs::read_to_string(&target).unwrap();
assert!(
original.contains("@export greet\n@export greet"),
"fixture must have duplicate export"
);
let out = mds_bin()
.arg("lint")
.arg("--fix")
.arg("dup.mds") .current_dir(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"--fix on bare filename should exit 0 after fixing; stderr: {stderr}"
);
let after = fs::read_to_string(&target).unwrap();
assert_ne!(after, original, "--fix must have rewritten the file");
assert_eq!(
after.matches("@export greet").count(),
1,
"exactly one @export greet should remain after --fix; got:\n{after}"
);
}
#[test]
fn lint_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("esc_test.mds");
fs::write(&file, b"@define \x1bfoo:\nhello\n").unwrap();
let out = lint_path(&file, &[]);
assert_eq!(
out.status.code(),
Some(2),
"syntax error should exit 2; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(
!out.stderr.contains(&0x1Bu8),
"raw ESC byte (0x1B) must be sanitized before writing to stderr; \
got (hex): {:02x?}",
&out.stderr[..out.stderr.len().min(512)]
);
}
#[test]
fn lint_single_file_esc_in_diagnostic_frame_is_sanitized() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("esc_lint.mds");
fs::write(&file, b"Hello \x1b{name} world\n").unwrap();
let out = lint_path(&file, &[]);
let stderr_str = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"legacy-interpolation is warn-only; expected exit 1; stderr: {stderr_str}"
);
assert_no_control_chars(&stderr_str, "T-5 stderr");
assert!(
stderr_str.contains("Hello"),
"source context word 'Hello' must be visible in output; got: {stderr_str:?}"
);
assert!(
out.stdout.is_empty(),
"human mode must not write to stdout; got: {}",
String::from_utf8_lossy(&out.stdout)
);
}
#[test]
fn lint_directory_esc_in_diagnostic_frame_is_sanitized() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("esc_lint.mds"), b"Hello \x1b{name} world\n").unwrap();
let out = lint_path(dir.path(), &[]);
let stderr_str = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"directory mode: expected exit 1; stderr: {stderr_str}"
);
assert_no_control_chars(&stderr_str, "T-6 stderr");
assert!(
stderr_str.contains("Hello"),
"directory mode: 'Hello' must be visible in output; got: {stderr_str:?}"
);
assert!(
out.stdout.is_empty(),
"directory mode: stdout must be empty; got: {}",
String::from_utf8_lossy(&out.stdout)
);
}
#[test]
fn lint_stdin_esc_in_diagnostic_frame_is_sanitized() {
let input = "Hello \x1b{name} world\n";
let out = lint_stdin(input, &[]);
let stderr_str = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"stdin mode: expected exit 1; stderr: {stderr_str}"
);
assert_no_control_chars(&stderr_str, "T-7 stderr");
assert!(
stderr_str.contains("Hello"),
"stdin mode: 'Hello' must be visible in output; got: {stderr_str:?}"
);
}
#[test]
fn lint_del_and_c1_in_diagnostic_frame_is_sanitized() {
let dir = tempfile::tempdir().unwrap();
let content = "Hello\u{007F}and\u{0085}{name}world\n";
fs::write(dir.path().join("del_c1_lint.mds"), content.as_bytes()).unwrap();
let out = lint_path(dir.path(), &[]);
let stderr_str = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"del/c1 test: expected exit 1; stderr: {stderr_str}"
);
assert!(
!stderr_str.contains('\u{007F}'),
"raw DEL must not appear on stderr; got: {stderr_str:?}"
);
assert!(
!stderr_str.contains('\u{0085}'),
"raw C1 NEL must not appear on stderr; got: {stderr_str:?}"
);
assert!(
stderr_str.contains('\u{00A0}'),
"neutralized C1 NEL must appear as NBSP (U+00A0) in source frame; got: {stderr_str:?}"
);
assert!(
stderr_str.contains("Hello"),
"source context word 'Hello' must be visible; got: {stderr_str:?}"
);
}
fn lint_json(file: &Path, label: &str) -> (serde_json::Value, String) {
let out = lint_path(file, &["--format", "json"]);
let stdout_str = String::from_utf8_lossy(&out.stdout).into_owned();
let json: serde_json::Value = serde_json::from_str(&stdout_str).unwrap_or_else(|e| {
panic!("{label}: lint --format json must emit valid JSON; parse error: {e}; stdout: {stdout_str:?}")
});
assert_eq!(json["version"], 1, "{label}: JSON version must be 1");
(json, stdout_str)
}
fn json_diagnostics<'a>(json: &'a serde_json::Value, label: &str) -> Vec<&'a serde_json::Value> {
let files = json["files"]
.as_array()
.unwrap_or_else(|| panic!("{label}: JSON must have 'files' array; got: {json}"));
assert!(
!files.is_empty(),
"{label}: files array must be non-empty; got: {json}"
);
files
.iter()
.flat_map(|f| {
f["diagnostics"].as_array().unwrap_or_else(|| {
panic!("{label}: every file entry needs 'diagnostics'; got: {f}")
})
})
.collect()
}
#[test]
fn literal_directive_reports_a_fixed_message_and_a_safe_source_frame() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("literal.mds");
let esc = char::from(0x1b);
let bidi = char::from_u32(0x202e).unwrap();
let line = format!(" @if tag{esc}{bidi}tail:");
let source = format!("{line}\n");
fs::write(&path, &source).unwrap();
let message = "This conditional line is literal text.";
let out = lint_path(&path, &[]);
let stderr = String::from_utf8(out.stderr).unwrap();
assert_eq!(out.status.code(), Some(1), "{stderr}");
assert!(stderr.contains("literal-directive"), "{stderr}");
assert!(stderr.contains(message), "{stderr}");
let safe_line = format!("@if tag?{}tail:", char::REPLACEMENT_CHARACTER);
assert!(stderr.contains(&safe_line), "{stderr:?}");
assert!(!stderr.contains([esc, bidi]), "{stderr:?}");
let (json, wire) = lint_json(&path, "literal directive");
assert!(!wire.contains([esc, bidi]), "{wire:?}");
let findings = json_diagnostics(&json, "literal directive");
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0]["rule"], "literal-directive");
assert_eq!(findings[0]["message"], message);
assert_eq!(findings[0]["span"]["offset"], 0);
assert_eq!(findings[0]["span"]["length"], line.len());
let build = mds_bin()
.arg("build")
.arg(&path)
.args(["-o", "-"])
.output()
.unwrap();
assert!(build.status.success(), "{:?}", build.stderr);
assert_eq!(build.stdout, source.as_bytes());
assert!(build.stderr.is_empty(), "{:?}", build.stderr);
}
#[test]
fn lint_json_hostile_source_output_contains_no_raw_control_bytes() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("nel.mds");
fs::write(&file, b"---\n\"fo\\x85o\": 1\n---\nHello\n").unwrap();
let (json, stdout_str) = lint_json(&file, "T-9");
assert_no_control_chars(&stdout_str, "T-9 JSON wire output");
let all_diags = json_diagnostics(&json, "T-9");
assert!(
all_diags.iter().any(|d| d["rule"] == "unused-variable"),
"T-9: unused-variable must fire; got rules: {:?}",
all_diags.iter().map(|d| &d["rule"]).collect::<Vec<_>>()
);
for diag in &all_diags {
let msg = diag["message"]
.as_str()
.unwrap_or_else(|| panic!("T-9: diagnostic must have a string 'message'; got: {diag}"));
assert_no_control_chars(msg, "T-9 diagnostic message");
}
let escaped_nel = format!("\\u{:04X}", 0x85);
assert!(
all_diags.iter().any(|d| d["message"]
.as_str()
.is_some_and(|m| m.contains(&escaped_nel))),
"T-9: {escaped_nel} must appear in at least one diagnostic message; got: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
}
#[test]
fn lint_json_bidi_override_in_frontmatter_key_is_escaped() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("rlo.mds");
let yaml_escape = format!("\\u{:04X}", 0x202E);
fs::write(
&file,
format!("---\n\"fo{yaml_escape}gnp\": 1\n---\nHello\n"),
)
.unwrap();
let (json, stdout_str) = lint_json(&file, "T-9b");
assert_no_control_chars(&stdout_str, "T-9b JSON wire output");
let all_diags = json_diagnostics(&json, "T-9b");
assert!(
all_diags.iter().any(|d| d["rule"] == "unused-variable"),
"T-9b: unused-variable must fire; got rules: {:?}",
all_diags.iter().map(|d| &d["rule"]).collect::<Vec<_>>()
);
assert!(
all_diags.iter().any(|d| d["message"]
.as_str()
.is_some_and(|m| m.contains(&yaml_escape))),
"T-9b: {yaml_escape} must appear in at least one diagnostic message; got: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
}
#[cfg(unix)]
#[test]
fn lint_json_forbidden_char_in_import_path_is_refused_at_input() {
for ch in ['\u{0085}', '\u{202E}'] {
let dir = tempfile::tempdir().unwrap();
let name = format!("fo{ch}o.mds");
fs::write(dir.path().join(&name), "hi\n").unwrap();
let import_line = format!("@import \"./{name}\"\n");
let main_file = dir.path().join("main.mds");
fs::write(&main_file, format!("{import_line}{import_line}")).unwrap();
let out = lint_path(&main_file, &["--format", "json"]);
let stdout_str = String::from_utf8_lossy(&out.stdout);
let u = format!("U+{:04X}", u32::from(ch));
assert_eq!(out.status.code(), Some(2), "{u}: stdout {stdout_str:?}");
assert_no_control_chars(&stdout_str, "refused import JSON");
let json: serde_json::Value = serde_json::from_str(&stdout_str)
.unwrap_or_else(|e| panic!("{u}: invalid JSON ({e}): {stdout_str:?}"));
assert_eq!(json["error"]["code"], "mds::import", "{u}: {json}");
let expected = format!(
"import path contains forbidden character {u}: \"./fo\\u{:04X}o.mds\"",
u32::from(ch)
);
let message = json["error"]["message"].as_str().unwrap_or_default();
assert!(
message.contains(&expected),
"{u}: {expected:?} in {message:?}"
);
}
}
#[test]
fn lint_json_newline_in_frontmatter_key_is_escaped_on_the_wire() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("forge.mds");
fs::write(
&file,
b"---\n\"a\\nerror[mds::forged]: FAKE\\nb\": 1\n---\nHello\n",
)
.unwrap();
let out = lint_path(&file, &["--format", "json"]);
let stdout_str = String::from_utf8_lossy(&out.stdout);
let json: serde_json::Value = serde_json::from_str(&stdout_str).unwrap_or_else(|e| {
panic!("T-9c: lint --format json must emit valid JSON; parse error: {e}; stdout: {stdout_str:?}")
});
assert_eq!(json["version"], 1, "T-9c: JSON version must be 1");
let files = json["files"]
.as_array()
.unwrap_or_else(|| panic!("T-9c: JSON must have 'files' array; got: {json}"));
assert!(
!files.is_empty(),
"T-9c: files array must be non-empty; got: {json}"
);
let all_diags: Vec<&serde_json::Value> = files
.iter()
.flat_map(|f| {
f["diagnostics"]
.as_array()
.unwrap_or_else(|| panic!("T-9c: every file entry needs 'diagnostics'; got: {f}"))
})
.collect();
assert!(
all_diags.iter().any(|d| d["rule"] == "unused-variable"),
"T-9c: unused-variable must fire; got rules: {:?}",
all_diags.iter().map(|d| &d["rule"]).collect::<Vec<_>>()
);
for diag in &all_diags {
let msg = diag["message"].as_str().unwrap_or_else(|| {
panic!("T-9c: diagnostic must have a string 'message'; got: {diag}")
});
assert!(
!msg.contains('\n'),
"T-9c: raw newline must not survive into a wire message; got: {msg:?}"
);
}
assert!(
all_diags
.iter()
.any(|d| d["message"].as_str().is_some_and(|m| m.contains("\\u000A"))),
"T-9c: escaped \\u000A literal must appear in at least one diagnostic message; \
got messages: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
assert!(
all_diags.iter().any(|d| d["message"]
.as_str()
.is_some_and(|m| m.contains("error[mds::forged]"))),
"T-9c: message body must be preserved verbatim; got messages: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
}
#[cfg(unix)]
#[test]
fn lint_fix_preserves_mode_0644() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("perm_lint.mds");
fs::write(
&target,
"@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n",
)
.unwrap();
fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap();
let out = lint_path(&target, &["--fix"]);
assert!(
out.status.success(),
"lint --fix should succeed on duplicate-export fixture; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let mode = fs::metadata(&target).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode, 0o644,
"lint --fix must preserve file mode 0644 after atomic write; got 0{mode:o}"
);
}
#[cfg(unix)]
#[test]
fn lint_write_failure_includes_filename_in_stderr() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("write_fail.mds");
fs::write(
&target,
"@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n",
)
.unwrap();
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&target, &["--fix"]);
let _ = fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755));
assert_ne!(
out.status.code(),
Some(0),
"lint --fix must fail when the parent dir is read-only"
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("write_fail.mds"),
"error stderr must contain the target filename; got: {stderr}"
);
}
#[cfg(unix)]
#[test]
fn lint_fix_write_failure_does_not_print_fixed_label_single_file() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("no_fixed_label.mds");
fs::write(
&target,
"@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n",
)
.unwrap();
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&target, &["--fix"]);
let _ = fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&out.stderr);
assert_ne!(
out.status.code(),
Some(0),
"lint --fix must fail when the parent dir is read-only; stderr: {stderr}"
);
assert!(
!stderr.contains("Fixed:"),
"stderr must not contain 'Fixed:' when the write failed; got: {stderr}"
);
}
#[cfg(unix)]
#[test]
fn lint_fix_write_failure_does_not_print_fixed_label_directory() {
use std::os::unix::fs::PermissionsExt as _;
let outer = tempfile::tempdir().unwrap();
let inner = outer.path().join("files");
fs::create_dir(&inner).unwrap();
let target = inner.join("no_fixed_label_dir.mds");
fs::write(
&target,
"@define greet(name):\n Hello {{name}}!\n@end\n\n@export greet\n@export greet\n",
)
.unwrap();
fs::set_permissions(&inner, fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&inner, &["--fix"]);
let _ = fs::set_permissions(&inner, fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Fixed:"),
"stderr must not contain 'Fixed:' when the directory-mode write failed; got: {stderr}"
);
}
#[cfg(unix)]
#[test]
fn lint_fix_write_failure_json_dir_does_not_print_fixed_label() {
use std::os::unix::fs::PermissionsExt as _;
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("fixable.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Fixed:"),
"positive control: dir --fix --format json must emit 'Fixed:' when the write \
succeeds (otherwise the absence assertion below is vacuous; ADR-009); \
got stderr: {stderr:?}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"stdout must be valid JSON in dir --fix --format json; err: {e}; stdout: {stdout}"
)
});
}
let outer = tempfile::tempdir().unwrap();
let inner = outer.path().join("files");
fs::create_dir(&inner).unwrap();
let target = inner.join("no_fixed_label_json.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
fs::set_permissions(&inner, fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&inner, &["--fix", "--format", "json"]);
let _ = fs::set_permissions(&inner, fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Fixed:"),
"stderr must not contain 'Fixed:' when the JSON-dir write failed \
(`Rewrite::WriteFailed` is shown without `ResultSink::fixed`); got: {stderr:?}"
);
}
#[cfg(unix)]
#[test]
fn file_fix_json_dir_write_failure_emits_structured_error_not_stale_result() {
use std::os::unix::fs::PermissionsExt as _;
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("fixable.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"positive control: dir --fix --format json must exit 0 after a successful fix; \
stderr: {stderr}"
);
assert!(
stderr.contains("Fixed:"),
"positive control: dir --fix --format json must emit 'Fixed:' when write succeeds \
(otherwise the error-entry absence assertion below is vacuous; ADR-009); \
got stderr: {stderr:?}"
);
let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"positive control: dir --fix --format json must emit valid JSON; \
err: {e}; stdout: {stdout}"
)
});
let files = json["files"].as_array().expect("files[] must be an array");
assert!(
!files.iter().any(|f| f.get("error").is_some()),
"positive control: files[] must not contain an error entry on success; got: {files:?}"
);
}
let outer = tempfile::tempdir().unwrap();
let inner = outer.path().join("files");
fs::create_dir(&inner).unwrap();
fs::copy(fixture("lint_error.mds"), inner.join("fixable.mds")).unwrap();
fs::set_permissions(&inner, fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&inner, &["--fix", "--format", "json"]);
let _ = fs::set_permissions(&inner, fs::Permissions::from_mode(0o755));
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_ne!(
out.status.code(),
Some(0),
"dir --fix --format json with a read-only inner dir must exit non-zero; \
stderr: {stderr}"
);
let json: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"dir --fix --format json must emit parseable JSON even on write failure \
(AC-F-14); parse error: {e}; stdout: '{stdout}'"
)
});
let files = json["files"].as_array().expect("files[] must be an array");
assert!(
!files.is_empty(),
"files[] must be non-empty — the failed file must have an entry; got: {json}"
);
assert!(
files.iter().any(|f| f.get("error").is_some()),
"files[] must contain a structured error entry ({{\"file\":…,\"error\":…}}) for the \
file whose write failed; got files: {files:?}"
);
assert!(
!files.iter().any(|f| f.get("diagnostics").is_some()),
"files[] must NOT contain a diagnostics entry for the write-failed file — \
the stale post-fix result must not be pushed before the write; got: {files:?}"
);
}
#[test]
fn lint_directory_esc_byte_in_syntax_error_is_sanitized_on_stderr() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("esc_dir.mds"), b"@define \x1bfoo:\nhello\n").unwrap();
let out = lint_path(dir.path(), &[]);
assert_ne!(
out.status.code(),
Some(0),
"lint dir with syntax error should exit non-zero; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(
!out.stderr.contains(&0x1Bu8),
"raw ESC byte (0x1B) must be sanitized before writing to stderr (directory mode); \
got (hex): {:02x?}",
&out.stderr[..out.stderr.len().min(512)]
);
assert!(
!out.stdout.contains(&0x1Bu8),
"raw ESC byte (0x1B) must not appear in stdout; \
got (hex): {:02x?}",
&out.stdout[..out.stdout.len().min(512)]
);
}
#[test]
fn lint_dir_nested_config_per_file_discovery() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
fs::write(
root.join("mds.json"),
r#"{"lint":{"rules":{"shadow-variable":"off"}}}"#,
)
.unwrap();
let shadow_template = "---\nitem: outer\nitems: [a, b]\n---\n\
Before: {item}\n@for item in items:\n- {item}\n@end\nAfter: {item}\n";
fs::write(root.join("top.mds"), shadow_template).unwrap();
let sub = root.join("sub");
fs::create_dir(&sub).unwrap();
fs::write(
sub.join("mds.json"),
r#"{"lint":{"rules":{"shadow-variable":"error"}}}"#,
)
.unwrap();
fs::write(sub.join("sub.mds"), shadow_template).unwrap();
let out = lint_path(root, &[]);
assert_eq!(
out.status.code(),
Some(2),
"lint dir with nested config (shadow-variable=error in sub/) must exit 2; \
stderr: {}\nstdout: {}",
String::from_utf8_lossy(&out.stderr),
String::from_utf8_lossy(&out.stdout),
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("sub.mds") || stderr.contains("sub"),
"stderr must mention sub.mds as the source of the error; got: {stderr}"
);
}
#[test]
fn lint_dir_nested_malformed_config_per_file_error() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
fs::write(
root.join("clean.mds"),
"---\ngreeting: hi\n---\n{{greeting}} world!\n",
)
.unwrap();
let bad = root.join("bad");
fs::create_dir(&bad).unwrap();
fs::write(bad.join("mds.json"), "{ INVALID JSON").unwrap();
fs::write(
bad.join("bad.mds"),
"---\ngreeting: hi\n---\n{{greeting}} world!\n",
)
.unwrap();
let out = lint_path(root, &[]);
assert_eq!(
out.status.code(),
Some(2),
"lint dir with malformed nested mds.json must exit 2; \
stderr: {}\nstdout: {}",
String::from_utf8_lossy(&out.stderr),
String::from_utf8_lossy(&out.stdout),
);
let combined = format!(
"{}{}",
String::from_utf8_lossy(&out.stderr),
String::from_utf8_lossy(&out.stdout)
);
assert!(
combined.contains("mds.json") || combined.contains("config") || combined.contains("bad"),
"output must reference the malformed config source; got: {combined}"
);
}
fn write_unknown_rule_config(dir: &std::path::Path) {
let config = serde_json::json!({
"lint": {
"rules": {
"no-such-rule-xyzzy": "warn"
}
}
});
std::fs::write(
dir.join("mds.json"),
serde_json::to_string(&config).unwrap(),
)
.unwrap();
}
#[test]
fn unknown_rule_warning_to_stderr_not_stdout_in_json_mode() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("clean.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!(
"AC-224-21: stdout must be valid JSON even when unknown rules are present; \
parse error: {e}; stdout: {stdout}"
)
});
assert_eq!(
parsed["version"].as_u64(),
Some(1),
"AC-224-21: JSON must have version:1; got: {parsed}"
);
assert!(
!stdout.contains("unknown"),
"AC-224-21: 'unknown' warning text must not appear in stdout JSON; got: {stdout}"
);
assert!(
stderr.contains("unknown lint rule") && stderr.contains("no-such-rule-xyzzy"),
"AC-224-11: the unknown-rule warning must go to stderr and name the rule; \
got stderr: {stderr}"
);
}
#[test]
fn unknown_rule_json_wire_shape_unchanged() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let parsed: serde_json::Value =
serde_json::from_str(stdout.trim()).expect("stdout must be valid JSON");
assert!(
parsed.get("files").is_some(),
"AC-224-10: 'files' key must be present in the JSON output; got: {parsed}"
);
assert!(
parsed.get("truncated").is_some(),
"AC-224-10: 'truncated' key must be present in the JSON output; got: {parsed}"
);
assert!(
parsed.get("error").is_none(),
"AC-224-10: no 'error' key must appear for a lint-continues result; got: {parsed}"
);
assert_eq!(
out.status.code(),
Some(0),
"AC-224-10: exit code must be 0 when the only unknown element is a rule name; \
got stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
}
#[test]
fn unknown_rule_warning_suppressed_by_quiet() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.arg("--quiet")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("unknown lint rule") && !stderr.contains("no-such-rule-xyzzy"),
"AC-224-22: --quiet must suppress the unknown-rule warning; got stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(0),
"AC-224-22: exit code must be 0; got stderr: {stderr}"
);
}
#[test]
fn unknown_rule_one_warning_per_invocation_not_per_file() {
let dir = tempfile::tempdir().unwrap();
for subdir in ["a", "b", "c", "c/d"] {
let sub = dir.path().join(subdir);
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(sub.join("file.mds"), "Hello!\n").unwrap();
}
std::fs::write(dir.path().join("root.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("unknown lint rule") && stderr.contains("no-such-rule-xyzzy"),
"AC-224-19: warning must appear on stderr; got stderr: {stderr}"
);
let warning_count = stderr
.lines()
.filter(|l| l.contains("unknown lint rule"))
.count();
assert_eq!(
warning_count, 1,
"AC-224-19: warning must appear exactly once per distinct config directory \
(got {warning_count} — one per subdir instead of one per config); \
got stderr:\n{stderr}"
);
}
#[test]
fn unknown_rule_plural_sorted_warning() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
write_rules_config(
dir.path(),
serde_json::json!({
"zzz-bad": "warn",
"aaa-bad": "error",
"unused-variable": "off"
}),
);
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("aaa-bad"),
"AC-224-2: 'aaa-bad' must appear in the plural warning; got stderr: {stderr}"
);
assert!(
stderr.contains("zzz-bad"),
"AC-224-2: 'zzz-bad' must appear in the plural warning; got stderr: {stderr}"
);
assert!(
stderr.contains("unknown lint rules"),
"AC-224-2: plural form must be used for two unknown names; got stderr: {stderr}"
);
let aaa_pos = stderr
.find("aaa-bad")
.expect("aaa-bad must appear in stderr");
let zzz_pos = stderr
.find("zzz-bad")
.expect("zzz-bad must appear in stderr");
assert!(
aaa_pos < zzz_pos,
"AC-224-2: 'aaa-bad' must appear before 'zzz-bad' (lexicographic order); \
got stderr: {stderr}"
);
assert!(
stderr.contains("recognised rules are"),
"recognised-rules list must be included in the plural warning; got stderr: {stderr}"
);
let warning_line = stderr
.lines()
.find(|l| l.contains("unknown lint rules"))
.unwrap_or_else(|| panic!("no plural unknown-rule warning line; got stderr: {stderr}"));
assert!(
!warning_line.contains("'unused-variable'"),
"a recognised rule name must not appear quoted in the unknown-names list; \
got warning line: {warning_line}"
);
}
#[test]
fn unknown_rule_cli_exact_golden() {
#[rustfmt::skip]
let recognised = concat!(
"duplicate-export, duplicate-import, empty-block, legacy-interpolation, ",
"literal-directive, redundant-else, shadow-variable, unreachable-branch, ",
"unused-function, unused-import, unused-variable"
);
{
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
write_rules_config(
dir.path(),
serde_json::json!({ "no-such-rule-xyzzy": "warn" }),
);
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
let expected_singular = format!(
"{}unknown lint rule 'no-such-rule-xyzzy'; \
recognised rules are: {recognised}; ignoring",
unknown_rule_warning_prefix(dir.path())
);
let warning_line = stderr
.lines()
.find(|l| l.contains("unknown lint rule"))
.unwrap_or_else(|| {
panic!("no singular unknown-rule warning line; got stderr: {stderr}")
});
assert_eq!(
warning_line.trim(),
expected_singular,
"AC-224-2/AC-224-3 singular golden mismatch"
);
}
{
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!\n").unwrap();
write_rules_config(
dir.path(),
serde_json::json!({ "zzz-bad": "warn", "aaa-bad": "error" }),
);
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
let expected_plural = format!(
"{}unknown lint rules: 'aaa-bad', 'zzz-bad'; \
recognised rules are: {recognised}; ignoring",
unknown_rule_warning_prefix(dir.path())
);
let warning_line = stderr
.lines()
.find(|l| l.contains("unknown lint rules"))
.unwrap_or_else(|| panic!("no plural unknown-rule warning line; got stderr: {stderr}"));
assert_eq!(
warning_line.trim(),
expected_plural,
"AC-224-2/AC-224-3 plural golden mismatch"
);
}
}
#[test]
fn unknown_rule_cli_exact_golden_single_file() {
#[rustfmt::skip]
let recognised = concat!(
"duplicate-export, duplicate-import, empty-block, legacy-interpolation, ",
"literal-directive, redundant-else, shadow-variable, unreachable-branch, ",
"unused-function, unused-import, unused-variable"
);
{
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
std::fs::write(&file, "Hello!\n").unwrap();
write_rules_config(
dir.path(),
serde_json::json!({ "no-such-rule-xyzzy": "warn" }),
);
let out = mds_bin()
.arg("lint")
.arg(&file)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
let expected_singular = format!(
"{}unknown lint rule 'no-such-rule-xyzzy'; \
recognised rules are: {recognised}; ignoring",
unknown_rule_warning_prefix(dir.path())
);
let warning_line = stderr
.lines()
.find(|l| l.contains("unknown lint rule"))
.unwrap_or_else(|| {
panic!(
"AC-224-2/AC-224-3 single-file: no singular unknown-rule warning; \
got stderr: {stderr}"
)
});
assert_eq!(
warning_line.trim(),
expected_singular,
"AC-224-2/AC-224-3 single-file singular golden mismatch"
);
}
{
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
std::fs::write(&file, "Hello!\n").unwrap();
write_rules_config(
dir.path(),
serde_json::json!({ "zzz-bad": "warn", "aaa-bad": "error" }),
);
let out = mds_bin()
.arg("lint")
.arg(&file)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
let expected_plural = format!(
"{}unknown lint rules: 'aaa-bad', 'zzz-bad'; \
recognised rules are: {recognised}; ignoring",
unknown_rule_warning_prefix(dir.path())
);
let warning_line = stderr
.lines()
.find(|l| l.contains("unknown lint rules"))
.unwrap_or_else(|| {
panic!(
"AC-224-2/AC-224-3 single-file: no plural unknown-rule warning; \
got stderr: {stderr}"
)
});
assert_eq!(
warning_line.trim(),
expected_plural,
"AC-224-2/AC-224-3 single-file plural golden mismatch"
);
}
}
fn write_mixed_lint_tree(dir: &std::path::Path) {
std::fs::write(dir.join("clean.mds"), "Hello!\n").unwrap();
std::fs::write(
dir.join("unused.mds"),
"---\nunused_key: value\n---\nHello!\n",
)
.unwrap();
std::fs::write(
dir.join("dup.mds"),
"---\nanother_unused: v\n---\nHi there!\n",
)
.unwrap();
}
fn write_rules_config(dir: &std::path::Path, rules: serde_json::Value) {
let config = serde_json::json!({ "lint": { "rules": rules } });
std::fs::write(
dir.join("mds.json"),
serde_json::to_string(&config).unwrap(),
)
.unwrap();
}
fn unknown_rule_warning_prefix(config_dir: &std::path::Path) -> String {
format!("warning: in {}: ", config_dir.join("mds.json").display())
}
#[test]
fn unknown_rule_warning_names_the_mds_json_as_the_input_reached_it() {
let lint_from = |cwd: &std::path::Path, args: &[&str]| {
let out = mds_bin()
.current_dir(cwd)
.arg("lint")
.args(args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
String::from_utf8_lossy(&out.stderr).into_owned()
};
let shown = |parts: &[&str]| -> String {
let path: std::path::PathBuf = parts.iter().collect();
format!("warning: in {}: unknown lint rule", path.display())
};
let top = tempfile::tempdir().unwrap();
std::fs::write(top.path().join("top.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(top.path());
let stderr = lint_from(top.path(), &["."]);
let want = shown(&[".", "mds.json"]);
assert!(
stderr.lines().any(|l| l.starts_with(&want)),
"`mds lint .` must name the config as {want:?}; stderr: {stderr}"
);
let root = tempfile::tempdir().unwrap();
std::fs::create_dir(root.path().join("sub")).unwrap();
std::fs::write(root.path().join("sub").join("a.mds"), "Hello!\n").unwrap();
write_unknown_rule_config(root.path());
let sub_file = std::path::Path::new("sub").join("a.mds");
for (args, parts) in [
(&["sub"][..], &["sub", "..", "mds.json"][..]),
(
&[sub_file.to_str().unwrap()][..],
&["sub", "..", "mds.json"][..],
),
(&["."][..], &[".", "sub", "..", "mds.json"][..]),
] {
let stderr = lint_from(root.path(), args);
let want = shown(parts);
assert!(
stderr.lines().any(|l| l.starts_with(&want)),
"`mds lint {args:?}` must name the config as {want:?}; stderr: {stderr}"
);
}
let tree = tempfile::tempdir().unwrap();
std::fs::create_dir(tree.path().join("sub")).unwrap();
std::fs::write(tree.path().join("sub").join("a.mds"), "Hello!\n").unwrap();
std::fs::write(tree.path().join("mds.json"), "{}").unwrap();
write_unknown_rule_config(&tree.path().join("sub"));
let stderr = lint_from(tree.path(), &["."]);
let want = shown(&[".", "sub", "mds.json"]);
assert!(
stderr.lines().any(|l| l.starts_with(&want)),
"a nested config must be named as {want:?}; stderr: {stderr}"
);
}
#[test]
fn unknown_rule_json_stdout_is_byte_identical_to_run_without_it() {
let with_dir = tempfile::tempdir().unwrap();
write_mixed_lint_tree(with_dir.path());
write_rules_config(
with_dir.path(),
serde_json::json!({ "unused-variable": "warn", "no-such-rule-xyzzy": "warn" }),
);
let without_dir = tempfile::tempdir().unwrap();
write_mixed_lint_tree(without_dir.path());
write_rules_config(
without_dir.path(),
serde_json::json!({ "unused-variable": "warn" }),
);
let run = |dir: &std::path::Path| {
mds_bin()
.arg("lint")
.arg(dir)
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
};
let with = run(with_dir.path());
let without = run(without_dir.path());
let with_stderr = String::from_utf8_lossy(&with.stderr);
assert!(
with_stderr.contains("unknown lint rule") && with_stderr.contains("no-such-rule-xyzzy"),
"non-vacuity: the unknown-rule warning must fire on stderr; got: {with_stderr}"
);
let without_stderr = String::from_utf8_lossy(&without.stderr);
assert!(
!without_stderr.contains("unknown lint rule"),
"control run must not warn; got: {without_stderr}"
);
assert_eq!(
with.stdout,
without.stdout,
"AC-224-10: stdout must be byte-identical with and without the unknown rule name;\n\
with: {}\nwithout: {}",
String::from_utf8_lossy(&with.stdout),
String::from_utf8_lossy(&without.stdout)
);
assert_eq!(
with.status.code(),
without.status.code(),
"AC-224-13: the exit code must not move because of an unknown rule name"
);
let parsed: serde_json::Value =
serde_json::from_str(String::from_utf8_lossy(&with.stdout).trim())
.expect("stdout must be valid JSON");
let obj = parsed.as_object().expect("envelope must be a JSON object");
let mut top_keys: Vec<&str> = obj.keys().map(String::as_str).collect();
top_keys.sort_unstable();
assert_eq!(
top_keys,
["files", "truncated", "version"],
"AC-224-10: the top-level key set must be exactly {{files, truncated, version}}; \
got: {parsed}"
);
assert_eq!(parsed["version"].as_u64(), Some(1));
let files = parsed["files"].as_array().expect("files must be an array");
assert!(
!files.is_empty(),
"non-vacuity: the fixture tree must produce at least one files[] entry; got: {parsed}"
);
for entry in files {
let e = entry.as_object().expect("files[] entry must be an object");
assert!(
e.contains_key("diagnostics"),
"AC-224-10: every files[] entry must carry a diagnostics key; got: {entry}"
);
assert!(
!e.contains_key("error"),
"AC-224-10: no files[] entry may carry an error key; got: {entry}"
);
}
}
#[test]
fn unknown_rule_json_stdout_contains_no_warning_text() {
let dir = tempfile::tempdir().unwrap();
write_mixed_lint_tree(dir.path());
write_rules_config(
dir.path(),
serde_json::json!({ "no-such-rule-xyzzy": "warn" }),
);
let out = mds_bin()
.arg("lint")
.arg(dir.path())
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("no-such-rule-xyzzy") && stderr.contains("recognised rules are"),
"positive control: the warning must be on stderr; got: {stderr}"
);
for needle in [
"no-such-rule-xyzzy",
"recognised rules are",
"warning",
"ignoring",
] {
assert!(
!stdout.contains(needle),
"AC-224-21: stdout must not contain {needle:?}; got: {stdout}"
);
}
serde_json::from_str::<serde_json::Value>(stdout.trim())
.expect("AC-224-21: stdout must parse as a single JSON document");
}
#[test]
fn unknown_rule_json_stdout_clean_single_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("clean.mds");
std::fs::write(&file, "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let out = mds_bin()
.arg("lint")
.arg(&file)
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("unknown lint rule") && stderr.contains("no-such-rule-xyzzy"),
"AC-224-21 (file): warning must fire on stderr; got: {stderr}"
);
serde_json::from_str::<serde_json::Value>(stdout.trim()).unwrap_or_else(|e| {
panic!("AC-224-21 (file): stdout must be valid JSON; error: {e}; got: {stdout}")
});
for needle in [
"no-such-rule-xyzzy",
"recognised rules are",
"warning",
"ignoring",
] {
assert!(
!stdout.contains(needle),
"AC-224-21 (file): stdout must not contain {needle:?}; got: {stdout}"
);
}
}
#[test]
fn unknown_rule_json_stdout_clean_stdin() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
write_unknown_rule_config(dir.path());
let mut child = mds_bin()
.arg("lint")
.arg("-")
.arg("--format")
.arg("json")
.current_dir(dir.path())
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(b"Hello!\n");
let out = child.wait_with_output().unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("unknown lint rule") && stderr.contains("no-such-rule-xyzzy"),
"AC-224-21 (stdin): warning must fire on stderr; got: {stderr}"
);
serde_json::from_str::<serde_json::Value>(stdout.trim()).unwrap_or_else(|e| {
panic!("AC-224-21 (stdin): stdout must be valid JSON; error: {e}; got: {stdout}")
});
for needle in [
"no-such-rule-xyzzy",
"recognised rules are",
"warning",
"ignoring",
] {
assert!(
!stdout.contains(needle),
"AC-224-21 (stdin): stdout must not contain {needle:?}; got: {stdout}"
);
}
}
#[test]
fn unknown_rule_warning_suppressed_by_global_quiet_form() {
let dir = tempfile::tempdir().unwrap();
write_mixed_lint_tree(dir.path());
write_rules_config(
dir.path(),
serde_json::json!({ "no-such-rule-xyzzy": "warn" }),
);
let loud = mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
assert!(
String::from_utf8_lossy(&loud.stderr).contains("unknown lint rule"),
"positive control: the non-quiet run must warn"
);
for args in [vec!["lint", "--quiet"], vec!["--quiet", "lint"]] {
let mut cmd = mds_bin();
for a in &args {
cmd.arg(a);
}
let out = cmd
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("unknown lint rule") && !stderr.contains("no-such-rule-xyzzy"),
"AC-224-22: `mds {}` must suppress the unknown-rule warning; got: {stderr}",
args.join(" ")
);
assert_eq!(
out.status.code(),
loud.status.code(),
"AC-224-22: --quiet must not move the exit code (form: {})",
args.join(" ")
);
}
}
#[test]
fn unknown_rule_warning_suppressed_by_quiet_single_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("clean.mds");
std::fs::write(&file, "Hello!\n").unwrap();
write_unknown_rule_config(dir.path());
let loud = mds_bin()
.arg("lint")
.arg(&file)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
assert!(
String::from_utf8_lossy(&loud.stderr).contains("unknown lint rule"),
"positive control: single-file mode without --quiet must warn; got: {}",
String::from_utf8_lossy(&loud.stderr)
);
let out = mds_bin()
.arg("lint")
.arg(&file)
.arg("--quiet")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("unknown lint rule") && !stderr.contains("no-such-rule-xyzzy"),
"AC-224-22 (single-file): --quiet must suppress the unknown-rule warning; got: {stderr}"
);
assert_eq!(
out.status.code(),
loud.status.code(),
"AC-224-22 (single-file): --quiet must not move the exit code; got stderr: {stderr}"
);
}
#[test]
fn unknown_rule_warning_suppressed_by_quiet_stdin() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
write_unknown_rule_config(dir.path());
let mut loud_child = mds_bin()
.arg("lint")
.arg("-")
.current_dir(dir.path())
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = loud_child.stdin.take().unwrap().write_all(b"Hello!\n");
let loud = loud_child.wait_with_output().unwrap();
assert!(
String::from_utf8_lossy(&loud.stderr).contains("unknown lint rule"),
"positive control: stdin mode without --quiet must warn; got: {}",
String::from_utf8_lossy(&loud.stderr)
);
let mut child = mds_bin()
.arg("lint")
.arg("-")
.arg("--quiet")
.current_dir(dir.path())
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(b"Hello!\n");
let out = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("unknown lint rule") && !stderr.contains("no-such-rule-xyzzy"),
"AC-224-22 (stdin): --quiet must suppress the unknown-rule warning; got: {stderr}"
);
assert_eq!(
out.status.code(),
loud.status.code(),
"AC-224-22 (stdin): --quiet must not move the exit code; got stderr: {stderr}"
);
}
#[test]
fn unknown_rule_does_not_change_fix_behaviour() {
fn build_tree(rules: serde_json::Value) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("lint_error.mds");
fs::copy(fixture("lint_error.mds"), &target).unwrap();
write_rules_config(dir.path(), rules);
(dir, target)
}
let valid_rules = serde_json::json!({ "duplicate-export": "error" });
let mut with_rules = valid_rules.clone();
with_rules["no-such-rule-xyzzy"] = serde_json::json!("warn");
let (with_dir, with_target) = build_tree(with_rules.clone());
let (without_dir, without_target) = build_tree(valid_rules.clone());
let with_before = fs::read(&with_target).unwrap();
let with_check = lint_path(with_dir.path(), &["--fix", "--check"]);
let without_check = lint_path(without_dir.path(), &["--fix", "--check"]);
assert!(
String::from_utf8_lossy(&with_check.stderr).contains("unknown lint rule"),
"non-vacuity: the unknown-rule tree must warn"
);
assert_eq!(
with_check.status.code(),
without_check.status.code(),
"AC-224-12: --fix --check exit code must not move"
);
assert_eq!(
fs::read(&with_target).unwrap(),
with_before,
"AC-224-12: --fix --check must not write"
);
let with_diff = lint_path(with_dir.path(), &["--fix", "--diff"]);
let without_diff = lint_path(without_dir.path(), &["--fix", "--diff"]);
let normalize = |bytes: &[u8], root: &std::path::Path| {
String::from_utf8_lossy(bytes).replace(root.to_string_lossy().as_ref(), "<DIR>")
};
let with_diff_text = normalize(&with_diff.stdout, with_dir.path());
let without_diff_text = normalize(&without_diff.stdout, without_dir.path());
assert!(
with_diff_text.contains("@export greet"),
"non-vacuity: --fix --diff must actually render a hunk; got: {with_diff_text}"
);
assert_eq!(
with_diff_text, without_diff_text,
"AC-224-12: --fix --diff output must be identical once the tempdir root is normalised"
);
assert_eq!(
with_diff.status.code(),
without_diff.status.code(),
"AC-224-12: --fix --diff exit code must not move"
);
assert_eq!(
fs::read(&with_target).unwrap(),
with_before,
"AC-224-12: --fix --diff must not write"
);
let with_fix = lint_path(with_dir.path(), &["--fix"]);
let without_fix = lint_path(without_dir.path(), &["--fix"]);
assert_eq!(
with_fix.status.code(),
without_fix.status.code(),
"AC-224-12: --fix exit code must not move"
);
let with_after = fs::read(&with_target).unwrap();
let without_after = fs::read(&without_target).unwrap();
assert_eq!(
with_after, without_after,
"AC-224-12: the fixed file bytes must be identical with and without the unknown rule"
);
assert_ne!(
with_after, with_before,
"non-vacuity: a fix must actually have been applied, or the parity above is empty"
);
for dir in [with_dir.path(), without_dir.path()] {
for entry in fs::read_dir(dir).unwrap() {
let name = entry.unwrap().file_name();
let name = name.to_string_lossy();
assert!(
name == "lint_error.mds" || name == "mds.json",
"AC-224-12: --fix must leave no temp or backup artefact; found {name}"
);
}
}
}
#[test]
fn unknown_rule_human_stdout_empty_and_per_file_output_unchanged() {
let dir = tempfile::tempdir().unwrap();
write_mixed_lint_tree(dir.path());
let run = || {
mds_bin()
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
};
write_rules_config(
dir.path(),
serde_json::json!({ "unused-variable": "warn", "no-such-rule-xyzzy": "warn" }),
);
let with = run();
write_rules_config(dir.path(), serde_json::json!({ "unused-variable": "warn" }));
let without = run();
let with_stderr = String::from_utf8_lossy(&with.stderr);
let without_stderr = String::from_utf8_lossy(&without.stderr);
assert!(
with_stderr.contains("unknown lint rule") && with_stderr.contains("no-such-rule-xyzzy"),
"non-vacuity: the unknown-rule warning must fire on stderr in human mode; \
got: {with_stderr}"
);
assert!(
!without_stderr.contains("unknown lint rule"),
"control run must not warn; got: {without_stderr}"
);
assert!(
without_stderr.contains("unused-variable"),
"non-vacuity: the fixture tree must produce per-file diagnostics on stderr; \
got: {without_stderr}"
);
assert!(
with.stdout.is_empty(),
"AC-224-11: human-format stdout must be empty on the unknown-rule path; got: {}",
String::from_utf8_lossy(&with.stdout)
);
assert!(
without.stdout.is_empty(),
"AC-224-11: human-format stdout must be empty in the control run; got: {}",
String::from_utf8_lossy(&without.stdout)
);
let with_minus_warning: String = with_stderr
.lines()
.filter(|l| !l.contains("unknown lint rule"))
.map(|l| format!("{l}\n"))
.collect();
let without_normalized: String = without_stderr.lines().map(|l| format!("{l}\n")).collect();
assert_eq!(
with_minus_warning, without_normalized,
"AC-224-11: apart from the added warning line, human-mode stderr must be \
identical with and without the unknown rule name;\nwith:\n{with_stderr}\n\
without:\n{without_stderr}"
);
assert_eq!(
with.status.code(),
without.status.code(),
"AC-224-13: the exit code must not move because of an unknown rule name in human mode"
);
}
#[test]
fn unknown_rule_nested_config_warns_once_and_envelope_unchanged() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir_all(&sub).unwrap();
std::fs::write(
dir.path().join("root.mds"),
"---\nroot_unused: v\n---\nHi!\n",
)
.unwrap();
std::fs::write(sub.join("nested.mds"), "---\nsub_unused: v\n---\nHo!\n").unwrap();
let run = || {
mds_bin()
.arg("lint")
.arg(dir.path())
.arg("--format")
.arg("json")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
};
write_rules_config(
&sub,
serde_json::json!({ "unused-variable": "warn", "no-such-rule-xyzzy": "warn" }),
);
let with = run();
write_rules_config(&sub, serde_json::json!({ "unused-variable": "warn" }));
let without = run();
let with_stderr = String::from_utf8_lossy(&with.stderr);
let warning_count = with_stderr
.lines()
.filter(|l| l.contains("unknown lint rule"))
.count();
assert_eq!(
warning_count, 1,
"AC-224-19 (nested): the subdirectory config must warn exactly once; got stderr:\n\
{with_stderr}"
);
assert!(
with_stderr.contains("no-such-rule-xyzzy"),
"non-vacuity: the warning must name the unknown rule; got: {with_stderr}"
);
assert!(
!String::from_utf8_lossy(&without.stderr).contains("unknown lint rule"),
"control run must not warn; got: {}",
String::from_utf8_lossy(&without.stderr)
);
assert_eq!(
with.stdout,
without.stdout,
"AC-224-10 (nested): stdout must be byte-identical with and without the unknown \
rule name;\nwith: {}\nwithout: {}",
String::from_utf8_lossy(&with.stdout),
String::from_utf8_lossy(&without.stdout)
);
assert_eq!(
with.status.code(),
without.status.code(),
"AC-224-13 (nested): the exit code must not move"
);
let parsed: serde_json::Value =
serde_json::from_str(String::from_utf8_lossy(&with.stdout).trim())
.expect("stdout must be valid JSON");
let files: Vec<String> = parsed["files"]
.as_array()
.expect("files must be an array")
.iter()
.map(|f| f["file"].as_str().unwrap_or_default().to_string())
.collect();
assert!(
files.iter().any(|f| f == "root.mds"),
"non-vacuity: the root file must still be linted; got files: {files:?}"
);
assert!(
files.iter().any(|f| f == "sub/nested.mds"),
"non-vacuity: the nested file must still be linted; got files: {files:?}"
);
}
#[test]
fn lint_directory_prints_summary_when_clean() {
let dir = tempfile::tempdir().unwrap();
for name in &["a.mds", "b.mds", "c.mds"] {
fs::copy(fixture("lint_clean.mds"), dir.path().join(name)).unwrap();
}
let out = lint_path(dir.path(), &[]);
assert_eq!(
out.status.code(),
Some(0),
"clean directory must exit 0; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.is_empty(),
"stdout must be empty in human mode; got: {stdout:?}"
);
let stderr_trimmed = String::from_utf8_lossy(&out.stderr).trim().to_string();
assert_eq!(
stderr_trimmed, "3 clean, 0 with warnings, 0 with errors, 0 resource-limited",
"AC-Q06: trimmed stderr must equal the exact summary string"
);
}
#[test]
fn lint_directory_summary_counts_each_severity_bucket() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean1.mds")).unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean2.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("warn.mds")).unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"directory with an error file must exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("2 clean, 1 with warnings, 1 with errors, 0 resource-limited"),
"AC-Q07: summary must contain '2 clean, 1 with warnings, 1 with errors, 0 resource-limited'; \
got: {stderr:?}"
);
let counts = parse_summary_counts(&stderr);
assert_eq!(
counts,
[2, 1, 1, 0],
"AC-Q08: counters must partition the 4-file set (clean+warn+error+limit == 4)"
);
}
fn parse_summary_counts(stderr: &str) -> [usize; 4] {
fn leading_usize(s: &str) -> Option<usize> {
s.split_whitespace().next()?.parse().ok()
}
for line in stderr.lines() {
if let Some(rest) = line.strip_suffix(" resource-limited") {
let parts: Vec<&str> = rest.split(", ").collect();
if parts.len() == 4 {
if let (Some(c), Some(w), Some(e), Some(l)) = (
leading_usize(parts[0]),
leading_usize(parts[1]),
leading_usize(parts[2]),
leading_usize(parts[3]),
) {
return [c, w, e, l];
}
}
}
}
[0, 0, 0, 0]
}
fn make_resource_limit_content() -> String {
(0..257)
.map(|i| format!("@block block_{i}:\n@end\n"))
.collect()
}
#[test]
fn lint_directory_summary_counts_resource_limited() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
fs::write(
dir.path().join("too_many_blocks.mds"),
make_resource_limit_content(),
)
.unwrap();
let out = lint_path(dir.path(), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(3),
"directory with a resource-limited file must exit 3; stderr: {stderr}"
);
assert!(
stderr.contains("1 clean, 0 with warnings, 0 with errors, 1 resource-limited"),
"AC-Q09: summary must show '1 clean, 0 with warnings, 0 with errors, 1 resource-limited'; \
got: {stderr:?}"
);
let counts = parse_summary_counts(&stderr);
assert_eq!(
counts.iter().sum::<usize>(),
2,
"AC-Q08: counters must partition the 2-file set"
);
}
#[test]
fn lint_directory_quiet_suppresses_summary_when_only_warnings() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("b.mds")).unwrap();
let quiet = lint_path(dir.path(), &["--quiet"]);
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
assert_eq!(
quiet.status.code(),
Some(1),
"warn-only directory under --quiet must exit 1; stderr: {quiet_stderr:?}"
);
assert!(
!quiet_stderr.contains("clean,"),
"AC-Q10: --quiet warn-only must NOT emit the summary; got: {quiet_stderr:?}"
);
let control = lint_path(dir.path(), &[]);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert!(
control_stderr.contains("clean,"),
"positive control: non-quiet run must emit the summary so the quiet absence \
assertion is non-vacuous; got: {control_stderr:?}"
);
}
#[test]
fn lint_directory_quiet_still_prints_summary_on_errors() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("warn.mds")).unwrap();
let out = lint_path(dir.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"directory with error file under --quiet must exit 2; stderr: {stderr:?}"
);
assert!(
stderr.contains("1 clean, 1 with warnings, 1 with errors, 0 resource-limited"),
"AC-Q11: --quiet with error files must still print summary; got: {stderr:?}"
);
assert!(
stderr.contains("duplicate-export"),
"AC-Q11: error-severity diagnostic body must survive --quiet; got: {stderr:?}"
);
let control = lint_path(dir.path(), &[]);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert!(
control_stderr.contains("unused-variable"),
"positive control: non-quiet run must print 'unused-variable' warn diagnostic \
so the absence assertion below is non-vacuous; got: {control_stderr:?}"
);
assert!(
!stderr.contains("unused-variable"),
"AC-Q11: warn-severity 'unused-variable' diagnostic body must be suppressed \
under --quiet; got: {stderr:?}"
);
}
#[test]
fn lint_directory_quiet_still_prints_summary_on_resource_limit() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
fs::write(
dir.path().join("too_many_blocks.mds"),
make_resource_limit_content(),
)
.unwrap();
let out = lint_path(dir.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(3),
"directory with resource-limited file under --quiet must exit 3; stderr: {stderr:?}"
);
assert!(
stderr.contains("1 resource-limited"),
"AC-Q12: --quiet with resource-limited file must still print summary with count; got: {stderr:?}"
);
}
#[test]
fn lint_directory_check_exit_still_prints_summary() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("fix_me.mds");
fs::copy(fixture("lint_partial_fix.mds"), &target).unwrap();
let content_before = fs::read_to_string(&target).unwrap();
let out = lint_path(dir.path(), &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check with pending fixes must exit 1; stderr: {stderr}"
);
let counts = parse_summary_counts(&stderr);
assert_eq!(
counts.iter().sum::<usize>(),
1,
"AC-Q08/AC-Q13: the summary must be emitted on the --fix --check exit path and its \
four counters must partition the 1-file tree; got stderr: {stderr:?}"
);
let content_after = fs::read_to_string(&target).unwrap();
assert_eq!(
content_before, content_after,
"--fix --check must never modify files"
);
}
#[test]
fn lint_directory_quiet_check_exit_matches_d1a_contract() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("fix_me.mds");
fs::copy(fixture("lint_fixable_warn.mds"), &target).unwrap();
let out = lint_path(dir.path(), &["--fix", "--check", "--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(1),
"--fix --check --quiet with pending fixes must still exit 1 (exit codes unaffected); \
stderr: {stderr:?}"
);
assert!(
!stderr.contains("clean,"),
"D1-a: --fix --check --quiet with warn-only residual must not print summary; \
got: {stderr:?}"
);
assert!(
!stderr.contains("Would fix:"),
"D1-a: --fix --check --quiet must not print 'Would fix:'; got: {stderr:?}"
);
let control = lint_path(dir.path(), &["--fix", "--check"]);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert_eq!(
control.status.code(),
Some(1),
"positive control: the same tree without --quiet must also exit 1; \
got stderr: {control_stderr:?}"
);
assert!(
control_stderr.contains("clean,"),
"positive control: the same tree WITHOUT --quiet must print the summary, proving the \
--quiet absence assertion above is non-vacuous; got: {control_stderr:?}"
);
assert!(
control_stderr.contains("Would fix:"),
"positive control: --fix --check without --quiet must print 'Would fix:', confirming \
the test exercises the --fix --check code path and not just an ordinary warn exit; \
got: {control_stderr:?}"
);
}
#[test]
fn lint_directory_json_summary_goes_to_stderr_only() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("warn.mds")).unwrap();
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
serde_json::from_str::<serde_json::Value>(stdout.trim()).is_ok(),
"AC-Q15: stdout must be a parseable JSON object; got: {stdout:?}"
);
assert!(
!stdout.contains("clean,"),
"AC-Q15: stdout must NOT contain the summary text in JSON mode; got: {stdout:?}"
);
assert!(
stderr.contains("clean,"),
"AC-Q15 positive control: stderr must contain the summary; got: {stderr:?}"
);
}
#[test]
fn lint_directory_json_envelope_key_contract_unchanged() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.path().join("b.mds")).unwrap();
let out = lint_path(dir.path(), &["--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let json: serde_json::Value =
serde_json::from_str(stdout.trim()).expect("stdout must be valid JSON");
let keys: Vec<&str> = json
.as_object()
.expect("top-level must be an object")
.keys()
.map(|k| k.as_str())
.collect();
assert_eq!(
keys,
vec!["files", "truncated", "version"],
"AC-Q16 (D2-B): JSON envelope keys must remain exactly [files, truncated, version]; \
got: {keys:?}"
);
assert_eq!(
json["version"], 1,
"AC-Q16: version must remain the integer 1"
);
}
#[test]
fn lint_single_file_prints_no_directory_summary() {
let out = lint_path(&fixture("lint_clean.mds"), &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(0), "clean single file must exit 0");
assert!(
stderr.contains("Clean:"),
"single-file clean lint must still print 'Clean:' line; got: {stderr:?}"
);
assert!(
!stderr.contains("clean,"),
"AC-Q18: single-file lint must NOT print a directory summary; got: {stderr:?}"
);
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("a.mds")).unwrap();
let control = lint_path(dir.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("clean,"),
"positive control: the same source in directory mode must produce a summary \
containing the exact needle \"clean,\"; got: {:?}",
String::from_utf8_lossy(&control.stderr)
);
}
#[test]
fn lint_stdin_prints_no_directory_summary() {
let content = fs::read_to_string(fixture("lint_clean.mds")).unwrap();
let out = lint_stdin(&content, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(0),
"clean stdin lint must exit 0; stderr: {stderr}"
);
assert!(
!stderr.contains("clean,"),
"AC-Q19: stdin lint must NOT print a directory summary; got: {stderr:?}"
);
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("a.mds"), &content).unwrap();
let control = lint_path(dir.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("clean,"),
"positive control: the same source in directory mode must produce a summary \
containing the exact needle \"clean,\"; got: {:?}",
String::from_utf8_lossy(&control.stderr)
);
}
const FIX_REJECTED_SOURCE: &str = "\
@define empty_fn():
@end
@export empty_fn
";
#[test]
fn fix_rejected_message_honours_quiet_in_all_four_modes() {
let needle = "fix rejected";
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("r.mds");
fs::write(&target, FIX_REJECTED_SOURCE).unwrap();
let loud = lint_path(&target, &["--fix"]);
let loud_stderr = String::from_utf8_lossy(&loud.stderr);
assert!(
loud_stderr.contains(needle),
"positive control (single file): without --quiet the rejection MUST be reported, \
otherwise the quiet assertion below is vacuous; got: {loud_stderr:?}"
);
let quiet = lint_path(&target, &["--fix", "--quiet"]);
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
assert!(
!quiet_stderr.contains(needle),
"single-file --fix --quiet must suppress 'fix rejected:' (D4/PF-004); got: {quiet_stderr:?}"
);
assert_eq!(
quiet.status.code(),
loud.status.code(),
"single file: --quiet must not move the exit code"
);
let loud_stdin = lint_stdin(FIX_REJECTED_SOURCE, &["--fix"]);
let loud_stdin_stderr = String::from_utf8_lossy(&loud_stdin.stderr);
assert!(
loud_stdin_stderr.contains(needle),
"positive control (stdin): without --quiet the rejection MUST be reported; \
got: {loud_stdin_stderr:?}"
);
let quiet_stdin = lint_stdin(FIX_REJECTED_SOURCE, &["--fix", "--quiet"]);
let quiet_stdin_stderr = String::from_utf8_lossy(&quiet_stdin.stderr);
assert!(
!quiet_stdin_stderr.contains(needle),
"stdin --fix --quiet must suppress 'fix rejected:' (D4/PF-004); got: {quiet_stdin_stderr:?}"
);
assert_eq!(
quiet_stdin.status.code(),
loud_stdin.status.code(),
"stdin: --quiet must not move the exit code"
);
let loud_dir = lint_path(dir.path(), &["--fix"]);
let loud_dir_stderr = String::from_utf8_lossy(&loud_dir.stderr);
assert!(
loud_dir_stderr.contains(needle),
"positive control (directory): without --quiet the rejection MUST be reported; \
got: {loud_dir_stderr:?}"
);
let quiet_dir = lint_path(dir.path(), &["--fix", "--quiet"]);
let quiet_dir_stderr = String::from_utf8_lossy(&quiet_dir.stderr);
assert!(
!quiet_dir_stderr.contains(needle),
"directory --fix --quiet must suppress 'fix rejected:' (D4/PF-004); got: {quiet_dir_stderr:?}"
);
assert_eq!(
quiet_dir.status.code(),
loud_dir.status.code(),
"directory: --quiet must not move the exit code"
);
let loud_json = lint_path(dir.path(), &["--fix", "--format", "json"]);
let loud_json_stderr = String::from_utf8_lossy(&loud_json.stderr);
assert!(
loud_json_stderr.contains(needle),
"positive control (dir --fix --format json): without --quiet the rejection MUST be \
reported in stderr; got: {loud_json_stderr:?}"
);
let quiet_json = lint_path(dir.path(), &["--fix", "--format", "json", "--quiet"]);
let quiet_json_stderr = String::from_utf8_lossy(&quiet_json.stderr);
assert!(
!quiet_json_stderr.contains(needle),
"dir --fix --format json --quiet must suppress 'fix rejected:' \
(the quiet gate of `ResultSink::fix_rejected`); \
got: {quiet_json_stderr:?}"
);
assert_eq!(
quiet_json.status.code(),
loud_json.status.code(),
"dir --format json --fix: --quiet must not move the exit code"
);
let loud_json_check = lint_path(dir.path(), &["--fix", "--check", "--format", "json"]);
let loud_json_check_stderr = String::from_utf8_lossy(&loud_json_check.stderr);
assert!(
loud_json_check_stderr.contains(needle),
"positive control (dir --fix --check --format json): without --quiet the rejection MUST \
be reported in stderr; got: {loud_json_check_stderr:?}"
);
let quiet_json_check = lint_path(
dir.path(),
&["--fix", "--check", "--format", "json", "--quiet"],
);
let quiet_json_check_stderr = String::from_utf8_lossy(&quiet_json_check.stderr);
assert!(
!quiet_json_check_stderr.contains(needle),
"dir --fix --check --format json --quiet must suppress 'fix rejected:' \
(the quiet gate of `ResultSink::fix_rejected`); \
got: {quiet_json_check_stderr:?}"
);
assert_eq!(
quiet_json_check.status.code(),
loud_json_check.status.code(),
"dir --format json --fix --check: --quiet must not move the exit code"
);
assert_eq!(
fs::read_to_string(&target).unwrap(),
FIX_REJECTED_SOURCE,
"a rejected fix must never rewrite the source file"
);
}
fn make_cap_source() -> String {
(0..=1000)
.map(|i| format!("{{var_{i}}}"))
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn cap_notice_honours_quiet_in_all_four_modes() {
let needle = "diagnostic cap";
let source = make_cap_source();
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("cap.mds");
fs::write(&target, &source).unwrap();
let loud = lint_path(&target, &["--fix", "--check"]);
let loud_stderr = String::from_utf8_lossy(&loud.stderr);
assert!(
loud_stderr.contains(needle),
"positive control (single file): without --quiet the cap notice MUST be reported \
(otherwise the quiet assertion is vacuous; ADR-009); got: {loud_stderr:?}"
);
let quiet = lint_path(&target, &["--fix", "--check", "--quiet"]);
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
assert!(
!quiet_stderr.contains(needle),
"single-file --fix --check --quiet must suppress the cap notice (D4/PF-004); \
got: {quiet_stderr:?}"
);
assert_eq!(
quiet.status.code(),
loud.status.code(),
"single file: --quiet must not move the exit code"
);
let loud_stdin = lint_stdin(&source, &["--fix", "--check"]);
let loud_stdin_stderr = String::from_utf8_lossy(&loud_stdin.stderr);
assert!(
loud_stdin_stderr.contains(needle),
"positive control (stdin): without --quiet the cap notice MUST be reported; \
got: {loud_stdin_stderr:?}"
);
let quiet_stdin = lint_stdin(&source, &["--fix", "--check", "--quiet"]);
let quiet_stdin_stderr = String::from_utf8_lossy(&quiet_stdin.stderr);
assert!(
!quiet_stdin_stderr.contains(needle),
"stdin --fix --check --quiet must suppress the cap notice (D4/PF-004); \
got: {quiet_stdin_stderr:?}"
);
assert_eq!(
quiet_stdin.status.code(),
loud_stdin.status.code(),
"stdin: --quiet must not move the exit code"
);
let loud_dir = lint_path(dir.path(), &["--fix", "--check"]);
let loud_dir_stderr = String::from_utf8_lossy(&loud_dir.stderr);
assert!(
loud_dir_stderr.contains(needle),
"positive control (directory): without --quiet the cap notice MUST be reported; \
got: {loud_dir_stderr:?}"
);
let quiet_dir = lint_path(dir.path(), &["--fix", "--check", "--quiet"]);
let quiet_dir_stderr = String::from_utf8_lossy(&quiet_dir.stderr);
assert!(
!quiet_dir_stderr.contains(needle),
"directory --fix --check --quiet must suppress the cap notice (D4/PF-004); \
got: {quiet_dir_stderr:?}"
);
assert_eq!(
quiet_dir.status.code(),
loud_dir.status.code(),
"directory: --quiet must not move the exit code"
);
let loud_json = lint_path(dir.path(), &["--fix", "--check", "--format", "json"]);
let loud_json_stderr = String::from_utf8_lossy(&loud_json.stderr);
assert!(
loud_json_stderr.contains(needle),
"positive control (dir --format json): without --quiet the cap notice MUST be reported \
(otherwise the quiet assertion is vacuous; ADR-009); got: {loud_json_stderr:?}"
);
let quiet_json = lint_path(
dir.path(),
&["--fix", "--check", "--format", "json", "--quiet"],
);
let quiet_json_stderr = String::from_utf8_lossy(&quiet_json.stderr);
assert!(
!quiet_json_stderr.contains(needle),
"directory --fix --check --format json --quiet must suppress the cap notice \
(the quiet gate of `ResultSink::cap_reached`); got: {quiet_json_stderr:?}"
);
assert_eq!(
quiet_json.status.code(),
loud_json.status.code(),
"dir --format json: --quiet must not move the exit code"
);
}
#[test]
fn bare_lint_never_enters_directory_mode() {
let dir1 = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir1.path().join("template.mds")).unwrap();
let out1 = mds_bin()
.arg("lint")
.current_dir(dir1.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr1 = String::from_utf8_lossy(&out1.stderr);
assert_eq!(
out1.status.code(),
Some(0),
"bare lint in single-file dir must exit 0; stderr: {stderr1}"
);
assert!(
stderr1.contains("Clean:"),
"bare lint must print 'Clean:' (single-file); got: {stderr1:?}"
);
assert!(
!stderr1.contains("clean,"),
"AC-Q20: bare lint must NOT enter directory mode; got: {stderr1:?}"
);
let dir2 = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir2.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_clean.mds"), dir2.path().join("b.mds")).unwrap();
let out2 = mds_bin()
.arg("lint")
.current_dir(dir2.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let stderr2 = String::from_utf8_lossy(&out2.stderr);
assert!(
!out2.status.success(),
"bare lint with two files must fail; stderr: {stderr2}"
);
assert!(
!stderr2.contains("clean,"),
"AC-Q20: bare lint with two files must NOT emit a directory summary; got: {stderr2:?}"
);
let control_dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), control_dir.path().join("a.mds")).unwrap();
let control = lint_path(control_dir.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("clean,"),
"positive control: a clean file in directory mode must produce a summary \
containing the exact needle \"clean,\"; got: {:?}",
String::from_utf8_lossy(&control.stderr)
);
}
#[test]
fn lint_directory_empty_exits_two_prints_no_summary() {
let dir = tempfile::tempdir().unwrap();
let non_quiet = lint_path(dir.path(), &[]);
let stderr_nq = String::from_utf8_lossy(&non_quiet.stderr);
let stdout_nq = String::from_utf8_lossy(&non_quiet.stdout);
assert_eq!(
non_quiet.status.code(),
Some(2),
"empty directory lint must exit 2; stderr: {stderr_nq}"
);
assert!(
stderr_nq.contains("no .mds files found in"),
"empty directory must print the empty-tree diagnostic; got: {stderr_nq:?}"
);
assert!(
stderr_nq.contains("nothing was linted"),
"empty directory must say nothing was linted; got: {stderr_nq:?}"
);
assert!(
!stderr_nq.contains("clean,"),
"AC-Q21: empty directory must NOT print a summary; got: {stderr_nq:?}"
);
assert!(
!stdout_nq.contains("clean,"),
"AC-Q21: empty directory must NOT print a summary on stdout; got: {stdout_nq:?}"
);
let quiet = lint_path(dir.path(), &["--quiet"]);
let stderr_q = String::from_utf8_lossy(&quiet.stderr);
let stdout_q = String::from_utf8_lossy(&quiet.stdout);
assert_eq!(
quiet.status.code(),
Some(2),
"empty directory lint --quiet must exit 2; stderr: {stderr_q}"
);
assert!(
stderr_q.contains("no .mds files found in"),
"#204: the empty-tree diagnostic must appear under --quiet; got: {stderr_q:?}"
);
assert!(
stderr_q.contains("nothing was linted"),
"#204: --quiet must still say nothing was linted; got: {stderr_q:?}"
);
assert!(
!stderr_q.contains("clean,"),
"AC-Q21: empty directory under --quiet must NOT print a summary; got: {stderr_q:?}"
);
assert!(
!stdout_q.contains("clean,"),
"AC-Q21: empty directory under --quiet must NOT print a summary on stdout; \
got: {stdout_q:?}"
);
let control_dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), control_dir.path().join("a.mds")).unwrap();
let control = lint_path(control_dir.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("clean,"),
"positive control: a clean file in directory mode must produce a summary \
containing the exact needle \"clean,\"; got: {:?}",
String::from_utf8_lossy(&control.stderr)
);
}
#[test]
fn lint_directory_empty_format_json_exits_two_with_the_error_document() {
let dir = tempfile::tempdir().unwrap();
let out = lint_path(dir.path(), &["--format", "json"]);
assert_eq!(
json_exit(&out),
JsonExit::error(2, "mds::io"),
"empty directory lint --format json"
);
let message = error_message(&out).unwrap_or_default();
assert!(
message.starts_with("no .mds files found in ") && message.ends_with("; nothing was linted"),
"the error says nothing was linted; got: {message:?}"
);
let control_dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), control_dir.path().join("a.mds")).unwrap();
let control = lint_path(control_dir.path(), &["--format", "json"]);
assert!(
String::from_utf8_lossy(&control.stdout).contains('{'),
"positive control: a non-empty directory must emit a JSON envelope on stdout; \
got: {:?}",
String::from_utf8_lossy(&control.stdout)
);
}
#[test]
fn lint_directory_all_excluded_quiet_no_summary() {
let dir = tempfile::tempdir().unwrap();
let hidden = dir.path().join(".github");
fs::create_dir(&hidden).unwrap();
fs::write(hidden.join("template.mds"), "Hello!\n").unwrap();
let out = lint_path(dir.path(), &["--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!out.status.success(),
"all-excluded under --quiet must exit non-zero; stderr: {stderr}"
);
assert!(
stderr.contains("excluded") || stderr.contains("default-excluded"),
"AC-Q22: all-excluded diagnostic must appear under --quiet; got: {stderr:?}"
);
assert!(
!stderr.contains("clean,"),
"AC-Q22: all-excluded must NOT emit a summary line; got: {stderr:?}"
);
let control_dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), control_dir.path().join("a.mds")).unwrap();
let control = lint_path(control_dir.path(), &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("clean,"),
"positive control: a clean file in directory mode must produce a summary \
containing the exact needle \"clean,\"; got: {:?}",
String::from_utf8_lossy(&control.stderr)
);
}
#[cfg(unix)]
#[test]
fn lint_directory_summary_is_not_forgeable() {
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let esc_byte: u8 = 0x1b;
let forged_suffix = b"3 clean, 0 with warnings, 0 with errors, 0 resource-limited";
let mut hostile_name_bytes = vec![esc_byte];
hostile_name_bytes.extend_from_slice(forged_suffix);
hostile_name_bytes.extend_from_slice(b".mds");
let hostile_os = std::ffi::OsStr::from_bytes(&hostile_name_bytes);
let hostile_path = dir.path().join(hostile_os);
let error_content = fs::read(fixture("lint_error.mds")).unwrap();
fs::write(&hostile_path, &error_content).unwrap();
let out = lint_path(dir.path(), &[]);
let stderr_bytes = &out.stderr;
let stderr = String::from_utf8_lossy(stderr_bytes);
assert_eq!(out.status.code(), Some(2), "AC-Q25: got {stderr:?}");
assert!(
stderr.contains("mds::io") && stderr.contains("U+001B"),
"AC-Q25: the refusal must be mds::io naming U+001B; got: {stderr:?}"
);
assert!(
!stderr_bytes.contains(&esc_byte),
"AC-Q25: raw ESC byte must not appear in stderr; got: {stderr:?}"
);
let escaped_esc = format!("\\u{:04X}", esc_byte);
assert!(
stderr.contains(&escaped_esc),
"AC-Q25 positive control: {escaped_esc} must appear in stderr; got: {stderr:?}"
);
let forged_line = "3 clean, 0 with warnings, 0 with errors, 0 resource-limited";
assert!(
!stderr.lines().any(|l| l.trim() == forged_line),
"AC-Q25: forged summary text must not appear as a standalone summary line; \
got: {stderr:?}"
);
let genuine_summary = "0 clean, 0 with warnings, 1 with errors, 0 resource-limited";
let genuine_count = stderr
.lines()
.filter(|l| l.trim() == genuine_summary)
.count();
assert_eq!(
genuine_count, 1,
"AC-Q25: genuine summary must appear exactly once in stderr; got: {stderr:?}"
);
}
#[test]
fn help_documents_quiet_summary_contract() {
let lint_help = mds_bin()
.arg("lint")
.arg("--help")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let help_text = String::from_utf8_lossy(&lint_help.stdout);
assert!(
help_text.contains("summary line to stderr"),
"AC-Q26: mds lint --help long_about must document the directory summary line; \
got: {help_text:?}"
);
assert!(
help_text.contains("N clean, N with warnings, N with errors, N resource-limited"),
"AC-Q26: mds lint --help must show the literal summary format string so the shipped \
format and the documented format cannot drift; got: {help_text:?}"
);
assert!(
help_text.contains("mds lint --quiet ."),
"AC-Q26: mds lint --help must carry the `mds lint --quiet .` directory example; \
got: {help_text:?}"
);
let global_help = mds_bin()
.arg("--help")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
let global_text = String::from_utf8_lossy(&global_help.stdout);
assert!(
global_text.contains("Suppress status"),
"AC-Q26: mds --help must contain the --quiet description; got: {global_text:?}"
);
}
#[test]
fn lint_directory_quiet_works_in_pre_subcommand_position() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("a.mds")).unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("b.mds")).unwrap();
let post = lint_path(dir.path(), &["--quiet"]);
let pre = mds_bin()
.arg("--quiet")
.arg("lint")
.arg(dir.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap();
assert_eq!(
pre.status.code(),
post.status.code(),
"AC-Q30: pre-subcommand --quiet must produce the same exit code as post-subcommand"
);
assert_eq!(
pre.stderr, post.stderr,
"AC-Q30: pre-subcommand --quiet must produce identical stderr to post-subcommand"
);
assert!(
post.stderr.is_empty(),
"AC-Q30 anchor: a clean tree under --quiet must produce empty stderr in BOTH \
orderings, not merely equal stderr; got: {:?}",
String::from_utf8_lossy(&post.stderr)
);
let control = lint_path(dir.path(), &[]);
assert_eq!(
String::from_utf8_lossy(&control.stderr).trim(),
"2 clean, 0 with warnings, 0 with errors, 0 resource-limited",
"positive control: the same tree without --quiet must print the summary"
);
}
#[test]
fn lint_directory_config_failure_counted_in_error_bucket() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::copy(fixture("lint_clean.mds"), root.join("clean.mds")).unwrap();
let bad = root.join("bad");
fs::create_dir(&bad).unwrap();
fs::write(bad.join("mds.json"), "{ INVALID JSON").unwrap();
fs::copy(fixture("lint_clean.mds"), bad.join("bad.mds")).unwrap();
let out = lint_path(root, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"config-load failure must cause exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("1 clean, 0 with warnings, 1 with errors, 0 resource-limited"),
"D3-a: config-load failure must be counted as 'with errors' in the summary; \
got: {stderr:?}"
);
let counts = parse_summary_counts(&stderr);
assert_eq!(
counts,
[1, 0, 1, 0],
"D3-a/AC-Q08: 1 clean + 0 warn + 1 error + 0 limit must sum to 2 files; \
got counts: {counts:?}"
);
}
#[test]
fn lint_directory_config_failure_forces_summary_under_quiet() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::copy(fixture("lint_clean.mds"), root.join("clean.mds")).unwrap();
let bad = root.join("bad");
fs::create_dir(&bad).unwrap();
fs::write(bad.join("mds.json"), "{ INVALID JSON").unwrap();
fs::copy(fixture("lint_clean.mds"), bad.join("bad.mds")).unwrap();
let quiet = lint_path(root, &["--quiet"]);
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
assert_eq!(
quiet.status.code(),
Some(2),
"config-load failure under --quiet must still exit 2; stderr: {quiet_stderr:?}"
);
assert!(
quiet_stderr.contains("with errors"),
"D3-a: config-load failure must force the summary under --quiet \
(error_file_count > 0 gate); got: {quiet_stderr:?}"
);
let control = lint_path(root, &[]);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert!(
control_stderr.contains("with errors"),
"positive control: non-quiet run with config-load failure must also emit the \
summary with 'with errors', proving the --quiet assertion is non-vacuous; \
got: {control_stderr:?}"
);
}
#[cfg(unix)]
#[test]
fn lint_directory_unreadable_file_counted_in_error_bucket() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
let unreadable = dir.path().join("unreadable.mds");
fs::copy(fixture("lint_clean.mds"), &unreadable).unwrap();
fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).unwrap();
let out = lint_path(dir.path(), &[]);
let _ = fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o644));
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"chmod-000 file must cause exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("1 clean, 0 with warnings, 1 with errors, 0 resource-limited"),
"D3-a: source-read failure must be counted as 'with errors' in the summary; \
got: {stderr:?}"
);
let counts = parse_summary_counts(&stderr);
assert_eq!(
counts,
[1, 0, 1, 0],
"D3-a/AC-Q08: 1 clean + 0 warn + 1 error + 0 limit must sum to 2 files; \
got counts: {counts:?}"
);
}
#[cfg(unix)]
#[test]
fn lint_directory_unreadable_file_forces_summary_under_quiet() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_clean.mds"), dir.path().join("clean.mds")).unwrap();
let unreadable = dir.path().join("unreadable.mds");
fs::copy(fixture("lint_clean.mds"), &unreadable).unwrap();
fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).unwrap();
let quiet = lint_path(dir.path(), &["--quiet"]);
let control = lint_path(dir.path(), &[]);
let _ = fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o644));
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
let control_stderr = String::from_utf8_lossy(&control.stderr);
assert_eq!(
quiet.status.code(),
Some(2),
"chmod-000 file under --quiet must still exit 2; stderr: {quiet_stderr:?}"
);
assert!(
quiet_stderr.contains("with errors"),
"D3-a: source-read failure must force the summary under --quiet; \
got: {quiet_stderr:?}"
);
assert!(
control_stderr.contains("with errors"),
"positive control: non-quiet run with unreadable file must also show 'with errors', \
proving the --quiet assertion is non-vacuous; got: {control_stderr:?}"
);
}
#[test]
fn dir_json_fix_emits_fixed_and_quiet_suppresses_it() {
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Fixed:"),
"D4/PF-004: dir --fix --format json must emit 'Fixed:' without --quiet; \
got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("stdout must be valid JSON; err: {e}; stdout: {stdout}"));
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--format", "json", "--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Fixed:"),
"D4/PF-004: dir --fix --format json --quiet must suppress 'Fixed:'; \
got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!("stdout must remain valid JSON under --quiet; err: {e}; stdout: {stdout}")
});
}
}
#[test]
fn dir_json_fix_check_emits_would_fix_and_quiet_suppresses_it() {
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--check", "--format", "json"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix:"),
"D4/PF-004: dir --fix --check --format json must emit 'Would fix:' without \
--quiet; got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("stdout must be valid JSON; err: {e}; stdout: {stdout}"));
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(
dir.path(),
&["--fix", "--check", "--format", "json", "--quiet"],
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Would fix:"),
"D4/PF-004: dir --fix --check --format json --quiet must suppress 'Would fix:'; \
got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
let _: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
panic!("stdout must remain valid JSON under --quiet; err: {e}; stdout: {stdout}")
});
}
}
#[test]
fn dir_human_fix_emits_fixed_and_quiet_suppresses_it() {
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Fixed:"),
"dir --fix (human format) must emit 'Fixed:' when a file is \
successfully fixed (`ResultSink::fixed`); got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.is_empty(),
"dir --fix human format must not write to stdout; got: {stdout:?}"
);
}
{
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("err.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--quiet"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Fixed:"),
"dir --fix --quiet (human format) must suppress 'Fixed:' \
(the quiet gate of `ResultSink::fixed`); got stderr: {stderr}"
);
}
}
#[test]
fn lint_fix_diff_format_json_diff_precedes_json_envelope() {
let dir = tempfile::tempdir().unwrap();
fs::copy(fixture("lint_error.mds"), dir.path().join("fixable.mds")).unwrap();
let out = lint_path(dir.path(), &["--fix", "--diff", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let lines: Vec<&str> = stdout.lines().collect();
assert!(
!lines.is_empty(),
"--fix --diff --format json must produce output on stdout; got empty"
);
let last = lines[lines.len() - 1];
let _: serde_json::Value = serde_json::from_str(last).unwrap_or_else(|e| {
panic!(
"final stdout line must parse as JSON (the envelope follows the diff); \
err: {e}; last line: {last:?}; full stdout: {stdout:?}"
)
});
let diff_present = lines[..lines.len().saturating_sub(1)]
.iter()
.any(|l| l.starts_with("@@") || l.starts_with("--- ") || l.starts_with("+++ "));
assert!(
diff_present,
"unified diff must precede the JSON envelope on stdout (spec §7.5, \
`run_lint_directory`'s doc); full stdout: {stdout:?}"
);
assert!(
serde_json::from_str::<serde_json::Value>(stdout.trim()).is_err(),
"stdout as a whole must not parse as JSON under --fix --diff --format json; \
this is the documented exception (spec §7.5); stdout: {stdout:?}"
);
}
fn lint_stdin_in_dir(dir: &Path, input: &str, extra_args: &[&str]) -> std::process::Output {
use std::io::Write;
let mut child = mds_bin()
.current_dir(dir)
.arg("lint")
.args(extra_args)
.arg("-")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(input.as_bytes());
child.wait_with_output().unwrap()
}
fn preview_exit_tempdir(files: &[&str]) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
fs::copy(
fixture("lint_preview_exit/mds.json"),
dir.path().join("mds.json"),
)
.unwrap();
for name in files {
fs::copy(
fixture(&format!("lint_preview_exit/{name}")),
dir.path().join(name),
)
.unwrap();
}
dir
}
#[test]
fn d1_file_fix_check_residual_error_exits_2() {
let target = fixture("lint_preview_exit/lint_fixable_plus_error.mds");
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix:"),
"preview exit: --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: --fix --check must exit 2 when the residual carries an error-severity \
finding (was hardcoded 1); stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(&target).unwrap(),
original,
"--fix --check must never write"
);
}
#[test]
fn d1_file_fix_diff_residual_error_exits_2() {
let target = fixture("lint_preview_exit/lint_fixable_plus_error.mds");
let original = fs::read_to_string(&target).unwrap();
let out = lint_path(&target, &["--fix", "--diff"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("@@"),
"non-vacuity: --fix --diff must render a hunk; stdout: {stdout}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: --fix --diff must exit 2 when the residual carries an error-severity \
finding; stdout: {stdout}"
);
assert_eq!(
fs::read_to_string(&target).unwrap(),
original,
"--fix --diff must never write"
);
}
#[test]
fn d1_stdin_fix_check_residual_error_exits_2() {
let source =
fs::read_to_string(fixture("lint_preview_exit/lint_fixable_plus_error.mds")).unwrap();
let config_dir = fixture("lint_preview_exit");
let out = lint_stdin_in_dir(&config_dir, &source, &["--fix", "--check"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix: <stdin>"),
"preview exit: stdin --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: stdin --fix --check must exit 2 when the residual carries an \
error-severity finding (was hardcoded 1); stderr: {stderr}"
);
assert!(
stdout.is_empty(),
"stdin --fix --check must not write the fixed source to stdout; got: {stdout}"
);
}
#[test]
fn d1_stdin_fix_diff_residual_error_exits_2() {
let source =
fs::read_to_string(fixture("lint_preview_exit/lint_fixable_plus_error.mds")).unwrap();
let config_dir = fixture("lint_preview_exit");
let out = lint_stdin_in_dir(&config_dir, &source, &["--fix", "--diff"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("@@"),
"non-vacuity: stdin --fix --diff must render a hunk; stdout: {stdout}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: stdin --fix --diff must exit 2 when the residual carries an \
error-severity finding; stdout: {stdout}"
);
}
#[test]
fn d1_dir_fix_check_residual_error_exits_2() {
let dir = preview_exit_tempdir(&["lint_fixable_plus_error.mds"]);
let out = lint_path(dir.path(), &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("Would fix:"),
"preview exit: dir --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: dir --fix --check must exit 2 when any residual carries an \
error-severity finding (the old early exit(1) shadowed max_tally); \
stderr: {stderr}"
);
}
#[test]
fn d1_dir_fix_diff_residual_error_exits_2() {
let dir = preview_exit_tempdir(&["lint_fixable_plus_error.mds"]);
let out = lint_path(dir.path(), &["--fix", "--diff"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("@@"),
"non-vacuity: dir --fix --diff must render a hunk; stdout: {stdout}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: dir --fix --diff must exit 2 when any residual carries an \
error-severity finding; stdout: {stdout}"
);
}
#[test]
fn d1_fix_diff_residual_clean_info_only_exits_1() {
let dir = tempfile::tempdir().unwrap();
fs::write(
dir.path().join("mds.json"),
r#"{ "lint": { "rules": { "empty-block": "info" } } }"#,
)
.unwrap();
let target = dir.path().join("floor.mds");
fs::write(&target, "@if \"a\" == \"a\":\n@end\n\nHello\n").unwrap();
let out = lint_path(&target, &["--fix", "--diff"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stdout.contains("@@"),
"non-vacuity: --fix --diff must render a hunk; stdout: {stdout}"
);
assert_eq!(
out.status.code(),
Some(1),
"preview exit: --fix --diff must exit at least 1 when a fix is pending, even when \
every finding is info-severity (was 0); stderr: {stderr}"
);
}
#[test]
fn d1_fix_check_nothing_fixable_error_exits_2() {
let target = fixture("lint_preview_exit/lint_nothing_fixable_error.mds");
let out = lint_path(&target, &["--fix", "--check"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("Would fix:"),
"nothing-fixable file must not report a pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"--fix --check with nothing fixable and an error finding must exit 2; \
stderr: {stderr}"
);
}
#[test]
fn d1_file_fix_check_json_body_pre_fix_and_exit_2() {
let target = fixture("lint_preview_exit/lint_fixable_plus_error.mds");
let out = lint_path(&target, &["--fix", "--check", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let json: serde_json::Value = serde_json::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("stdout must be one parseable envelope ({e}); got: {stdout}"));
let diags = json["files"][0]["diagnostics"]
.as_array()
.expect("diagnostics array");
let rules: Vec<&str> = diags.iter().filter_map(|d| d["rule"].as_str()).collect();
assert!(
rules.contains(&"unused-variable") && rules.contains(&"empty-block"),
"preview exit: JSON body must stay PRE-fix (both findings present); got rules: {rules:?}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: exit must reflect the residual error while the body stays pre-fix; \
stdout: {stdout}"
);
}
#[test]
fn d1_dir_fix_check_json_body_pre_fix_and_exit_2() {
let dir = preview_exit_tempdir(&["lint_fixable_plus_error.mds"]);
let out = lint_path(dir.path(), &["--fix", "--check", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let json: serde_json::Value = serde_json::from_str(stdout.trim())
.unwrap_or_else(|e| panic!("stdout must be one parseable envelope ({e}); got: {stdout}"));
let diags = json["files"][0]["diagnostics"]
.as_array()
.expect("diagnostics array");
let rules: Vec<&str> = diags.iter().filter_map(|d| d["rule"].as_str()).collect();
assert!(
rules.contains(&"unused-variable") && rules.contains(&"empty-block"),
"preview exit: dir JSON body must stay PRE-fix (both findings present); got rules: {rules:?}"
);
assert_eq!(
out.status.code(),
Some(2),
"preview exit: dir --fix --check --format json must emit the envelope AND exit 2 \
(residual error); stdout: {stdout}"
);
}
#[cfg(unix)]
#[test]
fn lint_single_file_non_utf8_path_exits_2() {
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
let clean = fs::read_to_string(fixture("lint_clean.mds")).unwrap();
let control_dir = tempfile::tempdir().unwrap();
fs::write(control_dir.path().join("ok.mds"), &clean).unwrap();
let control = lint_path(&control_dir.path().join("ok.mds"), &[]);
assert_eq!(
control.status.code(),
Some(0),
"control: a clean file named in UTF-8 must exit 0; stderr: {}",
String::from_utf8_lossy(&control.stderr)
);
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, &clean).is_err() {
#[cfg(not(target_os = "macos"))]
panic!(
"lint_single_file_non_utf8_path_exits_2: a non-UTF-8 filename was rejected \
by the filesystem — unexpected on this platform"
);
#[cfg(target_os = "macos")]
return;
}
let out = lint_path(&hostile, &[]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
out.status.code(),
Some(2),
"#217: a single-file path that cannot be named must exit 2; stderr: {stderr}"
);
assert!(
stderr.contains("not valid UTF-8"),
"the diagnostic must say why; got: {stderr}"
);
}
const PARTIAL_WITH_AN_UNUSED_DEFINE: &str = "---\ngreeting: hello\n---\n\
@if \"x\" == \"y\":\ndead\n@end\n\
@define helper():\nhelp text\n@end\n\
@export * from \"./_lib.mds\"\n{{greeting}}\n";
const PARTIAL_WITH_AN_UNUSED_DEFINE_FIXED: &str = "---\ngreeting: hello\n---\n\
@define helper():\nhelp text\n@end\n\
@export * from \"./_lib.mds\"\n{{greeting}}\n";
fn lint_dir_in(cwd: &Path, dir: &str, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.current_dir(cwd)
.arg("lint")
.args(extra_args)
.arg(dir)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
fn findings_of(report: &std::process::Output) -> Vec<String> {
let json: serde_json::Value = serde_json::from_slice(&report.stdout).unwrap_or_else(|e| {
panic!(
"stdout must be the JSON report: {e}; stdout: {}; stderr: {}",
String::from_utf8_lossy(&report.stdout),
String::from_utf8_lossy(&report.stderr)
)
});
let mut findings = Vec::new();
for entry in json["files"].as_array().expect("the report has files[]") {
let file = entry["file"].as_str().expect("each entry names its file");
for diag in entry["diagnostics"]
.as_array()
.expect("each entry has diagnostics[]")
{
let rule = diag["rule"].as_str().expect("each finding names its rule");
findings.push(format!("{file} {rule}"));
}
}
findings
}
#[test]
fn fix_of_a_partial_in_a_directory_applies_and_reports_no_unused_function() {
let tmp = tempfile::tempdir().unwrap();
for dir in ["d", "c"] {
fs::create_dir(tmp.path().join(dir)).unwrap();
fs::write(tmp.path().join(dir).join("_lib.mds"), "Shared text.\n").unwrap();
}
let partial = tmp.path().join("d").join("_p.mds");
fs::write(&partial, PARTIAL_WITH_AN_UNUSED_DEFINE).unwrap();
let full = tmp.path().join("c").join("full.mds");
fs::write(&full, PARTIAL_WITH_AN_UNUSED_DEFINE).unwrap();
let control = lint_dir_in(tmp.path(), "c", &["--format", "json"]);
assert_eq!(
findings_of(&control),
["full.mds unreachable-branch", "full.mds unused-function"],
"control: a file that is not a partial reports the unused define"
);
let control = lint_dir_in(tmp.path(), "c", &[]);
assert!(
String::from_utf8_lossy(&control.stderr).contains("unused-function"),
"control: the human report names the unused define; stderr: {}",
String::from_utf8_lossy(&control.stderr)
);
let before = lint_dir_in(tmp.path(), "d", &["--format", "json"]);
assert_eq!(
findings_of(&before),
["_p.mds unreachable-branch"],
"the partial reports only its dead block before the fix"
);
let out = lint_dir_in(tmp.path(), "d", &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.contains("fix rejected"),
"the fix of a partial must not be refused; stderr: {stderr}"
);
let fixed_line = format!(
"Fixed: {}",
"d/_p.mds".replace('/', std::path::MAIN_SEPARATOR_STR)
);
assert!(
stderr.contains(&fixed_line),
"the partial must be fixed ({fixed_line:?}); stderr: {stderr}"
);
assert!(
!stderr.contains("unused-"),
"no unused-* finding may be reported for a partial; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(0),
"nothing is left to report once the dead block is gone; stderr: {stderr}"
);
assert_eq!(
fs::read_to_string(&partial).unwrap(),
PARTIAL_WITH_AN_UNUSED_DEFINE_FIXED,
"the dead block is removed and the define kept"
);
let after = lint_dir_in(tmp.path(), "d", &["--format", "json"]);
assert_eq!(
findings_of(&after),
Vec::<String>::new(),
"the fixed partial reports nothing"
);
assert_eq!(after.status.code(), Some(0));
}
const A_WARNING_BELOW_A_DEAD_BLOCK: &str = "---\nflag: true\n---\n\
@if \"x\" == \"y\":\nhidden\n@end\n\
first padding line\nsecond padding line\n\
@if flag:\nsame\n@else:\nsame\n@end\n";
const A_WARNING_BELOW_A_DEAD_BLOCK_FIXED: &str = "---\nflag: true\n---\n\
first padding line\nsecond padding line\n\
@if flag:\nsame\n@else:\nsame\n@end\n";
const A_WARNING_ABOVE_A_DEAD_BLOCK: &str = "---\nflag: true\n---\n\
@if flag:\nsame\n@else:\nsame\n@end\n\
padding line\n\
@if \"x\" == \"y\":\nhidden\n@end\n";
fn redundant_else_frame(stderr: &str, label: &str) -> (usize, usize, String) {
let finding = stderr
.find("[redundant-else]")
.unwrap_or_else(|| panic!("no redundant-else finding; stderr: {stderr}"));
let header = format!("╭─[{label}:");
let start = finding
+ stderr[finding..]
.find(&header)
.unwrap_or_else(|| panic!("no frame for {label:?}; stderr: {stderr}"))
+ header.len();
let (position, _) = stderr[start..]
.split_once(']')
.expect("the frame header closes");
let (line, col) = position.split_once(':').expect("<line>:<col>");
let line: usize = line.parse().expect("a line number");
let col: usize = col.parse().expect("a column number");
let gutter = format!("{line} │");
let shown = stderr[start..]
.lines()
.find_map(|l| l.trim_start().strip_prefix(gutter.as_str()))
.unwrap_or_else(|| panic!("the frame shows no line {line}; stderr: {stderr}"));
(
line,
col,
shown.strip_prefix(' ').unwrap_or(shown).to_string(),
)
}
fn assert_framed_over(stderr: &str, label: &str, text: &str, line: usize, what: &str) {
let (at, col, shown) = redundant_else_frame(stderr, label);
let line_of_text = at
.checked_sub(1)
.and_then(|index| text.lines().nth(index))
.unwrap_or("<past the end of the text>");
assert_eq!(
shown, line_of_text,
"{what}: the frame's line {at} must show line {at} of the text its spans index; \
stderr: {stderr}"
);
assert_eq!(
(at, col, shown.as_str()),
(line, 1, "@if flag:"),
"{what}: the frame must point at the warning's @if; stderr: {stderr}"
);
}
fn redundant_else_json_line(report: &std::process::Output, file: &str, text: &str) -> usize {
let json: serde_json::Value = serde_json::from_slice(&report.stdout).unwrap_or_else(|e| {
panic!(
"stdout must be the JSON report: {e}; stdout: {}",
String::from_utf8_lossy(&report.stdout)
)
});
let entry = json["files"]
.as_array()
.expect("the report has files[]")
.iter()
.find(|entry| entry["file"] == file)
.unwrap_or_else(|| panic!("no entry for {file:?}: {json}"));
let diag = entry["diagnostics"]
.as_array()
.expect("the entry has diagnostics[]")
.iter()
.find(|diag| diag["rule"] == "redundant-else")
.unwrap_or_else(|| panic!("no redundant-else finding: {entry}"));
let offset = diag["span"]["offset"]
.as_u64()
.and_then(|o| usize::try_from(o).ok())
.expect("the finding has a span offset");
let (before, after) = text.split_at_checked(offset).unwrap_or_else(|| {
panic!(
"the span offset {offset} lies past the {}-byte text",
text.len()
)
});
assert!(
before.ends_with('\n') && after.starts_with("@if flag:"),
"the span offset {offset} must index the warning's @if; text after it: {after:?}"
);
before.matches('\n').count() + 1
}
#[test]
fn a_finding_left_by_a_fix_of_a_file_points_into_the_written_file() {
let tmp = tempfile::tempdir().unwrap();
let above = tmp.path().join("y.mds");
let below = tmp.path().join("x.mds");
fs::write(&above, A_WARNING_ABOVE_A_DEAD_BLOCK).unwrap();
let out = lint_path(&above, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
let written = fs::read_to_string(&above).unwrap();
assert_ne!(
written, A_WARNING_ABOVE_A_DEAD_BLOCK,
"control: the fix is written"
);
assert_framed_over(&stderr, "y.mds", &written, 4, "control");
fs::write(&below, A_WARNING_BELOW_A_DEAD_BLOCK).unwrap();
let out = lint_path(&below, &["--fix", "--format", "json"]);
let written = fs::read_to_string(&below).unwrap();
assert_eq!(written, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED);
assert_eq!(redundant_else_json_line(&out, "x.mds", &written), 6);
assert_eq!(out.status.code(), Some(1), "the warning is left");
fs::write(&below, A_WARNING_BELOW_A_DEAD_BLOCK).unwrap();
let out = lint_path(&below, &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
let written = fs::read_to_string(&below).unwrap();
assert_eq!(written, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED);
assert_framed_over(&stderr, "x.mds", &written, 6, "a file argument");
assert_eq!(out.status.code(), Some(1), "the warning is left");
}
#[test]
fn a_finding_left_by_a_fix_of_a_directory_entry_points_into_the_written_file() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let write_both = || {
fs::write(d.join("x.mds"), A_WARNING_BELOW_A_DEAD_BLOCK).unwrap();
fs::write(d.join("y.mds"), A_WARNING_ABOVE_A_DEAD_BLOCK).unwrap();
};
write_both();
let out = lint_dir_in(tmp.path(), "d", &["--fix", "--format", "json"]);
let x = fs::read_to_string(d.join("x.mds")).unwrap();
let y = fs::read_to_string(d.join("y.mds")).unwrap();
assert_eq!(x, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED);
assert_eq!(redundant_else_json_line(&out, "y.mds", &y), 4, "control");
assert_eq!(redundant_else_json_line(&out, "x.mds", &x), 6);
write_both();
let out = lint_dir_in(tmp.path(), "d", &["--fix"]);
let stderr = String::from_utf8_lossy(&out.stderr);
let x = fs::read_to_string(d.join("x.mds")).unwrap();
let y = fs::read_to_string(d.join("y.mds")).unwrap();
assert_framed_over(&stderr, "y.mds", &y, 4, "control");
assert_eq!(x, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED);
assert_framed_over(&stderr, "x.mds", &x, 6, "a directory entry");
assert_eq!(out.status.code(), Some(1), "the warnings are left");
}
#[test]
fn a_finding_left_by_a_fix_of_stdin_points_into_the_source_it_emits() {
let out = lint_stdin(A_WARNING_BELOW_A_DEAD_BLOCK, &["--fix"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(stdout, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED);
assert_framed_over(&stderr, "<stdin>", &stdout, 6, "stdin");
}
#[test]
fn a_fix_preview_frames_the_findings_over_the_file_as_read() {
let tmp = tempfile::tempdir().unwrap();
let below = tmp.path().join("x.mds");
fs::write(&below, A_WARNING_BELOW_A_DEAD_BLOCK).unwrap();
for mode in [&["--fix", "--check"][..], &["--fix", "--diff"]] {
let out = lint_path(&below, mode);
let stderr = String::from_utf8_lossy(&out.stderr);
let file = fs::read_to_string(&below).unwrap();
assert_eq!(
file, A_WARNING_BELOW_A_DEAD_BLOCK,
"{mode:?} writes nothing"
);
assert_framed_over(&stderr, "x.mds", &file, 9, &format!("{mode:?}"));
}
}
#[cfg(unix)]
#[test]
fn a_finding_left_by_a_fix_that_cannot_be_written_points_into_the_fixed_source() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let below = dir.path().join("x.mds");
fs::write(&below, A_WARNING_BELOW_A_DEAD_BLOCK).unwrap();
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap();
let out = lint_path(&below, &["--fix"]);
let _ = fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755));
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
fs::read_to_string(&below).unwrap(),
A_WARNING_BELOW_A_DEAD_BLOCK,
"the write failed; stderr: {stderr}"
);
assert_framed_over(
&stderr,
"x.mds",
A_WARNING_BELOW_A_DEAD_BLOCK_FIXED,
6,
"a failed write",
);
assert_eq!(out.status.code(), Some(2), "stderr: {stderr}");
}
const LINT_MODES: [&[&str]; 5] = [
&[],
&["--fix"],
&["--fix", "--check"],
&["--fix", "--diff"],
&["--fix", "--check", "--diff"],
];
const UNDER_THE_CAP: &str = "---\nv0: 1\n---\nHello\n";
fn over_the_cap_unfixable() -> String {
use std::fmt::Write as _;
let mut source = String::from("---\n");
for i in 0..=mds::MAX_DIAGNOSTICS {
let _ = writeln!(source, "v{i}: 1");
}
source.push_str("---\nHello\n");
source
}
fn over_the_cap_fixable() -> String {
let mut source = String::from("---\nflag: true\n---\n");
for _ in 0..=mds::MAX_DIAGNOSTICS {
source.push_str("@if flag:\n@end\n");
}
source
}
const OVER_THE_CAP_FIXED: &str = "---\nflag: true\n---\n@if flag:\n@end\n";
fn cap_notice() -> String {
format!(
"diagnostic cap ({}) reached; further findings were suppressed",
mds::MAX_DIAGNOSTICS
)
}
fn cap_notice_under_fix() -> String {
format!("{} — re-run --fix to continue", cap_notice())
}
fn entry_cap_notice(notice: &str) -> String {
format!(
"{}: {notice}",
"d/x.mds".replace('/', std::path::MAIN_SEPARATOR_STR)
)
}
fn cap_notice_in(mode: &[&str]) -> String {
if mode == ["--fix"] {
cap_notice_under_fix()
} else {
cap_notice()
}
}
fn head_of(stderr: &str) -> Vec<&str> {
stderr.lines().take(3).collect()
}
fn truncated_of(out: &std::process::Output) -> bool {
let stdout = String::from_utf8_lossy(&out.stdout);
let document = stdout.lines().last().unwrap_or_else(|| {
panic!(
"no JSON document on stdout; stderr starts {:?}",
head_of(&String::from_utf8_lossy(&out.stderr))
)
});
let json: serde_json::Value = serde_json::from_str(document)
.unwrap_or_else(|e| panic!("stdout must end with the JSON document: {e}"));
json["truncated"]
.as_bool()
.unwrap_or_else(|| panic!("the document has no `truncated` flag"))
}
#[test]
fn truncated_is_true_for_a_capped_residual_in_every_mode() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let file = d.join("x.mds");
fs::write(&file, UNDER_THE_CAP).unwrap();
assert!(
!truncated_of(&lint_path(&file, &["--format", "json"])),
"control: one finding is not truncated"
);
let source = over_the_cap_unfixable();
fs::write(&file, &source).unwrap();
assert!(
truncated_of(&lint_stdin(&source, &["--format", "json"])),
"stdin, a report"
);
for mode in LINT_MODES {
let args = [mode, &["--format", "json"][..]].concat();
assert!(truncated_of(&lint_path(&file, &args)), "a file, {mode:?}");
assert!(
truncated_of(&lint_dir_in(tmp.path(), "d", &args)),
"a directory, {mode:?}"
);
}
assert_eq!(fs::read_to_string(&file).unwrap(), source, "nothing to fix");
}
#[test]
fn truncated_is_false_once_a_fix_clears_a_capped_fixable_set() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let file = d.join("x.mds");
let source = over_the_cap_fixable();
let mut seen = Vec::new();
for mode in LINT_MODES {
let args = [mode, &["--format", "json"][..]].concat();
fs::write(&file, &source).unwrap();
seen.push(("a file", mode, truncated_of(&lint_path(&file, &args))));
fs::write(&file, &source).unwrap();
let dir = lint_dir_in(tmp.path(), "d", &args);
seen.push(("a directory", mode, truncated_of(&dir)));
if mode == ["--fix"] {
assert_eq!(
fs::read_to_string(&file).unwrap(),
OVER_THE_CAP_FIXED,
"--fix removes the blocks it is shown"
);
}
}
let expected: Vec<_> = seen
.iter()
.map(|&(input, mode, _)| (input, mode, mode.is_empty()))
.collect();
assert_eq!(seen, expected, "truncated: the report's alone");
}
#[test]
fn a_report_announces_the_cap_first_in_every_input_and_format() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let file = d.join("x.mds");
fs::write(&file, UNDER_THE_CAP).unwrap();
let control = lint_path(&file, &[]);
let stderr = String::from_utf8_lossy(&control.stderr);
assert!(
stderr.contains("[unused-variable]") && !stderr.contains("diagnostic cap"),
"control: the finding shows, and no cap; stderr: {stderr}"
);
let source = over_the_cap_unfixable();
fs::write(&file, &source).unwrap();
for format in ["human", "json"] {
let args = ["--format", format];
let runs = [
("stdin", lint_stdin(&source, &args), cap_notice()),
("a file", lint_path(&file, &args), cap_notice()),
(
"a directory",
lint_dir_in(tmp.path(), "d", &args),
entry_cap_notice(&cap_notice()),
),
];
for (input, out, notice) in runs {
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(
stderr.lines().next(),
Some(notice.as_str()),
"{input}, {format}: the cap comes first; stderr starts {:?}",
head_of(&stderr)
);
assert_eq!(
stderr.matches("diagnostic cap").count(),
1,
"{input}, {format}: one notice"
);
assert_eq!(out.status.code(), Some(1), "{input}, {format}: warnings");
}
}
}
#[test]
fn quiet_suppresses_the_cap_notice_in_a_report() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let file = d.join("x.mds");
let source = over_the_cap_unfixable();
fs::write(&file, &source).unwrap();
for format in ["human", "json"] {
let run = |input: &str, quiet: bool| {
let mut args = vec!["--format", format];
if quiet {
args.push("--quiet");
}
match input {
"stdin" => lint_stdin(&source, &args),
"a file" => lint_path(&file, &args),
_ => lint_dir_in(tmp.path(), "d", &args),
}
};
for input in ["stdin", "a file", "a directory"] {
let loud = run(input, false);
let loud_stderr = String::from_utf8_lossy(&loud.stderr);
assert!(
loud_stderr.contains("diagnostic cap"),
"positive control ({input}, {format}): without --quiet the notice prints; \
stderr starts {:?}",
head_of(&loud_stderr)
);
let quiet = run(input, true);
let quiet_stderr = String::from_utf8_lossy(&quiet.stderr);
assert!(
!quiet_stderr.contains("diagnostic cap"),
"{input}, {format}: --quiet suppresses the notice; stderr starts {:?}",
head_of(&quiet_stderr)
);
assert_eq!(
quiet.status.code(),
loud.status.code(),
"{input}, {format}: --quiet leaves the exit code"
);
}
}
}
#[test]
fn the_cap_notice_advises_re_running_fix_under_fix_alone() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
fs::create_dir(&d).unwrap();
let file = d.join("x.mds");
let source = over_the_cap_unfixable();
fs::write(&file, &source).unwrap();
let mut seen = Vec::new();
let mut expected = Vec::new();
for mode in LINT_MODES {
let notice = cap_notice_in(mode);
for format in ["human", "json"] {
let args = [mode, &["--format", format][..]].concat();
let file_run = lint_path(&file, &args);
let dir_run = lint_dir_in(tmp.path(), "d", &args);
for (input, out, notice) in [
("a file", file_run, notice.clone()),
("a directory", dir_run, entry_cap_notice(¬ice)),
] {
let stderr = String::from_utf8_lossy(&out.stderr);
let first = stderr.lines().next().unwrap_or_default().to_string();
seen.push((input, mode, format, first));
expected.push((input, mode, format, notice));
}
}
let stdin_run = lint_stdin(&source, mode);
let stderr = String::from_utf8_lossy(&stdin_run.stderr);
let first = stderr.lines().next().unwrap_or_default().to_string();
seen.push(("stdin", mode, "human", first));
expected.push(("stdin", mode, "human", notice));
}
assert!(
expected
.iter()
.any(|(_, _, _, notice)| notice.ends_with("re-run --fix to continue")),
"non-vacuity: the advice is expected somewhere"
);
assert_eq!(seen, expected, "the first stderr line of each run");
assert_eq!(fs::read_to_string(&file).unwrap(), source, "nothing to fix");
}
#[cfg(unix)]
struct ReadOnlyDir(std::path::PathBuf);
#[cfg(unix)]
impl ReadOnlyDir {
fn new(dir: &Path) -> Option<Self> {
use std::os::unix::fs::PermissionsExt as _;
fs::set_permissions(dir, fs::Permissions::from_mode(0o555)).unwrap();
let guard = Self(dir.to_path_buf());
let probe = dir.join(".write-probe");
if fs::write(&probe, "").is_ok() {
let _ = fs::remove_file(&probe);
eprintln!(
"skipped: a file can be created in {} at mode 0o555 (running as euid 0?)",
dir.display()
);
return None;
}
Some(guard)
}
}
#[cfg(unix)]
impl Drop for ReadOnlyDir {
fn drop(&mut self) {
use std::os::unix::fs::PermissionsExt as _;
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o755));
}
}
#[cfg(unix)]
fn a_fix_that_cannot_be_written() -> Option<(tempfile::TempDir, ReadOnlyDir)> {
let tmp = tempfile::tempdir().unwrap();
for dir in ["ro", "rw"] {
fs::create_dir(tmp.path().join(dir)).unwrap();
fs::write(
tmp.path().join(dir).join("x.mds"),
A_WARNING_BELOW_A_DEAD_BLOCK,
)
.unwrap();
}
let ro = ReadOnlyDir::new(&tmp.path().join("ro"))?;
Some((tmp, ro))
}
#[cfg(unix)]
fn lint_in(cwd: &Path, input: &Path, extra_args: &[&str]) -> std::process::Output {
mds_bin()
.current_dir(cwd)
.arg("lint")
.args(extra_args)
.arg(input)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.unwrap()
}
#[cfg(unix)]
fn write_failure(typed: &Path) -> String {
format!(
"cannot write {}: {}",
typed.display(),
std::io::Error::from_raw_os_error(libc::EACCES)
)
}
#[cfg(unix)]
fn failure_reported(out: &std::process::Output, typed: &Path) -> Option<String> {
let stdout = String::from_utf8_lossy(&out.stdout);
if let Ok(document) = serde_json::from_str::<serde_json::Value>(&stdout) {
let entry_error = document["files"]
.as_array()
.and_then(|files| files.iter().find_map(|entry| entry.get("error")));
let error = document.get("error").or(entry_error)?;
return error["message"].as_str().map(str::to_string);
}
let typed = typed.display().to_string();
let stderr = String::from_utf8_lossy(&out.stderr);
let line = stderr.lines().find(|line| line.contains(&typed))?.trim();
Some(line.strip_prefix("× ").unwrap_or(line).to_string())
}
#[cfg(unix)]
#[test]
fn a_file_fix_that_cannot_be_written_prints_the_io_error_document() {
let Some((tmp, _ro)) = a_fix_that_cannot_be_written() else {
return;
};
let typed = Path::new("ro").join("x.mds");
let out = lint_in(tmp.path(), &typed, &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(stdout.lines().count(), 1, "one document; stdout: {stdout}");
let document: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("stdout must be a JSON document: {e}; stdout: {stdout}"));
let expected = serde_json::json!({
"version": 1,
"error": {
"code": "mds::io",
"message": write_failure(&typed),
"help": null,
"span": null,
},
});
assert_eq!(document, expected, "stderr: {stderr}");
assert_eq!(stderr, "", "the document is the one report of the failure");
assert_eq!(out.status.code(), Some(2));
assert_eq!(
fs::read_to_string(tmp.path().join(&typed)).unwrap(),
A_WARNING_BELOW_A_DEAD_BLOCK,
"nothing was written"
);
let typed = Path::new("rw").join("x.mds");
let out = lint_in(tmp.path(), &typed, &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let document: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("control: a JSON document: {e}; stdout: {stdout}"));
assert_eq!(
document["files"][0]["diagnostics"][0]["rule"], "redundant-else",
"control: the warning the fix left; stdout: {stdout}"
);
assert_eq!(out.status.code(), Some(1), "control");
assert_eq!(
fs::read_to_string(tmp.path().join(&typed)).unwrap(),
A_WARNING_BELOW_A_DEAD_BLOCK_FIXED,
"control: the fix was written"
);
}
#[cfg(unix)]
#[test]
fn a_directory_entry_whose_fix_cannot_be_written_is_recorded_as_that_failure_alone() {
let Some((tmp, _ro)) = a_fix_that_cannot_be_written() else {
return;
};
let typed = Path::new("ro").join("x.mds");
let out = lint_in(tmp.path(), Path::new("ro"), &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let document: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("stdout must be a JSON document: {e}; stdout: {stdout}"));
let expected = serde_json::json!([{
"file": "x.mds",
"error": {
"code": "mds::io",
"message": write_failure(&typed),
"help": null,
"span": null,
},
}]);
assert_eq!(document["files"], expected, "stdout: {stdout}");
assert_eq!(out.status.code(), Some(2));
assert_eq!(
fs::read_to_string(tmp.path().join(&typed)).unwrap(),
A_WARNING_BELOW_A_DEAD_BLOCK,
"nothing was written"
);
let out = lint_in(tmp.path(), Path::new("rw"), &["--fix", "--format", "json"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let document: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("control: a JSON document: {e}; stdout: {stdout}"));
assert_eq!(
document["files"][0]["diagnostics"][0]["rule"], "redundant-else",
"control: the warning the fix left; stdout: {stdout}"
);
assert_eq!(out.status.code(), Some(1), "control");
}
#[cfg(unix)]
#[test]
fn a_fix_that_cannot_be_written_is_reported_in_one_wording_in_every_mode() {
let Some((tmp, _ro)) = a_fix_that_cannot_be_written() else {
return;
};
let mut seen = Vec::new();
let mut expected = Vec::new();
let mut controls = Vec::new();
for dir in ["ro", "rw"] {
let typed = Path::new(dir).join("x.mds");
for (input, arg) in [("a file", typed.clone()), ("a directory", dir.into())] {
for format in ["human", "json"] {
fs::write(
tmp.path().join("rw").join("x.mds"),
A_WARNING_BELOW_A_DEAD_BLOCK,
)
.unwrap();
let out = lint_in(tmp.path(), &arg, &["--fix", "--format", format]);
let reported = failure_reported(&out, &typed);
let both = [out.stdout.as_slice(), out.stderr.as_slice()].concat();
let named = String::from_utf8_lossy(&both)
.matches(typed.display().to_string().as_str())
.count();
if dir == "ro" {
seen.push((input, format, reported, named));
expected.push((input, format, Some(write_failure(&typed)), 1));
} else {
let fixed = fs::read_to_string(tmp.path().join(&typed)).unwrap();
let status = (format == "human").then(|| format!("Fixed: {}", typed.display()));
controls.push((input, format, reported, status, out.status.code(), fixed));
}
}
}
}
assert_eq!(
seen, expected,
"(input, format, failure, times the file is named)"
);
for (input, format, reported, status, code, fixed) in controls {
assert_eq!(reported, status, "control, {input}, {format}: no failure");
assert_eq!(
code,
Some(1),
"control, {input}, {format}: the warning stays"
);
assert_eq!(
fixed, A_WARNING_BELOW_A_DEAD_BLOCK_FIXED,
"control, {input}, {format}: the fix was written"
);
}
assert_eq!(
fs::read_to_string(tmp.path().join("ro").join("x.mds")).unwrap(),
A_WARNING_BELOW_A_DEAD_BLOCK,
"nothing was written"
);
}
fn a_tree_with_a_file_of(len: u64) -> tempfile::TempDir {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("d");
fs::create_dir(&dir).unwrap();
fs::copy(fixture("lint_warn_only.mds"), dir.join("warn.mds")).unwrap();
let len = usize::try_from(len).unwrap();
fs::write(dir.join("big.mds"), "a".repeat(len - 1) + "\n").unwrap();
tmp
}
#[derive(Debug, PartialEq)]
struct SizeReport {
exit: Option<i32>,
error: Option<String>,
summary: Option<String>,
rest_linted: bool,
}
fn size_report(cwd: &Path, input: &Path, format: &str, mode: &[&str]) -> SizeReport {
let out = mds_bin()
.current_dir(cwd)
.arg("lint")
.args(mode)
.args(["--format", format])
.arg(input)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let summary = stderr
.lines()
.find(|line| line.ends_with(" resource-limited"))
.map(str::to_string);
let (error, rest_linted) = if format == "json" {
let document: serde_json::Value = stdout
.lines()
.last()
.and_then(|line| serde_json::from_str(line).ok())
.unwrap_or_else(|| panic!("a JSON document on stdout; got {stdout:?}"));
let entry = |name: &str| {
document["files"]
.as_array()
.and_then(|files| files.iter().find(|entry| entry["file"] == name))
.cloned()
};
let error = document
.get("error")
.cloned()
.or_else(|| entry("big.mds").map(|entry| entry["error"].clone()));
let rest_linted = entry("warn.mds")
.is_some_and(|entry| entry["diagnostics"][0]["rule"] == "unused-variable");
let code = error.and_then(|error| error["code"].as_str().map(str::to_string));
(code, rest_linted)
} else {
let code = stderr
.lines()
.map(str::trim)
.find(|line| line.starts_with("mds::") && !line.starts_with("mds::lint::"))
.map(str::to_string);
(code, stderr.contains("[unused-variable]"))
};
SizeReport {
exit: out.status.code(),
error,
summary,
rest_linted,
}
}
#[test]
fn a_file_over_the_size_cap_is_resource_limited_in_every_lint_mode() {
let file = Path::new("d").join("big.mds");
let inputs = [("a file", file.as_path()), ("a directory", Path::new("d"))];
let over = a_tree_with_a_file_of(mds::MAX_FILE_SIZE + 1);
let mut seen = Vec::new();
let mut expected = Vec::new();
for (input, arg) in inputs {
let in_dir = input == "a directory";
for format in ["human", "json"] {
for mode in LINT_MODES {
let report = size_report(over.path(), arg, format, mode);
seen.push((input, format, mode, report));
let report = SizeReport {
exit: Some(3),
error: Some("mds::resource_limit".to_string()),
summary: in_dir.then(|| {
"0 clean, 1 with warnings, 0 with errors, 1 resource-limited".into()
}),
rest_linted: in_dir,
};
expected.push((input, format, mode, report));
}
}
}
assert_eq!(seen, expected, "(input, format, mode, what it reported)");
assert_eq!(
fs::metadata(over.path().join(&file)).unwrap().len(),
mds::MAX_FILE_SIZE + 1,
"nothing was written"
);
let at = a_tree_with_a_file_of(mds::MAX_FILE_SIZE);
let mut controls = Vec::new();
let mut expected = Vec::new();
for (input, arg) in inputs {
let in_dir = input == "a directory";
for format in ["human", "json"] {
for mode in [&[][..], &["--fix"]] {
let report = size_report(at.path(), arg, format, mode);
controls.push((input, format, mode, report));
let report = SizeReport {
exit: Some(i32::from(in_dir)),
error: None,
summary: in_dir.then(|| {
"1 clean, 1 with warnings, 0 with errors, 0 resource-limited".into()
}),
rest_linted: in_dir,
};
expected.push((input, format, mode, report));
}
}
}
assert_eq!(
controls, expected,
"control, (input, format, mode, what it reported)"
);
}
#[test]
fn a_config_that_cannot_load_is_reported_before_a_file_over_the_size_cap() {
let file = Path::new("d").join("big.mds");
let inputs = [("a file", file.as_path()), ("a directory", Path::new("d"))];
let mut seen = Vec::new();
let mut expected = Vec::new();
for (config, valid) in [("{", false), ("{}", true)] {
let tree = a_tree_with_a_file_of(mds::MAX_FILE_SIZE + 1);
fs::write(tree.path().join("d").join("mds.json"), config).unwrap();
for (input, arg) in inputs {
let in_dir = input == "a directory";
for format in ["human", "json"] {
for mode in [&[][..], &["--fix"]] {
let report = size_report(tree.path(), arg, format, mode);
seen.push((config, input, format, mode, report));
let report = if valid {
SizeReport {
exit: Some(3),
error: Some("mds::resource_limit".to_string()),
summary: in_dir.then(|| {
"0 clean, 1 with warnings, 0 with errors, 1 resource-limited".into()
}),
rest_linted: in_dir,
}
} else {
SizeReport {
exit: Some(2),
error: Some("mds::io".to_string()),
summary: in_dir.then(|| {
"0 clean, 0 with warnings, 2 with errors, 0 resource-limited".into()
}),
rest_linted: false,
}
};
expected.push((config, input, format, mode, report));
}
}
}
}
assert_eq!(
seen, expected,
"(mds.json, input, format, mode, what it reported)"
);
}
#[test]
fn a_vars_file_over_the_size_cap_exits_3() {
let tmp = tempfile::tempdir().unwrap();
fs::write(tmp.path().join("x.mds"), "Hello!\n").unwrap();
let mut seen = Vec::new();
let mut expected = Vec::new();
for (len, exit, code) in [
(mds::MAX_FILE_SIZE, 0, None),
(mds::MAX_FILE_SIZE + 1, 3, Some("mds::resource_limit")),
] {
let (head, tail) = ("{\"pad\":\"", "\"}");
let pad = usize::try_from(len).unwrap() - head.len() - tail.len();
fs::write(
tmp.path().join("vars.json"),
format!("{head}{}{tail}", "a".repeat(pad)),
)
.unwrap();
let human = lint_with_stdin(tmp.path(), &["--vars", "vars.json", "x.mds"], b"");
let human_code = String::from_utf8_lossy(&human.stderr)
.lines()
.map(str::trim)
.find(|line| line.starts_with("mds::"))
.map(str::to_string);
seen.push((len, "human", human.status.code(), human_code, None));
expected.push((len, "human", Some(exit), code.map(str::to_string), None));
let json = lint_with_stdin(
tmp.path(),
&["--format", "json", "--vars", "vars.json", "x.mds"],
b"",
);
let json = json_exit(&json);
let rest = (json.documents, json.stderr);
seen.push((len, "json", json.exit, json.code, Some(rest)));
expected.push((
len,
"json",
Some(exit),
code.map(str::to_string),
Some((Some(1), String::new())),
));
}
assert_eq!(
seen, expected,
"(vars file length, format, exit, error code, (documents, stderr))"
);
}
fn json_documents(stdout: &[u8]) -> Option<Vec<serde_json::Value>> {
serde_json::Deserializer::from_slice(stdout)
.into_iter::<serde_json::Value>()
.collect::<Result<_, _>>()
.ok()
}
#[derive(Debug, PartialEq)]
struct JsonExit {
exit: Option<i32>,
documents: Option<usize>,
code: Option<String>,
stderr: String,
}
impl JsonExit {
fn error(exit: i32, code: &str) -> Self {
Self {
exit: Some(exit),
documents: Some(1),
code: Some(code.to_string()),
stderr: String::new(),
}
}
}
fn json_exit(out: &std::process::Output) -> JsonExit {
let documents = json_documents(&out.stdout);
let code = match documents.as_deref() {
Some([document]) => document["error"]["code"].as_str().map(str::to_string),
_ => None,
};
JsonExit {
exit: out.status.code(),
documents: documents.map(|documents| documents.len()),
code,
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
}
}
fn error_message(out: &std::process::Output) -> Option<String> {
match json_documents(&out.stdout).as_deref() {
Some([document]) => document["error"]["message"].as_str().map(str::to_string),
_ => None,
}
}
fn lint_with_stdin(cwd: &Path, args: &[&str], stdin: &[u8]) -> std::process::Output {
use std::io::Write;
let mut child = mds_bin()
.current_dir(cwd)
.arg("lint")
.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
let _ = child.stdin.take().unwrap().write_all(stdin);
child.wait_with_output().unwrap()
}
#[test]
fn every_failure_that_stops_a_json_run_prints_one_error_document() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
fs::write(root.join("x.mds"), "Hello!\n").unwrap();
for dir in ["none", "empty", "several", "cfg"] {
fs::create_dir(root.join(dir)).unwrap();
}
fs::write(root.join("several").join("a.mds"), "A\n").unwrap();
fs::write(root.join("several").join("b.mds"), "B\n").unwrap();
fs::write(root.join("cfg").join("mds.json"), "{").unwrap();
fs::write(root.join("cfg").join("x.mds"), "Hello!\n").unwrap();
let excluded = root.join("excluded").join("node_modules");
fs::create_dir_all(&excluded).unwrap();
fs::write(excluded.join("a.mds"), "A\n").unwrap();
let configured = Path::new("cfg").join("x.mds");
let configured = configured.to_str().unwrap();
let over_the_cap = vec![b'a'; usize::try_from(mds::MAX_FILE_SIZE).unwrap() + 1];
let (none, several, cfg) = (root.join("none"), root.join("several"), root.join("cfg"));
#[allow(clippy::type_complexity)]
let rows: [(&str, &Path, &[&str], &[u8], bool, i32, &str, &str); 9] = [
(
"--vars that cannot load",
root,
&["--vars", "missing.json", "x.mds"],
b"",
true,
2,
"mds::file_not_found",
"missing.json",
),
(
"no file to auto-detect",
&none,
&[],
b"",
true,
2,
"mds::io",
"no .mds files found in current directory",
),
(
"more than one file to auto-detect",
&several,
&[],
b"",
true,
2,
"mds::io",
"multiple .mds files found",
),
(
"an mds.json that cannot load, a file argument",
root,
&[configured],
b"",
true,
2,
"mds::io",
"invalid mds.json",
),
(
"an mds.json that cannot load, stdin",
&cfg,
&["-"],
b"Hello!\n",
false,
2,
"mds::io",
"invalid mds.json",
),
(
"stdin over the size cap",
root,
&["-"],
&over_the_cap,
false,
3,
"mds::resource_limit",
"maximum size",
),
(
"stdin that is not UTF-8",
root,
&["-"],
b"Hello \xff\n",
false,
2,
"mds::io",
"valid UTF-8",
),
(
"a directory with no .mds file",
root,
&["empty"],
b"",
true,
2,
"mds::io",
"no .mds files found in empty; nothing was linted",
),
(
"a directory whose every .mds file is excluded",
root,
&["excluded"],
b"",
true,
2,
"mds::io",
"1 .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was linted",
),
];
let mut seen = Vec::new();
let mut expected = Vec::new();
let mut messages = Vec::new();
for (what, cwd, args, stdin, every_mode, exit, code, words) in rows {
let modes: &[&[&str]] = if every_mode { &LINT_MODES } else { &[&[]] };
for mode in modes {
for quiet in [&[][..], &["--quiet"]] {
let mut all = vec!["--format", "json"];
all.extend_from_slice(mode);
all.extend_from_slice(quiet);
all.extend_from_slice(args);
let out = lint_with_stdin(cwd, &all, stdin);
let run = all.join(" ");
messages.push((what, run.clone(), error_message(&out), words));
seen.push((what, run.clone(), json_exit(&out)));
expected.push((what, run, JsonExit::error(exit, code)));
}
}
}
assert_eq!(
seen, expected,
"(what stops the run, arguments, what it printed)"
);
for (what, run, message, words) in messages {
assert!(
message.as_deref().is_some_and(|m| m.contains(words)),
"{what} (`mds lint {run}`): the message holds {words:?}; got {message:?}"
);
}
for (dir, words) in [("empty", rows[7].7), ("excluded", rows[8].7)] {
let human = lint_with_stdin(root, &[dir], b"");
assert_eq!(
(
human.status.code(),
String::from_utf8_lossy(&human.stdout).into_owned(),
String::from_utf8_lossy(&human.stderr).into_owned()
),
(Some(2), String::new(), format!("{words}\n")),
"control: the human report of {dir}"
);
let json = lint_with_stdin(root, &["--format", "json", dir], b"");
assert_eq!(
error_message(&json).as_deref(),
Some(words),
"the error document of {dir} words it as the human report does"
);
}
let linted = lint_with_stdin(root, &["--format", "json", "x.mds"], b"");
assert_eq!(
json_exit(&linted),
JsonExit {
exit: Some(0),
documents: Some(1),
code: None,
stderr: String::new(),
},
"control: a clean file"
);
let document = &json_documents(&linted.stdout).unwrap()[0];
let mut keys: Vec<&String> = document.as_object().unwrap().keys().collect();
keys.sort();
assert_eq!(
keys,
["files", "truncated", "version"],
"control: {document}"
);
}
#[test]
fn an_auto_detection_failure_carries_its_hint_in_help() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in ["none", "several"] {
fs::create_dir(root.join(dir)).unwrap();
}
fs::write(root.join("several").join("b.mds"), "B\n").unwrap();
fs::write(root.join("several").join("a.mds"), "A\n").unwrap();
let rows = [
(
"none",
"no .mds files found in current directory",
"run 'mds init' to create a starter template",
),
(
"several",
"multiple .mds files found: a.mds, b.mds",
"specify which file, e.g. 'mds lint a.mds'",
),
];
for (dir, message, help) in rows {
let cwd = root.join(dir);
for mode in LINT_MODES {
let mut args = vec!["--format", "json"];
args.extend_from_slice(mode);
let out = lint_with_stdin(&cwd, &args, b"");
assert_eq!(
(
out.status.code(),
json_documents(&out.stdout),
String::from_utf8_lossy(&out.stderr).into_owned()
),
(
Some(2),
Some(vec![serde_json::json!({
"version": 1,
"error": {
"code": "mds::io",
"message": message,
"help": help,
"span": null
}
})]),
String::new()
),
"`mds lint {}` in {dir}",
args.join(" ")
);
}
let human = lint_with_stdin(&cwd, &[], b"");
let shown = String::from_utf8_lossy(&human.stderr).into_owned();
assert_eq!(human.status.code(), Some(2), "human, {dir}: {shown}");
assert!(
shown
.lines()
.any(|line| line.trim() == format!("help: {help}"))
&& shown.contains(message)
&& !shown.contains("hint:"),
"human, {dir}: the hint is the report's help line; got: {shown}"
);
}
}
const STDIN_FIX_JSON_REFUSAL: &str = "--fix --format json with stdin input is not supported; \
use `mds lint --fix -` for filter mode or `mds lint --format json` for JSON output";
#[test]
fn stdin_under_fix_in_json_is_refused_with_one_error_document() {
let tmp = tempfile::tempdir().unwrap();
let mut seen = Vec::new();
let mut expected = Vec::new();
for mode in &LINT_MODES[1..] {
for quiet in [&[][..], &["--quiet"]] {
let mut args = vec!["--format", "json"];
args.extend_from_slice(mode);
args.extend_from_slice(quiet);
args.push("-");
let out = lint_with_stdin(tmp.path(), &args, b"Hello!\n");
seen.push((args.join(" "), json_exit(&out), error_message(&out)));
expected.push((
args.join(" "),
JsonExit::error(2, "mds::io"),
Some(STDIN_FIX_JSON_REFUSAL.to_string()),
));
}
}
assert_eq!(seen, expected, "(arguments, what it printed, its message)");
let filter = lint_with_stdin(tmp.path(), &["--fix", "-"], b"Hello!\n");
assert_eq!(
(
filter.status.code(),
String::from_utf8_lossy(&filter.stdout).into_owned()
),
(Some(0), "Hello!\n".to_string()),
"control: the filter; stderr: {}",
String::from_utf8_lossy(&filter.stderr)
);
let report = lint_with_stdin(tmp.path(), &["--format", "json", "-"], b"Hello!\n");
assert_eq!(
json_exit(&report),
JsonExit {
exit: Some(0),
documents: Some(1),
code: None,
stderr: String::new(),
},
"control: a report of stdin"
);
}
#[test]
fn fix_diff_in_json_prints_its_diffs_then_exactly_one_document() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("d");
fs::create_dir(&dir).unwrap();
fs::copy(fixture("lint_error.mds"), dir.join("a.mds")).unwrap();
fs::copy(fixture("lint_error.mds"), dir.join("b.mds")).unwrap();
let file = Path::new("d").join("a.mds");
let file = file.to_str().unwrap();
for (input, files) in [(file, 1), ("d", 2)] {
let out = lint_with_stdin(
tmp.path(),
&["--fix", "--diff", "--format", "json", input],
b"",
);
let stdout = String::from_utf8_lossy(&out.stdout);
let lines: Vec<&str> = stdout.lines().collect();
let start = lines
.iter()
.position(|line| line.starts_with('{'))
.unwrap_or_else(|| panic!("{input}: a document on stdout; got {stdout:?}"));
let headers = lines[..start]
.iter()
.filter(|line| line.starts_with("--- "))
.count();
assert_eq!(
headers, files,
"{input}: a diff per file comes first; stdout: {stdout:?}"
);
let rest = lines[start..].join("\n");
let documents = json_documents(rest.as_bytes())
.unwrap_or_else(|| panic!("{input}: only JSON after the diffs; got {rest:?}"));
assert_eq!(documents.len(), 1, "{input}: then one document: {rest}");
assert!(
documents[0]["files"].is_array() && documents[0]["version"] == 1,
"{input}: the findings document: {rest}"
);
let check = lint_with_stdin(
tmp.path(),
&["--fix", "--check", "--format", "json", input],
b"",
);
assert_eq!(
json_documents(&check.stdout).map(|documents| documents.len()),
Some(1),
"control: {input} under --fix --check; stdout: {:?}",
String::from_utf8_lossy(&check.stdout)
);
}
}
#[cfg(unix)]
fn run_where_the_working_directory_is_gone(
gone: &Path,
args: &[&str],
stdin: &[u8],
) -> std::process::Output {
use std::io::Write;
use std::os::unix::ffi::OsStrExt as _;
use std::os::unix::process::CommandExt as _;
fs::create_dir(gone).unwrap();
let target =
std::ffi::CString::new(gone.as_os_str().as_bytes()).expect("a temporary path holds no NUL");
let mut cmd = mds_bin();
cmd.current_dir(gone)
.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
unsafe {
cmd.pre_exec(move || {
if libc::rmdir(target.as_ptr()) == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
});
}
let mut child = cmd.spawn().unwrap();
let _ = child.stdin.take().unwrap().write_all(stdin);
let out = child.wait_with_output().unwrap();
assert!(
!gone.exists(),
"control: the run's working directory was gone; stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
out
}
#[cfg(unix)]
#[test]
fn stdin_where_the_working_directory_is_gone_fails_in_the_words_build_uses() {
const CANNOT_DETERMINE: &str = "cannot determine current directory: ";
let tmp = tempfile::tempdir().unwrap();
let gone = |name: &str, args: &[&str]| {
run_where_the_working_directory_is_gone(&tmp.path().join(name), args, b"Hello!\n")
};
let build = gone("build", &["build", "-"]);
let build_stderr = String::from_utf8_lossy(&build.stderr).into_owned();
assert_eq!(
build.status.code(),
Some(2),
"control: build: {build_stderr}"
);
assert!(
build_stderr.contains("mds::io") && build_stderr.contains(CANNOT_DETERMINE),
"control: build fails in mds-core's words; stderr: {build_stderr}"
);
for args in [&["lint", "-"][..], &["lint", "--fix", "-"]] {
let human = gone(&args.join("-"), args);
assert_eq!(
(
human.status.code(),
String::from_utf8_lossy(&human.stdout).into_owned(),
String::from_utf8_lossy(&human.stderr).into_owned()
),
(build.status.code(), String::new(), build_stderr.clone()),
"`mds {}` fails as `mds build -` does",
args.join(" ")
);
}
let json = gone("json", &["lint", "--format", "json", "-"]);
assert_eq!(json_exit(&json), JsonExit::error(2, "mds::io"), "json");
assert!(
error_message(&json).is_some_and(|m| m.starts_with(CANNOT_DETERMINE)),
"json: in the same words; got {:?}",
error_message(&json)
);
let here = lint_with_stdin(tmp.path(), &["--format", "json", "-"], b"Hello!\n");
assert_eq!(
json_exit(&here),
JsonExit {
exit: Some(0),
documents: Some(1),
code: None,
stderr: String::new(),
},
"control: where the working directory exists"
);
}