use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::panic::AssertUnwindSafe;
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, ProjectConfig, RuntimeVarArgs,
};
use crate::lint_sink::{HumanSink, JsonSink, ResultSink};
use crate::output::{
catch_compile, collect_mds_files_detailed, eprint_warning, render_unified_diff, safe_inline,
safe_path, walked_pin, Panicked, RootPaths, WalkResult, WriteTarget, STDIN_DISPLAY_LABEL,
};
use crate::write::{
read_stamped, replace_if_unchanged, replace_owing_sync, DirectorySyncs, Durability, Flushed,
ReadForRewrite, Renamed, Rewritten, Synced,
};
const STDIN_FIX_JSON_REFUSAL: &str = "--fix --format json with stdin input is not supported; \
use `mds lint --fix -` for filter mode or `mds lint --format json` for JSON output";
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) enum LintSource<'a> {
Stdin,
File { typed: &'a Path, name: &'a str },
DirEntry {
root: &'a Path,
path: &'a Path,
key: &'a str,
},
}
impl<'a> LintSource<'a> {
fn file(typed: &'a Path) -> std::result::Result<Self, MdsError> {
let name = typed
.file_name()
.and_then(std::ffi::OsStr::to_str)
.ok_or_else(|| MdsError::Io {
message: format!(
"path has no UTF-8 file name: {}",
mds::escape_path_for_message(&typed.to_string_lossy())
),
})?;
Ok(Self::File { typed, name })
}
pub(crate) fn display_label(&self) -> &'a str {
match *self {
Self::Stdin => STDIN_DISPLAY_LABEL,
Self::File { name, .. } => name,
Self::DirEntry { key, .. } => key,
}
}
fn lint_name(&self) -> &'a str {
match *self {
Self::Stdin => mds::STRING_SOURCE_MAP_LABEL,
Self::File { name, .. } => name,
Self::DirEntry { key, .. } => key.rsplit_once('/').map_or(key, |(_, name)| name),
}
}
fn path(&self) -> &'a Path {
match *self {
Self::Stdin => Path::new("-"),
Self::File { typed, .. } => typed,
Self::DirEntry { path, .. } => path,
}
}
fn diff_label(&self) -> Cow<'a, str> {
match *self {
Self::Stdin => Cow::Borrowed(STDIN_DISPLAY_LABEL),
Self::File { typed, .. } => Cow::Owned(safe_path(typed)),
Self::DirEntry { path, .. } => Cow::Owned(safe_path(path)),
}
}
}
pub(crate) fn run_lint(args: LintArgs) -> i32 {
let quiet = args.quiet;
match args.format {
LintFormat::Human => lint_through(args, &mut HumanSink::new(quiet)),
LintFormat::Json => lint_through(args, &mut JsonSink::new(quiet)),
}
}
fn lint_through(args: LintArgs, sink: &mut impl ResultSink) -> i32 {
match do_lint(args, sink) {
Ok(code) => code,
Err(e) => {
let code = e.downcast_ref::<MdsError>().map_or(2, mds_error_exit_code);
sink.setup_failed(e);
code
}
}
}
fn do_lint(args: LintArgs, sink: &mut impl ResultSink) -> Result<i32> {
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>() {
sink.analysis_failed(mds_err, None);
return Ok(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("-") {
let refusal = MdsError::Io {
message: STDIN_FIX_JSON_REFUSAL.to_string(),
};
return Ok(analysis_failed(sink, &refusal, None));
}
if input == Path::new("-") {
return Ok(run_lint_stdin(flags, runtime_vars, sink));
}
if input.is_dir() {
return Ok(match crate::input::resolve_directory_argument(&input) {
Ok(canonical) => run_lint_directory(&input, &canonical, flags, runtime_vars, sink),
Err(mds_err) => {
sink.analysis_failed(&mds_err, None);
2
}
});
}
if let Err(mds_err) = ensure_existing_mds_file(&input) {
return Ok(analysis_failed(sink, &mds_err, None));
}
Ok(run_lint_file(&input, flags, runtime_vars, sink))
}
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(project) => {
let shown_file = project.shown_file();
let (lint_config, unknown) = project.config.lint.into_core_config();
if let Some(unknown) = unknown {
emit_unknown_rule_warning(&unknown, &shown_file, quiet);
}
Ok(lint_config)
}
}
}
fn emit_unknown_rule_warning(unknown: &mds::UnknownRuleNames, shown_file: &Path, quiet: bool) {
if quiet {
return;
}
let core_msg = mds::format_unknown_rule_names_warning(unknown);
eprint_warning(&format!(
"warning: in {}: {}",
safe_path(shown_file),
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) -> std::result::Result<String, MdsError> {
let escapes = || MdsError::Io {
message: format!(
"path escapes lint root {}: {}",
safe_path(root),
safe_path(path)
),
};
let rel = path.strip_prefix(root).map_err(|_| escapes())?;
let mut out = String::new();
for c in rel.components() {
let std::path::Component::Normal(name) = c else {
return Err(escapes());
};
let name = name.to_str().ok_or_else(|| MdsError::Io {
message: format!("path is not valid UTF-8: {}", safe_path(path)),
})?;
if !out.is_empty() {
out.push('/');
}
out.push_str(name);
}
Ok(out)
}
pub(crate) fn read_source_file(
path: &Path,
pin: Option<mds::EntryPin>,
) -> std::result::Result<String, MdsError> {
let canonical = NativeFs::check_symlink(path)?;
read_canonical_source(&canonical, path, pin)
}
fn read_canonical_source(
canonical: &Path,
path: &Path,
pin: Option<mds::EntryPin>,
) -> std::result::Result<String, MdsError> {
let path_str = canonical.to_str().ok_or_else(|| MdsError::Io {
message: format!("path is not valid UTF-8: {}", safe_path(path)),
})?;
let fs = match pin {
Some(pin) => NativeFs::new().with_entry_pin(pin),
None => NativeFs::new(),
};
fs.anchor_base_dir(&effective_parent(canonical).display().to_string())?;
let key = fs.resolve_entry(path_str).map_err(|mut error| {
let shown = safe_path(path);
match &mut error {
MdsError::FileNotFound { path, .. } => *path = shown,
MdsError::ImportError { message, .. } | MdsError::Io { message } => {
*message = message.replace(path_str, &shown);
}
_ => {}
}
error
})?;
fs.read(&key)
}
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 {
failure_tally(err).exit_code()
}
enum FixPipelineOutcome {
Fixed {
new_source: String,
residual: mds::LintResult,
},
PartiallyFixed {
new_source: String,
residual: mds::LintResult,
applied_count: usize,
total_count: usize,
},
Rejected { reason: String },
NothingToFix,
}
struct ReverifyGate<'a> {
name: &'a str,
base_dir: &'a Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
config: &'a mds::LintConfig,
original_output: Option<mds::CompiledOutput>,
}
impl<'a> ReverifyGate<'a> {
fn new(
plan: &mds::fix::FixPlan,
source: &str,
name: &'a str,
base_dir: &'a Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
config: &'a mds::LintConfig,
) -> Self {
let all_output_neutral = plan
.edits
.iter()
.all(|e| mds::fix::is_output_neutral(&e.rule));
let original_output = all_output_neutral
.then(|| {
mds::compile_str_collecting_warnings(source, Some(base_dir), runtime_vars.clone())
.ok()
.map(|r| r.output)
})
.flatten();
Self {
name,
base_dir,
runtime_vars,
config,
original_output,
}
}
fn verify(&self, candidate: &str) -> std::result::Result<mds::LintResult, MdsError> {
let residual = mds::lint_str_named(
candidate,
Some(self.base_dir),
self.runtime_vars.clone(),
self.config,
self.name,
)?;
if let Some(original_output) = &self.original_output {
match mds::compile_str_collecting_warnings(
candidate,
Some(self.base_dir),
self.runtime_vars.clone(),
) {
Ok(compiled) if compiled.output != *original_output => {
return Err(MdsError::Io {
message: "lint --fix would change compiled output; \
edit reverted to preserve template semantics"
.to_string(),
});
}
_ => {}
}
}
Ok(residual)
}
}
fn run_fix_pipeline(
input: &LintSource<'_>,
result: &mds::LintResult,
source: &str,
base_dir: &Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
config: &mds::LintConfig,
) -> FixPipelineOutcome {
let plan = mds::fix::plan_fixes_with_options(result, source, result.is_standalone);
if plan.edits.is_empty() && !plan.overlap_rejected {
return FixPipelineOutcome::NothingToFix;
}
let total_edits = plan.edits.len();
let gate = ReverifyGate::new(
&plan,
source,
input.lint_name(),
base_dir,
runtime_vars,
config,
);
let outcome =
mds::fix::apply_fixes_incremental(source, plan, result, |candidate| gate.verify(candidate));
match outcome {
mds::fix::FixOutcome::Fixed {
source: new_source,
mut residual,
} => {
set_diag_display_path(&mut residual, input.display_label());
FixPipelineOutcome::Fixed {
new_source,
residual,
}
}
mds::fix::FixOutcome::PartiallyFixed {
source: new_source,
mut residual,
rejected,
} => {
set_diag_display_path(&mut residual, input.display_label());
FixPipelineOutcome::PartiallyFixed {
new_source,
residual,
applied_count: total_edits - rejected.len(),
total_count: total_edits,
}
}
mds::fix::FixOutcome::Rejected { reason, .. } => FixPipelineOutcome::Rejected { reason },
mds::fix::FixOutcome::NothingToFix => FixPipelineOutcome::NothingToFix,
_ => FixPipelineOutcome::NothingToFix,
}
}
struct Linted<'a> {
input: LintSource<'a>,
base_dir: &'a Path,
config: Rc<mds::LintConfig>,
source: SourceText<'a>,
result: mds::LintResult,
}
enum SourceText<'a> {
Read(String),
Unread(&'a Path, Option<mds::EntryPin>),
}
impl SourceText<'_> {
fn into_text(self) -> Option<String> {
match self {
Self::Read(text) => Some(text),
Self::Unread(_, _) => None,
}
}
fn read(self) -> std::result::Result<String, MdsError> {
match self {
Self::Read(text) => Ok(text),
Self::Unread(path, pin) => read_source_file(path, pin),
}
}
}
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
enum FileTally {
#[default]
Clean = 0,
WarnOnly = 1,
Error = 2,
ResourceLimit = 3,
Internal = crate::output::PANIC_EXIT as isize,
}
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 failure_tally(e: &MdsError) -> FileTally {
match e {
MdsError::ResourceLimit { .. } => FileTally::ResourceLimit,
MdsError::Internal => FileTally::Internal,
_ => FileTally::Error,
}
}
#[derive(Clone, Copy, Default)]
struct InputVerdict {
tally: FileTally,
would_fix: bool,
truncated: bool,
}
impl InputVerdict {
fn exit_code(self) -> i32 {
let code = self.tally.exit_code();
if self.would_fix {
code.max(1)
} else {
code
}
}
fn merge(self, other: Self) -> Self {
Self {
tally: self.tally.max(other.tally),
would_fix: self.would_fix || other.would_fix,
truncated: self.truncated || other.truncated,
}
}
}
#[derive(Clone, Copy, Default)]
pub(crate) struct DirSummary {
pub(crate) clean_count: usize,
pub(crate) warn_file_count: usize,
pub(crate) error_file_count: usize,
pub(crate) limit_file_count: usize,
verdict: InputVerdict,
}
impl DirSummary {
fn count(mut self, verdict: InputVerdict) -> Self {
match verdict.tally {
FileTally::Clean => self.clean_count += 1,
FileTally::WarnOnly => self.warn_file_count += 1,
FileTally::Error | FileTally::Internal => self.error_file_count += 1,
FileTally::ResourceLimit => self.limit_file_count += 1,
}
self.verdict = self.verdict.merge(verdict);
self
}
fn truncated(&self) -> bool {
self.verdict.truncated
}
fn exit_code(&self) -> i32 {
self.verdict.exit_code()
}
}
fn analysis_failed(
sink: &mut impl ResultSink,
error: &MdsError,
stdin_source: Option<&str>,
) -> i32 {
sink.analysis_failed(error, stdin_source);
mds_error_exit_code(error)
}
struct FileReport<'a> {
input: LintSource<'a>,
capped: Option<CapNotice>,
outcome: Outcome,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CapNotice {
Plain,
RerunFix,
}
impl CapNotice {
fn for_mode(flags: LintFlags) -> Self {
if flags.fix && !flags.check && !flags.diff {
Self::RerunFix
} else {
Self::Plain
}
}
}
enum Outcome {
Reported {
findings: mds::LintResult,
text: Option<String>,
},
Failed { error: MdsError, tally: FileTally },
Panicked,
Previewed {
findings: mds::LintResult,
text: String,
fix: PreviewFix,
},
Rewritten {
findings: mds::LintResult,
text: String,
fix: Rewrite,
},
Filtered {
findings: mds::LintResult,
output: String,
fix: FilterFix,
},
}
impl Outcome {
fn truncated(&self) -> bool {
match self {
Outcome::Reported { findings, .. } | Outcome::Filtered { findings, .. } => {
findings.truncated
}
Outcome::Failed { .. } | Outcome::Panicked => false,
Outcome::Previewed { findings, fix, .. } => match fix {
PreviewFix::Pending { residual, .. } => residual.truncated,
PreviewFix::Refused { .. } | PreviewFix::Nothing => findings.truncated,
},
Outcome::Rewritten { findings, fix, .. } => match fix {
Rewrite::Refused { .. } | Rewrite::Unchanged => findings.truncated,
Rewrite::Written { residual, .. } => residual.findings.truncated,
Rewrite::WriteFailed { residual, .. } => residual
.as_ref()
.is_some_and(|residual| residual.findings.truncated),
},
}
}
}
enum PreviewFix {
Pending {
residual: mds::LintResult,
diff: Option<String>,
check: bool,
},
Refused { reason: String },
Nothing,
}
enum Rewrite {
Refused { reason: String },
Unchanged,
Written {
residual: Residual,
partial: Option<(usize, usize)>,
sync: DirectorySync,
},
WriteFailed {
error: MdsError,
residual: Option<Residual>,
},
}
enum DirectorySync {
Made(Option<MdsError>),
Owed(Renamed),
}
struct OwedFix {
renamed: Renamed,
partial: Option<(usize, usize)>,
}
struct Residual {
findings: mds::LintResult,
fixed: String,
}
enum FilterFix {
Fixed { partial: Option<(usize, usize)> },
Refused { reason: String },
Unchanged,
}
fn lint_input<'a>(
linted: Linted<'a>,
flags: LintFlags,
runtime_vars: &Option<HashMap<String, mds::Value>>,
) -> FileReport<'a> {
let Linted {
input,
base_dir,
config,
source,
mut result,
} = linted;
set_diag_display_path(&mut result, input.display_label());
let capped = result.truncated.then_some(CapNotice::for_mode(flags));
if !flags.fix {
let outcome = Outcome::Reported {
findings: result,
text: source.into_text(),
};
return FileReport {
input,
capped,
outcome,
};
}
let text = match source.read() {
Ok(text) => text,
Err(error) => {
let tally = failure_tally(&error);
let outcome = Outcome::Failed { error, tally };
return FileReport {
input,
capped,
outcome,
};
}
};
let fix = catch_compile(
input.path(),
AssertUnwindSafe(|| {
run_fix_pipeline(
&input,
&result,
&text,
base_dir,
runtime_vars.clone(),
&config,
)
}),
);
let fix = match fix {
Ok(fix) => fix,
Err(Panicked) => {
return FileReport {
input,
capped,
outcome: Outcome::Panicked,
}
}
};
let outcome = if flags.check || flags.diff {
preview_fix(&input, result, text, fix, flags)
} else {
match input {
LintSource::Stdin => fix_stdin(result, text, fix),
LintSource::File { typed, .. } => apply_fix(
&WriteTarget::as_typed(typed.to_path_buf()),
result,
text,
fix,
flags.format,
rewrite_synced,
),
LintSource::DirEntry { root, path, .. } => apply_fix(
&WriteTarget::walked_below(RootPaths::as_typed(root), path),
result,
text,
fix,
flags.format,
rewrite_owing_sync,
),
}
};
FileReport {
input,
capped,
outcome,
}
}
fn preview_fix(
input: &LintSource<'_>,
findings: mds::LintResult,
text: String,
fix: FixPipelineOutcome,
flags: LintFlags,
) -> Outcome {
let fix = match fix {
FixPipelineOutcome::Fixed {
new_source,
residual,
}
| FixPipelineOutcome::PartiallyFixed {
new_source,
residual,
..
} => PreviewFix::Pending {
diff: flags
.diff
.then(|| render_unified_diff(&text, &new_source, &input.diff_label())),
residual,
check: flags.check,
},
FixPipelineOutcome::Rejected { reason } => PreviewFix::Refused { reason },
FixPipelineOutcome::NothingToFix => PreviewFix::Nothing,
};
Outcome::Previewed {
findings,
text,
fix,
}
}
fn rewrite_synced(
read: ReadForRewrite,
fixed: &str,
) -> std::result::Result<DirectorySync, MdsError> {
let rewritten = replace_if_unchanged(read, fixed, Durability::Fsync)?;
Ok(DirectorySync::Made(match rewritten {
Rewritten::Done => None,
Rewritten::NotSynced(error) => Some(error),
}))
}
fn rewrite_owing_sync(
read: ReadForRewrite,
fixed: &str,
) -> std::result::Result<DirectorySync, MdsError> {
replace_owing_sync(read, fixed).map(DirectorySync::Owed)
}
fn apply_fix(
target: &WriteTarget,
findings: mds::LintResult,
text: String,
fix: FixPipelineOutcome,
format: LintFormat,
rewrite: impl FnOnce(ReadForRewrite, &str) -> std::result::Result<DirectorySync, MdsError>,
) -> Outcome {
let (new_source, residual, partial) = match fix {
FixPipelineOutcome::Fixed {
new_source,
residual,
} => (new_source, residual, None),
FixPipelineOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => (new_source, residual, Some((applied_count, total_count))),
FixPipelineOutcome::Rejected { reason } => {
let fix = Rewrite::Refused { reason };
return Outcome::Rewritten {
findings,
text,
fix,
};
}
FixPipelineOutcome::NothingToFix => {
let fix = Rewrite::Unchanged;
return Outcome::Rewritten {
findings,
text,
fix,
};
}
};
let residual = Residual {
findings: residual,
fixed: new_source,
};
let fix = match read_stamped(target, &text).and_then(|read| rewrite(read, &residual.fixed)) {
Ok(sync) => Rewrite::Written {
residual,
partial,
sync,
},
Err(error) => {
let failure_alone = format == LintFormat::Json;
Rewrite::WriteFailed {
error,
residual: (!failure_alone).then_some(residual),
}
}
};
Outcome::Rewritten {
findings,
text,
fix,
}
}
fn fix_stdin(findings: mds::LintResult, text: String, fix: FixPipelineOutcome) -> Outcome {
let (output, findings, fix) = match fix {
FixPipelineOutcome::Fixed {
new_source,
residual,
} => (new_source, residual, FilterFix::Fixed { partial: None }),
FixPipelineOutcome::PartiallyFixed {
new_source,
residual,
applied_count,
total_count,
} => (
new_source,
residual,
FilterFix::Fixed {
partial: Some((applied_count, total_count)),
},
),
FixPipelineOutcome::Rejected { reason } => (text, findings, FilterFix::Refused { reason }),
FixPipelineOutcome::NothingToFix => (text, findings, FilterFix::Unchanged),
};
Outcome::Filtered {
findings,
output,
fix,
}
}
fn render(report: FileReport<'_>, sink: &mut impl ResultSink) -> Shown {
let FileReport {
input,
capped,
outcome,
} = report;
let mut owed = None;
if let Some(notice) = capped {
sink.cap_reached(&input, notice);
}
let truncated = outcome.truncated();
let (tally, would_fix) = match outcome {
Outcome::Reported { findings, text } => {
sink.findings(&input, &findings, text.as_deref(), truncated);
sink.clean(&input, &findings);
(tally_from_result(&findings), false)
}
Outcome::Failed { error, tally } => {
sink.failed(&input, error);
(tally, false)
}
Outcome::Panicked => {
sink.panicked(&input);
(FileTally::Error, false)
}
Outcome::Previewed {
findings,
text,
fix,
} => {
let verdict = match fix {
PreviewFix::Pending {
residual,
diff,
check,
} => {
let diff_lost = diff.is_some_and(|diff| sink.diff(&diff));
if check {
sink.would_fix(&input);
}
let tally = if diff_lost {
FileTally::Error
} else {
tally_from_result(&residual)
};
(tally, true)
}
PreviewFix::Refused { reason } => {
sink.fix_rejected(&input, &reason);
(tally_from_result(&findings), false)
}
PreviewFix::Nothing => (tally_from_result(&findings), false),
};
sink.findings(&input, &findings, Some(&text), truncated);
verdict
}
Outcome::Rewritten {
findings,
text,
fix,
} => match fix {
Rewrite::Refused { reason } => {
sink.fix_rejected(&input, &reason);
sink.findings(&input, &findings, Some(&text), truncated);
(tally_from_result(&findings), false)
}
Rewrite::Unchanged => {
sink.findings(&input, &findings, Some(&text), truncated);
sink.clean(&input, &findings);
(tally_from_result(&findings), false)
}
Rewrite::Written {
residual,
partial,
sync,
} => {
sink.findings(&input, &residual.findings, Some(&residual.fixed), truncated);
match sync {
DirectorySync::Made(None) => sink.fixed(&input, partial),
DirectorySync::Made(Some(error)) => sink.not_synced(&input, error),
DirectorySync::Owed(renamed) => owed = Some(OwedFix { renamed, partial }),
}
(tally_from_result(&residual.findings), false)
}
Rewrite::WriteFailed { error, residual } => {
if let Some(residual) = &residual {
sink.findings(&input, &residual.findings, Some(&residual.fixed), truncated);
}
sink.write_failed(&input, error);
(FileTally::Error, false)
}
},
Outcome::Filtered {
findings,
output,
fix,
} => {
match fix {
FilterFix::Fixed { partial } => sink.fixed(&input, partial),
FilterFix::Refused { reason } => sink.fix_rejected(&input, &reason),
FilterFix::Unchanged => {}
}
sink.findings(&input, &findings, Some(&output), truncated);
sink.fixed_source(&output);
(tally_from_result(&findings), false)
}
};
Shown {
verdict: InputVerdict {
tally,
would_fix,
truncated,
},
owed,
}
}
struct Shown {
verdict: InputVerdict,
owed: Option<OwedFix>,
}
impl Shown {
fn exit_code(self) -> i32 {
debug_assert!(
self.owed.is_none(),
"stdin and a file argument owe no directory sync"
);
self.verdict.exit_code()
}
}
fn run_lint_stdin(
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
sink: &mut impl ResultSink,
) -> i32 {
let source = match read_stdin() {
Ok(source) => source,
Err(e) => return analysis_failed(sink, &e, None),
};
if let Err(e) = crate::output::current_dir() {
return analysis_failed(sink, &e, Some(&source));
}
let cwd = Path::new(".");
let config = match load_lint_config(cwd, flags.quiet) {
Ok(c) => c,
Err(e) => {
let mds_err = MdsError::Io {
message: format!("{e}"),
};
return analysis_failed(sink, &mds_err, Some(&source));
}
};
let result = match mds::lint_str_with(&source, Some(cwd), runtime_vars.clone(), &config) {
Ok(r) => r,
Err(e) => return analysis_failed(sink, &e, Some(&source)),
};
let linted = Linted {
input: LintSource::Stdin,
base_dir: cwd,
config: Rc::new(config),
source: SourceText::Read(source),
result,
};
render(lint_input(linted, flags, &runtime_vars), sink).exit_code()
}
fn run_lint_file(
path: &Path,
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
sink: &mut impl ResultSink,
) -> i32 {
let base_dir = effective_parent(path);
let config = match load_lint_config(base_dir, flags.quiet) {
Ok(c) => c,
Err(e) => {
let mds_err = MdsError::Io {
message: format!("{e}"),
};
return analysis_failed(sink, &mds_err, None);
}
};
let source = match read_source_file(path, None) {
Ok(s) => s,
Err(e) => return analysis_failed(sink, &e, None),
};
let result = match mds::lint(path, runtime_vars.clone(), &config) {
Ok(r) => r,
Err(e) => return analysis_failed(sink, &e, None),
};
let input = match LintSource::file(path) {
Ok(input) => input,
Err(e) => return analysis_failed(sink, &e, None),
};
let linted = Linted {
input,
base_dir,
config: Rc::new(config),
source: SourceText::Read(source),
result,
};
render(lint_input(linted, flags, &runtime_vars), sink).exit_code()
}
struct LintDirCtx<'a> {
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(project) => {
let shown_file = project.shown_file();
let ProjectConfig {
config: mds_config,
dir: config_dir,
..
} = project;
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, &shown_file, 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)
}
}
}
}
fn run_lint_directory(
dir: &Path,
canonical_dir: &Path,
flags: LintFlags,
runtime_vars: Option<std::collections::HashMap<String, mds::Value>>,
sink: &mut impl ResultSink,
) -> i32 {
const MAX_DEPTH: usize = 64;
let walk = collect_mds_files_detailed(dir, MAX_DEPTH, None);
if walk.files.is_empty() {
sink.nothing_to_lint(dir, &walk);
return 2;
}
let files = &walk.files;
let mut keyed: Vec<(&PathBuf, String)> = Vec::with_capacity(files.len());
for p in files {
match relative_display(p, dir) {
Ok(display) => keyed.push((p, display)),
Err(e) => return analysis_failed(sink, &e, None),
}
}
keyed.sort_by_cached_key(|(p, display)| {
(
mds::sanitize_control_chars_wire(display).into_owned(),
p.as_os_str().to_os_string(),
)
});
let ctx = LintDirCtx {
flags,
runtime_vars: &runtime_vars,
base_dir_cache: RefCell::new(HashMap::new()),
config_dir_cache: RefCell::new(HashMap::new()),
};
sink.start_document();
let mut syncs = DirectorySyncs::new(keyed.iter().map(|(path, _)| path.as_path()));
let summary = keyed
.iter()
.enumerate()
.map(|(place, (path, key))| {
let Shown { verdict, owed } = render(
lint_dir_entry(dir, path, key, &walk, canonical_dir, &ctx),
sink,
);
if let Some(OwedFix { renamed, partial }) = owed {
let fixed = FixedEntry {
entry: LintSource::DirEntry {
root: dir,
path,
key,
},
partial,
};
show_synced(syncs.landed(place, renamed, fixed), sink);
}
show_synced(syncs.past(place), sink);
verdict
})
.fold(DirSummary::default(), DirSummary::count);
sink.end_document(summary.truncated());
sink.summary(&summary);
summary.exit_code()
}
struct FixedEntry<'a> {
entry: LintSource<'a>,
partial: Option<(usize, usize)>,
}
fn show_synced(flushed: Option<Flushed<FixedEntry<'_>>>, sink: &mut impl ResultSink) {
for synced in flushed.into_iter().flatten() {
match synced {
Synced::Durable(FixedEntry { entry, partial }) => sink.fixed(&entry, partial),
Synced::NotSynced(FixedEntry { entry, .. }, error) => sink.not_synced(&entry, error),
}
}
}
fn lint_dir_entry<'a>(
root: &'a Path,
path: &'a Path,
key: &'a str,
walk: &WalkResult,
canonical_dir: &Path,
ctx: &LintDirCtx<'_>,
) -> FileReport<'a> {
let entry = move || LintSource::DirEntry { root, path, key };
let failed = move |error: MdsError, tally: FileTally| FileReport {
input: entry(),
capped: None,
outcome: Outcome::Failed { error, tally },
};
let base_dir = effective_parent(path);
let config = match ctx.config_for(base_dir) {
Ok(config) => config,
Err(e) => return failed(e, FileTally::Error),
};
let pin = || walked_pin(walk, path, root, canonical_dir);
let source_pin = match pin() {
Ok(pin) => pin,
Err(e) => return failed(e, FileTally::Error),
};
let source = if ctx.flags.format == LintFormat::Json {
SourceText::Unread(path, Some(source_pin))
} else {
match read_source_file(path, Some(source_pin)) {
Ok(text) => SourceText::Read(text),
Err(e) => {
let tally = failure_tally(&e);
return failed(e, tally);
}
}
};
let fs = match pin() {
Ok(pin) => NativeFs::new().with_entry_pin(pin),
Err(e) => return failed(e, FileTally::Error),
};
let linted = catch_compile(
path,
AssertUnwindSafe(|| mds::lint_native_fs(fs, path, ctx.runtime_vars.clone(), &config)),
);
let result = match linted {
Ok(Ok(result)) => result,
Ok(Err(e)) => {
let tally = failure_tally(&e);
return failed(e, tally);
}
Err(Panicked) => {
return FileReport {
input: entry(),
capped: None,
outcome: Outcome::Panicked,
}
}
};
let linted = Linted {
input: entry(),
base_dir,
config,
source,
result,
};
lint_input(linted, ctx.flags, ctx.runtime_vars)
}
#[cfg(test)]
mod tests {
use super::{
apply_fix, fix_stdin, lint_input, render, rewrite_owing_sync, rewrite_synced,
run_fix_pipeline, set_diag_display_path, CapNotice, DirSummary, DirectorySync, FileReport,
FileTally, FilterFix, FixPipelineOutcome, InputVerdict, LintFlags, LintFormat, LintSource,
Linted, Outcome, PreviewFix, Residual, ReverifyGate, Rewrite, SourceText,
};
use crate::lint_sink::{HumanSink, JsonSink, ResultSink};
use crate::output::{safe_path, STDIN_DISPLAY_LABEL};
use mds::{FixLineSpan, LintDiagnostic, LintResult, MdsError, SerializedSpan, Severity};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::rc::Rc;
#[test]
fn fix_pipeline_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 input = LintSource::DirEntry {
root: Path::new("."),
path: Path::new("overlap.mds"),
key: "overlap.mds",
};
let outcome = run_fix_pipeline(
&input,
&result,
source,
Path::new("."),
None,
&mds::LintConfig::default(),
);
assert!(
matches!(outcome, FixPipelineOutcome::Rejected { .. }),
"run_fix_pipeline must return Rejected for an overlap_rejected plan, not \
NothingToFix, Fixed or PartiallyFixed (preview must be as honest as apply)"
);
}
#[test]
fn fix_pipeline_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 input = LintSource::DirEntry {
root: Path::new("."),
path: Path::new("sub/custom-label.mds"),
key: "sub/custom-label.mds",
};
let outcome = run_fix_pipeline(&input, &result, source, Path::new("."), None, &config);
match outcome {
FixPipelineOutcome::Fixed { ref residual, .. }
| FixPipelineOutcome::PartiallyFixed { 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("sub/custom-label.mds"),
"R1: every residual diagnostic must carry the caller-supplied \
display label"
);
}
}
_ => panic!(
"run_fix_pipeline must return Fixed or PartiallyFixed for a source with a \
fixable empty-block finding"
),
}
}
#[test]
fn an_input_is_linted_under_its_file_name_and_stdin_under_the_string_label() {
assert_eq!(LintSource::Stdin.lint_name(), mds::STRING_SOURCE_MAP_LABEL);
let typed = Path::new("templates/_p.mds");
let file = LintSource::File {
typed,
name: "_p.mds",
};
assert_eq!(file.lint_name(), "_p.mds");
for key in ["_p.mds", "sub/_p.mds", "sub/deeper/_p.mds"] {
let path = Path::new(key);
let entry = LintSource::DirEntry {
root: Path::new("."),
path,
key,
};
assert_eq!(entry.lint_name(), "_p.mds", "the entry keyed {key:?}");
assert_eq!(
path.file_name().and_then(OsStr::to_str),
Some(entry.lint_name()),
"the name `mds::lint` takes from the path, for the entry keyed {key:?}"
);
}
}
const EMPTY_BLOCK_SOURCE: &str = "@if \"a\" == \"a\":\n@end\n\nHello\n";
const OUTPUT_CHANGED: &str =
"lint --fix would change compiled output; edit reverted to preserve template semantics";
fn compiled(source: &str) -> mds::CompiledOutput {
mds::compile_str_collecting_warnings(source, Some(Path::new(".")), None)
.expect("fixture source must compile")
.output
}
fn lint_and_plan(source: &str, config: &mds::LintConfig) -> (LintResult, mds::fix::FixPlan) {
let result = mds::lint_str_with(source, Some(Path::new(".")), None, config)
.expect("fixture source must lint");
let plan = mds::fix::plan_fixes_with_options(&result, source, result.is_standalone);
(result, plan)
}
#[test]
fn reverify_gate_refuses_a_candidate_that_changes_compiled_output() {
let config = mds::LintConfig::default();
let (_, plan) = lint_and_plan(EMPTY_BLOCK_SOURCE, &config);
assert!(
!plan.edits.is_empty()
&& plan
.edits
.iter()
.all(|e| mds::fix::is_output_neutral(&e.rule)),
"precondition: the plan must have edits, all output-neutral; got {:?}",
plan.edits
);
let gate = ReverifyGate::new(
&plan,
EMPTY_BLOCK_SOURCE,
mds::STRING_SOURCE_MAP_LABEL,
Path::new("."),
None,
&config,
);
let fixed = mds::fix::apply_plan_unchecked(EMPTY_BLOCK_SOURCE, &plan);
assert_eq!(
compiled(&fixed),
compiled(EMPTY_BLOCK_SOURCE),
"precondition: the plan's own fix must keep the compiled output"
);
if let Err(err) = gate.verify(&fixed) {
panic!("control: the gate must accept an output-identical candidate; got: {err}");
}
let changed = EMPTY_BLOCK_SOURCE.replace("Hello", "Goodbye");
if let Err(err) = mds::lint_str_with(&changed, Some(Path::new(".")), None, &config) {
panic!(
"precondition: the changed candidate must lint, so that only the output \
check can refuse it; got: {err}"
);
}
assert_ne!(
compiled(&changed),
compiled(EMPTY_BLOCK_SOURCE),
"precondition: the changed candidate must compile to different output"
);
let err = gate
.verify(&changed)
.expect_err("the gate must refuse a candidate that changes the compiled output");
assert!(
matches!(err, mds::MdsError::Io { .. }),
"the refusal must be an Io error; got: {err:?}"
);
assert_eq!(err.to_string(), OUTPUT_CHANGED);
assert_eq!(
miette::Diagnostic::code(&err)
.map(|code| code.to_string())
.as_deref(),
Some("mds::io")
);
}
#[test]
fn reverify_gate_skips_the_output_check_for_a_plan_that_changes_output() {
let source = "@if \"a\" == \"a\":\n@end\n\nHello {name}\n";
let config = mds::LintConfig::default();
let neutral = |e: &mds::fix::ByteEdit| mds::fix::is_output_neutral(&e.rule);
let (_, plan) = lint_and_plan(source, &config);
assert!(
plan.edits.iter().any(neutral) && !plan.edits.iter().all(neutral),
"precondition: the plan must mix output-neutral and output-changing edits; \
got {:?}",
plan.edits
);
let changed = source.replace("Hello", "Goodbye");
assert_ne!(
compiled(&changed),
compiled(source),
"precondition: the changed candidate must compile to different output"
);
let gate = ReverifyGate::new(
&plan,
source,
mds::STRING_SOURCE_MAP_LABEL,
Path::new("."),
None,
&config,
);
if let Err(err) = gate.verify(&changed) {
panic!("a plan with an output-changing edit must skip the output check; got: {err}");
}
let (_, mut neutral_plan) = lint_and_plan(source, &config);
neutral_plan.edits.retain(neutral);
assert!(
!neutral_plan.edits.is_empty(),
"precondition: the control plan must keep the output-neutral edit"
);
let neutral_gate = ReverifyGate::new(
&neutral_plan,
source,
mds::STRING_SOURCE_MAP_LABEL,
Path::new("."),
None,
&config,
);
let err = neutral_gate
.verify(&changed)
.expect_err("control: an all-neutral plan must refuse the changed candidate");
assert_eq!(err.to_string(), OUTPUT_CHANGED);
}
#[test]
fn fix_pipeline_rejects_a_fix_that_would_change_compiled_output() {
let config = mds::LintConfig::default();
let input = LintSource::DirEntry {
root: Path::new("."),
path: Path::new("output.mds"),
key: "output.mds",
};
let (real, _) = lint_and_plan(EMPTY_BLOCK_SOURCE, &config);
let outcome = run_fix_pipeline(
&input,
&real,
EMPTY_BLOCK_SOURCE,
Path::new("."),
None,
&config,
);
assert!(
matches!(outcome, FixPipelineOutcome::Fixed { .. }),
"control: the real empty-block fix must apply"
);
let hello = EMPTY_BLOCK_SOURCE
.find("Hello")
.expect("the fixture has a Hello line");
let crafted = LintResult::new(vec![LintDiagnostic::new(
"empty-block",
Severity::Warn,
"crafted",
)
.with_fix_removals(vec![FixLineSpan::range_inclusive(hello, hello)])]);
match run_fix_pipeline(
&input,
&crafted,
EMPTY_BLOCK_SOURCE,
Path::new("."),
None,
&config,
) {
FixPipelineOutcome::Rejected { reason } => assert_eq!(
reason,
format!(
"could not verify fix — the edited source did not re-parse cleanly \
({OUTPUT_CHANGED}); leaving the file unchanged"
)
),
_ => panic!(
"run_fix_pipeline must return Rejected for a fix that would change the \
compiled output, not Fixed, PartiallyFixed or NothingToFix"
),
}
}
const DIR_JSON_FIX: LintFlags = LintFlags {
fix: true,
check: false,
diff: false,
quiet: true,
format: LintFormat::Json,
};
const FIX_LEAVES_A_FINDING: &str =
"---\nunused_key: value\n---\n\n@if \"a\" == \"a\":\n@end\n\nHello\n";
fn fix_leaving_a_finding(input: &LintSource<'_>) -> (LintResult, FixPipelineOutcome) {
let config = mds::LintConfig::default();
let mut result =
mds::lint_str_with(FIX_LEAVES_A_FINDING, Some(Path::new(".")), None, &config)
.expect("fixture source must lint");
set_diag_display_path(&mut result, input.display_label());
let outcome = run_fix_pipeline(
input,
&result,
FIX_LEAVES_A_FINDING,
Path::new("."),
None,
&config,
);
match &outcome {
FixPipelineOutcome::Fixed { residual, .. }
| FixPipelineOutcome::PartiallyFixed { residual, .. } => assert!(
!residual.diagnostics.is_empty(),
"precondition: the fix must leave a finding"
),
_ => panic!("precondition: the empty-block finding must be fixed"),
}
(result, outcome)
}
fn fix_in_a_json_directory(
input: LintSource<'_>,
path: &Path,
result: LintResult,
outcome: FixPipelineOutcome,
) -> (InputVerdict, Vec<serde_json::Value>) {
let outcome = apply_fix(
&crate::output::WriteTarget::as_typed(path.to_path_buf()),
result,
FIX_LEAVES_A_FINDING.to_string(),
outcome,
DIR_JSON_FIX.format,
rewrite_owing_sync,
);
let mut sink = JsonSink::new(DIR_JSON_FIX.quiet);
sink.start_document();
let report = FileReport {
input,
capped: None,
outcome,
};
let verdict = render(report, &mut sink).verdict;
(verdict, sink.document().to_vec())
}
#[test]
fn directory_json_fix_records_a_failed_rewrite_as_its_only_entry() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
let writable = root.join("x.mds");
std::fs::write(&writable, FIX_LEAVES_A_FINDING).unwrap();
let input = LintSource::DirEntry {
root: Path::new("."),
path: &writable,
key: "x.mds",
};
let (result, outcome) = fix_leaving_a_finding(&input);
let (verdict, document) = fix_in_a_json_directory(input, &writable, result, outcome);
let rewritten = std::fs::read_to_string(&writable).unwrap();
assert!(
!rewritten.contains("@if"),
"control: the rewrite must land; got {rewritten:?}"
);
assert!(
verdict.tally == FileTally::WarnOnly,
"control: the file counts by the warning the fix left"
);
assert_eq!(
document.len(),
1,
"control: one entry, the remaining warning; got {document:?}"
);
assert_eq!(document[0]["file"], "x.mds");
assert_eq!(
document[0]["diagnostics"][0]["rule"], "unused-variable",
"control: got {document:?}"
);
let unwritable = root.join("gone").join("x.mds");
let input = LintSource::DirEntry {
root: Path::new("."),
path: &unwritable,
key: "x.mds",
};
let (result, outcome) = fix_leaving_a_finding(&input);
let (verdict, document) = fix_in_a_json_directory(input, &unwritable, result, outcome);
assert!(!unwritable.exists(), "precondition: nothing was written");
assert!(
verdict.tally == FileTally::Error,
"a failed rewrite counts under \"with errors\""
);
assert_eq!(
document.len(),
1,
"the failure must be the file's only entry; got {document:?}"
);
assert_eq!(document[0]["file"], "x.mds");
assert_eq!(document[0]["error"]["code"], "mds::io", "got {document:?}");
assert!(
document[0].get("diagnostics").is_none(),
"no findings for a file that was not rewritten; got {document:?}"
);
}
#[test]
fn directory_json_fix_records_an_entry_it_cannot_read_as_a_failure() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
let config = Rc::new(mds::LintConfig::default());
let fix = |path: &Path, key: &str| {
let linted = Linted {
input: LintSource::DirEntry {
root: Path::new("."),
path,
key,
},
base_dir: &root,
config: Rc::clone(&config),
source: SourceText::Unread(path, None),
result: LintResult::new(vec![]).truncated(),
};
let mut sink = JsonSink::new(DIR_JSON_FIX.quiet);
sink.start_document();
let verdict = render(lint_input(linted, DIR_JSON_FIX, &None), &mut sink).verdict;
(verdict, sink.document().to_vec())
};
let readable = root.join("x.mds");
std::fs::write(&readable, "Hello\n").unwrap();
let (verdict, document) = fix(&readable, "x.mds");
assert!(
verdict.tally == FileTally::Clean,
"control: nothing to fix and no findings"
);
assert!(
verdict.truncated,
"control: a capped result marks the document truncated"
);
assert!(
document.is_empty(),
"control: no findings, no entry; got {document:?}"
);
let missing = root.join("gone.mds");
let expected = super::read_source_file(&missing, None)
.expect_err("precondition: the file must not read")
.serialize();
let (verdict, document) = fix(&missing, "gone.mds");
assert!(
verdict.tally == FileTally::Error,
"an entry that cannot be read to fix counts under \"with errors\""
);
assert!(
!verdict.truncated,
"an entry recorded as a failure does not mark the document truncated"
);
assert_eq!(
document,
vec![serde_json::json!({ "file": "gone.mds", "error": expected })]
);
}
#[test]
fn directory_json_fix_counts_an_entry_over_the_size_cap_as_resource_limited() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
let config = Rc::new(mds::LintConfig::default());
let path = root.join("x.mds");
let fix = |len: u64| {
let len = usize::try_from(len).unwrap();
std::fs::write(&path, "a".repeat(len - 1) + "\n").unwrap();
let linted = Linted {
input: LintSource::DirEntry {
root: Path::new("."),
path: &path,
key: "x.mds",
},
base_dir: &root,
config: Rc::clone(&config),
source: SourceText::Unread(&path, None),
result: LintResult::new(vec![]),
};
let mut sink = JsonSink::new(DIR_JSON_FIX.quiet);
sink.start_document();
let verdict = render(lint_input(linted, DIR_JSON_FIX, &None), &mut sink).verdict;
(verdict, sink.document().to_vec())
};
let (verdict, document) = fix(mds::MAX_FILE_SIZE);
assert!(
verdict.tally == FileTally::Clean,
"control: read within the cap, nothing to fix"
);
assert!(document.is_empty(), "control: no entry; got {document:?}");
let (verdict, document) = fix(mds::MAX_FILE_SIZE + 1);
assert!(
verdict.tally == FileTally::ResourceLimit,
"an entry over the size cap counts under \"resource-limited\""
);
assert_eq!(
document.len(),
1,
"the failure is the entry; got {document:?}"
);
assert_eq!(document[0]["file"], "x.mds", "got {document:?}");
assert_eq!(
document[0]["error"]["code"], "mds::resource_limit",
"got {document:?}"
);
}
#[test]
fn directory_summary_counts_each_verdict_once() {
let verdict = |tally, would_fix, truncated| InputVerdict {
tally,
would_fix,
truncated,
};
let counts = |s: &DirSummary| {
(
s.clean_count,
s.warn_file_count,
s.error_file_count,
s.limit_file_count,
)
};
let summary = [
verdict(FileTally::Clean, false, false),
verdict(FileTally::WarnOnly, true, false),
verdict(FileTally::Error, false, true),
verdict(FileTally::Clean, false, false),
verdict(FileTally::ResourceLimit, false, false),
]
.into_iter()
.fold(DirSummary::default(), DirSummary::count);
assert_eq!(counts(&summary), (2, 1, 1, 1));
assert!(
summary.truncated(),
"one capped file marks the run truncated"
);
assert_eq!(
summary.exit_code(),
3,
"the worst tally is resource-limited"
);
let empty = DirSummary::default();
assert_eq!(counts(&empty), (0, 0, 0, 0), "control: nothing counted");
assert!(!empty.truncated());
assert_eq!(empty.exit_code(), 0, "control: nothing to fail");
let pending = [verdict(FileTally::Clean, true, false)]
.into_iter()
.fold(DirSummary::default(), DirSummary::count);
assert_eq!(counts(&pending), (1, 0, 0, 0));
assert_eq!(
pending.exit_code(),
1,
"control: a preview that would fix a clean file exits 1"
);
}
#[test]
fn lint_analysis_failure_exits_101_for_an_internal_error() {
let mut sink = Recorder::default();
assert_eq!(
super::analysis_failed(&mut sink, &MdsError::Internal, None),
101
);
assert_eq!(sink.calls, ["analysis failure"]);
}
#[test]
fn lint_batch_keeps_the_internal_exit_code_after_the_next_file() {
let root = Path::new("templates");
let first = root.join("a.mds");
let next = root.join("b.mds");
let error = MdsError::Internal;
let reports = [
(
&first,
"a.mds",
Outcome::Failed {
tally: super::failure_tally(&error),
error,
},
),
(
&next,
"b.mds",
Outcome::Reported {
findings: LintResult::new(vec![]),
text: None,
},
),
];
let mut sink = Recorder::default();
let summary =
reports
.into_iter()
.fold(DirSummary::default(), |summary, (path, key, outcome)| {
let report = FileReport {
input: LintSource::DirEntry { root, path, key },
capped: None,
outcome,
};
summary.count(render(report, &mut sink).verdict)
});
assert_eq!(
sink.calls,
[
"failed (mds::internal) a.mds",
"findings (0) b.mds",
"clean b.mds"
]
);
assert_eq!(
(
summary.error_file_count,
summary.clean_count,
summary.exit_code()
),
(1, 1, 101)
);
}
fn code_of(error: &MdsError) -> String {
miette::Diagnostic::code(error)
.map(|code| code.to_string())
.unwrap_or_default()
}
#[derive(Default)]
struct Recorder {
calls: Vec<String>,
#[cfg(unix)]
syncs_seen: Vec<usize>,
}
impl Recorder {
fn record(&mut self, call: &str, input: &LintSource<'_>) {
self.calls.push(format!("{call} {}", input.display_label()));
}
fn note_syncs(&mut self) {
#[cfg(unix)]
self.syncs_seen
.push(crate::write::sync_probe::directory_syncs());
}
}
impl ResultSink for Recorder {
fn quiet(&self) -> bool {
false
}
fn findings(
&mut self,
input: &LintSource<'_>,
findings: &LintResult,
_: Option<&str>,
_: bool,
) {
let call = format!("findings ({})", findings.diagnostics.len());
self.record(&call, input);
}
fn failed(&mut self, input: &LintSource<'_>, error: MdsError) {
let call = format!("failed ({})", code_of(&error));
self.record(&call, input);
}
fn panicked(&mut self, input: &LintSource<'_>) {
self.record("panicked", input);
}
fn write_failed(&mut self, input: &LintSource<'_>, _: MdsError) {
self.record("write failed", input);
}
fn not_synced(&mut self, input: &LintSource<'_>, _: MdsError) {
self.record("not synced", input);
self.note_syncs();
}
fn clean(&mut self, input: &LintSource<'_>, _: &LintResult) {
self.record("clean", input);
}
fn analysis_failed(&mut self, _: &MdsError, _: Option<&str>) {
self.calls.push("analysis failure".to_string());
}
fn start_document(&mut self) {
self.calls.push("start document".to_string());
}
fn end_document(&mut self, _: bool) {
self.calls.push("end document".to_string());
}
fn cap_reached(&mut self, input: &LintSource<'_>, notice: CapNotice) {
let call = match notice {
CapNotice::Plain => "cap reached",
CapNotice::RerunFix => "cap reached, re-run --fix",
};
self.record(call, input);
}
fn fix_rejected(&mut self, input: &LintSource<'_>, _: &str) {
self.record("fix rejected", input);
}
fn would_fix(&mut self, input: &LintSource<'_>) {
self.record("would fix", input);
}
fn fixed(&mut self, input: &LintSource<'_>, partial: Option<(usize, usize)>) {
let call = format!("fixed {partial:?}");
self.record(&call, input);
self.note_syncs();
}
fn diff(&mut self, _: &str) -> bool {
self.calls.push("diff".to_string());
false
}
fn fixed_source(&mut self, _: &str) {
self.calls.push("fixed source".to_string());
}
}
#[test]
fn a_capped_entry_that_cannot_be_read_announces_the_cap_before_its_failure() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
let config = Rc::new(mds::LintConfig::default());
let calls_with = |flags: LintFlags, path: &Path, key: &str, result: LintResult| {
let linted = Linted {
input: LintSource::DirEntry {
root: Path::new("."),
path,
key,
},
base_dir: &root,
config: Rc::clone(&config),
source: SourceText::Unread(path, None),
result,
};
let mut sink = Recorder::default();
render(lint_input(linted, flags, &None), &mut sink);
sink.calls
};
let calls = |path: &Path, key: &str, result| calls_with(DIR_JSON_FIX, path, key, result);
let missing = root.join("gone.mds");
let read_failure = code_of(
&super::read_source_file(&missing, None)
.expect_err("precondition: the file must not read"),
);
assert_eq!(
calls(&missing, "gone.mds", LintResult::new(vec![]).truncated()),
[
"cap reached, re-run --fix gone.mds".to_string(),
format!("failed ({read_failure}) gone.mds"),
],
);
let readable = root.join("x.mds");
std::fs::write(&readable, "Hello\n").unwrap();
assert_eq!(
calls(&readable, "x.mds", LintResult::new(vec![]).truncated()),
[
"cap reached, re-run --fix x.mds",
"findings (0) x.mds",
"clean x.mds"
],
"control: a capped entry with nothing to fix announces the cap before its findings"
);
for preview in [
LintFlags {
check: true,
..DIR_JSON_FIX
},
LintFlags {
diff: true,
..DIR_JSON_FIX
},
] {
let calls = calls_with(
preview,
&readable,
"x.mds",
LintResult::new(vec![]).truncated(),
);
assert_eq!(
calls.first().map(String::as_str),
Some("cap reached x.mds"),
"a capped preview announces the plain cap notice first; calls: {calls:?}"
);
}
let report = LintFlags {
fix: false,
..DIR_JSON_FIX
};
assert_eq!(
calls_with(
report,
&readable,
"x.mds",
LintResult::new(vec![]).truncated()
),
["cap reached x.mds", "findings (0) x.mds", "clean x.mds"],
"a capped report announces the cap before its findings"
);
assert_eq!(
calls(&missing, "gone.mds", LintResult::new(vec![])),
[format!("failed ({read_failure}) gone.mds")],
"control: an uncapped result announces no cap"
);
}
#[test]
fn truncated_is_the_residual_s_and_a_cap_is_announced_first_in_every_outcome() {
let capped = || LintResult::new(vec![]).truncated();
let uncapped = || LintResult::new(vec![]);
let fixed = |findings| Residual {
findings,
fixed: String::new(),
};
let unwritable = || MdsError::Io {
message: "unwritable".to_string(),
};
let previewed = |fix| Outcome::Previewed {
findings: capped(),
text: String::new(),
fix,
};
let pending = |residual| PreviewFix::Pending {
residual,
diff: None,
check: false,
};
let rewritten = |fix| Outcome::Rewritten {
findings: capped(),
text: String::new(),
fix,
};
let filtered = |findings, fix| Outcome::Filtered {
findings,
output: String::new(),
fix,
};
let refused = || "refused".to_string();
let cases = [
(
"report",
Outcome::Reported {
findings: capped(),
text: None,
},
true,
),
(
"report, uncapped (control)",
Outcome::Reported {
findings: uncapped(),
text: None,
},
false,
),
(
"failed",
Outcome::Failed {
error: unwritable(),
tally: FileTally::Error,
},
false,
),
("panicked", Outcome::Panicked, false),
("preview, fix clears", previewed(pending(uncapped())), false),
(
"preview, fix leaves a cap",
previewed(pending(capped())),
true,
),
(
"preview, refused",
previewed(PreviewFix::Refused { reason: refused() }),
true,
),
("preview, nothing", previewed(PreviewFix::Nothing), true),
(
"rewrite, refused",
rewritten(Rewrite::Refused { reason: refused() }),
true,
),
("rewrite, unchanged", rewritten(Rewrite::Unchanged), true),
(
"rewrite, written, uncapped (control)",
rewritten(Rewrite::Written {
residual: fixed(uncapped()),
partial: None,
sync: DirectorySync::Made(None),
}),
false,
),
(
"rewrite, written",
rewritten(Rewrite::Written {
residual: fixed(capped()),
partial: Some((1, 2)),
sync: DirectorySync::Made(None),
}),
true,
),
(
"rewrite, write failed, the failure is the record",
rewritten(Rewrite::WriteFailed {
error: unwritable(),
residual: None,
}),
false,
),
(
"rewrite, write failed, its findings shown",
rewritten(Rewrite::WriteFailed {
error: unwritable(),
residual: Some(fixed(capped())),
}),
true,
),
(
"filter, fixed, uncapped (control)",
filtered(uncapped(), FilterFix::Fixed { partial: None }),
false,
),
(
"filter, unchanged",
filtered(capped(), FilterFix::Unchanged),
true,
),
];
let typed = Path::new("x.mds");
let mut seen = Vec::new();
let mut expected = Vec::new();
for (what, outcome, truncated) in cases {
let report = FileReport {
input: LintSource::File {
typed,
name: "x.mds",
},
capped: Some(CapNotice::Plain),
outcome,
};
let mut sink = Recorder::default();
let verdict = render(report, &mut sink).verdict;
seen.push((what, verdict.truncated, sink.calls.first().cloned()));
expected.push((what, truncated, Some("cap reached x.mds".to_string())));
}
assert_eq!(seen, expected);
}
#[test]
fn a_fix_whose_directory_cannot_be_synced_shows_the_failure_in_place_of_fixed() {
let shown = |not_synced| {
let report = FileReport {
input: LintSource::File {
typed: Path::new("x.mds"),
name: "x.mds",
},
capped: None,
outcome: Outcome::Rewritten {
findings: LintResult::new(vec![]),
text: String::new(),
fix: Rewrite::Written {
residual: Residual {
findings: LintResult::new(vec![]),
fixed: String::new(),
},
partial: None,
sync: DirectorySync::Made(not_synced),
},
},
};
let mut sink = Recorder::default();
let verdict = render(report, &mut sink).verdict;
(sink.calls, verdict.tally == FileTally::Clean)
};
let not_synced = MdsError::Io {
message: "x.mds written, but its directory could not be synced: EIO".to_string(),
};
assert_eq!(
shown(Some(not_synced)),
(
vec![
"findings (0) x.mds".to_string(),
"not synced x.mds".to_string(),
],
true
)
);
assert_eq!(
shown(None),
(
vec![
"findings (0) x.mds".to_string(),
"fixed None x.mds".to_string()
],
true
),
"control: synced"
);
}
#[cfg(unix)]
#[test]
fn a_directory_fix_syncs_each_directory_once_and_then_shows_its_files() {
use crate::write::sync_probe::{directory_syncs, failing_with};
let dir = tempfile::TempDir::new().unwrap();
let src = dir.path().canonicalize().unwrap().join("src");
std::fs::create_dir_all(src.join("sub")).unwrap();
let files = ["a.mds", "b.mds", "sub/c.mds", "z.mds"].map(|file| src.join(file));
let fix = || {
for file in &files {
std::fs::write(file, "@if \"x\" == \"y\":\nhidden\n@end\nAlpha\n").unwrap();
}
let mut sink = Recorder::default();
let before = directory_syncs();
let code = super::run_lint_directory(&src, &src, DIR_JSON_FIX, None, &mut sink);
for file in &files {
assert_eq!(
std::fs::read_to_string(file).unwrap(),
"Alpha\n",
"{file:?}"
);
}
let seen = sink
.syncs_seen
.iter()
.map(|n| n - before)
.collect::<Vec<_>>();
(sink.calls, directory_syncs() - before, seen, code)
};
let calls = |shown: &str| {
[
"start document".to_string(),
"findings (0) a.mds".to_string(),
"findings (0) b.mds".to_string(),
"findings (0) sub/c.mds".to_string(),
format!("{shown} sub/c.mds"),
"findings (0) z.mds".to_string(),
format!("{shown} a.mds"),
format!("{shown} b.mds"),
format!("{shown} z.mds"),
"end document".to_string(),
]
.to_vec()
};
assert_eq!(fix(), (calls("fixed None"), 2, vec![1, 2, 2, 2], 0));
let failing = failing_with(5);
assert_eq!(
fix(),
(calls("not synced"), 2, vec![1, 2, 2, 2], 0),
"a failed sync shows each file of its directory once, and no `Fixed:` line"
);
drop(failing);
}
const CHILD: &str = "MDS_LINT_TEST_CHILD";
fn in_a_child(name: &str, scenario: &OsStr) -> (String, String) {
let binary = std::env::current_exe().expect("the test binary's path");
let run = std::process::Command::new(binary)
.args([name, "--exact", "--nocapture", "--test-threads=1"])
.env(CHILD, scenario)
.env("NO_COLOR", "1")
.env_remove("FORCE_COLOR")
.env_remove("CLICOLOR_FORCE")
.output()
.expect("the child runs");
let product = String::from_utf8(run.stdout).expect("the child's stdout is UTF-8");
let shown = String::from_utf8(run.stderr).expect("the child's stderr is UTF-8");
assert!(
run.status.success() && product.contains("1 passed"),
"the child `{name}` ({scenario:?}) must run that one test and pass; status {:?}\n\
stdout:\n{product}\nstderr:\n{shown}",
run.status
);
(product, shown)
}
#[test]
fn a_human_finding_without_its_text_shows_no_file_name_and_no_snippet() {
const NAME: &str =
"lint::tests::a_human_finding_without_its_text_shows_no_file_name_and_no_snippet";
const FILE_NAME: &str = "frame-name-sentinel";
const SOURCE_TEXT: &str = "source-text-sentinel";
const MESSAGE: &str = "a finding shown without its text";
if let Some(scenario) = std::env::var_os(CHILD) {
let text = match scenario.to_str() {
Some("with text") => Some(format!("{SOURCE_TEXT}\n")),
Some("without text") => None,
_ => panic!("unknown scenario {scenario:?}"),
};
let key = format!("{FILE_NAME}.mds");
let path = Path::new("walked").join(&key);
let finding = LintDiagnostic::new("empty-block", Severity::Error, MESSAGE)
.with_span(SerializedSpan::new(0, SOURCE_TEXT.len()))
.with_file(key.as_str());
let report = FileReport {
input: LintSource::DirEntry {
root: Path::new("."),
path: &path,
key: &key,
},
capped: None,
outcome: Outcome::Reported {
findings: LintResult::new(vec![finding]),
text,
},
};
let verdict = render(report, &mut HumanSink::new(false)).verdict;
assert!(
verdict.tally == FileTally::Error,
"the error-severity finding counts"
);
return;
}
let (_, framed) = in_a_child(NAME, OsStr::new("with text"));
for needle in [MESSAGE, FILE_NAME, SOURCE_TEXT] {
assert!(
framed.contains(needle),
"control: a frame over its text shows {needle:?}; got:\n{framed}"
);
}
let (_, bare) = in_a_child(NAME, OsStr::new("without text"));
assert!(
bare.contains(MESSAGE),
"the finding still shows; got:\n{bare}"
);
assert!(
!bare.contains(FILE_NAME),
"no source, so no frame header names the file; got:\n{bare}"
);
assert!(!bare.contains(SOURCE_TEXT), "no snippet; got:\n{bare}");
}
const PARTIAL_BEFORE: &str = "before-fix-sentinel\n";
const PARTIAL_AFTER: &str = "after-fix-sentinel\n";
const PARTIAL_LEFT: &str = "a finding the partial fix left";
const PARTIAL_REMOVED: &str = "a finding the partial fix removed";
fn partial_fix(label: &str, left_at: SerializedSpan) -> (LintResult, FixPipelineOutcome) {
let left = || {
LintDiagnostic::new("empty-block", Severity::Warn, PARTIAL_LEFT)
.with_file(label)
.with_span(left_at.clone())
};
let removed =
LintDiagnostic::new("empty-block", Severity::Warn, PARTIAL_REMOVED).with_file(label);
let before = LintResult::new(vec![removed, left()]);
let fix = FixPipelineOutcome::PartiallyFixed {
new_source: PARTIAL_AFTER.to_string(),
residual: LintResult::new(vec![left()]),
applied_count: 1,
total_count: 2,
};
(before, fix)
}
#[test]
fn a_partial_fix_of_a_file_is_announced_after_the_findings_it_leaves() {
const NAME: &str =
"lint::tests::a_partial_fix_of_a_file_is_announced_after_the_findings_it_leaves";
const AFTER_LINE: &str = "after-fix-sentinel";
const BEFORE_LINE: &str = "before-fix-sentinel";
if let Some(path) = std::env::var_os(CHILD) {
let path = PathBuf::from(path);
let input = LintSource::File {
typed: &path,
name: "partial.mds",
};
let left_at = SerializedSpan::new(0, AFTER_LINE.len());
let (before, fix) = partial_fix(input.display_label(), left_at);
let text = PARTIAL_BEFORE.to_string();
let outcome = apply_fix(
&crate::output::WriteTarget::as_typed(path.clone()),
before,
text,
fix,
LintFormat::Human,
rewrite_synced,
);
let report = FileReport {
input,
capped: None,
outcome,
};
let verdict = render(report, &mut HumanSink::new(false)).verdict;
assert!(
verdict.tally == FileTally::WarnOnly,
"the file counts by the warning the fix left"
);
return;
}
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().canonicalize().unwrap().join("partial.mds");
std::fs::write(&path, PARTIAL_BEFORE).unwrap();
let (_, shown) = in_a_child(NAME, path.as_os_str());
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
PARTIAL_AFTER,
"precondition: the partly fixed source was written"
);
let announced = format!(
"Partially fixed: {} (1 of 2 fixes applied)",
safe_path(&path)
);
assert_eq!(
shown.lines().last(),
Some(announced.as_str()),
"the last line names the file and the counts; got:\n{shown}"
);
assert_eq!(
shown.matches("Partially fixed:").count(),
1,
"announced once; got:\n{shown}"
);
assert!(
shown.contains(PARTIAL_LEFT) && shown.contains(AFTER_LINE),
"the finding the fix left shows before the announcement, framed over the \
written source; got:\n{shown}"
);
assert!(
!shown.contains(BEFORE_LINE),
"not framed over the source as read; got:\n{shown}"
);
assert!(
!shown.contains(PARTIAL_REMOVED),
"the finding the fix removed does not show; got:\n{shown}"
);
}
#[test]
fn a_partial_fix_of_stdin_is_announced_before_the_findings_it_leaves() {
const NAME: &str =
"lint::tests::a_partial_fix_of_stdin_is_announced_before_the_findings_it_leaves";
const AFTER_LINE: &str = "after-fix-sentinel";
const BEFORE_LINE: &str = "before-fix-sentinel";
if std::env::var_os(CHILD).is_some() {
let left_at = SerializedSpan::new(0, AFTER_LINE.len());
let (before, fix) = partial_fix(STDIN_DISPLAY_LABEL, left_at);
let outcome = fix_stdin(before, PARTIAL_BEFORE.to_string(), fix);
let report = FileReport {
input: LintSource::Stdin,
capped: None,
outcome,
};
let verdict = render(report, &mut HumanSink::new(false)).verdict;
assert!(
verdict.tally == FileTally::WarnOnly,
"stdin counts by the warning the fix left"
);
return;
}
let (product, shown) = in_a_child(NAME, OsStr::new("stdin"));
let announced = format!("Partially fixed: {STDIN_DISPLAY_LABEL} (1 of 2 fixes applied)");
assert_eq!(
shown.lines().next(),
Some(announced.as_str()),
"the first line names stdin and the counts; got:\n{shown}"
);
assert_eq!(
shown.matches("Partially fixed:").count(),
1,
"announced once; got:\n{shown}"
);
assert!(
shown.contains(PARTIAL_LEFT) && shown.contains(AFTER_LINE),
"the finding the fix left follows, framed over the emitted source; got:\n{shown}"
);
assert!(
!shown.contains(BEFORE_LINE),
"not framed over the source as given; got:\n{shown}"
);
assert!(
!shown.contains(PARTIAL_REMOVED),
"the finding the fix removed does not show; got:\n{shown}"
);
assert!(
product.contains(PARTIAL_AFTER),
"the partly fixed source goes to stdout; got:\n{product}"
);
}
#[test]
fn relative_display_rejects_path_outside_root() {
use super::relative_display;
use std::path::Path;
let root = Path::new("/lint-root");
let err = relative_display(Path::new("/other/x.mds"), root)
.expect_err("a path outside the lint root must not produce a display key");
let message = err.to_string();
assert!(
message.contains("escapes lint root"),
"out-of-root rejection must name the condition; got: {message:?}"
);
let rel_root = Path::new("lint-root");
let rel_err = relative_display(Path::new("other/x.mds"), rel_root)
.expect_err("a relative path outside the lint root must not produce a display key");
let rel_message = rel_err.to_string();
assert!(
rel_message.contains("escapes lint root"),
"relative out-of-root rejection must name the condition; got: {rel_message:?}"
);
assert_eq!(
relative_display(Path::new("/lint-root/a/b.mds"), root)
.expect("an in-root path must still produce a display key"),
"a/b.mds",
"control: the in-root key must be byte-identical to the pre-#217 output"
);
assert_eq!(
relative_display(Path::new("lint-root/a/b.mds"), rel_root)
.expect("an in-root path under a relative root must still produce a key"),
"a/b.mds",
"control: the relative-root in-root key must be byte-identical too"
);
}
#[cfg(unix)]
#[test]
fn relative_display_rejects_non_utf8_component() {
use super::relative_display;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
let root = Path::new("/lint-root");
let raw: Vec<u8> = vec![0xff, 0xfe, b'.', b'm', b'd', b's'];
let hostile = root.join(std::ffi::OsStr::from_bytes(&raw));
let err = relative_display(&hostile, root)
.expect_err("a non-UTF-8 entry name must not produce a display key");
let message = err.to_string();
assert!(
message.contains("not valid UTF-8"),
"non-UTF-8 rejection must name the condition; got: {message:?}"
);
assert_eq!(
relative_display(&root.join("ok.mds"), root)
.expect("a valid-UTF-8 entry must still produce a display key"),
"ok.mds",
"control: the valid-UTF-8 key must be byte-identical to the pre-#217 output"
);
}
#[cfg(unix)]
#[test]
fn a_name_that_is_not_utf8_is_escaped_in_its_message() {
use super::{read_canonical_source, relative_display};
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
let root = Path::new("/lint-root");
let lossy = char::REPLACEMENT_CHARACTER;
for control in [0x0a_u8, 0x1b] {
let raw = [0xff, b'a', control, b'b', b'.', b'm', b'd', b's'];
let hostile = root.join(OsStr::from_bytes(&raw));
let raw_char = char::from(control);
assert!(
hostile.to_string_lossy().contains(raw_char),
"control: the hostile path must carry the raw byte 0x{control:02X}"
);
let expected = format!(
"path is not valid UTF-8: /lint-root/{lossy}a{}u{control:04X}b.mds",
'\\'
);
let walked = relative_display(&hostile, root)
.expect_err("a non-UTF-8 entry name must not produce a display key")
.to_string();
let read = read_canonical_source(&hostile, &hostile, None)
.expect_err("a non-UTF-8 path must not be read")
.to_string();
for message in [walked, read] {
assert_eq!(
message, expected,
"the path must be shown escaped, never with the raw byte 0x{control:02X}"
);
}
}
let plain = root.join(OsStr::from_bytes(&[0xff, b'.', b'm', b'd', b's']));
assert_eq!(
relative_display(&plain, root)
.expect_err("a non-UTF-8 entry name must not produce a display key")
.to_string(),
format!("path is not valid UTF-8: /lint-root/{lossy}.mds"),
"control: an ordinary name that is not UTF-8 keeps its text"
);
}
#[test]
fn a_path_outside_the_lint_root_is_escaped_in_its_message() {
use super::relative_display;
use std::path::Path;
let (lf, esc) = (char::from(0x0a_u8), char::from(0x1b_u8));
let root = format!("/lint{esc}root");
let path = format!("/other{lf}x.mds");
let message = relative_display(Path::new(&path), Path::new(&root))
.expect_err("a path outside the lint root must not produce a display key")
.to_string();
assert_eq!(
message,
format!(
"path escapes lint root /lint{}u001Broot: /other{}u000Ax.mds",
'\\', '\\'
),
"the root and the path must be shown escaped"
);
assert_eq!(
relative_display(Path::new("/other/x.mds"), Path::new("/lint-root"))
.expect_err("a path outside the lint root must not produce a display key")
.to_string(),
"path escapes lint root /lint-root: /other/x.mds",
"control: an ordinary pair keeps its text"
);
}
#[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).expect("in-root path");
let display_backslash = relative_display(backslash_name, root).expect("in-root path");
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)"
);
}
#[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).expect("in-root path");
let normal_raw = relative_display(normal_path, root).expect("in-root path");
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).expect("in-root path");
let display_sub_a = relative_display(&file_sub_a, &root).expect("in-root path");
let display_sub_bracket = relative_display(&file_sub_bracket, &root).expect("in-root path");
let display_z = relative_display(&file_z, &root).expect("in-root path");
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).expect("in-root path"))
.into_owned()
});
let sorted: Vec<String> = paths
.iter()
.map(|p| relative_display(p, &root).expect("in-root path"))
.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).expect("in-root path");
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"
);
}
#[test]
fn read_canonical_source_names_a_deleted_file_as_typed() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
std::fs::write(&file, "Hello!\n").unwrap();
let canonical = mds::NativeFs::check_symlink(&file).unwrap();
std::fs::remove_file(&file).unwrap();
let typed = Path::new("src").join("a.mds");
let error = super::read_canonical_source(&canonical, &typed, None).unwrap_err();
assert!(matches!(error, MdsError::FileNotFound { .. }), "{error:?}");
assert_eq!(
error.to_string(),
format!("file not found: {}", safe_path(&typed))
);
assert!(!error.to_string().contains(&safe_path(&canonical)));
}
#[cfg(unix)]
#[test]
fn read_canonical_source_names_a_symlink_refusal_as_typed() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
let victim = dir.path().join("victim.mds");
std::fs::write(&file, "Hello!\n").unwrap();
std::fs::write(&victim, "Victim\n").unwrap();
let canonical = mds::NativeFs::check_symlink(&file).unwrap();
std::fs::remove_file(&file).unwrap();
std::os::unix::fs::symlink(&victim, &file).unwrap();
let typed = Path::new("src").join("a.mds");
let error = super::read_canonical_source(&canonical, &typed, None).unwrap_err();
assert!(matches!(error, MdsError::ImportError { .. }), "{error:?}");
assert_eq!(
error.to_string(),
format!(
"import error: symlinks are not allowed in imports: {}",
safe_path(&typed)
)
);
assert!(!error.to_string().contains(&safe_path(&canonical)));
}
#[test]
fn read_canonical_source_reports_an_anchor_failure() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
let missing = root.join("gone").join("x.mds");
let err = super::read_canonical_source(&missing, &missing, None).unwrap_err();
assert!(
matches!(err, mds::MdsError::Io { .. }),
"expected mds::io, got {err:?}"
);
assert!(
err.to_string().contains("cannot resolve path"),
"the anchor failure must surface, got: {err}"
);
assert_eq!(super::mds_error_exit_code(&err), 2);
let file = root.join("ok.mds");
std::fs::write(&file, "Hello!\n").unwrap();
assert_eq!(
super::read_canonical_source(&file, &file, None).unwrap(),
"Hello!\n"
);
}
}