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()
}
#[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_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!(
out.status.code(),
Some(2),
"--fix --format json stdin must exit 2 (usage error)"
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stderr.is_empty(),
"usage error message must appear on stderr"
);
}
#[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_file") && !stderr.contains("not an .mds"),
"must NOT report 'not an .mds file' for a non-existent path; 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 out = lint_path(&missing, &["--format", "json"]);
assert_eq!(
out.status.code(),
Some(2),
"--format json + nonexistent .txt 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}")
});
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",
"JSON envelope code must be mds::file_not_found (not mds::not_mds_file); got: {code}"
);
}
#[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 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:?}"
);
}
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:?}"
);
}
#[test]
fn lint_json_hostile_source_output_contains_no_raw_control_bytes() {
let dir = tempfile::tempdir().unwrap();
let nel_name = "fo\u{0085}o.mds";
let nel_module = dir.path().join(nel_name);
fs::write(&nel_module, "hi\n").unwrap();
let import_line = format!("@import \"./{nel_name}\"\n");
let main_content = format!("{import_line}{import_line}");
let main_file = dir.path().join("main.mds");
fs::write(&main_file, main_content.as_bytes()).unwrap();
let out = lint_path(&main_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-9: lint --format json must emit valid JSON; parse error: {e}; \
stdout: {stdout_str:?}"
)
});
assert_eq!(json["version"], 1, "T-9: JSON version must be 1");
assert_no_control_chars(&stdout_str, "T-9 JSON wire output");
let files = json["files"]
.as_array()
.unwrap_or_else(|| panic!("T-9: JSON must have 'files' array; got: {json}"));
assert!(
!files.is_empty(),
"T-9: files array must be non-empty (duplicate-import should fire); got: {json}"
);
let all_diags: Vec<&serde_json::Value> = files
.iter()
.flat_map(|f| {
f["diagnostics"].as_array().unwrap_or_else(|| {
panic!(
"T-9: every file entry must have a 'diagnostics' array; \
got: {f}"
)
})
})
.collect();
assert!(
!all_diags.is_empty(),
"T-9: must have at least one diagnostic; got: {files:?}"
);
let has_dup_import = all_diags.iter().any(|d| d["rule"] == "duplicate-import");
assert!(
has_dup_import,
"T-9: duplicate-import must be among the diagnostics; 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 has_sanitized_nel = all_diags.iter().any(|d| {
d["message"]
.as_str()
.map(|m| m.contains("\\u0085"))
.unwrap_or(false)
});
assert!(
has_sanitized_nel,
"T-9: sanitized \\u0085 literal must appear in at least one diagnostic message; \
got messages: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
}
#[test]
fn lint_json_bidi_override_in_import_path_is_escaped() {
let dir = tempfile::tempdir().unwrap();
let rlo_name = "fo\u{202E}gnp.mds";
fs::write(dir.path().join(rlo_name), "hi\n").unwrap();
let import_line = format!("@import \"./{rlo_name}\"\n");
let main_file = dir.path().join("main.mds");
fs::write(&main_file, format!("{import_line}{import_line}").as_bytes()).unwrap();
let out = lint_path(&main_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-9b: lint --format json must emit valid JSON; parse error: {e}; stdout: {stdout_str:?}")
});
assert_eq!(json["version"], 1, "T-9b: JSON version must be 1");
assert_no_control_chars(&stdout_str, "T-9b JSON wire output");
let files = json["files"]
.as_array()
.unwrap_or_else(|| panic!("T-9b: JSON must have 'files' array; got: {json}"));
assert!(
!files.is_empty(),
"T-9b: files array must be non-empty (duplicate-import should fire); got: {json}"
);
let all_diags: Vec<&serde_json::Value> = files
.iter()
.flat_map(|f| {
f["diagnostics"]
.as_array()
.unwrap_or_else(|| panic!("T-9b: every file entry needs 'diagnostics'; got: {f}"))
})
.collect();
assert!(
all_diags.iter().any(|d| d["rule"] == "duplicate-import"),
"T-9b: duplicate-import must be among the diagnostics; got rules: {:?}",
all_diags.iter().map(|d| &d["rule"]).collect::<Vec<_>>()
);
let has_escaped_rlo = all_diags
.iter()
.any(|d| d["message"].as_str().is_some_and(|m| m.contains("\\u202E")));
assert!(
has_escaped_rlo,
"T-9b: escaped \\u202E literal must appear in at least one diagnostic message; \
got messages: {:?}",
all_diags.iter().map(|d| &d["message"]).collect::<Vec<_>>()
);
}
#[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 \
(lint_one_file_accumulating, lint.rs:1535 guard); 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, ",
"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!(
"warning: in mds.json: unknown lint rule 'no-such-rule-xyzzy'; \
recognised rules are: {recognised}; ignoring"
);
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!(
"warning: in mds.json: unknown lint rules: 'aaa-bad', 'zzz-bad'; \
recognised rules are: {recognised}; ignoring"
);
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, ",
"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!(
"warning: in mds.json: unknown lint rule 'no-such-rule-xyzzy'; \
recognised rules are: {recognised}; ignoring"
);
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!(
"warning: in mds.json: unknown lint rules: 'aaa-bad', 'zzz-bad'; \
recognised rules are: {recognised}; ignoring"
);
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();
}
#[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:' \
(D4/PF-004 lint_one_file_accumulating FixFileOutcome::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:' \
(D4/PF-004 lint_one_file_accumulating PreviewOutcome::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 \
(D4/PF-004 lint_one_file_accumulating cap-notice gate); 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_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);
assert_eq!(
non_quiet.status.code(),
Some(0),
"empty directory lint must exit 0; stderr: {stderr_nq}"
);
assert!(
stderr_nq.contains("No .mds files found"),
"empty directory must print 'No .mds files found'; got: {stderr_nq:?}"
);
assert!(
!stderr_nq.contains("clean,"),
"AC-Q21: empty directory must NOT print a summary; got: {stderr_nq:?}"
);
let quiet = lint_path(dir.path(), &["--quiet"]);
let stderr_q = String::from_utf8_lossy(&quiet.stderr);
assert_eq!(
quiet.status.code(),
Some(0),
"empty directory lint --quiet must exit 0; stderr: {stderr_q}"
);
assert!(
stderr_q.is_empty(),
"AC-Q21: empty directory under --quiet must produce no stderr; got: {stderr_q:?}"
);
}
#[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!(
!stderr_bytes.contains(&esc_byte),
"AC-Q25: raw ESC byte must not appear in stderr; got: {stderr:?}"
);
assert!(
stderr.contains("\\u001B")
|| stderr.contains("\\u001b")
|| stderr.contains("\\x1B")
|| stderr.contains("\\x1b"),
"AC-Q25 positive control: escaped form of ESC must appear in stderr, \
confirming the hostile file was processed; 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:"),
"D4/PF-004: dir --fix (human format) must emit 'Fixed:' when a file is \
successfully fixed (lint_one_file_human gate, lint.rs:1723); got stderr: {stderr}"
);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.is_empty(),
"D4: 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:"),
"D4/PF-004: dir --fix --quiet (human format) must suppress 'Fixed:' \
(lint_one_file_human gate, lint.rs:1723); 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!(
"D1-a: 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,
"D1-a: unified diff must precede the JSON envelope on stdout (spec.md:938, \
lint.rs:1231-1233); full stdout: {stdout:?}"
);
assert!(
serde_json::from_str::<serde_json::Value>(stdout.trim()).is_err(),
"D1-a: stdout as a whole must not parse as JSON under --fix --diff --format json; \
this is the documented exception (spec.md:938); 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:"),
"R1: --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"R1: --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),
"R1: --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>"),
"R1: stdin --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"R1: 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),
"R1: 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:"),
"R1: dir --fix --check must still report the pending fix; stderr: {stderr}"
);
assert_eq!(
out.status.code(),
Some(2),
"R1: 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),
"R1: 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),
"R1: --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"),
"R1: JSON body must stay PRE-fix (both findings present); got rules: {rules:?}"
);
assert_eq!(
out.status.code(),
Some(2),
"R1: 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"),
"R1: dir JSON body must stay PRE-fix (both findings present); got rules: {rules:?}"
);
assert_eq!(
out.status.code(),
Some(2),
"R1: dir --fix --check --format json must emit the envelope AND exit 2 \
(residual error); stdout: {stdout}"
);
}