//! File discovery, path utilities, and pattern expansion use core::error::Error; use ignore::WalkBuilder; use ignore::overrides::OverrideBuilder; use rumdl_config::{WITHHELD, resolve_rule_names}; use rumdl_lib::config as rumdl_config; use rumdl_lib::discovery::{ ExcludeMatchers, LintableFileMode, LintablePathSelector, MARKDOWNLINTIGNORE, MarkdownWalkOptions, apply_markdown_walk_options, apply_walk_options_with_markdownlintignore, exclude_override_rule, expand_directory_pattern, expand_include_directory, has_markdown_extension, include_pattern_compiles, is_exclude_negation, normalize_pattern_for_base, path_relative_to, skip_version_control_directories, strip_verbatim_prefix, }; use rumdl_lib::rule::Rule; use std::collections::HashSet; use std::path::Path; use crate::{CodeBlockToolsMode, FixMode}; /// Which auxiliary code-block-tool phases a command performs. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AuxiliaryExecutionPlan { pub lint: bool, pub format: bool, pub relint: bool, } impl AuxiliaryExecutionPlan { /// The phases follow the command, not the mode: only mode decides which rules /// run over the outer document, and leaves the tool phases where the same /// command without the flag put them. Keeping the two independent is what /// makes an only-mode run a subset of the same command's normal output rather /// than a different pass that can hide a tool finding it cannot fix. fn from_args(args: &crate::CheckArgs) -> Self { if args.code_block_tools_mode() == CodeBlockToolsMode::Disabled { return Self { lint: false, format: false, relint: false, }; } match (args.fix_mode, args.diff) { (FixMode::Check, false) => Self { lint: true, format: false, relint: false, }, _ => Self { lint: true, format: true, relint: true, }, } } pub fn cache_key(self) -> &'static str { match (self.lint, self.format, self.relint) { (false, false, false) => "none", (true, false, false) => "lint", (true, true, true) => "lint-format-relint", _ => "custom", } } } /// Rule sets with deliberately separate outer-document and embedded roles. pub struct RuleSets { pub mode: CodeBlockToolsMode, /// The invocation's rule selection, config and CLI flags resolved, before /// any role narrows it. The guards that run before a document is parsed /// (MD092, MD094) read this: they explain why a file is left unwritten, and /// a file is left unwritten whatever the mode is doing with the other sets. /// Per-file ignores stay out of it, since each guard applies its own. pub selected: std::sync::Arc>>, pub document: Vec>, pub embedded_markdown: Vec>, pub auxiliary: AuxiliaryExecutionPlan, } impl RuleSets { /// Clone both roles after applying the file's per-file ignores. pub fn for_file(&self, ignored_rules: &HashSet) -> Self { let filter = |rules: &[Box]| { rules .iter() .filter(|rule| !ignored_rules.contains(rule.name())) .map(|rule| dyn_clone::clone_box(&**rule)) .collect() }; Self { mode: self.mode, selected: self.selected.clone(), document: filter(&self.document), embedded_markdown: filter(&self.embedded_markdown), auxiliary: self.auxiliary, } } /// Rules for which an inline enable or rule-specific `.editorconfig` /// setting can observably affect this operation. pub fn configuration_relevant_rule_names(&self, config: &rumdl_config::Config) -> HashSet { use rumdl_lib::rule::FixCapability; let mut names: HashSet = self.document.iter().map(|rule| rule.name().to_string()).collect(); if self.auxiliary.lint && rumdl_lib::embedded_lint::should_lint_embedded_markdown(&config.code_block_tools) { names.extend( self.embedded_markdown .iter() .filter(|rule| !matches!(rule.name(), "MD041" | "MD047")) .map(|rule| rule.name().to_string()), ); } if self.auxiliary.format && rumdl_lib::embedded_lint::should_format_embedded_markdown(&config.code_block_tools) { names.extend( self.embedded_markdown .iter() // MD047 is passed through the formatter, but its newline // change is restored at the fenced-content boundary. .filter(|rule| rule.name() != "MD047") .filter(|rule| super::processing::is_rule_actually_fixable(config, rule.name())) .filter(|rule| rule.fix_capability() != FixCapability::Unfixable) .map(|rule| rule.name().to_string()), ); } names } } /// The rule-selection flags of one `check` or `fmt` invocation, as typed: /// comma-separated rule IDs or aliases, with the `all` keyword. pub struct RuleSelectionFlags<'a> { pub enable: Option<&'a str>, pub disable: Option<&'a str>, pub extend_enable: Option<&'a str>, pub extend_disable: Option<&'a str>, } impl<'a> From<&'a crate::cli_types::SharedCliArgs> for RuleSelectionFlags<'a> { fn from(args: &'a crate::cli_types::SharedCliArgs) -> Self { Self { enable: args.enable.as_deref(), disable: args.disable.as_deref(), extend_enable: args.extend_enable.as_deref(), extend_disable: args.extend_disable.as_deref(), } } } /// Canonical rule IDs named by a CLI list, in a stable order. fn resolve_flag(list: Option<&str>) -> Vec { let mut names: Vec = list.map(resolve_rule_names).unwrap_or_default().into_iter().collect(); names.sort_unstable(); names } /// A config list with the rules a CLI flag names appended, first mention wins. fn extended(base: &[String], flag: Option<&str>) -> Vec { let mut names = base.to_vec(); for name in resolve_flag(flag) { if !names.contains(&name) { names.push(name); } } names } /// Resolve the CLI flags against the config's own rule lists into the /// `GlobalConfig` that `filter_rules` selects from, so the CLI, the LSP and /// wasm all select rules with one function. /// /// `--enable` has the semantics of ruff's `--select`: it replaces the config's /// whole rule selection, and the other three flags then act within that /// explicit scope alone. Without it, each CLI list extends the config's list /// of the same name, so a rule disabled by either source stays disabled. pub fn rule_selection( flags: &RuleSelectionFlags<'_>, config: &rumdl_config::GlobalConfig, ) -> rumdl_config::GlobalConfig { match flags.enable { Some(enable) => rumdl_config::GlobalConfig { enable: resolve_flag(Some(enable)), enable_is_explicit: true, disable: resolve_flag(flags.disable), extend_enable: resolve_flag(flags.extend_enable), extend_disable: resolve_flag(flags.extend_disable), ..config.clone() }, None => rumdl_config::GlobalConfig { disable: extended(&config.disable, flags.disable), extend_enable: extended(&config.extend_enable, flags.extend_enable), extend_disable: extended(&config.extend_disable, flags.extend_disable), ..config.clone() }, } } fn selected_rules(args: &crate::CheckArgs, config: &rumdl_config::Config) -> Vec> { let selection = rule_selection(&RuleSelectionFlags::from(&args.shared), &config.global); let all_rules = rumdl_lib::rules::all_rules(config); rumdl_lib::rules::filter_rules(&all_rules, &selection) } fn print_rules(label: &str, rules: &[Box]) { println!("{label}:"); for rule in rules { println!(" - {} ({})", rule.name(), rule.description()); } println!(); } pub fn get_enabled_rules_from_checkargs(args: &crate::CheckArgs, config: &rumdl_config::Config) -> Vec> { let final_rules = selected_rules(args, config); if args.verbose { print_rules("Enabled rules", &final_rules); } final_rules } pub fn get_rule_sets_from_checkargs(args: &crate::CheckArgs, config: &rumdl_config::Config) -> RuleSets { let selected = std::sync::Arc::new(selected_rules(args, config)); let mode = args.code_block_tools_mode(); let document = if mode == CodeBlockToolsMode::Only { Vec::new() } else { selected.to_vec() }; let embedded_markdown = if rumdl_lib::embedded_lint::should_lint_embedded_markdown(&config.code_block_tools) || rumdl_lib::embedded_lint::should_format_embedded_markdown(&config.code_block_tools) { selected.to_vec() } else { Vec::new() }; if args.verbose { // Preserve the established heading for the outer document. Only mode // makes this list empty and prints its fenced-Markdown rules separately. print_rules("Enabled rules", &document); if !embedded_markdown.is_empty() { print_rules("Enabled fenced-Markdown rules", &embedded_markdown); } } RuleSets { mode, selected, document, embedded_markdown, auxiliary: AuxiliaryExecutionPlan::from_args(args), } } /// Canonicalize a file path to resolve symlinks and prevent duplicate linting. /// /// Returns the canonical path if successful, or the original path if canonicalization /// fails (e.g., file doesn't exist yet, permission denied, network path). #[inline] fn canonicalize_path_safe(path_str: &str) -> String { Path::new(path_str) .canonicalize() .map(|p| p.to_string_lossy().to_string()) .unwrap_or_else(|_| path_str.to_string()) } /// Convert an absolute file path to a relative path for display purposes. /// /// Tries to make the path relative to project_root first, then falls back to CWD. /// If neither works, returns the original path unchanged. /// /// This improves readability in CI logs and terminal output by showing /// `docs/guide.md:12:5` instead of `/home/runner/work/myproj/docs/guide.md:12:5`. pub fn to_display_path(file_path: &str, project_root: Option<&Path>) -> String { let path = Path::new(file_path); // Canonicalize the file path once (handles symlinks) let canonical_file = path.canonicalize().ok(); relative_display_path(canonical_file.as_deref().unwrap_or(path), file_path, project_root) } /// [`to_display_path`] for a selected path the check runner canonicalized. /// /// Resolving the selected path again would repeat the same filesystem walk /// once per report for nothing. pub fn discovered_display_path(file_path: &str, project_root: Option<&Path>) -> String { relative_display_path(Path::new(file_path), file_path, project_root) } /// The display form of `resolved`, the file `file_path` names with symlinks /// resolved: relative to the project root, else to the working directory, /// else `file_path` as given. fn relative_display_path(resolved: &Path, file_path: &str, project_root: Option<&Path>) -> String { // Try project root first (preferred for consistent output across the project) if let Some(root) = project_root && let Some(relative) = strip_base_prefix(resolved, root) { return normalize_for_display(relative); } // Fall back to CWD-relative. The cached working directory, because reading // it afresh walks the path on macOS, once per reported file. if let Some(cwd) = rumdl_lib::utils::project_root::working_directory() && let Some(relative) = strip_base_prefix(resolved, cwd) { return normalize_for_display(relative); } // If all else fails, return as-is normalize_for_display(file_path.to_string()) } /// Resolve the path string to show in output for a file. /// /// With `show_full_path` the path is shown in full (not relativized); otherwise /// it is relativized via [`to_display_path`]. In both cases the result is /// normalized by [`normalize_for_display`], so every output format shows the /// same string for a file. pub fn resolve_display_path(file_path: &str, show_full_path: bool, project_root: Option<&Path>) -> String { if show_full_path { normalize_for_display(file_path.to_string()) } else { to_display_path(file_path, project_root) } } /// [`resolve_display_path`] for a path [`find_markdown_files`] returned; see /// [`discovered_display_path`]. pub fn resolve_discovered_display_path(file_path: &str, show_full_path: bool, project_root: Option<&Path>) -> String { if show_full_path { normalize_for_display(file_path.to_string()) } else { discovered_display_path(file_path, project_root) } } /// Normalize a path for output: `/` separators on every platform, and no Win32 /// verbatim prefix. /// /// Only the platform's native separator is converted: on Windows `\` becomes `/`. /// On Unix this is a no-op, where `\` is a legal filename character that must be /// preserved. Windows paths also shed the `\\?\` prefix `canonicalize` adds, so /// a file shown in full reads `C:/Users/dev/docs/guide.md`; the verbatim form is /// an implementation detail of how the file was resolved, and read literally /// its `//?/` opening names a host to any consumer treating the path as a URI. fn normalize_for_display(path: String) -> String { if cfg!(windows) { windows_display_path(&path) } else { path } } /// The Windows half of [`normalize_for_display`]: pure string logic, so it is /// tested on every platform. pub(super) fn windows_display_path(path: &str) -> String { strip_verbatim_prefix(path).replace('\\', "/") } /// Try to strip a base path prefix from a file path. /// /// An absolute base is tried as given first: the bases here (the project root, /// the working directory) are usually canonical already, and one that prefixes /// the path as written is the answer either way. Otherwise the base is resolved /// (e.g. `/tmp` -> `/private/tmp` on macOS) and tried again. A base that is not /// absolute must resolve to an existing directory before it counts, since the /// empty path prefixes every path as written; once it does, a match as written /// still stands. On Windows that covers a drive-relative root such as `/`, /// which is not absolute and resolves to `\\?\C:\`, a prefix a path written as /// `/usr/local/test.md` does not carry. pub(super) fn strip_base_prefix(file_path: &Path, base: &Path) -> Option { let relative = match file_path.strip_prefix(base) { Ok(relative) if base.is_absolute() => relative, as_written => { let canonical = base.canonicalize().ok()?; file_path.strip_prefix(&canonical).or(as_written).ok()? } }; Some(relative.to_string_lossy().to_string()) } /// Why a discovery walk produced no files to check. /// /// "There is no markdown here" and "every markdown file was filtered out" are /// different facts. Reporting both as a bare absence makes a misconfigured run /// indistinguishable from a clean one, so each variant names which happened. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EmptyDiscovery { /// No lintable file was reachable at all, before any filtering. NoMarkdownFiles, /// Lintable files were reachable and every one of them was filtered out. AllFiltered { /// How many files existed but went unchecked. Always at least one, and /// at least the sum of the per-cause counts below. total: usize, /// Removed by the gitignore family (`.gitignore`, `.ignore`, git's /// excludes), which `--respect-gitignore=false` turns off. gitignore: usize, /// Removed by `.markdownlintignore`, which applies whatever /// `--respect-gitignore` says. markdownlintignore: usize, /// Removed by both, so undoing either alone does not bring them back. both_ignores: usize, /// Removed by an `exclude` pattern. exclude: usize, /// Selected by no active `include` pattern. not_included: usize, /// One line per `include` pattern that no reachable file matches, so a /// pattern naming nothing is distinguished from one losing to another /// filter. Already written out, because a pattern read from an `extends` /// target may not be quoted and the line for it says something else /// entirely (see [`unmatched_include_lines`]). unmatched_includes: Vec, }, } impl EmptyDiscovery { /// The filtered-out tally, or [`Self::NoMarkdownFiles`] when it is zero. /// /// Keeps the invariant that [`Self::AllFiltered`] always accounts for at /// least one file, so its message can never read "all 0 were filtered out". /// /// `total` counts every file that existed and went unchecked, which is what /// the headline reports. The per-cause counts only cover files a cause was /// positively shown to have removed, so they may sum to less; a cause is /// never asserted by elimination. fn filtered( total: usize, ignored: IgnoredBy, exclude: usize, not_included: usize, unmatched_includes: Vec, ) -> Self { if total == 0 { return Self::NoMarkdownFiles; } Self::AllFiltered { total, gitignore: ignored.gitignore, markdownlintignore: ignored.markdownlintignore, both_ignores: ignored.both, exclude, not_included, unmatched_includes, } } /// The run was handed `count` named files, and an exclude pattern removed /// every one of them. pub fn all_named_files_excluded(count: usize) -> Self { Self::filtered(count, IgnoredBy::default(), count, 0, Vec::new()) } /// Whether the emptiness points at a configuration problem rather than a /// directory that simply holds no markdown. pub fn is_misconfiguration(&self) -> bool { matches!(self, Self::AllFiltered { .. }) } } impl std::fmt::Display for EmptyDiscovery { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NoMarkdownFiles => write!(f, "No markdown files found to check."), Self::AllFiltered { total, gitignore, markdownlintignore, both_ignores, exclude, not_included, unmatched_includes, } => { let (noun, verb) = if *total == 1 { ("file", "was") } else { ("files", "were") }; write!( f, "No markdown files left to check: {total} {noun} found {verb} filtered out." )?; if *gitignore > 0 { write!( f, "\n {gitignore} by ignore files (.gitignore, .ignore, git excludes); pass --respect-gitignore=false to keep them" )?; } if *markdownlintignore > 0 { write!( f, "\n {markdownlintignore} by .markdownlintignore; remove them from it, or name them on the command line, to keep them" )?; } if *both_ignores > 0 { write!( f, "\n {both_ignores} by both .markdownlintignore and ignore files; remove them from .markdownlintignore and pass --respect-gitignore=false, or name them on the command line, to keep them" )?; } if *exclude > 0 { write!(f, "\n {exclude} by exclude patterns; pass --no-exclude to keep them")?; } if *not_included > 0 { write!(f, "\n {not_included} by include patterns")?; } for line in unmatched_includes { write!(f, "\n {line}")?; } Ok(()) } } } } /// How many files each ignore source hid, for an empty run's explanation. #[derive(Debug, Default, Clone, Copy)] struct IgnoredBy { gitignore: usize, markdownlintignore: usize, both: usize, } /// The files a discovery walk selected, and why it selected none. pub struct Discovered { /// Files to check, deduplicated. Paths retain their supplied or walked name /// until configuration grouping and CLI2 ignore selection have completed. pub files: Vec, /// Why `files` is empty; `None` whenever at least one file was found. pub empty_reason: Option, /// Source-code files the selection named (an argument or an `include` /// match), held out of `files`: rumdl can only read them as Markdown, and /// fixing them that way rewrites the program. See /// [`rumdl_lib::discovery::classify_file`]. pub refused: Vec, #[cfg(unix)] pub(crate) canonical_walk_root: Option, /// Source-code files an `include` wildcard swept up while walking, held out /// of `files`. A wildcard names no file, so these are skipped with a warning /// rather than refused; a file that is also named explicitly is in `refused`. pub skipped: Vec, } /// Whether `pattern` holds an unescaped glob operator. A backslash escapes the /// character after it, so `\[x\].py` names the file `[x].py`. fn has_glob_syntax(pattern: &str) -> bool { let mut chars = pattern.chars(); while let Some(c) = chars.next() { match c { '\\' => { chars.next(); } // A closing bracket or brace with no opener is a literal character. '*' | '?' | '[' | '{' => return true, _ => {} } } false } /// The `include` patterns that name one file outright, with no glob syntax. /// Such a pattern is as deliberate as a path argument, so what it selects is /// refused rather than skipped like a wildcard match. fn literal_include_matchers(patterns: &[String]) -> rumdl_lib::discovery::ExplicitIncludeMatchers { let literal: Vec = patterns .iter() .filter(|pattern| { !pattern.is_empty() && !pattern.ends_with('/') && !pattern.starts_with('!') && !has_glob_syntax(pattern) }) .cloned() .collect(); rumdl_lib::discovery::ExplicitIncludeMatchers::new(&literal) } /// Whether a literal `include` pattern selects `path` itself. fn names_literal_include( literal: &rumdl_lib::discovery::ExplicitIncludeMatchers, project_root: Option<&Path>, path: &Path, ) -> bool { // Without a project root, include patterns are rooted at the current directory. let current_dir = std::env::current_dir().and_then(|dir| dir.canonicalize()).ok(); let relative = project_root .or(current_dir.as_deref()) .and_then(|root| rumdl_lib::discovery::path_relative_to(path, root)) .unwrap_or_else(|| path.to_string_lossy().into_owned()); literal.matches_relative_path(&relative) } /// Split the files rumdl cannot read out of `files`. fn take_source_code(files: &mut Vec, #[cfg(unix)] walk: Option<&mut WalkSourcePaths>) -> Vec { use rayon::prelude::*; #[cfg(unix)] let mut walk = walk; #[cfg(unix)] if let Some(walk) = walk.as_deref_mut() { walk.prime(files); } // Classification costs a metadata syscall per file, so it runs in parallel; // the indexed collect keeps each verdict beside its file. #[cfg(unix)] let shared = walk.as_deref(); let verdicts: Vec<(bool, Option)> = files .par_iter() .map(|file| { // A regular leaf from this non-following walk has the same filename // under its canonical parent. Reuse that resolution for classification; // explicit names, symlinks and metadata failures keep the legacy path. #[cfg(unix)] let leaf = shared.and_then(|walk| walk.resolve(file)); #[cfg(not(unix))] let leaf: Option = None; let source = match &leaf { Some(resolved) => rumdl_lib::discovery::classify_file(resolved), None => rumdl_lib::discovery::classify_file(Path::new(&canonicalize_path_safe(file))), } == rumdl_lib::discovery::FileKind::SourceCode; (source, leaf) }) .collect(); let (is_source, leaves): (Vec, Vec<_>) = verdicts.into_iter().unzip(); #[cfg(unix)] if let Some(walk) = walk { walk.remember(files.iter().cloned().zip(leaves)); } #[cfg(not(unix))] drop(leaves); let (refused, kept) = std::mem::take(files) .into_iter() .zip(is_source) .partition::, _>(|(_, source)| *source); *files = kept.into_iter().map(|(file, _)| file).collect(); refused.into_iter().map(|(file, _)| file).collect() } /// Every file reachable from `roots`, streamed in the form the walker produces. /// /// Vendor directories are traversed, because the discovery walk this explains /// traverses them too: a markdown file under `node_modules` or `target` is one /// rumdl checks, so a filter removing it removed a real file. Skipping them here /// would report those files as never having existed, which is the same silent /// absence this diagnosis exists to replace. /// /// Paths come out exactly as the `ignore` walker yields them, which is the form /// the pattern matchers are fed during the walk being explained. Canonicalizing /// here would cost a syscall per file for a comparison almost no caller needs. fn reachable_files( roots: &[&str], respect_gitignore: bool, markdownlintignore: bool, overrides: Option<&ignore::overrides::Override>, ) -> impl Iterator + use<> { reachable_entries(roots, respect_gitignore, markdownlintignore, overrides) .filter(|entry| entry.file_type().is_some_and(|file_type| file_type.is_file())) .map(ignore::DirEntry::into_path) } /// Every entry the walk reaches, directories included. /// /// A directory an ignore file hid is pruned before the walk descends, so which /// directories were reached is what separates a file the walk declined from one /// it never saw. /// /// `overrides` are the run's include patterns as its walk applies them, for a /// caller that needs to know what that walk would reach rather than what exists: /// an include outranks an ignore file listing a file, so without them a file the /// real walk would keep reads as hidden. fn reachable_entries( roots: &[&str], respect_gitignore: bool, markdownlintignore: bool, overrides: Option<&ignore::overrides::Override>, ) -> impl Iterator + use<> { let walk = roots.split_first().map(|(first, rest)| { let mut builder = WalkBuilder::new(first); for root in rest { builder.add(root); } if let Some(overrides) = overrides { builder.overrides(overrides.clone()); } apply_walk_options_with_markdownlintignore( &mut builder, roots, &MarkdownWalkOptions { respect_gitignore, skip_vendor_dirs: false, }, markdownlintignore, ); builder.build() }); walk.into_iter().flatten().filter_map(Result::ok) } /// The override set for `rules` anchored at `base`. /// /// Invalid rules are skipped; the discovery walk already warns about them. An /// empty set matches nothing either way, which is what an inactive filter means. fn overrides_from(base: &Path, rules: impl IntoIterator) -> ignore::overrides::Override { let mut builder = OverrideBuilder::new(base); for rule in rules { let _ = builder.add(&rule); } builder.build().unwrap_or_else(|_| ignore::overrides::Override::empty()) } /// The path in the canonical form the walk records, from the raw form the walker /// yields. /// /// Costs a syscall, so callers reach for it only where a matcher needs the /// canonical shape rather than the walker's. fn canonical_walk_path(path: &Path) -> std::path::PathBuf { let raw = path.to_string_lossy(); std::path::PathBuf::from(canonicalize_path_safe(raw.strip_prefix("./").unwrap_or(&raw))) } /// Everything that could have kept a file out of a discovery walk. /// /// Carried as one value so the diagnosis below is built from the same /// determination the walk used, rather than from a separately assembled set of /// arguments that could describe a different run. #[derive(Clone, Copy)] struct DiscoveryFilters<'a> { /// The gate the walk applies to everything its filters let through. lintable: &'a LintablePathSelector, /// The post-walk exclude matchers, which also carry absolute patterns. exclude_matchers: &'a ExcludeMatchers, /// The exclude patterns as the walker's overrides see them. exclude_patterns: &'a [String], /// The include patterns as the walker's overrides see them. include_patterns: &'a [String], /// How to name the file those patterns came from when the diagnosis may not /// quote them, and `None` when it may (see [`unmatched_include_lines`]). include_source_withheld: Option<&'a str>, /// Files named on the command line that an exclude pattern already dropped. named_excluded: &'a [std::path::PathBuf], /// The directory the include and exclude patterns are anchored to. pattern_base: &'a Path, /// The project root in canonical form, for relative pattern matching. canonical_project_root: Option<&'a Path>, /// Whether the gitignore family applies. respect_gitignore: bool, } /// Explain why a walk over `roots` under `filters` selected no file. /// /// Each cause is established positively: a file counts against a filter only /// because that filter is shown to drop it, never because the other checks /// happened not to claim it. A cause asserted by elimination would name the /// wrong knob whenever this diagnosis and the real walk differ for a reason not /// modelled here, and would do it with full confidence. Every verdict comes from /// the matcher the walker itself consults, given the path in the form the walker /// gives it, so the two cannot drift apart; a second walk could. /// /// A file no cause claims still counts toward the total, so the headline stays /// an accurate tally of what went unchecked while the breakdown stays verified. /// /// Ignore files are what keep a walk small, so walking without them is by far /// the expensive step. It runs only when nothing survived ignore handling, which /// is the one case its answer can change. fn diagnose_empty_discovery(roots: &[&str], filters: &DiscoveryFilters<'_>) -> EmptyDiscovery { let DiscoveryFilters { lintable, exclude_matchers, exclude_patterns, include_patterns, include_source_withheld, named_excluded, pattern_base, canonical_project_root, respect_gitignore, } = *filters; let excluded_by_pattern = overrides_from(pattern_base, exclude_patterns.iter().map(|p| exclude_override_rule(p))); let included_by_pattern = overrides_from( pattern_base, include_patterns.iter().flat_map(|p| expand_include_directory(p)), ); // Kept apart from the combined set so an unmatched pattern can be named // individually: a pattern that selects nothing is a typo, while a pattern // losing to another filter is not. let per_include: Vec = include_patterns .iter() .map(|pattern| overrides_from(pattern_base, expand_include_directory(pattern))) .collect(); // A file rumdl would have had to check: markdown by default, plus whatever an // `include` pattern both selects and the walk's own gate then keeps. An // include that widens the walk without admitting a new file type reaches no // further, so a file it merely touches was never a candidate and must not be // reported as one the configuration removed. let literal_includes = literal_include_matchers(include_patterns); // Source code a wildcard sweeps up is skipped, never a file a filter lost, so // it cannot make an otherwise empty run a configuration problem. let is_skipped_source = |path: &Path| { if has_markdown_extension(path) || !included_by_pattern.matched(path, false).is_whitelist() { return false; } rumdl_lib::discovery::classify_file(&canonical_walk_path(path)) == rumdl_lib::discovery::FileKind::SourceCode && !names_literal_include(&literal_includes, canonical_project_root, path) }; let is_lintable = |path: &Path| { if has_markdown_extension(path) { return true; } if !included_by_pattern.matched(path, false).is_whitelist() || is_skipped_source(path) { return false; } lintable.keeps(&canonical_walk_path(path)) }; // Absolute patterns and paths outside the walk root reach the run only // through the post-walk matchers, which work on canonical paths. let excluded_after_walk = |path: &Path| { if exclude_matchers.is_empty() { return false; } let canonical = canonical_walk_path(path); let relative = canonical_project_root.and_then(|root| path_relative_to(&canonical, root)); exclude_matchers.excludes_file(relative.as_deref(), &canonical) }; // Overlapping roots (`rumdl check . docs`) hand the walker the same file // once per root, and the walk they explain reduces those to one file. // Recognising a repeat means canonicalizing, which costs a syscall per file, // so it is done only when there is more than one root to overlap. let mut seen_paths: HashSet = HashSet::new(); let mut is_repeat = move |path: &Path| roots.len() > 1 && !seen_paths.insert(canonical_walk_path(path)); let named_excluded_paths: HashSet<&Path> = named_excluded.iter().map(std::path::PathBuf::as_path).collect(); let already_counted = |path: &Path| { if named_excluded_paths.is_empty() { return false; } named_excluded_paths.contains(canonical_walk_path(path).as_path()) }; let mut matched_includes = vec![false; per_include.len()]; let mut matched_only_skipped = vec![false; per_include.len()]; let note_include_matches = |path: &Path, matched: &mut Vec| { for (pattern, seen) in per_include.iter().zip(matched.iter_mut()) { *seen = *seen || pattern.matched(path, false).is_whitelist(); } }; // What the include patterns say about a file. An include outranks the // ignore files, so this decides whether they could have applied at all, and // both walks below ask it first. With no include patterns at all the verdict // is neither, which leaves the ignore files free to act. let include_verdict = |path: &Path| included_by_pattern.matched(path, false); // Files that survived ignore handling. Whatever removed these is one of the // user's own patterns, so their causes are decided here. The directories // reached along the way are kept for the second walk. let (mut total, mut exclude, mut not_included) = (0, 0, 0); let mut reached_dirs: HashSet = HashSet::new(); // What the walk reaches with the include patterns applied is added to what it // reaches without them: an include outranks the ignore files for the entry it // names, so a directory an include names is entered by the real walk even when // an ignore file lists it, and its files are candidates like any other. let rescued_by_include = (!include_patterns.is_empty()) .then(|| reachable_entries(roots, respect_gitignore, true, Some(&included_by_pattern))) .into_iter() .flatten(); let mut seen_entries: HashSet = HashSet::new(); for entry in reachable_entries(roots, respect_gitignore, true, None).chain(rescued_by_include) { if !seen_entries.insert(entry.path().to_path_buf()) { continue; } if entry.file_type().is_some_and(|file_type| file_type.is_dir()) { reached_dirs.insert(canonical_walk_path(entry.path())); continue; } if !entry.file_type().is_some_and(|file_type| file_type.is_file()) { continue; } let path = entry.into_path(); if is_skipped_source(&path) { note_include_matches(&path, &mut matched_only_skipped); } if !is_lintable(&path) || is_repeat(&path) { continue; } note_include_matches(&path, &mut matched_includes); // A named file is tallied below from the command line, where its cause // was already established, so meeting it again here is a repeat. if already_counted(&path) { continue; } total += 1; if excluded_by_pattern.matched(&path, false).is_ignore() || excluded_after_walk(&path) { exclude += 1; } else if include_verdict(&path).is_ignore() { not_included += 1; } } // No candidate turned up at all, so this walk asks what ignore files hid. A // file named on the command line and excluded is a candidate whose cause is // already established, exactly like one the walk itself found, and either // makes this step redundant: an empty run needs one setting to undo, not a // census of everything else that went unchecked. Whether a file was named // or only walked must not change the diagnosis. // // The include patterns decide what the ignore files were even allowed to // do, so they are asked first. An include that selects nothing is why the // ignore files applied at all. One that selects a file the walk reached // overrides them, so the real walk did reach it too and only an exclude can // have dropped it; the run being empty is what makes that a conclusion // rather than a guess. An include reaches into a directory only by naming // it, and the walk above has entered those, so a file whose directory an // ignore file pruned is the ignore file's doing however plainly an include // names the file. Without include // patterns the ignore files are the only thing left, and this walk finding a // file the first one could not see is the evidence. Their exclude patterns // are never asked: an ignored path never reached them, and answering for a // matcher that never ran would be a guess dressed as a finding. // // `.markdownlintignore` applies whatever `respect_gitignore` says, so this // walk reads no ignore file at all, and a run that already ignores the // gitignore family still has one source left to explain. let mut ignored = IgnoredBy::default(); if total == 0 && named_excluded.is_empty() { let reached = |path: &Path| { path.parent() .is_some_and(|dir| reached_dirs.contains(&canonical_walk_path(dir))) }; let mut hidden: HashSet = HashSet::new(); let mut markdownlintignore_seen = markdownlintignore_above(roots); for path in reachable_files(roots, false, false, None) { markdownlintignore_seen |= path.file_name().is_some_and(|name| name == MARKDOWNLINTIGNORE); if !is_lintable(&path) || is_repeat(&path) { continue; } note_include_matches(&path, &mut matched_includes); total += 1; let verdict = include_verdict(&path); if verdict.is_ignore() { not_included += 1; } else if verdict.is_whitelist() && reached(&path) { exclude += 1; } else { hidden.insert(path); } } ignored = attribute_ignored( roots, respect_gitignore, markdownlintignore_seen, &included_by_pattern, &hidden, ); } // A pattern the overrides rejected never selected anything to begin with, so // "matches no file" would describe it as a glob that names nothing when it is // not a glob at all. The walk reports those itself, and reporting them here // again would also quote a pattern that walk deliberately did not. let unselected = |skipped_only: bool| -> Vec<&str> { include_patterns .iter() .zip(matched_includes.iter().zip(&matched_only_skipped)) .filter(|(pattern, (matched, skipped))| { !**matched && **skipped == skipped_only && include_pattern_compiles(pattern) }) .map(|(pattern, _)| pattern.as_str()) .collect() }; let mut unmatched_includes = unmatched_include_lines(&unselected(false), include_source_withheld); // A pattern whose only matches were skipped source files did select them, so // it is described as that rather than as matching nothing. if include_source_withheld.is_none() { unmatched_includes.extend( unselected(true).into_iter().map(|pattern| { format!("include pattern '{pattern}' matches only files that are not Markdown (skipped)") }), ); } let named = named_excluded.len(); EmptyDiscovery::filtered( total + named, ignored, exclude + named, not_included, unmatched_includes, ) } /// Whether a `.markdownlintignore` sits above any of `roots`, where a walk reads /// it without ever yielding it as an entry. fn markdownlintignore_above(roots: &[&str]) -> bool { roots.iter().any(|root| { std::fs::canonicalize(root).is_ok_and(|root| { root.ancestors() .skip(1) .any(|dir| dir.join(MARKDOWNLINTIGNORE).is_file()) }) }) } /// Which ignore source hid each of `hidden`, the files only a walk reading no /// ignore file reaches. /// /// Each source is judged by walking with the other one alone: a file that walk /// reaches is hidden by the source left out, and undoing that source alone /// brings it back. A file neither walk reaches is hidden by both, so neither /// remedy alone would work and the notice must not offer either as if it did. /// /// With no `.markdownlintignore` anywhere the walk could read one, only the /// gitignore family can have hidden anything, and with the gitignore family off /// only `.markdownlintignore` can, so neither case needs another walk. That /// keeps the common case, a `.gitignore` alone emptying the run, at one walk /// without ignore handling, the expensive kind. A file no source can be shown /// to have hidden is left to the headline total rather than blamed on one. /// /// Both walks apply `overrides`, the run's include patterns, so an include /// outranking the source left in counts the way the real walk would. Exclude /// patterns stay out: they never see a path an ignore file hid, so they have no /// say in which source hid it, and applying them would hide the file from both /// walks and blame both sources. fn attribute_ignored( roots: &[&str], respect_gitignore: bool, markdownlintignore_seen: bool, overrides: &ignore::overrides::Override, hidden: &HashSet, ) -> IgnoredBy { if hidden.is_empty() { return IgnoredBy::default(); } match (respect_gitignore, markdownlintignore_seen) { (true, false) => { return IgnoredBy { gitignore: hidden.len(), ..IgnoredBy::default() }; } (false, true) => { return IgnoredBy { markdownlintignore: hidden.len(), ..IgnoredBy::default() }; } (false, false) => return IgnoredBy::default(), (true, true) => {} } let reached_among_hidden = |respect_gitignore: bool, markdownlintignore: bool| -> HashSet { reachable_files(roots, respect_gitignore, markdownlintignore, Some(overrides)) .filter(|path| hidden.contains(path)) .collect() }; let without_markdownlintignore = reached_among_hidden(true, false); let without_gitignore = if without_markdownlintignore.len() == hidden.len() { HashSet::new() } else { reached_among_hidden(false, true) }; let mut ignored = IgnoredBy::default(); for path in hidden { if without_markdownlintignore.contains(path) { ignored.markdownlintignore += 1; } else if without_gitignore.contains(path) { ignored.gitignore += 1; } else { ignored.both += 1; } } ignored } /// How an empty run describes the `include` patterns that selected nothing. /// /// A pattern is quoted, which is what makes the notice actionable, unless it /// came from an `extends` target: that is text out of a file the extending /// project only pointed at, and a valid pattern is no less that file's own words /// than one that does not compile. `withheld_source` then names the file /// instead, once for the whole list, since lines that quote nothing carry /// nothing to tell them apart. fn unmatched_include_lines(unmatched: &[&str], withheld_source: Option<&str>) -> Vec { match withheld_source { None => unmatched .iter() .map(|pattern| format!("include pattern '{pattern}' matches no file")) .collect(), Some(_) if unmatched.is_empty() => Vec::new(), Some(source) => { let (noun, verb) = if unmatched.len() == 1 { ("pattern", "matches") } else { ("patterns", "match") }; vec![format!("{} include {noun} in {source} {verb} no file", unmatched.len())] } } } /// The exclude patterns a run applies, as written: none under `--no-exclude`, /// the `--exclude` list when one is given (it replaces the configured patterns /// rather than adding to them), and the configured list otherwise. fn effective_exclude_patterns(args: &crate::CheckArgs, config: &rumdl_config::Config) -> Vec { if args.no_exclude { Vec::new() } else if let Some(cli_exclude) = args.exclude.as_deref() { cli_exclude .split(',') .map(|p| p.trim().to_string()) .filter(|p| !p.is_empty()) .collect() } else { config.global.exclude.clone() } } /// Compile exclude patterns, reporting each one that does not compile. Such a /// pattern matches nothing. fn compile_exclude_matchers(patterns: &[String]) -> ExcludeMatchers { let matchers = ExcludeMatchers::new(patterns); for (pattern, error) in &matchers.invalid { eprintln!("Warning: Invalid exclude pattern '{pattern}': {error}"); } matchers } /// Matchers for the exclude patterns a run applies (see /// [`effective_exclude_patterns`]), for deciding about a file the caller named /// without walking for any. /// /// A pattern that does not compile matches nothing and is not reported here. /// The discovery walk reports it, so reporting it again from every caller that /// consults the patterns would print the same warning once per caller. pub fn run_exclude_matchers(args: &crate::CheckArgs, config: &rumdl_config::Config) -> ExcludeMatchers { ExcludeMatchers::new(&effective_exclude_patterns(args, config)) } /// The exclude pattern that removes a file the caller named directly, if any: /// a path argument, or the name a document read from stdin was given. /// /// Patterns are written relative to the project root, so that form is tried /// first. A file outside the project is matched relative to the working /// directory, and failing that as written. The file need not exist, since an /// editor names an unsaved buffer exactly as it names a saved one. Absolute /// patterns match the absolute path. pub fn named_file_exclude_pattern<'m>( matchers: &'m ExcludeMatchers, project_root: Option<&Path>, path: &Path, ) -> Option<&'m str> { if matchers.is_empty() { return None; } let relative = project_root .and_then(|root| path_relative_to(path, root)) .or_else(|| { std::env::current_dir() .ok() .and_then(|cwd| path_relative_to(path, &cwd)) }) .unwrap_or_else(|| { let as_written = path.to_string_lossy(); as_written.strip_prefix("./").unwrap_or(&as_written).to_string() }); matchers.matched_pattern_for_file(Some(&relative), path) } /// Explain, under `--verbose`, which pattern skipped a file the caller named. /// /// Excluding a named file is a deliberate configuration choice, so this is an /// informational notice rather than a warning, and it stays out of the default /// output the way a discovery walk excludes silently. `--silent` suppresses it. pub fn report_named_file_excluded(args: &crate::CheckArgs, name: &str, pattern: &str) { if args.verbose && !args.silent { let display_path = normalize_for_display(name.to_string()); eprintln!("{display_path} ignored because of exclude pattern '{pattern}'. Use --no-exclude to override"); } } pub fn find_markdown_files( paths: &[String], args: &crate::CheckArgs, config: &rumdl_config::Config, project_root: Option<&std::path::Path>, ) -> Result> { let mut file_paths = Vec::new(); // Determine if running in discovery mode (e.g., "rumdl ." or "rumdl check ." or "rumdl check") let is_discovery_mode = paths.is_empty() || paths == ["."]; // Track whether config-based include patterns are active in discovery mode let has_config_include = is_discovery_mode && !config.global.include.is_empty(); // Include patterns are matched relative to the same base the walker's // overrides use, so `~` is expanded and an absolute pattern under that base // is rewritten relative to it (see `normalize_pattern_for_base`). let include_base = project_root .map(Path::to_path_buf) .or_else(|| std::env::current_dir().ok()); let normalize_include = |pattern: &str| normalize_pattern_for_base(pattern, include_base.as_deref()); let config_include: Vec = config .global .include .iter() .map(|pattern| normalize_include(pattern)) .collect(); // --- Determine Effective Include/Exclude Patterns --- // Include patterns: CLI > Config (only in discovery mode) > Default (only in discovery mode) let final_include_patterns: Vec = if let Some(cli_include) = args.include.as_deref() { // 1. CLI --include always wins cli_include .split(',') .map(|p| p.trim()) .filter(|p| !p.is_empty()) .map(normalize_include) .collect() } else if is_discovery_mode && !config.global.include.is_empty() { // 2. Config include is used ONLY in discovery mode if specified config_include.clone() } else if is_discovery_mode { // 3. Default: Don't add include patterns as overrides - the type filter already handles // selecting markdown files (lines 183-199). Using overrides here would bypass gitignore // because overrides take precedence over gitignore in the ignore crate. Vec::new() } else { // 4. Explicit path mode: No includes applied by default. Walk starts from explicit paths. Vec::new() }; // How to name the file the include patterns came from when a message about one // may not quote it. A CLI `--include` is the user's own text and stays // quotable, so only the config branch above can carry the mark. let include_source_withheld: Option<&str> = args .include .is_none() .then_some(config.global.include_withheld.as_deref()) .flatten(); // Exclude patterns: CLI > Config (but disabled if --no-exclude is set) // A negation is reported by `compile_exclude_matchers` and applied nowhere, so // the walker, the named-file matchers and the empty-run notice agree on it. let raw_exclude_patterns = effective_exclude_patterns(args, config); let applied_exclude_patterns: Vec = raw_exclude_patterns .iter() .filter(|pattern| !is_exclude_negation(pattern)) .cloned() .collect(); // Expand directory-only patterns to also match their contents (for the // walker overrides; ExcludeMatchers applies the same expansion itself) let final_exclude_patterns: Vec = applied_exclude_patterns .iter() .flat_map(|p| expand_directory_pattern(p)) .collect(); // Debug: Log exclude patterns if args.verbose { eprintln!("Exclude patterns: {final_exclude_patterns:?}"); } let exclude_matchers = compile_exclude_matchers(&raw_exclude_patterns); let canonical_project_root = project_root.and_then(|root| root.canonicalize().ok()); let selector_base = canonical_project_root.clone().or_else(|| std::env::current_dir().ok()); let selector_includes = if has_config_include { config_include.as_slice() } else { &[] }; let selector_mode = if args.include.is_some() { LintableFileMode::Any } else if has_config_include { LintableFileMode::MarkdownAndRust } else { LintableFileMode::Markdown }; let mut lintable = LintablePathSelector::new(selector_base.as_deref(), selector_includes, selector_mode); if args.include.is_some() { // A pattern that names a directory selects the Markdown beneath it; only // a pattern that reaches a file itself widens the run to other types. lintable = lintable.with_named_files(overrides_from( project_root.unwrap_or(Path::new(".")), final_include_patterns.iter().cloned(), )); } // --- End Pattern Determination --- // --- Split explicit paths into named files and directory roots --- // A file named on the command line is trusted as-is: it is linted even // without a markdown extension and bypasses the walker's type/ignore // filters, subject only to exclude patterns (issue #99). Directory // arguments are walked below exactly like discovery-mode roots, so a // mixed invocation checks the union of both (issue #741). let mut explicit_files: Vec = Vec::new(); let mut explicit_dirs: Vec<&str> = Vec::new(); // Named files an exclude pattern dropped, so an emptied explicit run can say // that its arguments were excluded rather than absent. Held as paths, not a // count, because a directory argument can rediscover the same file and the // diagnosis below must not tally it twice. let mut excluded_named_files: Vec = Vec::new(); if !is_discovery_mode { for path_str in paths { let path = Path::new(path_str); if !path.exists() { return Err(format!("File not found: {path_str}").into()); } if !path.is_file() { explicit_dirs.push(path_str.as_str()); continue; } // The file as shown and keyed: relative to the current directory // when it lies under it, so output reads the same for relative and // absolute arguments. let cleaned_path = if path.is_absolute() { std::env::current_dir() .ok() .and_then(|cwd| { path.strip_prefix(cwd) .ok() .map(|relative| relative.to_string_lossy().into_owned()) }) .unwrap_or_else(|| path_str.clone()) } else if let Some(stripped) = path_str.strip_prefix("./") { stripped.to_string() } else { path_str.clone() }; // Check if this file should be excluded based on exclude patterns // This is the default behavior to match user expectations and avoid // duplication between rumdl config and pre-commit config (issue #99) if !args.no_exclude && config .cli2_ignores .iter() .any(|scope| scope.root && scope.matches(path)) { excluded_named_files.push(std::path::PathBuf::from(canonicalize_path_safe(&cleaned_path))); report_named_file_excluded(args, &cleaned_path, "markdownlint-cli2 ignores"); } else if let Some(pattern) = named_file_exclude_pattern(&exclude_matchers, canonical_project_root.as_deref(), path) { excluded_named_files.push(std::path::PathBuf::from(canonicalize_path_safe(&cleaned_path))); report_named_file_excluded(args, &cleaned_path, pattern); } else { explicit_files.push(cleaned_path); } } // One file can be named several times, or under spellings that resolve // to the same path. It is still one file, and a count of what an exclude // pattern removed has to say so. excluded_named_files.sort(); excluded_named_files.dedup(); // Nothing to walk when every argument is a file. Returns the explicit // set even if exclusions emptied it, so the caller reports "no files" // instead of silently falling back to a cwd walk. if explicit_dirs.is_empty() { explicit_files.sort(); explicit_files.dedup(); let refused = take_source_code( &mut explicit_files, #[cfg(unix)] None, ); let excluded = excluded_named_files.len(); let empty_reason = (explicit_files.is_empty() && refused.is_empty()) .then(|| EmptyDiscovery::all_named_files_excluded(excluded)); return Ok(Discovered { files: explicit_files, empty_reason, refused, #[cfg(unix)] canonical_walk_root: None, skipped: Vec::new(), }); } } // --- Configure ignore::WalkBuilder over the directory roots --- // Discovery mode walks the cwd (`.`); explicit mode walks only the // directory arguments (named files were collected above). let walk_roots: Vec<&str> = if is_discovery_mode { vec![paths.first().map(String::as_str).unwrap_or(".")] } else { explicit_dirs.clone() }; let mut walk_builder = { let (first, rest) = walk_roots.split_first().expect("a walk always has at least one root"); let mut builder = WalkBuilder::new(first); for dir in rest { builder.add(dir); } builder }; // The shared gate configures the coarse walker types; it is consulted again // after the walk for precise root-relative explicit-include matching. lintable.configure_types(&mut walk_builder)?; // ----------------------------------------- // Apply overrides using the determined patterns if !final_include_patterns.is_empty() || !final_exclude_patterns.is_empty() { // Use project_root as the pattern base for OverrideBuilder // The walker paths are relative to the walk roots, but the ignore crate // handles the path matching internally when both are consistent directories let pattern_base = project_root.unwrap_or(Path::new(".")); let mut override_builder = OverrideBuilder::new(pattern_base); // Add includes (these act as positive filters) for pattern in &final_include_patterns { // Important: In ignore crate, bare patterns act as includes if no exclude (!) is present. // If we add excludes later, these includes ensure *only* matching files are considered. // If no excludes are added, these effectively define the set of files to walk. let added = expand_include_directory(pattern) .iter() .try_for_each(|rule| override_builder.add(rule).map(|_| ())); match (added, include_source_withheld) { (Ok(()), _) => {} // The error quotes the pattern it could not parse, which is text // out of a file this may not repeat. Which file pointed at it is // the extending config's own text, so that much can still be said. (Err(_), Some(source)) => { eprintln!("Warning: Invalid include pattern in {source}: {WITHHELD}"); } (Err(e), None) => eprintln!("Warning: Invalid include pattern '{pattern}': {e}"), } } // Add excludes (these filter *out* files) - MUST start with '!' for pattern in &final_exclude_patterns { let exclude_rule = exclude_override_rule(pattern); if let Err(e) = override_builder.add(&exclude_rule) { eprintln!("Warning: Invalid exclude pattern '{pattern}': {e}"); } } // Build and apply the overrides match override_builder.build() { Ok(overrides) => { walk_builder.overrides(overrides); } Err(e) => { eprintln!("Error building path overrides: {e}"); } }; } // Configure ignore handling *SECOND*: gitignore family per config, // hidden files included, .markdownlintignore honored. Shared with the // LSP workspace scan so both walk the same files. apply_markdown_walk_options( &mut walk_builder, &walk_roots, &MarkdownWalkOptions { respect_gitignore: config.global.respect_gitignore, skip_vendor_dirs: false, }, ); // Without the Markdown type filter nothing else keeps the walk out of `.git`. if lintable.selects_every_file_type() { skip_version_control_directories(&mut walk_builder); } // A non-following walk supplies each regular file's actual filename. // Retain that provenance through configuration/ignore selection: regular // selected leaves can then share their parent-directory canonicalization. // Supplied spellings remain untouched until configuration/ignores resolve. #[cfg(unix)] let mut canonical_walk_root = if walk_roots.len() == 1 && explicit_files.is_empty() { walk_builder.follow_links(false); WalkSourcePaths::new(Path::new(walk_roots[0])) } else { None }; // --- Execute Walk --- // Directories are read on the parallel walker's threads. Entries and errors // arrive in a nondeterministic order, so both are sorted before use. let walked_files = std::sync::Mutex::new(Vec::new()); let walk_errors = std::sync::Mutex::new(Vec::new()); let saw_non_utf8 = std::sync::atomic::AtomicBool::new(false); // Directory walking is bound by filesystem syscalls, which contend in the // kernel past a few threads: four keeps nearly all of the wall-time gain // while more threads mostly add system CPU. let walk_threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(4)); walk_builder.threads(walk_threads); walk_builder.build_parallel().run(|| { // Each walker thread fills its own buffer and hands it over once, // when the walk drops the visitor. let mut local = ThreadFiles { files: Vec::new(), sink: &walked_files, }; let (walk_errors, saw_non_utf8) = (&walk_errors, &saw_non_utf8); Box::new(move |result| { match result { Ok(entry) => { let path = entry.path(); // We are primarily interested in files. ignore crate handles dir traversal. // Check if it's a file and if it wasn't explicitly excluded by overrides if entry.file_type().is_some_and(|file_type| file_type.is_file()) { if path.to_str().is_none() { saw_non_utf8.store(true, std::sync::atomic::Ordering::Relaxed); } let file_path = path.to_string_lossy().to_string(); // Clean the path before pushing let cleaned_path = if let Some(stripped) = file_path.strip_prefix("./") { stripped.to_string() } else { file_path }; local.files.push(cleaned_path); } } Err(err) => { // Only show generic walking errors for directories, not for missing files if is_discovery_mode { walk_errors.lock().unwrap().push(err.to_string()); } } } ignore::WalkState::Continue }) }); let mut walk_errors = walk_errors.into_inner().unwrap(); walk_errors.sort(); for err in walk_errors { eprintln!("Error walking directory: {err}"); } // The legacy selection stores lossy UTF-8 paths. If any entry needs that // conversion, retain filesystem resolution for the whole walk, including // possible spelling collisions. #[cfg(unix)] if saw_non_utf8.into_inner() { canonical_walk_root = None; } file_paths.extend(walked_files.into_inner().unwrap()); // Remove duplicate paths if WalkBuilder might yield them (e.g. multiple input paths) file_paths.sort(); file_paths.dedup(); // --- Post-walk exclude pattern filtering --- // The ignore crate's overrides may not work correctly when the walker path prefix // differs from the config file location. Apply exclude patterns manually here. // This also carries absolute patterns, which the walker's overrides cannot // express: the ignore crate anchors a leading `/` to the walk root. if !exclude_matchers.is_empty() { file_paths.retain(|file_path| { let path = Path::new(file_path); // Compute path relative to project_root for pattern matching. Without // a project root, or outside it, only the absolute form applies. let path_for_matching = canonical_project_root .as_deref() .and_then(|root| path_relative_to(path, root)); // Check if any exclude pattern matches !exclude_matchers.excludes_file(path_for_matching.as_deref(), path) }); } // --- Final Lintable File Filter --- // Explicit include patterns are matched against the same base the walker // overrides use, so the full pattern path applies: a broad sibling pattern // must not inherit another pattern's allowance for files that merely share // its name. file_paths.retain(|path_str| lintable.keeps(Path::new(path_str))); // ------------------------------------- // Globby prunes some directories for complemented ignore expressions. // Apply that only to walked files: explicit names bypass directory traversal. let before_cli2_walk_filter = file_paths.len(); if !args.no_exclude && config .cli2_ignores .iter() .any(|scope| scope.root && scope.prunes_directories()) { let absolute = |path: &Path| rumdl_lib::workspace_index::absolute_selection_path(path).ok(); let roots: Vec<_> = walk_roots.iter().filter_map(|root| absolute(Path::new(root))).collect(); file_paths.retain(|file| { let Some(path) = absolute(Path::new(file)) else { return true; }; let matching: Vec<_> = roots.iter().filter(|root| path.starts_with(root)).collect(); matching.is_empty() || matching.iter().any(|root| { !config .cli2_ignores .iter() .any(|scope| scope.root && scope.prunes_walked_path(&path, root)) }) }); } let cli2_walk_excluded = before_cli2_walk_filter - file_paths.len(); // Supplied and walked names survive until per-directory ignores are applied. // The check runner canonicalizes and deduplicates the selected groups. // Only the walked set is separable from the named files here: whatever the // walk matched without being named is skipped, and a file that is also named // goes through `explicit_files` and is refused below. let walked_source = take_source_code( &mut file_paths, #[cfg(unix)] canonical_walk_root.as_mut(), ); let literal_includes = literal_include_matchers(&final_include_patterns); let (named_by_include, mut skipped): (Vec, Vec) = walked_source .into_iter() .partition(|file| names_literal_include(&literal_includes, canonical_project_root.as_deref(), Path::new(file))); skipped.sort(); skipped.dedup(); file_paths.extend(explicit_files); file_paths.sort(); file_paths.dedup(); let mut refused = take_source_code( &mut file_paths, #[cfg(unix)] canonical_walk_root.as_mut(), ); refused.extend(named_by_include); refused.sort(); refused.dedup(); skipped.retain(|file| !refused.contains(file)); // Only an empty result pays for the diagnosis, and only it needs one. let empty_reason = (file_paths.is_empty() && refused.is_empty()).then(|| { if cli2_walk_excluded > 0 { return EmptyDiscovery::all_named_files_excluded(cli2_walk_excluded + excluded_named_files.len()); } diagnose_empty_discovery( &walk_roots, &DiscoveryFilters { lintable: &lintable, exclude_matchers: &exclude_matchers, exclude_patterns: &final_exclude_patterns, include_patterns: &final_include_patterns, include_source_withheld, named_excluded: &excluded_named_files, pattern_base: project_root.unwrap_or(Path::new(".")), canonical_project_root: canonical_project_root.as_deref(), respect_gitignore: config.global.respect_gitignore, }, ) }); Ok(Discovered { files: file_paths, empty_reason, refused, #[cfg(unix)] canonical_walk_root, skipped, }) } /// One walker thread's files, merged into the shared list when dropped. struct ThreadFiles<'a> { files: Vec, sink: &'a std::sync::Mutex>, } impl Drop for ThreadFiles<'_> { fn drop(&mut self) { self.sink.lock().unwrap().append(&mut self.files); } } /// Selected regular leaves from one non-following walk. Explicit names and /// unsupported spellings retain filesystem canonicalization. Each selected /// leaf is checked for metadata access, and only directory identities are /// shared; an inaccessible or replaced leaf is never assumed canonical. #[cfg(unix)] pub(crate) struct WalkSourcePaths { cwd: std::path::PathBuf, spelled: std::path::PathBuf, parents: std::collections::HashMap>, /// Each classified file's resolution, so later passes over the same /// selection reuse it instead of repeating the metadata check. leaves: std::collections::HashMap>, } #[cfg(unix)] impl WalkSourcePaths { fn new(root: &Path) -> Option { if !root.is_dir() { return None; } let cwd = std::env::current_dir().ok()?; let spelled = if root.is_absolute() { root.to_path_buf() } else { cwd.join(root) }; Some(Self { cwd, spelled, parents: std::collections::HashMap::new(), leaves: std::collections::HashMap::new(), }) } /// The absolute spelling of `file` when it names a leaf beneath the walk /// root through plain components only. fn walked_leaf(&self, file: &str) -> Option { let path = Path::new(file); let absolute = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) }; let suffix = absolute.strip_prefix(&self.spelled).ok()?; if suffix.as_os_str().is_empty() || suffix .components() .any(|part| !matches!(part, std::path::Component::Normal(_))) { return None; } Some(absolute) } /// Canonicalize every parent directory of `files` not yet known, so that /// [`Self::resolve`] can then run from any thread. /// /// Canonicalizing a path costs a lookup per component, which dominates /// discovery in trees with a directory per document. Below the root, a /// directory that is not a symlink is canonical under its canonical parent, /// so each one costs a single metadata check instead. Any directory that /// check does not confirm keeps full canonicalization. fn prime(&mut self, files: &[String]) { use rayon::prelude::*; let mut unknown = std::collections::HashSet::new(); for file in files { let Some(leaf) = self.walked_leaf(file) else { continue; }; let mut ancestors = leaf.ancestors().skip(1); // Walked leaves lie beneath the root, so the ancestors reach it. while let Some(dir) = ancestors.next() && !self.parents.contains_key(dir) && unknown.insert(dir.to_path_buf()) && dir != self.spelled {} } let mut checked: Vec<(std::path::PathBuf, bool)> = unknown .into_par_iter() .map(|dir| { let real = dir != self.spelled && std::fs::symlink_metadata(&dir).is_ok_and(|metadata| metadata.file_type().is_dir()); (dir, real) }) .collect(); // Parents sort before their children, so each derivation finds its // parent already resolved. checked.sort_by_cached_key(|(dir, _)| dir.components().count()); for (dir, real) in checked { let derived = real .then(|| { let parent = self.parents.get(dir.parent()?)?.as_ref()?; Some(parent.join(dir.file_name()?)) }) .flatten(); let canonical = derived.or_else(|| std::fs::canonicalize(&dir).ok()); self.parents.insert(dir, canonical); } } /// Record resolutions computed by [`Self::resolve`] for later lookups. fn remember(&mut self, resolved: impl IntoIterator)>) { self.leaves.extend(resolved); } pub(crate) fn resolve(&self, file: &str) -> Option { if let Some(resolved) = self.leaves.get(file) { return resolved.clone(); } let absolute = self.walked_leaf(file)?; // Directory entries alone do not prove metadata access. In particular // an ACL can deny canonicalization of a readable regular file. A // failed check keeps the legacy lookup and its supplied-path fallback. if !std::fs::symlink_metadata(&absolute).ok()?.is_file() { return None; } let parent = absolute.parent()?; let name = absolute.file_name()?; let canonical = match self.parents.get(parent) { Some(canonical) => canonical.clone(), None => std::fs::canonicalize(parent).ok(), }; Some(canonical?.join(name)) } } #[cfg(all(test, unix))] mod walk_source_tests { use super::*; use std::os::unix::fs::symlink; #[test] fn walk_source_classification_keeps_alias_and_missing_file_results() { let temp = tempfile::tempdir().unwrap(); let real = temp.path().join("real"); std::fs::create_dir_all(&real).unwrap(); for name in ["guide.md", "script.swift", "template.md.swift", "lib.rs"] { std::fs::write(real.join(name), "text\n").unwrap(); } symlink(real.join("script.swift"), real.join("source.md")).unwrap(); symlink(real.join("guide.md"), real.join("document.swift")).unwrap(); let alias = temp.path().join("alias"); symlink(&real, &alias).unwrap(); for root in [&real, &alias] { let original: Vec = [ "guide.md", "script.swift", "template.md.swift", "lib.rs", "source.md", "document.swift", "missing.swift", "missing.md", ] .into_iter() .map(|name| root.join(name).to_str().unwrap().to_owned()) .collect(); let mut expected = original.clone(); let expected_refused = take_source_code(&mut expected, None); let mut actual = original; let mut walk = WalkSourcePaths::new(root).unwrap(); let actual_refused = take_source_code(&mut actual, Some(&mut walk)); assert_eq!(actual, expected); assert_eq!(actual_refused, expected_refused); assert!(actual_refused.iter().any(|name| name.ends_with("source.md"))); assert!(actual.iter().any(|name| name.ends_with("document.swift"))); } } /// Resolve every regular file a non-following walk of `path` yields, both /// on demand and from primed parents, against full canonicalization. fn verify_walk(path: &Path) -> usize { let files: Vec = WalkBuilder::new(path) .follow_links(false) .build() .map(Result::unwrap) .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file())) .map(|entry| entry.path().to_str().unwrap().to_owned()) .collect(); verify_resolution(path, &files); files.len() } fn verify_resolution(root: &Path, files: &[String]) { let on_demand = WalkSourcePaths::new(root).unwrap(); let mut primed = WalkSourcePaths::new(root).unwrap(); primed.prime(files); for file in files { let expected = std::fs::canonicalize(file).unwrap(); assert_eq!(on_demand.resolve(file).unwrap(), expected, "{file}"); assert_eq!(primed.resolve(file).unwrap(), expected, "primed {file}"); } } #[test] fn primed_parents_resolve_through_a_directory_that_became_a_symlink() { let temp = tempfile::tempdir().unwrap(); let real = temp.path().join("real"); std::fs::create_dir_all(real.join("moved/deeper")).unwrap(); std::fs::write(real.join("moved/deeper/a.md"), "a").unwrap(); std::fs::write(real.join("moved/b.md"), "b").unwrap(); symlink(real.join("moved"), real.join("walked")).unwrap(); // The walk saw `walked` as a directory; it is a symlink by the time the // selection resolves, so neither it nor anything under it is derived. let files = [ real.join("walked/deeper/a.md").to_str().unwrap().to_owned(), real.join("walked/b.md").to_str().unwrap().to_owned(), real.join("moved/b.md").to_str().unwrap().to_owned(), ]; verify_resolution(&real, &files); } #[test] fn walk_source_matches_canonicalization_for_regular_descendants_and_symlink_roots() { let temp = tempfile::tempdir().unwrap(); let real = temp.path().join("real"); std::fs::create_dir_all(real.join("nested/é🦀")).unwrap(); std::fs::write(real.join("a.md"), "a").unwrap(); std::fs::write(real.join("nested/é🦀/b.md"), "b").unwrap(); symlink(real.join("a.md"), real.join("alias.md")).unwrap(); symlink(real.join("nested"), real.join("directory-alias")).unwrap(); symlink(&real, real.join("loop")).unwrap(); symlink(temp.path().join("missing"), real.join("broken.md")).unwrap(); let alias = temp.path().join("root-alias"); symlink(&real, &alias).unwrap(); assert_eq!(verify_walk(&real), 2); assert_eq!(verify_walk(&alias), 2); assert_eq!(verify_walk(&alias.join("nested/..")), 2); assert!(WalkSourcePaths::new(&real.join("a.md")).is_none()); let paths = WalkSourcePaths::new(&real).unwrap(); assert!(paths.resolve(real.join("alias.md").to_str().unwrap()).is_none()); assert!(paths.resolve(real.join("absent.md").to_str().unwrap()).is_none()); } #[test] fn walk_source_handles_cwd_spellings_and_declines_parent_or_unrelated_paths() { let root = WalkSourcePaths::new(Path::new(".")).unwrap(); for file in ["Cargo.toml", "./Cargo.toml", "src/main.rs", "./src/main.rs"] { assert_eq!(root.resolve(file).unwrap(), std::fs::canonicalize(file).unwrap()); } assert!(root.resolve("../outside.md").is_none()); assert!(root.resolve("src/../Cargo.toml").is_none()); assert!(root.resolve(".").is_none()); } }