use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use mds::{effective_parent, FileSystem, MdsError, NativeFs, Severity};
use miette::Result;
use crate::build::{
build_runtime_vars, emit_duplicate_var_warnings, ensure_existing_mds_file, load_config,
read_stdin, resolve_input, RuntimeVarArgs,
};
use crate::output::{
atomic_write_file, collect_mds_files_detailed, eprint_error, eprint_warning,
relabel_stdin_error, render_unified_diff, safe_file_display, safe_inline, safe_path,
STDIN_DISPLAY_LABEL,
};
pub(crate) struct LintArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) fix: bool,
pub(crate) check: bool,
pub(crate) diff: bool,
pub(crate) quiet: bool,
pub(crate) format: LintFormat,
pub(crate) vars: Option<PathBuf>,
pub(crate) set_vars: Vec<(String, String)>,
pub(crate) set_string_vars: Vec<(String, String)>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LintFormat {
Human,
Json,
}
#[derive(Clone, Copy)]
struct LintFlags {
fix: bool,
check: bool,
diff: bool,
quiet: bool,
format: LintFormat,
}
pub(crate) fn run_lint(args: LintArgs) -> Result<()> {
match do_lint(args) {
Ok(()) => Ok(()),
Err(e) => {
eprint_error(e);
std::process::exit(2);
}
}
}
fn do_lint(args: LintArgs) -> Result<()> {
let LintArgs {
input,
fix,
check,
diff,
quiet,
format,
vars,
set_vars,
set_string_vars,
} = args;
let flags = LintFlags {
fix,
check,
diff,
quiet,
format,
};
let resolved = match build_runtime_vars(RuntimeVarArgs {
vars,
set_vars,
set_string_vars,
}) {
Ok(r) => r,
Err(e) => {
if let Some(mds_err @ MdsError::VarConflict { .. }) = e.downcast_ref::<MdsError>() {
emit_analysis_failure_json_or_stderr(mds_err, format, None);
std::process::exit(1);
}
return Err(e);
}
};
emit_duplicate_var_warnings(&resolved, quiet);
let runtime_vars = resolved.vars;
let (input, _auto_detected) = resolve_input(input, "lint")?;
if fix && format == LintFormat::Json && input == Path::new("-") {
eprintln!(
"error: --fix --format json with stdin input is not supported; \
use `mds lint --fix -` for filter mode or `mds lint --format json` for JSON output"
);
std::process::exit(2);
}
if input == Path::new("-") {
return run_lint_stdin(flags, runtime_vars);
}
if input.is_dir() {
if input
.symlink_metadata()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
{
let mds_err = MdsError::Io {
message: format!(
"directory argument must not be a symlink: {}",
input.display()
),
};
emit_analysis_failure_json_or_stderr(&mds_err, format, None);
std::process::exit(2);
}
return run_lint_directory(&input, flags, runtime_vars);
}
if let Err(mds_err) = ensure_existing_mds_file(&input) {
emit_analysis_failure_json_or_stderr(&mds_err, format, None);
std::process::exit(mds_error_exit_code(&mds_err));
}
run_lint_file(&input, flags, runtime_vars)
}
fn load_lint_config(dir: &Path, quiet: bool) -> Result<mds::LintConfig> {
let config_opt = load_config(dir)?;
match config_opt {
None => Ok(mds::LintConfig::default()),
Some((mds_config, _config_dir)) => {
let (lint_config, unknown) = mds_config.lint.into_core_config();
if let Some(unknown) = unknown {
emit_unknown_rule_warning(&unknown, quiet);
}
Ok(lint_config)
}
}
}
fn emit_unknown_rule_warning(unknown: &mds::UnknownRuleNames, quiet: bool) {
if quiet {
return;
}
let core_msg = mds::format_unknown_rule_names_warning(unknown);
eprint_warning(&format!("warning: in mds.json: {}", safe_inline(&core_msg)));
}
fn set_diag_display_path(result: &mut mds::LintResult, display: &str) {
for diag in &mut result.diagnostics {
diag.file = Some(display.to_string());
}
}
fn relative_display(path: &Path, root: &Path) -> String {
let rel = path.strip_prefix(root).unwrap_or(path);
rel.components()
.filter(|c| matches!(c, std::path::Component::Normal(_)))
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/")
}
fn read_source_file(path: &Path) -> std::result::Result<String, MdsError> {
let canonical = NativeFs::check_symlink(path)?;
let path_str = canonical.to_str().ok_or_else(|| MdsError::Io {
message: format!("path is not valid UTF-8: {}", path.display()),
})?;
let fs = NativeFs::new();
let _ = fs.set_root(&effective_parent(&canonical).display().to_string());
fs.read(path_str)
}
fn write_stdout(s: &str) -> Result<()> {
let mut stdout = std::io::stdout();
if let Err(e) = stdout.write_all(s.as_bytes()) {
if e.kind() == std::io::ErrorKind::BrokenPipe {
return Ok(());
}
return Err(miette::miette!("cannot write to stdout: {e}"));
}
if let Err(e) = stdout.flush() {
if e.kind() != std::io::ErrorKind::BrokenPipe {
return Err(miette::miette!("cannot flush stdout: {e}"));
}
}
Ok(())
}
fn render_diag_human(diag: &mds::LintDiagnostic, quiet: bool, named_source: (&str, &str)) {
if quiet && matches!(diag.severity, Severity::Info | Severity::Warn) {
return;
}
let sanitized = diag.sanitized_for_render();
let (filename, src) = named_source;
let report = miette::Report::from(sanitized)
.with_source_code(mds::named_source_for_render(filename, src));
eprint_error(report);
}
fn render_result_human(result: &mds::LintResult, quiet: bool, named_source: (&str, &str)) {
for diag in &result.diagnostics {
render_diag_human(diag, quiet, named_source);
}
}
fn result_exit_code(result: &mds::LintResult) -> i32 {
let has_error = result
.diagnostics
.iter()
.any(|d| d.severity == Severity::Error);
let has_warn = result
.diagnostics
.iter()
.any(|d| d.severity == Severity::Warn);
if has_error {
2
} else if has_warn {
1
} else {
0
}
}
fn mds_error_exit_code(err: &MdsError) -> i32 {
match err {
MdsError::ResourceLimit { .. } => 3,
_ => 2,
}
}
fn exit_by_severity(result: &mds::LintResult) {
let exit = result_exit_code(result);
if exit != 0 {
std::process::exit(exit);
}
}
fn preview_exit_code(residual: &mds::LintResult) -> i32 {
result_exit_code(residual).max(1)
}
enum FixFileOutcome {
Fixed {
new_source: String,
residual: mds::LintResult,
},
PartiallyFixed {
new_source: String,
residual: mds::LintResult,
applied_count: usize,
total_count: usize,
},
Rejected {
reason: String,
original: mds::LintResult,
},
NothingToFix {
original: mds::LintResult,
},
}
fn plan_and_apply_fixes(
result: mds::LintResult,
source: &str,
base_dir: &Path,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
config: &mds::LintConfig,
display_label: &str,
) -> FixFileOutcome {
let is_standalone = result.is_standalone;
let plan = mds::fix::plan_fixes_with_options(&result, source, is_standalone);
if plan.edits.is_empty() && !plan.overlap_rejected {
return FixFileOutcome::NothingToFix { original: result };
}
let total_edits = plan.edits.len();
let all_output_neutral = plan
.edits
.iter()
.all(|e| mds::fix::is_output_neutral(&e.rule));
let original_output =
mds::compile_str_collecting_warnings(source, Some(base_dir), runtime_vars.clone())
.ok()
.map(|r| r.output);
let base_dir_owned = base_dir.to_path_buf();
let config_clone = config.clone();
let outcome = mds::fix::apply_fixes_incremental(source, plan, &result, |fixed| {
let residual = mds::lint_str_with(
fixed,
Some(&base_dir_owned),
runtime_vars.clone(),
&config_clone,
)?;
if all_output_neutral {
if let Some(ref orig_out) = original_output {
match mds::compile_str_collecting_warnings(
fixed,
Some(&base_dir_owned),
runtime_vars.clone(),
) {
Ok(fixed_compile) if fixed_compile.output != *orig_out => {
return Err(MdsError::Io {
message: "lint --fix would change compiled output; \
edit reverted to preserve template semantics"
.to_string(),
});
}
_ => {} }
}
}
Ok(residual)
});
match outcome {
mds::fix::FixOutcome::Fixed {
source: new_source,
mut residual,
} => {
set_diag_display_path(&mut residual, display_label);
FixFileOutcome::Fixed {
new_source,
residual,
}
}
mds::fix::FixOutcome::PartiallyFixed {
source: new_source,
mut residual,
rejected,
} => {
set_diag_display_path(&mut residual, display_label);
FixFileOutcome::PartiallyFixed {
new_source,
residual,
applied_count: total_edits - rejected.len(),
total_count: total_edits,
}
}
mds::fix::FixOutcome::Rejected { source: _, reason } => FixFileOutcome::Rejected {
reason,
original: result,
},
mds::fix::FixOutcome::NothingToFix => FixFileOutcome::NothingToFix { original: result },
_ => FixFileOutcome::NothingToFix { original: result },
}
}
enum PreviewOutcome {
WouldFix {
fixed: String,
residual: mds::LintResult,
},
Rejected(String),
NothingToFix,
}
fn preview_fixes(
result: &mds::LintResult,
source: &str,
base_dir: &Path,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
config: &mds::LintConfig,
display_label: &str,
) -> PreviewOutcome {
let is_standalone = result.is_standalone;
let plan = mds::fix::plan_fixes_with_options(result, source, is_standalone);
if plan.edits.is_empty() && !plan.overlap_rejected {
return PreviewOutcome::NothingToFix;
}
let all_output_neutral = plan
.edits
.iter()
.all(|e| mds::fix::is_output_neutral(&e.rule));
let original_output =
mds::compile_str_collecting_warnings(source, Some(base_dir), runtime_vars.clone())
.ok()
.map(|r| r.output);
let base_dir_owned = base_dir.to_path_buf();
let config_clone = config.clone();
let outcome = mds::fix::apply_fixes_incremental(source, plan, result, |fixed| {
let residual = mds::lint_str_with(
fixed,
Some(&base_dir_owned),
runtime_vars.clone(),
&config_clone,
)?;
if all_output_neutral {
if let Some(ref orig_out) = original_output {
match mds::compile_str_collecting_warnings(
fixed,
Some(&base_dir_owned),
runtime_vars.clone(),
) {
Ok(fixed_compile) if fixed_compile.output != *orig_out => {
return Err(MdsError::Io {
message: "lint --fix would change compiled output; \
edit reverted to preserve template semantics"
.to_string(),
});
}
_ => {}
}
}
}
Ok(residual)
});
match outcome {
mds::fix::FixOutcome::Fixed {
source: new_source,
mut residual,
}
| mds::fix::FixOutcome::PartiallyFixed {
source: new_source,
mut residual,
..
} => {
set_diag_display_path(&mut residual, display_label);
PreviewOutcome::WouldFix {
fixed: new_source,
residual,
}
}
mds::fix::FixOutcome::Rejected { reason, .. } => PreviewOutcome::Rejected(reason),
mds::fix::FixOutcome::NothingToFix => PreviewOutcome::NothingToFix,
_ => PreviewOutcome::NothingToFix,
}
}
fn run_lint_stdin(
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
let LintFlags {
fix,
check,
diff,
quiet,
format,
} = flags;
let (source, cwd) = read_stdin()?;
let config = match load_lint_config(&cwd, quiet) {
Ok(c) => c,
Err(e) => {
let mds_err = MdsError::Io {
message: format!("{e}"),
};
emit_analysis_failure_json_or_stderr(&mds_err, format, Some(&source));
std::process::exit(2);
}
};
let mut result = match mds::lint_str_with(&source, Some(&cwd), runtime_vars.clone(), &config) {
Ok(r) => r,
Err(e) => {
emit_analysis_failure_json_or_stderr(&e, format, Some(&source));
std::process::exit(mds_error_exit_code(&e));
}
};
set_diag_display_path(&mut result, STDIN_DISPLAY_LABEL);
if result.truncated && fix && !quiet {
eprintln!(
"diagnostic cap ({}) reached; further findings were suppressed — \
re-run --fix to continue",
mds::MAX_DIAGNOSTICS
);
}
if fix {
if check || diff {
let preview = preview_fixes(
&result,
&source,
&cwd,
runtime_vars.clone(),
&config,
STDIN_DISPLAY_LABEL,
);
let named_source = if format == LintFormat::Human {
Some((STDIN_DISPLAY_LABEL, source.as_str()))
} else {
None
};
match preview {
PreviewOutcome::WouldFix {
ref fixed,
ref residual,
} => {
if diff {
let diff_str = render_unified_diff(&source, fixed, STDIN_DISPLAY_LABEL);
let _ = write_stdout(&diff_str);
}
if check && !quiet {
eprintln!("Would fix: {STDIN_DISPLAY_LABEL}");
}
emit_result(format, &result, quiet, named_source);
std::process::exit(preview_exit_code(residual));
}
PreviewOutcome::Rejected(ref reason) => {
if !quiet {
eprintln!("fix rejected: {}", safe_inline(reason));
}
}
PreviewOutcome::NothingToFix => {}
}
emit_result(format, &result, quiet, named_source);
exit_by_severity(&result);
return Ok(());
}
let fix_outcome = plan_and_apply_fixes(
result,
&source,
&cwd,
runtime_vars,
&config,
STDIN_DISPLAY_LABEL,
);
let (output_src, diag_result) = match fix_outcome {
FixFileOutcome::Fixed {
new_source,
residual,
} => (new_source, residual),
FixFileOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => {
if !quiet {
eprintln!(
"Partially fixed: {STDIN_DISPLAY_LABEL} ({applied_count} of {total_count} fixes applied)"
);
}
(new_source, residual)
}
FixFileOutcome::Rejected { reason, original } => {
if !quiet {
eprintln!("fix rejected: {}", safe_inline(&reason));
}
(source, original)
}
FixFileOutcome::NothingToFix { original } => (source, original),
};
let named_source = (STDIN_DISPLAY_LABEL, output_src.as_str());
render_result_human(&diag_result, quiet, named_source);
let _ = write_stdout(&output_src);
exit_by_severity(&diag_result);
return Ok(());
}
let named_source = if format == LintFormat::Human {
Some((STDIN_DISPLAY_LABEL, source.as_str()))
} else {
None
};
emit_result(format, &result, quiet, named_source);
exit_by_severity(&result);
Ok(())
}
fn run_lint_file(
path: &Path,
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
let LintFlags {
fix,
check,
diff,
quiet,
format,
} = flags;
let base_dir = effective_parent(path);
let config = match load_lint_config(base_dir, quiet) {
Ok(c) => c,
Err(e) => {
let mds_err = MdsError::Io {
message: format!("{e}"),
};
emit_analysis_failure_json_or_stderr(&mds_err, format, None);
std::process::exit(2);
}
};
let source = match read_source_file(path) {
Ok(s) => s,
Err(e) => {
emit_analysis_failure_json_or_stderr(&e, format, None);
std::process::exit(mds_error_exit_code(&e));
}
};
let filename = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("<file>");
let mut result = match mds::lint(path, runtime_vars.clone(), &config) {
Ok(r) => r,
Err(e) => {
emit_analysis_failure_json_or_stderr(&e, format, None);
std::process::exit(mds_error_exit_code(&e));
}
};
set_diag_display_path(&mut result, filename);
if result.truncated && fix && !quiet {
eprintln!(
"diagnostic cap ({}) reached; further findings were suppressed — \
re-run --fix to continue",
mds::MAX_DIAGNOSTICS
);
}
let named_source = Some((filename, source.as_str()));
if fix && !check && !diff {
let fix_outcome =
plan_and_apply_fixes(result, &source, base_dir, runtime_vars, &config, filename);
match fix_outcome {
FixFileOutcome::Fixed {
new_source,
residual,
} => {
emit_result(format, &residual, quiet, named_source);
atomic_write_file(path, &new_source)?;
if !quiet {
eprintln!("Fixed: {}", safe_path(path));
}
exit_by_severity(&residual);
}
FixFileOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => {
emit_result(format, &residual, quiet, named_source);
atomic_write_file(path, &new_source)?;
if !quiet {
eprintln!(
"Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
safe_path(path)
);
}
exit_by_severity(&residual);
}
FixFileOutcome::Rejected { reason, original } => {
if !quiet {
eprintln!("fix rejected: {}", safe_inline(&reason));
}
emit_result(format, &original, quiet, named_source);
exit_by_severity(&original);
}
FixFileOutcome::NothingToFix { original } => {
emit_result(format, &original, quiet, named_source);
if !quiet && format == LintFormat::Human && original.diagnostics.is_empty() {
eprintln!("Clean: {}", safe_file_display(filename));
}
exit_by_severity(&original);
}
}
return Ok(());
}
if fix && (check || diff) {
let preview = preview_fixes(&result, &source, base_dir, runtime_vars, &config, filename);
match preview {
PreviewOutcome::WouldFix {
ref fixed,
ref residual,
} => {
if diff {
let label = safe_path(path);
let diff_str = render_unified_diff(&source, fixed, &label);
let _ = write_stdout(&diff_str);
}
if check && !quiet {
eprintln!("Would fix: {}", safe_path(path));
}
emit_result(format, &result, quiet, named_source);
std::process::exit(preview_exit_code(residual));
}
PreviewOutcome::Rejected(ref reason) => {
if !quiet {
eprintln!("fix rejected: {}", safe_inline(reason));
}
}
PreviewOutcome::NothingToFix => {}
}
emit_result(format, &result, quiet, named_source);
exit_by_severity(&result);
return Ok(());
}
emit_result(format, &result, quiet, named_source);
if !quiet && format == LintFormat::Human && result.diagnostics.is_empty() {
eprintln!("Clean: {}", safe_file_display(filename));
}
exit_by_severity(&result);
Ok(())
}
struct LintDirCtx<'a> {
lint_root: &'a Path,
flags: LintFlags,
runtime_vars: &'a Option<HashMap<String, mds::Value>>,
base_dir_cache: RefCell<HashMap<PathBuf, Rc<mds::LintConfig>>>,
config_dir_cache: RefCell<HashMap<PathBuf, Rc<mds::LintConfig>>>,
}
impl<'a> LintDirCtx<'a> {
fn config_for(&self, base_dir: &Path) -> Result<Rc<mds::LintConfig>, MdsError> {
{
let cache = self.base_dir_cache.borrow();
if let Some(cfg) = cache.get(base_dir) {
return Ok(Rc::clone(cfg));
}
}
let raw = load_config(base_dir).map_err(|e| MdsError::Io {
message: format!("{e}"),
})?;
match raw {
None => {
let rc = Rc::new(mds::LintConfig::default());
self.base_dir_cache
.borrow_mut()
.insert(base_dir.to_path_buf(), Rc::clone(&rc));
Ok(rc)
}
Some((mds_config, config_dir)) => {
if let Some(rc) = self
.config_dir_cache
.borrow()
.get(&config_dir)
.map(Rc::clone)
{
self.base_dir_cache
.borrow_mut()
.insert(base_dir.to_path_buf(), Rc::clone(&rc));
return Ok(rc);
}
let (lint_config, unknown) = mds_config.lint.into_core_config();
if let Some(unknown) = unknown {
emit_unknown_rule_warning(&unknown, self.flags.quiet);
}
let rc = Rc::new(lint_config);
self.base_dir_cache
.borrow_mut()
.insert(base_dir.to_path_buf(), Rc::clone(&rc));
self.config_dir_cache
.borrow_mut()
.insert(config_dir, Rc::clone(&rc));
Ok(rc)
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum FileTally {
Clean = 0,
WarnOnly = 1,
Error = 2,
ResourceLimit = 3,
}
impl FileTally {
fn exit_code(self) -> i32 {
self as i32
}
}
fn tally_from_result(result: &mds::LintResult) -> FileTally {
match result_exit_code(result) {
2 => FileTally::Error,
1 => FileTally::WarnOnly,
_ => FileTally::Clean,
}
}
fn run_lint_directory(
dir: &Path,
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
) -> Result<()> {
const MAX_DEPTH: usize = 64;
let LintFlags { quiet, format, .. } = flags;
let walk = collect_mds_files_detailed(dir, MAX_DEPTH, None);
let mut files = walk.files;
if files.is_empty() {
if walk.excluded_by_default > 0 {
eprintln!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was linted",
walk.excluded_by_default
);
std::process::exit(2);
}
if !quiet {
eprintln!("No .mds files found in {}", safe_path(dir));
}
return Ok(());
}
files.sort_by_cached_key(|p| {
(
mds::sanitize_control_chars_wire(&relative_display(p, dir)).into_owned(),
p.as_os_str().to_os_string(),
)
});
let mut max_tally = FileTally::Clean;
let mut json_files: Vec<serde_json::Value> = Vec::new();
let mut any_truncated = false;
let mut any_would_fix = false;
let mut clean_count: usize = 0;
let mut warn_file_count: usize = 0;
let mut error_file_count: usize = 0;
let mut limit_file_count: usize = 0;
let ctx = LintDirCtx {
lint_root: dir,
flags,
runtime_vars: &runtime_vars,
base_dir_cache: RefCell::new(HashMap::new()),
config_dir_cache: RefCell::new(HashMap::new()),
};
for file in &files {
let tally = if format == LintFormat::Json {
lint_one_file_accumulating(
file,
&ctx,
&mut json_files,
&mut any_truncated,
&mut any_would_fix,
)
} else {
lint_one_file_human(file, &ctx, &mut any_truncated, &mut any_would_fix)
};
match tally {
FileTally::Clean => clean_count += 1,
FileTally::WarnOnly => warn_file_count += 1,
FileTally::Error => error_file_count += 1,
FileTally::ResourceLimit => limit_file_count += 1,
}
if tally > max_tally {
max_tally = tally;
}
}
debug_assert_eq!(
clean_count + warn_file_count + error_file_count + limit_file_count,
files.len(),
"AD-216-5: FileTally partition invariant violated"
);
if format == LintFormat::Json {
let json = serde_json::json!({
"version": 1,
"files": json_files,
"truncated": any_truncated,
});
let _ = write_stdout(&format!(
"{}\n",
serde_json::to_string(&json).expect("canonical lint JSON is always serializable")
));
}
if !quiet || error_file_count > 0 || limit_file_count > 0 {
eprintln!(
"{clean_count} clean, {warn_file_count} with warnings, \
{error_file_count} with errors, {limit_file_count} resource-limited"
);
}
let mut exit = max_tally.exit_code();
if any_would_fix {
exit = exit.max(1);
}
if exit != 0 {
std::process::exit(exit);
}
Ok(())
}
fn lint_one_file_accumulating(
file: &Path,
ctx: &LintDirCtx<'_>,
json_files: &mut Vec<serde_json::Value>,
any_truncated: &mut bool,
any_would_fix: &mut bool,
) -> FileTally {
let LintFlags {
fix,
check,
diff,
quiet,
..
} = ctx.flags;
let display_path = relative_display(file, ctx.lint_root);
let file_key = mds::sanitize_control_chars_wire(&display_path).into_owned();
let base_dir = effective_parent(file);
let config = match ctx.config_for(base_dir) {
Ok(c) => c,
Err(ref e) => {
json_files.push(serde_json::json!({
"file": file_key,
"error": e.serialize()
}));
return FileTally::Error;
}
};
let mut result = match mds::lint(file, ctx.runtime_vars.clone(), &config) {
Ok(r) => r,
Err(ref e) => {
json_files.push(serde_json::json!({
"file": file_key,
"error": e.serialize()
}));
return if matches!(e, MdsError::ResourceLimit { .. }) {
FileTally::ResourceLimit
} else {
FileTally::Error
};
}
};
set_diag_display_path(&mut result, &display_path);
if result.truncated {
*any_truncated = true;
if fix && !quiet {
eprintln!(
"{}: diagnostic cap ({}) reached; further findings were suppressed — \
re-run --fix to continue",
safe_path(file),
mds::MAX_DIAGNOSTICS
);
}
}
if fix && !check && !diff {
let source = match read_source_file(file) {
Ok(s) => s,
Err(e) => {
json_files.push(serde_json::json!({
"file": file_key,
"error": e.serialize()
}));
return FileTally::Error;
}
};
let fix_outcome = plan_and_apply_fixes(
result,
&source,
base_dir,
ctx.runtime_vars.clone(),
&config,
&display_path,
);
match fix_outcome {
FixFileOutcome::Fixed {
new_source,
residual,
} => {
if let Err(e) = atomic_write_file(file, &new_source) {
json_files.push(serde_json::json!({
"file": file_key,
"error": MdsError::Io { message: format!("{e}") }.serialize()
}));
return FileTally::Error;
}
accumulate_result_json(&residual, json_files);
if !quiet {
eprintln!("Fixed: {}", safe_path(file));
}
tally_from_result(&residual)
}
FixFileOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => {
if let Err(e) = atomic_write_file(file, &new_source) {
json_files.push(serde_json::json!({
"file": file_key,
"error": MdsError::Io { message: format!("{e}") }.serialize()
}));
return FileTally::Error;
}
accumulate_result_json(&residual, json_files);
if !quiet {
eprintln!(
"Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
safe_path(file)
);
}
tally_from_result(&residual)
}
FixFileOutcome::Rejected { reason, original } => {
if !quiet {
eprintln!(
"{}: fix rejected: {}",
safe_path(file),
safe_inline(&reason)
);
}
accumulate_result_json(&original, json_files);
tally_from_result(&original)
}
FixFileOutcome::NothingToFix { original } => {
accumulate_result_json(&original, json_files);
tally_from_result(&original)
}
}
} else if fix && (check || diff) {
let source = match read_source_file(file) {
Ok(s) => s,
Err(e) => {
json_files.push(serde_json::json!({
"file": file_key,
"error": e.serialize()
}));
return FileTally::Error;
}
};
let tally = match preview_fixes(
&result,
&source,
base_dir,
ctx.runtime_vars.clone(),
&config,
&display_path,
) {
PreviewOutcome::WouldFix {
ref fixed,
ref residual,
} => {
*any_would_fix = true;
if diff {
let label = safe_path(file);
let diff_str = render_unified_diff(&source, fixed, &label);
let _ = write_stdout(&diff_str);
}
if check && !quiet {
eprintln!("Would fix: {}", safe_path(file));
}
tally_from_result(residual)
}
PreviewOutcome::Rejected(ref reason) => {
if !quiet {
eprintln!("{}: fix rejected: {}", safe_path(file), safe_inline(reason));
}
tally_from_result(&result)
}
PreviewOutcome::NothingToFix => tally_from_result(&result),
};
accumulate_result_json(&result, json_files);
tally
} else {
accumulate_result_json(&result, json_files);
tally_from_result(&result)
}
}
fn lint_one_file_human(
file: &Path,
ctx: &LintDirCtx<'_>,
any_truncated: &mut bool,
any_would_fix: &mut bool,
) -> FileTally {
let LintFlags {
fix,
check,
diff,
quiet,
..
} = ctx.flags;
let display_path = relative_display(file, ctx.lint_root);
let source = match read_source_file(file) {
Ok(s) => s,
Err(e) => {
eprint_error(miette::Report::from(e));
return FileTally::Error;
}
};
let base_dir = effective_parent(file);
let config = match ctx.config_for(base_dir) {
Ok(c) => c,
Err(e) => {
eprint_error(miette::Report::from(e));
return FileTally::Error;
}
};
let named_source = (display_path.as_str(), source.as_str());
let mut result = match mds::lint(file, ctx.runtime_vars.clone(), &config) {
Ok(r) => r,
Err(ref e) => {
eprint_error(miette::Report::from(e.clone()));
return if matches!(e, MdsError::ResourceLimit { .. }) {
FileTally::ResourceLimit
} else {
FileTally::Error
};
}
};
set_diag_display_path(&mut result, &display_path);
if result.truncated {
*any_truncated = true;
if fix && !quiet {
eprintln!(
"{}: diagnostic cap ({}) reached; further findings were suppressed — \
re-run --fix to continue",
safe_path(file),
mds::MAX_DIAGNOSTICS
);
}
}
if fix && !check && !diff {
let fix_outcome = plan_and_apply_fixes(
result,
&source,
base_dir,
ctx.runtime_vars.clone(),
&config,
&display_path,
);
match fix_outcome {
FixFileOutcome::Fixed {
new_source,
residual,
} => {
render_result_human(&residual, quiet, named_source);
if let Err(e) = atomic_write_file(file, &new_source) {
eprintln!("error writing {}: {}", safe_path(file), safe_inline(&e));
return FileTally::Error;
}
if !quiet {
eprintln!("Fixed: {}", safe_path(file));
}
tally_from_result(&residual)
}
FixFileOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => {
render_result_human(&residual, quiet, named_source);
if let Err(e) = atomic_write_file(file, &new_source) {
eprintln!("error writing {}: {}", safe_path(file), safe_inline(&e));
return FileTally::Error;
}
if !quiet {
eprintln!(
"Partially fixed: {} ({applied_count} of {total_count} fixes applied)",
safe_path(file)
);
}
tally_from_result(&residual)
}
FixFileOutcome::Rejected { reason, original } => {
if !quiet {
eprintln!(
"{}: fix rejected: {}",
safe_path(file),
safe_inline(&reason)
);
}
render_result_human(&original, quiet, named_source);
tally_from_result(&original)
}
FixFileOutcome::NothingToFix { original } => {
render_result_human(&original, quiet, named_source);
tally_from_result(&original)
}
}
} else if fix && (check || diff) {
let tally = match preview_fixes(
&result,
&source,
base_dir,
ctx.runtime_vars.clone(),
&config,
&display_path,
) {
PreviewOutcome::WouldFix {
ref fixed,
ref residual,
} => {
*any_would_fix = true;
if diff {
let label = safe_path(file);
let diff_str = render_unified_diff(&source, fixed, &label);
let _ = write_stdout(&diff_str);
}
if check && !quiet {
eprintln!("Would fix: {}", safe_path(file));
}
tally_from_result(residual)
}
PreviewOutcome::Rejected(ref reason) => {
if !quiet {
eprintln!("{}: fix rejected: {}", safe_path(file), safe_inline(reason));
}
tally_from_result(&result)
}
PreviewOutcome::NothingToFix => tally_from_result(&result),
};
render_result_human(&result, quiet, named_source);
tally
} else {
render_result_human(&result, quiet, named_source);
tally_from_result(&result)
}
}
fn emit_result(
format: LintFormat,
result: &mds::LintResult,
quiet: bool,
named_source: Option<(&str, &str)>,
) {
if format == LintFormat::Json {
let json = result.to_canonical_json();
let _ = write_stdout(&format!(
"{}\n",
serde_json::to_string(&json).expect("canonical lint JSON is always serializable")
));
} else {
render_result_human(
result,
quiet,
named_source.expect("Human format requires named_source"),
);
}
}
fn emit_analysis_failure_json_or_stderr(
e: &MdsError,
format: LintFormat,
stdin_source: Option<&str>,
) {
if format == LintFormat::Json {
let envelope = serde_json::json!({
"version": 1,
"error": e.serialize()
});
let _ = write_stdout(&format!(
"{}\n",
serde_json::to_string(&envelope).expect("canonical lint JSON is always serializable")
));
} else {
let report = match stdin_source {
Some(src) => relabel_stdin_error(e, src),
None => miette::Report::from(e.clone()),
};
eprint_error(report);
}
}
fn accumulate_result_json(result: &mds::LintResult, json_files: &mut Vec<serde_json::Value>) {
let inner = result.to_canonical_json();
if let Some(arr) = inner["files"].as_array() {
json_files.extend(arr.iter().cloned());
}
}
#[cfg(test)]
mod tests {
use super::{preview_fixes, PreviewOutcome};
use mds::{FixLineSpan, LintDiagnostic, LintResult, Severity};
use std::path::Path;
#[test]
fn preview_fixes_surfaces_rejected_on_overlap() {
let source = "line0\nline1\nline2\n";
let diag_a = LintDiagnostic::new("duplicate-import", Severity::Error, "a")
.with_fix_removals(vec![FixLineSpan::range_inclusive(
0, 6, )]);
let diag_b =
LintDiagnostic::new("empty-block", Severity::Warn, "b").with_fix_removals(vec![
FixLineSpan::range_inclusive(
6, 12, ),
]);
let result = LintResult::new(vec![diag_a, diag_b]);
let outcome = preview_fixes(
&result,
source,
Path::new("."),
None,
&mds::LintConfig::default(),
"overlap.mds",
);
assert!(
matches!(outcome, PreviewOutcome::Rejected(_)),
"preview_fixes must return Rejected for an overlap_rejected plan, \
not NothingToFix or WouldFix (PF-004 — preview must be as honest as apply)"
);
}
#[test]
fn preview_fixes_would_fix_relabels_residual_display_path() {
let source = "---\nunused_key: value\n---\n\n@if \"a\" == \"a\":\n@end\n\nHello\n";
let config = mds::LintConfig::default();
let result = mds::lint_str_with(source, Some(Path::new(".")), None, &config)
.expect("fixture source must lint");
let outcome = preview_fixes(
&result,
source,
Path::new("."),
None,
&config,
"custom-label.mds",
);
match outcome {
PreviewOutcome::WouldFix { ref residual, .. } => {
assert!(
!residual.diagnostics.is_empty(),
"non-vacuity (PF-013): the unused-variable finding must survive the fix"
);
assert!(
residual
.diagnostics
.iter()
.any(|d| d.rule == "unused-variable"),
"non-vacuity (PF-013): expected the surviving rule to be unused-variable; \
got: {:?}",
residual
.diagnostics
.iter()
.map(|d| d.rule.as_str())
.collect::<Vec<_>>()
);
for diag in &residual.diagnostics {
assert_eq!(
diag.file.as_deref(),
Some("custom-label.mds"),
"R1: every residual diagnostic must carry the caller-supplied \
display label"
);
}
}
_ => panic!(
"preview_fixes must return WouldFix for a source with a fixable \
empty-block finding"
),
}
}
#[cfg(unix)]
#[test]
fn relative_display_preserves_literal_backslash_on_unix() {
use super::relative_display;
use std::path::Path;
let root = Path::new("/lint-root");
let real_subdir = Path::new("/lint-root/a/b.mds");
let backslash_name = Path::new("/lint-root/a\\b.mds");
let display_subdir = relative_display(real_subdir, root);
let display_backslash = relative_display(backslash_name, root);
assert_eq!(
display_subdir, "a/b.mds",
"real subdirectory path should emit forward-slash-separated key"
);
assert_eq!(
display_backslash, "a\\b.mds",
"a literal backslash filename byte must be preserved in the emitted key on Unix"
);
assert_ne!(
display_subdir, display_backslash,
"a literal-backslash filename must not collide with the same letters \
separated by a real slash (was broken by the old .replace() approach)"
);
}
#[cfg(unix)]
#[test]
fn sort_key_sanitizes_control_byte_filenames() {
use super::relative_display;
use std::path::Path;
let root = Path::new("/lint-root");
let ctrl_char = char::from(1u8); let ctrl_filename = format!("{ctrl_char}a.mds");
let ctrl_path_buf = root.join(&ctrl_filename);
let ctrl_path: &Path = &ctrl_path_buf;
let normal_path = Path::new("/lint-root/P.mds");
let ctrl_raw = relative_display(ctrl_path, root);
let normal_raw = relative_display(normal_path, root);
assert!(
ctrl_raw < normal_raw,
"raw display: control-byte path ({ctrl_raw:?}) must sort before P.mds by \
unsanitized byte order (confirms old sort would have been wrong)"
);
let ctrl_sort_key = mds::sanitize_control_chars_wire(&ctrl_raw).into_owned();
let normal_sort_key = mds::sanitize_control_chars_wire(&normal_raw).into_owned();
assert!(
normal_sort_key < ctrl_sort_key,
"sanitized sort key: P.mds ({normal_sort_key:?}) must sort before \
control-byte file ({ctrl_sort_key:?}) — matching the emitted key order \
(AC-P1-10)"
);
}
#[test]
fn directory_sort_ascending_over_normalized_display_strings() {
use super::relative_display;
use std::path::PathBuf;
let root = PathBuf::from("lint-root");
let file_a = root.join("a.mds"); let file_sub_a = root.join("sub").join("a.mds"); let file_sub_bracket = root.join("sub[after.mds"); let file_z = root.join("z.mds");
let display_a = relative_display(&file_a, &root);
let display_sub_a = relative_display(&file_sub_a, &root);
let display_sub_bracket = relative_display(&file_sub_bracket, &root);
let display_z = relative_display(&file_z, &root);
assert_eq!(
display_a, "a.mds",
"flat file must display without separator"
);
assert_eq!(
display_sub_a, "sub/a.mds",
"nested file must use forward-slash separator"
);
assert_eq!(
display_sub_bracket, "sub[after.mds",
"flat file with [ in name must display as single component"
);
assert_eq!(
display_z, "z.mds",
"flat file must display without separator"
);
let mut paths = [
file_z.clone(),
file_sub_bracket.clone(),
file_a.clone(),
file_sub_a.clone(),
];
paths.sort_by_cached_key(|p| {
mds::sanitize_control_chars_wire(&relative_display(p, &root)).into_owned()
});
let sorted: Vec<String> = paths.iter().map(|p| relative_display(p, &root)).collect();
assert_eq!(
sorted,
vec!["a.mds", "sub/a.mds", "sub[after.mds", "z.mds"],
"directory sort must be byte-wise ascending over normalised forward-slash \
display strings; '/' (0x2F) must sort before '[' (0x5B) so nested paths \
appear before same-prefix flat files with bracket-containing names"
);
}
#[cfg(windows)]
#[test]
fn relative_display_normalizes_windows_separator_to_forward_slash() {
use super::relative_display;
use std::path::Path;
let path = Path::new(r"C:\proj\sub\c.mds");
let root = Path::new(r"C:\proj");
let display = relative_display(path, root);
assert_eq!(
display, "sub/c.mds",
"relative_display must emit forward-slash separator on Windows; \
got {display:?} — native backslash must not appear in the wire key"
);
}
}