Skip to main content

rumdl_lib/
discovery.rs

1//! Shared markdown file discovery semantics.
2//!
3//! The CLI walker (`file_processor::discovery` in the binary crate) and the
4//! LSP workspace index scanner answer the same question: which files does
5//! rumdl process here? The pieces of that answer that must never diverge
6//! live in this module:
7//!
8//! - the markdown extension set and how it is matched,
9//! - the final source-kind gate for each adapter's capabilities,
10//! - how ignore-file handling (`.gitignore`, `.markdownlintignore`, hidden
11//!   entries) is configured on a walker,
12//! - how `exclude` patterns from config are expanded and matched.
13//!
14//! Callers still differ deliberately: the LSP skips `.git`/`node_modules`/
15//! `target` outright as an editor-performance safety net, while the CLI
16//! walks whatever gitignore semantics allow.
17
18use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
19use std::borrow::Cow;
20use std::ffi::OsStr;
21use std::path::{Path, PathBuf};
22
23/// Glob metacharacters recognized when deciding whether an include pattern
24/// names files explicitly.
25const GLOB_METACHARS: &[char] = &['*', '?', '[', ']', '{', '}'];
26
27/// The file-name glob of an `include` pattern that explicitly names files,
28/// if it does.
29///
30/// A pattern names files explicitly when its final path component pins a
31/// literal dotted suffix: a wildcard stem ending in a literal extension
32/// chain (`**/*.md.jinja` yields `*.md.jinja`) or a fully literal file name
33/// with an extension (`templates/NOTES.tmpl` yields `NOTES.tmpl`). Such
34/// patterns widen the lintable-file filter beyond the standard markdown
35/// extensions: the user has spelled out exactly which files to process.
36///
37/// Directory patterns (`docs/`, `docs/**`), bare wildcards (`*`, `**/*`),
38/// patterns whose extension itself contains wildcards (`*.md*`,
39/// `*.{md,jinja}`), and negations (`!drafts/*.md.jinja`) yield `None`; they
40/// express "look here" or "not this", not "this exact kind of file", so the
41/// markdown-only filter stays in force for them.
42pub fn explicit_file_name_glob(pattern: &str) -> Option<&str> {
43    if pattern.starts_with('!') {
44        return None;
45    }
46    let file_name = pattern.rsplit('/').next().unwrap_or(pattern);
47    if file_name.is_empty() {
48        return None;
49    }
50    // The literal tail after the last glob metacharacter (the whole
51    // component when there is none) must end in a non-empty extension.
52    let literal_tail = match file_name.rfind(GLOB_METACHARS) {
53        Some(idx) => &file_name[idx + 1..],
54        None => file_name,
55    };
56    match literal_tail.rsplit_once('.') {
57        Some((_, ext)) if !ext.is_empty() => Some(file_name),
58        _ => None,
59    }
60}
61
62/// Compiled matchers for the explicitly-named files in a set of config
63/// `include` patterns (see [`explicit_file_name_glob`]).
64///
65/// The CLI walker consults this in two places that otherwise restrict
66/// discovery to markdown extensions: the walker's file-type filter and the
67/// final lintable-file filter. The type filter can only match file names,
68/// so it uses the (over-inclusive) file-name globs; the final filter is
69/// the precise gate and matches the full pattern against the root-relative
70/// path. Without the path check, a broad sibling pattern like `docs/**`
71/// would inherit the non-standard-extension allowance of an explicit
72/// pattern like `templates/NOTES.tmpl` for every file sharing its name.
73///
74/// Path matching follows gitignore anchoring: patterns without a `/` match
75/// at any depth, patterns with one are anchored to the root the relative
76/// path was computed against. `*` does not cross directory separators.
77///
78/// Invalid globs are skipped silently; the caller's override handling
79/// already warns about unparseable include patterns.
80pub struct ExplicitIncludeMatchers {
81    matchers: Vec<ExplicitInclude>,
82}
83
84struct ExplicitInclude {
85    file_name_glob: String,
86    path_matcher: GlobMatcher,
87}
88
89impl ExplicitIncludeMatchers {
90    pub fn new(patterns: &[String]) -> Self {
91        let matchers = patterns
92            .iter()
93            .filter_map(|pattern| {
94                let file_name_glob = explicit_file_name_glob(pattern)?;
95                let path_glob = if let Some(anchored) = pattern.strip_prefix('/') {
96                    anchored.to_string()
97                } else if pattern.contains('/') {
98                    pattern.clone()
99                } else {
100                    format!("**/{pattern}")
101                };
102                let path_matcher = globset::GlobBuilder::new(&path_glob)
103                    .literal_separator(true)
104                    .build()
105                    .ok()?
106                    .compile_matcher();
107                Some(ExplicitInclude {
108                    file_name_glob: file_name_glob.to_string(),
109                    path_matcher,
110                })
111            })
112            .collect();
113        Self { matchers }
114    }
115
116    pub fn is_empty(&self) -> bool {
117        self.matchers.is_empty()
118    }
119
120    /// The file-name globs, e.g. for registering on a walker type filter.
121    pub fn file_name_globs(&self) -> impl Iterator<Item = &str> {
122        self.matchers.iter().map(|m| m.file_name_glob.as_str())
123    }
124
125    /// Whether the root-relative `path` matches any explicit include
126    /// pattern in full.
127    pub fn matches_relative_path(&self, path: &str) -> bool {
128        self.matchers.iter().any(|m| m.path_matcher.is_match(path))
129    }
130}
131
132/// Source kinds an adapter can interpret after a path passes include matching.
133///
134/// The CLI can extract Markdown from Rust doc comments, while the language
135/// server indexes complete Markdown documents and must not parse a Rust source
136/// file as if the whole file were Markdown. A CLI `--include` is stronger still:
137/// it explicitly asks rumdl to process whatever the pattern selects.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum LintableFileMode {
140    Markdown,
141    MarkdownAndRust,
142    Any,
143}
144
145/// The shared final gate for files yielded by CLI and LSP discovery walks.
146///
147/// Include overrides decide *where* to look. This selector decides whether a
148/// matching file is a source the adapter can interpret. Explicit config
149/// includes can name template-like Markdown files beyond the standard
150/// extensions; Rust remains capability-gated even when explicitly named.
151pub struct LintablePathSelector {
152    base: Option<PathBuf>,
153    explicit: ExplicitIncludeMatchers,
154    mode: LintableFileMode,
155}
156
157impl LintablePathSelector {
158    pub fn new(base: Option<&Path>, includes: &[String], mode: LintableFileMode) -> Self {
159        Self {
160            base: base.map(Path::to_path_buf),
161            explicit: ExplicitIncludeMatchers::new(includes),
162            mode,
163        }
164    }
165
166    /// Whether an included path is a source this adapter can interpret.
167    pub fn keeps(&self, path: &Path) -> bool {
168        if self.mode == LintableFileMode::Any {
169            return true;
170        }
171        if has_markdown_extension(path) {
172            return true;
173        }
174
175        // Rust doc-comment extraction currently dispatches on lowercase `.rs`.
176        // Keep this capability gate identical to the downstream processor.
177        let is_rust = path.extension().and_then(OsStr::to_str) == Some("rs");
178        if is_rust {
179            return self.mode == LintableFileMode::MarkdownAndRust;
180        }
181
182        match self.base.as_deref().and_then(|base| path_relative_to(path, base)) {
183            Some(relative) => self.explicit.matches_relative_path(&relative),
184            // Outside the pattern base only unanchored patterns can still apply;
185            // matching the full path covers those.
186            None => self.explicit.matches_relative_path(&path.to_string_lossy()),
187        }
188    }
189
190    /// Apply the corresponding coarse file-type filter to a discovery walk.
191    /// [`Self::keeps`] remains the precise final gate because type filters only
192    /// see file names, not root-relative include paths.
193    pub fn configure_types(&self, builder: &mut ignore::WalkBuilder) -> Result<(), ignore::Error> {
194        if self.mode == LintableFileMode::Any {
195            return Ok(());
196        }
197
198        let mut types = ignore::types::TypesBuilder::new();
199        types.add_defaults();
200        for extension in MARKDOWN_EXTENSIONS {
201            types.add("markdown", &any_case_extension_glob(extension))?;
202        }
203        types.select("markdown");
204        if self.mode == LintableFileMode::MarkdownAndRust {
205            types.add("rustdoc", "*.rs")?;
206            types.select("rustdoc");
207        }
208        for glob in self.explicit.file_name_globs() {
209            types.add("configinclude", glob)?;
210        }
211        if !self.explicit.is_empty() {
212            types.select("configinclude");
213        }
214        builder.types(types.build()?);
215        Ok(())
216    }
217}
218
219/// File extensions rumdl treats as markdown, lowercase.
220pub const MARKDOWN_EXTENSIONS: &[&str] = &["md", "markdown", "mdx", "mkd", "mkdn", "mdown", "mdwn", "qmd", "rmd"];
221
222/// Whether `ext` is a markdown extension. Matches case-insensitively so
223/// conventional variants like `Rmd` (and shouting-case `MD`) qualify.
224#[inline]
225pub fn is_markdown_extension(ext: &OsStr) -> bool {
226    ext.to_str()
227        .is_some_and(|s| MARKDOWN_EXTENSIONS.iter().any(|known| s.eq_ignore_ascii_case(known)))
228}
229
230/// Whether `path` has a markdown extension.
231#[inline]
232pub fn has_markdown_extension(path: &Path) -> bool {
233    path.extension().is_some_and(is_markdown_extension)
234}
235
236/// A glob selecting `ext` in any letter case, as `*.[mM][dD]` for `md`.
237///
238/// Walk type globs match case-sensitively, so a plain `*.md` hides `README.MD`
239/// from a directory scan even though [`is_markdown_extension`] calls it
240/// markdown and naming the file on the command line lints it. Deriving the glob
241/// from the same extension keeps the walk's filter from being narrower than the
242/// definition it stands in for.
243pub fn any_case_extension_glob(ext: &str) -> String {
244    let mut glob = String::with_capacity(2 + ext.len() * 4);
245    glob.push_str("*.");
246    for ch in ext.chars() {
247        if ch.is_ascii_alphabetic() {
248            glob.push('[');
249            glob.push(ch.to_ascii_lowercase());
250            glob.push(ch.to_ascii_uppercase());
251            glob.push(']');
252        } else {
253            glob.push(ch);
254        }
255    }
256    glob
257}
258
259/// The linter-specific ignore file, read on every directory walk.
260pub const MARKDOWNLINTIGNORE: &str = ".markdownlintignore";
261
262/// Ignore-handling options applied to a markdown discovery walk.
263#[derive(Debug, Clone)]
264pub struct MarkdownWalkOptions {
265    /// Honor `.gitignore`, `.ignore`, global gitignore, `.git/info/exclude`,
266    /// and parent ignore files. Driven by `global.respect_gitignore`.
267    pub respect_gitignore: bool,
268    /// Skip `.git`, `node_modules`, and `target` directories outright, even
269    /// when gitignore handling is disabled or would not cover them.
270    pub skip_vendor_dirs: bool,
271}
272
273impl Default for MarkdownWalkOptions {
274    fn default() -> Self {
275        Self {
276            respect_gitignore: true,
277            skip_vendor_dirs: false,
278        }
279    }
280}
281
282/// Whether a walk over `roots` stops reading gitignores at the repository root.
283///
284/// Git reads no `.gitignore` above the repository root, so a walk that does hides
285/// files `git check-ignore` reports as visible. Worse, such a file can hide a
286/// whole directory, and a pruned directory is never descended into, so no include
287/// pattern gets the chance to name anything inside it.
288///
289/// Outside a repository there is no root to stop at, and ignore files are all a
290/// walk has to go on, so there they keep applying upward. One walk has one
291/// setting for all of its roots, so the boundary is only applied when every root
292/// has a repository to bound it.
293pub fn stops_at_repository_root<P: AsRef<Path>>(roots: &[P]) -> bool {
294    !roots.is_empty() && roots.iter().all(|root| in_repository(root.as_ref()))
295}
296
297/// Whether `path` sits inside a git or jujutsu repository.
298///
299/// A `.git` entry is a directory in an ordinary clone and a file in a worktree or
300/// submodule, so existence alone is the marker. This recognizes a repository the
301/// same way the walker does, which is what puts the boundary in the same place.
302fn in_repository(path: &Path) -> bool {
303    let Ok(absolute) = std::fs::canonicalize(path) else {
304        return false;
305    };
306    absolute
307        .ancestors()
308        .any(|dir| dir.join(".git").exists() || dir.join(".jj").exists())
309}
310
311/// Apply the shared ignore-handling configuration to a walker over `roots`.
312///
313/// Hidden entries are always walked (a hidden `docs/.pages.md` lints the
314/// same as a visible one); generated content is kept out by gitignore
315/// semantics and, for callers that opt in, the vendor-directory skip.
316/// `.markdownlintignore` is honored for markdownlint compatibility, whatever
317/// `respect_gitignore` says: markdownlint-cli applies it independently of any
318/// gitignore handling, and it is a list written for the linter alone, so
319/// turning off git's ignore files is not a request to lint what it names.
320///
321/// The roots decide where gitignore reading stops, so a caller passes the same
322/// ones it walks.
323pub fn apply_markdown_walk_options<P: AsRef<Path>>(
324    builder: &mut ignore::WalkBuilder,
325    roots: &[P],
326    options: &MarkdownWalkOptions,
327) {
328    apply_walk_options_with_markdownlintignore(builder, roots, options, true);
329}
330
331/// [`apply_markdown_walk_options`], with `.markdownlintignore` switchable.
332///
333/// Only an explanation of an empty run turns it off, to find out which ignore
334/// source hid a file. A walk deciding what to lint always reads it.
335pub fn apply_walk_options_with_markdownlintignore<P: AsRef<Path>>(
336    builder: &mut ignore::WalkBuilder,
337    roots: &[P],
338    options: &MarkdownWalkOptions,
339    markdownlintignore: bool,
340) {
341    let gitignore = options.respect_gitignore;
342    builder
343        .ignore(gitignore)
344        .git_ignore(gitignore)
345        .git_global(gitignore)
346        .git_exclude(gitignore)
347        // Parent directories are read for every walk: each source toggle above
348        // still decides what they contribute, so with the gitignore family off
349        // a parent `.markdownlintignore` is the only file read from them.
350        .parents(true)
351        .hidden(false)
352        // This setting does double duty in the walker: it gates gitignore
353        // handling on a repository being present, and it is what stops the walk
354        // reading gitignores above the repository root. Inside a repository both
355        // are wanted. Outside one, requiring a repository would drop `.gitignore`
356        // handling entirely, and there is no root to stop at in any case.
357        .require_git(stops_at_repository_root(roots));
358    if markdownlintignore {
359        builder.add_custom_ignore_filename(MARKDOWNLINTIGNORE);
360    }
361
362    if options.skip_vendor_dirs {
363        let roots: Vec<PathBuf> = roots.iter().map(|root| root.as_ref().to_path_buf()).collect();
364        builder.filter_entry(move |entry| {
365            if roots.iter().any(|root| root == entry.path()) {
366                return true;
367            }
368            let name = entry.file_name().to_str().unwrap_or("");
369            name != ".git" && name != "node_modules" && name != "target"
370        });
371    }
372}
373
374/// Build a walker over `root` configured with the shared options.
375pub fn markdown_walk_builder(root: &Path, options: &MarkdownWalkOptions) -> ignore::WalkBuilder {
376    let mut builder = ignore::WalkBuilder::new(root);
377    apply_markdown_walk_options(&mut builder, &[root], options);
378    builder
379}
380
381/// A complete, configured Markdown workspace scan.
382///
383/// This owns the selection policy shared by full scans and incremental file
384/// events: standard Markdown extensions, explicit nonstandard file includes,
385/// include filtering, excludes, ignore files, and optional vendor-directory
386/// pruning. Adapters choose the options; they do not reconstruct the policy.
387pub struct MarkdownWorkspaceScan<'a> {
388    options: &'a MarkdownWalkOptions,
389    includes: &'a [String],
390    excludes: &'a ExcludeMatchers,
391}
392
393impl<'a> MarkdownWorkspaceScan<'a> {
394    pub fn new(options: &'a MarkdownWalkOptions, includes: &'a [String], excludes: &'a ExcludeMatchers) -> Self {
395        Self {
396            options,
397            includes,
398            excludes,
399        }
400    }
401
402    /// Collect all selected files under `roots`.
403    pub fn collect(&self, roots: &[PathBuf]) -> Vec<PathBuf> {
404        let mut files = Vec::new();
405        for root in roots {
406            let selection = RootSelection::new(root, self.includes);
407            let mut builder = markdown_walk_builder(root, self.options);
408            selection.configure_walk(&mut builder);
409
410            for result in builder.build() {
411                match result {
412                    Ok(entry)
413                        if entry.file_type().is_some_and(|file_type| file_type.is_file())
414                            && selection.is_lintable(entry.path())
415                            && !self.excluded(root, entry.path()) =>
416                    {
417                        files.push(entry.into_path());
418                    }
419                    Ok(_) => {}
420                    Err(error) => log::warn!("Error scanning {}: {error}", root.display()),
421                }
422            }
423        }
424        files.sort();
425        files.dedup();
426        files
427    }
428
429    /// Whether an incremental file event would be absent from a full scan.
430    pub fn path_is_ignored(&self, roots: &[PathBuf], path: &Path) -> bool {
431        let Some(root) = roots
432            .iter()
433            .filter(|root| path.starts_with(root))
434            .max_by_key(|root| root.components().count())
435        else {
436            return false;
437        };
438
439        let selection = RootSelection::new(root, self.includes);
440        if !selection.selects(path) || self.excluded(root, path) {
441            return true;
442        }
443
444        if self.options.skip_vendor_dirs
445            && let Ok(relative) = path.strip_prefix(root)
446            && relative.components().any(|component| {
447                matches!(component, std::path::Component::Normal(name) if name == ".git" || name == "node_modules" || name == "target")
448            })
449        {
450            return true;
451        }
452
453        let target = path.to_path_buf();
454        let mut builder = markdown_walk_builder(root, self.options);
455        selection.configure_walk(&mut builder);
456        // `filter_entry` replaces the vendor filter, which was checked above.
457        builder.filter_entry(move |entry| target.starts_with(entry.path()));
458        !builder.build().flatten().any(|entry| entry.path() == path)
459    }
460
461    fn excluded(&self, root: &Path, path: &Path) -> bool {
462        self.excludes
463            .excludes_file(path_relative_to(path, root).as_deref(), path)
464    }
465}
466
467struct RootSelection {
468    lintable: LintablePathSelector,
469    overrides: Option<ignore::overrides::Override>,
470}
471
472impl RootSelection {
473    fn new(root: &Path, includes: &[String]) -> Self {
474        let normalized: Vec<String> = includes
475            .iter()
476            .map(|pattern| normalize_pattern_for_base(pattern, Some(root)))
477            .collect();
478        let overrides = if normalized.is_empty() {
479            None
480        } else {
481            let mut builder = ignore::overrides::OverrideBuilder::new(root);
482            for pattern in &normalized {
483                if let Err(error) = builder.add(pattern) {
484                    log::warn!("Invalid include pattern '{pattern}': {error}");
485                }
486            }
487            builder.build().ok()
488        };
489        Self {
490            lintable: LintablePathSelector::new(Some(root), &normalized, LintableFileMode::Markdown),
491            overrides,
492        }
493    }
494
495    fn configure_walk(&self, builder: &mut ignore::WalkBuilder) {
496        if let Err(error) = self.lintable.configure_types(builder) {
497            log::warn!("Failed to configure workspace source types: {error}");
498        }
499        if let Some(overrides) = &self.overrides {
500            builder.overrides(overrides.clone());
501        }
502    }
503
504    fn selects(&self, path: &Path) -> bool {
505        self.overrides
506            .as_ref()
507            .is_none_or(|overrides| overrides.matched(path, false).is_whitelist())
508            && self.is_lintable(path)
509    }
510
511    fn is_lintable(&self, path: &Path) -> bool {
512        self.lintable.keeps(path)
513    }
514}
515
516/// Drop Windows' verbatim `\\?\` prefix from a canonicalized path string.
517///
518/// `std::fs::canonicalize` returns the verbatim form (`\\?\C:\Users\dev`) on
519/// Windows. That form is useless for pattern matching: it does not compare
520/// equal to the ordinary paths rumdl works with, and normalizing its
521/// separators for globbing mangles it into `//?/C:/Users/dev`, which matches
522/// nothing. Only a drive path (`\\?\C:\...`) and a UNC share
523/// (`\\?\UNC\server\share` -> `\\server\share`) are unwrapped; any other
524/// verbatim path names a device namespace that has no ordinary equivalent, so
525/// it is left alone.
526///
527/// The prefix is recognized in whichever separator the path is written with:
528/// `\\?\` as `canonicalize` returns it, or `//?/` once the separators have
529/// been normalized. Displayed paths are stripped by the CLI's display layer;
530/// output formatters strip again because a path can reach them unchanged.
531///
532/// Pure string logic, compiled on every platform so it stays under test where
533/// Windows is not available. On other platforms no path ever carries this
534/// prefix.
535pub fn strip_verbatim_prefix(path: &str) -> Cow<'_, str> {
536    let Some(sep) = path.chars().next().filter(|c| matches!(c, '\\' | '/')) else {
537        return Cow::Borrowed(path);
538    };
539    let Some(rest) = path.strip_prefix(&format!("{sep}{sep}?{sep}")) else {
540        return Cow::Borrowed(path);
541    };
542    // `\\?\UNC\server\share` -> `\\server\share`. The remainder already starts
543    // with one separator, so restoring the UNC form needs one more prepended.
544    if let Some(share) = rest.strip_prefix("UNC")
545        && share.starts_with(sep)
546    {
547        return Cow::Owned(format!("{sep}{share}"));
548    }
549    let is_drive_path = rest.as_bytes().get(1) == Some(&b':');
550    if is_drive_path {
551        Cow::Borrowed(rest)
552    } else {
553        Cow::Borrowed(path)
554    }
555}
556
557/// Canonicalize `path` for pattern matching, or `None` when it cannot be
558/// resolved (a missing or unreadable file).
559///
560/// Canonical form is what patterns are matched against, so a symlinked
561/// location (`/home/dev` -> `/mnt/dev`, or a macOS `/var` -> `/private/var`)
562/// still matches. Windows' verbatim prefix is removed (see
563/// [`strip_verbatim_prefix`]).
564pub fn canonicalize_for_matching(path: &Path) -> Option<PathBuf> {
565    let canonical = path.canonicalize().ok()?;
566    if !cfg!(windows) {
567        return Some(canonical);
568    }
569    let as_str = canonical.to_string_lossy();
570    Some(PathBuf::from(strip_verbatim_prefix(&as_str).as_ref()))
571}
572
573/// Resolve `path` to the absolute form patterns are matched against, whether or
574/// not anything exists there.
575///
576/// A path that exists resolves exactly as [`canonicalize_for_matching`] resolves
577/// it. One that does not (an unsaved editor buffer, a file not written yet) is
578/// resolved through its deepest existing ancestor: that ancestor is
579/// canonicalized and the missing remainder appended, with its `.` and `..`
580/// resolved lexically, so the file is spelled the way it will canonicalize once
581/// it exists. A relative path is taken relative to the working directory, which
582/// is how the filesystem reads it.
583pub fn resolve_for_matching(path: &Path) -> PathBuf {
584    if let Some(canonical) = canonicalize_for_matching(path) {
585        return canonical;
586    }
587    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
588    let resolved = resolve_through_existing_ancestor(&absolute);
589    // A `..` in the missing remainder can climb back into directories that
590    // exist, and one of those may be a symlink. The lexical result holds no
591    // `..` any more, so resolving it once more settles it.
592    if absolute.components().any(|c| c == std::path::Component::ParentDir) {
593        resolve_through_existing_ancestor(&resolved)
594    } else {
595        resolved
596    }
597}
598
599/// Canonicalize the deepest ancestor of `absolute` that exists and append the
600/// rest of the path to it lexically (see [`resolve_for_matching`]).
601fn resolve_through_existing_ancestor(absolute: &Path) -> PathBuf {
602    for ancestor in absolute.ancestors() {
603        if let Some(canonical) = canonicalize_for_matching(ancestor) {
604            let remainder = absolute.strip_prefix(ancestor).unwrap_or(Path::new(""));
605            if remainder.as_os_str().is_empty() {
606                return canonical;
607            }
608            return crate::workspace_index::normalize_relative_path(&canonical.join(remainder));
609        }
610    }
611    crate::workspace_index::normalize_relative_path(absolute)
612}
613
614/// The user's home directory, or `None` when it cannot be resolved.
615///
616/// Canonicalized for matching (see [`canonicalize_for_matching`]), falling
617/// back to the path as reported when it cannot be canonicalized.
618///
619/// Wasm and WASI builds have no home directory to resolve, so patterns keep
620/// their `~` there (see [`expand_home_prefix`]).
621fn home_dir() -> Option<PathBuf> {
622    #[cfg(feature = "native")]
623    {
624        use etcetera::{BaseStrategy, choose_base_strategy};
625        choose_base_strategy()
626            .ok()
627            .map(|s| canonicalize_for_matching(s.home_dir()).unwrap_or_else(|| s.home_dir().to_path_buf()))
628    }
629    #[cfg(not(feature = "native"))]
630    {
631        None
632    }
633}
634
635/// Expand a leading `~` in a path pattern to the user's home directory, so a
636/// user-level config (`~/.config/rumdl/rumdl.toml`) can name a home path
637/// without hardcoding a username.
638///
639/// Only a bare `~` and a `~/` prefix expand. `~` is a legal filename character
640/// everywhere else (editor backups like `notes.md~`, a literal `docs/~drafts`),
641/// so it is left alone there. `~user` is not expanded either: resolving another
642/// user's home needs the password database, and treating it as the current
643/// user's home would silently match the wrong directory.
644///
645/// The expansion is a glob pattern, so separators are normalized to `/` on
646/// Windows: `\` is globset's escape character, and matched paths are normalized
647/// the same way (see [`path_relative_to`]).
648pub fn expand_home_prefix(pattern: &str) -> Cow<'_, str> {
649    // Resolve the home directory only for a pattern that references it: every
650    // other pattern would otherwise pay for the lookup and its canonicalization.
651    if !has_home_prefix(pattern) {
652        return Cow::Borrowed(pattern);
653    }
654    expand_home_prefix_impl(pattern, home_dir().as_deref())
655}
656
657/// Whether `pattern` starts with a home reference (`~` or `~/`).
658fn has_home_prefix(pattern: &str) -> bool {
659    pattern == "~" || pattern.starts_with("~/")
660}
661
662fn expand_home_prefix_impl<'a>(pattern: &'a str, home: Option<&Path>) -> Cow<'a, str> {
663    let Some(suffix) = (if pattern == "~" {
664        Some("")
665    } else {
666        pattern.strip_prefix("~/")
667    }) else {
668        return Cow::Borrowed(pattern);
669    };
670    let Some(home) = home else {
671        return Cow::Borrowed(pattern);
672    };
673
674    let home = normalize_pattern_separators(home.to_string_lossy());
675    let home = home.trim_end_matches('/');
676    if suffix.is_empty() {
677        Cow::Owned(home.to_string())
678    } else {
679        Cow::Owned(format!("{home}/{suffix}"))
680    }
681}
682
683/// Normalize path separators to `/` for glob matching. On Windows `\` is
684/// globset's escape character, so a native path must be rewritten before it can
685/// be used as - or matched against - a pattern. No-op on Unix, where `\` is a
686/// legal filename character.
687fn normalize_pattern_separators(path: Cow<'_, str>) -> Cow<'_, str> {
688    if cfg!(windows) && path.contains('\\') {
689        Cow::Owned(path.replace('\\', "/"))
690    } else {
691        path
692    }
693}
694
695/// Normalize a config path pattern for matching against paths discovered under
696/// `base`: expand a leading `~`, then rewrite an absolute pattern as one
697/// relative to `base` when `base` contains it.
698///
699/// The rewrite is what makes an absolute pattern usable as a walker override:
700/// the `ignore` crate reads a leading `/` as "anchored to the walk base", so
701/// `/home/dev/docs/**` would otherwise be understood as
702/// `<base>/home/dev/docs/**` and match nothing. A pattern pointing outside
703/// `base` is left absolute - nothing under this walk can match it, which is the
704/// correct outcome.
705///
706/// A pattern can also name `base`'s location through a symlink
707/// (`/var/folders/…` for a base at `/private/var/folders/…`), which no strip of
708/// `base` in either form removes. Its leading literal components are then
709/// resolved, giving the same location in the base's own spelling. Only that
710/// prefix is rewritten and the strip consumes it, so what survives is the
711/// pattern as written. A pattern whose *first* component holds a wildcard or a
712/// brace alternation has no such prefix and stays absolute.
713pub fn normalize_pattern_for_base(pattern: &str, base: Option<&Path>) -> String {
714    let expanded = expand_home_prefix(pattern);
715    let Some(base) = base else {
716        return expanded.into_owned();
717    };
718    if !is_absolute_pattern(&expanded) {
719        return expanded.into_owned();
720    }
721
722    if let Some(relative) = strip_base_prefix(Path::new(expanded.as_ref()), base) {
723        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
724    }
725    if let Some(canonical_pattern) = canonicalize_pattern_prefix(&expanded)
726        && let Some(relative) = strip_base_prefix(Path::new(&canonical_pattern), base)
727    {
728        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
729    }
730    expanded.into_owned()
731}
732
733/// `pattern` with `base` removed, trying the base as given and canonicalized so
734/// a symlinked or non-canonical base (macOS `/var`, a Windows 8.3 short name)
735/// still strips. `None` when the pattern does not live under `base`.
736fn strip_base_prefix<'a>(pattern: &'a Path, base: &Path) -> Option<&'a Path> {
737    pattern.strip_prefix(base).ok().or_else(|| {
738        let canonical = canonicalize_for_matching(base)?;
739        pattern.strip_prefix(canonical).ok()
740    })
741}
742
743/// Expands directory-style patterns to also match files within them.
744/// Pattern "dir/path" becomes ["dir/path", "dir/path/**"] to match both
745/// the directory itself and all contents recursively. A leading `~` is
746/// expanded first (see [`expand_home_prefix`]).
747///
748/// The expansion is driven by the pattern's *final* component: it names a
749/// directory only when it holds no wildcard. `docs/*` therefore stays as
750/// written (it names direct children, and `docs/*/**` would newly exclude
751/// nested contents), while `**/.cursor/plans` gains its contents-expansion
752/// despite the wildcard earlier in the pattern.
753pub fn expand_directory_pattern(pattern: &str) -> Vec<String> {
754    let pattern = expand_home_prefix(pattern);
755    let base = pattern.trim_end_matches('/');
756    let final_component = base.rsplit('/').next().unwrap_or(base);
757
758    if final_component.is_empty() || final_component.contains(['*', '?', '[']) {
759        return vec![pattern.to_string()];
760    }
761
762    vec![
763        base.to_string(),     // Match the directory itself
764        format!("{base}/**"), // Match everything underneath
765    ]
766}
767
768/// The `ignore` override rule that excludes `pattern`.
769///
770/// The crate spells exclusion with a leading `!`; a pattern already carrying one
771/// passes through.
772pub fn exclude_override_rule(pattern: &str) -> String {
773    if pattern.starts_with('!') {
774        pattern.to_string()
775    } else {
776        format!("!{pattern}")
777    }
778}
779
780/// Whether every glob an `exclude` pattern turns into compiles.
781///
782/// An exclude pattern reaches two consumers: [`ExcludeMatchers`] compiles each
783/// expansion with `globset`, and the walker adds each as an `ignore` override.
784/// Both are mirrored here so a caller holding only the pattern can tell whether
785/// either would reject it, which is also when either would print it.
786pub fn exclude_pattern_compiles(pattern: &str) -> bool {
787    expand_directory_pattern(pattern).iter().all(|expanded| {
788        exclude_glob(expanded).is_ok()
789            && ignore::overrides::OverrideBuilder::new(Path::new("."))
790                .add(&exclude_override_rule(expanded))
791                .is_ok()
792    })
793}
794
795/// Whether an `include` pattern compiles as a walker override.
796///
797/// Answers for the pattern as given, which is only the form the walker uses once
798/// [`normalize_pattern_for_base`] has run: stripping a base prefix removes
799/// whatever the base's own name held, and an absolute pattern under a directory
800/// called `notes [2019-2021]` carries a character class over a descending range
801/// until the prefix comes off. Ask this about the pattern the walker is about to
802/// add, never about the one a config file spelled.
803pub fn include_pattern_compiles(pattern: &str) -> bool {
804    ignore::overrides::OverrideBuilder::new(Path::new("."))
805        .add(&expand_home_prefix(pattern))
806        .is_ok()
807}
808
809/// The globs matching everything one expanded exclude pattern removes: the
810/// pattern itself, the contents of a directory it matches when `with_contents`,
811/// and each of those at any depth when the pattern `floats` (see
812/// [`ExcludeMatchers::new`]).
813fn exclusion_globs(pattern: &str, with_contents: bool, floats: bool) -> Result<GlobSet, globset::Error> {
814    let mut located = vec![pattern.to_string()];
815    if with_contents && !pattern.ends_with("/**") {
816        located.push(format!("{}/**", pattern.trim_end_matches('/')));
817    }
818    if floats {
819        let anywhere: Vec<String> = located.iter().map(|glob| format!("**/{glob}")).collect();
820        located.extend(anywhere);
821    }
822    let mut builder = GlobSetBuilder::new();
823    for glob in &located {
824        builder.add(exclude_glob(glob)?);
825    }
826    builder.build()
827}
828
829/// One exclude glob, compiled the way `.gitignore` reads it: `*` and `?` match
830/// within one path component, and only `**` spans a `/`.
831fn exclude_glob(glob: &str) -> Result<Glob, globset::Error> {
832    GlobBuilder::new(glob).literal_separator(true).build()
833}
834
835/// One expanded `exclude` pattern and the globs matching what it excludes.
836struct ExcludeMatcher {
837    pattern: String,
838    globs: GlobSet,
839    /// Whether any spelling of the pattern is absolute, which is what makes a
840    /// file's absolute path worth matching against it.
841    absolute: bool,
842}
843
844/// Compiled `exclude` patterns with directory-pattern expansion applied.
845///
846/// Match paths through [`matched_pattern`](Self::matched_pattern) using a
847/// root-relative path (the CLI relativizes against the project root, the
848/// LSP against the containing workspace root) so patterns like
849/// `docs/drafts` behave identically everywhere.
850pub struct ExcludeMatchers {
851    /// Each expanded pattern (see [`ExcludeMatchers::new`]).
852    matchers: Vec<ExcludeMatcher>,
853    /// Spellings of a file the absolute patterns reach through a symlink.
854    aliases: PathAliases,
855    /// Patterns that failed to compile, with their errors. Callers decide
856    /// how to surface these (CLI prints to stderr, LSP logs).
857    pub invalid: Vec<(String, String)>,
858}
859
860/// Whether `pattern` names an absolute location. A leading `/` counts on every
861/// platform: patterns use `/` separators, so a Unix-style path stays absolute
862/// when the same config is read on Windows.
863pub fn is_absolute_pattern(pattern: &str) -> bool {
864    pattern.starts_with('/') || Path::new(pattern).is_absolute()
865}
866
867/// Whether `pattern` names an absolute location in any of its spellings.
868///
869/// A brace alternation can put the absolute part past the start of the pattern
870/// (`{/opt,/srv}/docs/**`), where [`is_absolute_pattern`] cannot see it. Callers
871/// deciding whether to match a file's absolute path at all must ask this, or
872/// such a pattern is never given an absolute path to match.
873pub fn has_absolute_spelling(pattern: &str) -> bool {
874    if is_absolute_pattern(pattern) {
875        return true;
876    }
877    pattern.contains('{')
878        && expand_braces(pattern)
879            .iter()
880            .any(|spelling| is_absolute_pattern(spelling))
881}
882
883/// How many literal spellings one pattern's brace alternations may produce.
884///
885/// Expansion only *discovers* directory prefixes to canonicalize (see
886/// [`PathAliases`]); it never decides whether a pattern matches. Past this
887/// point a pattern like `{a,b}{c,d}{e,f}…` is multiplying out work that buys
888/// nothing, so the pattern is left unexpanded.
889const MAX_BRACE_EXPANSIONS: usize = 64;
890
891/// Every literal spelling of `pattern`'s brace alternations:
892/// `/{var/folders,tmp}/**` yields `/var/folders/**` and `/tmp/**`.
893///
894/// Returns just `pattern` when it holds no alternation, when its braces are
895/// unbalanced, or when expanding would exceed [`MAX_BRACE_EXPANSIONS`].
896/// Character classes are opaque, so a comma inside `[...]` stays literal.
897fn expand_braces(pattern: &str) -> Vec<String> {
898    let mut pending = vec![pattern.to_string()];
899    let mut expanded: Vec<String> = Vec::new();
900    while let Some(current) = pending.pop() {
901        let Some((prefix, alternatives, suffix)) = split_first_alternation(&current) else {
902            expanded.push(current);
903            continue;
904        };
905        if pending.len() + expanded.len() + alternatives.len() > MAX_BRACE_EXPANSIONS {
906            return vec![pattern.to_string()];
907        }
908        for alternative in alternatives {
909            pending.push(format!("{prefix}{alternative}{suffix}"));
910        }
911    }
912    expanded
913}
914
915/// Split `pattern` at its first top-level brace alternation into the text
916/// before it, its alternatives, and the text after it. `None` when there is no
917/// alternation to split on, including an unclosed `{`.
918///
919/// Empty alternatives are dropped, mirroring globset: it compiles `x{,y}` to
920/// `^x(?:y)$`, so `x` is not one of that pattern's spellings.
921fn split_first_alternation(pattern: &str) -> Option<(&str, Vec<&str>, &str)> {
922    let bytes = pattern.as_bytes();
923    let mut open = None;
924    let mut depth = 0usize;
925    let mut in_class = false;
926    let mut alternatives = Vec::new();
927    let mut alternative_start = 0;
928    let mut index = 0;
929    while index < bytes.len() {
930        match bytes[index] {
931            b'\\' if !cfg!(windows) => index += 1,
932            b'[' if !in_class => in_class = true,
933            b']' if in_class => in_class = false,
934            _ if in_class => {}
935            b'{' => {
936                depth += 1;
937                if depth == 1 {
938                    open = Some(index);
939                    alternative_start = index + 1;
940                }
941            }
942            b',' if depth == 1 => {
943                alternatives.push(&pattern[alternative_start..index]);
944                alternative_start = index + 1;
945            }
946            b'}' if depth > 0 => {
947                depth -= 1;
948                if depth == 0 {
949                    alternatives.push(&pattern[alternative_start..index]);
950                    alternatives.retain(|alternative| !alternative.is_empty());
951                    if alternatives.is_empty() {
952                        return None;
953                    }
954                    return Some((&pattern[..open?], alternatives, &pattern[index + 1..]));
955                }
956            }
957            _ => {}
958        }
959        index += 1;
960    }
961    None
962}
963
964/// The leading run of `pattern`'s path components that hold no glob
965/// metacharacter: `/var/folders/**` yields `/var/folders`, `/var/log/app*.md`
966/// yields `/var/log`, and a fully literal pattern yields itself.
967///
968/// `None` when the run is empty or names only the filesystem root, neither of
969/// which can resolve to a different location. The result is always a prefix
970/// slice of `pattern`, so the remainder can be re-attached by byte offset.
971///
972/// An escaped metacharacter (`\*` on Unix) simply ends the run early. That
973/// yields a shorter prefix, never a wrong one.
974fn literal_path_prefix(pattern: &str) -> Option<&str> {
975    let mut end = 0;
976    let mut saw_component = false;
977    for component in pattern.split('/') {
978        if component.contains(GLOB_METACHARS) {
979            break;
980        }
981        saw_component |= !component.is_empty();
982        // Skip past this component and the separator that follows it.
983        end += component.len() + 1;
984    }
985    if !saw_component {
986        return None;
987    }
988    // The loop counted a separator after the final component; the pattern only
989    // has one when the run did not reach its end. A trailing separator is
990    // dropped so the remainder re-attaches with exactly one.
991    let prefix = &pattern[..(end - 1).min(pattern.len())];
992    Some(prefix.strip_suffix('/').unwrap_or(prefix))
993}
994
995/// `pattern` with its leading literal components resolved through symlinks, or
996/// `None` when there is nothing to resolve, the prefix does not exist, or
997/// resolving changes nothing.
998fn canonicalize_pattern_prefix(pattern: &str) -> Option<String> {
999    let prefix = literal_path_prefix(pattern)?;
1000    let canonical = canonicalize_for_matching(Path::new(prefix))?;
1001    let canonical = normalize_pattern_separators(canonical.to_string_lossy()).into_owned();
1002    if canonical == prefix {
1003        return None;
1004    }
1005    Some(format!("{canonical}{}", &pattern[prefix.len()..]))
1006}
1007
1008/// Alternative spellings of a path, implied by the absolute patterns in a
1009/// configuration.
1010///
1011/// A pattern names a location the way the user wrote it (`/var/folders/**` on
1012/// macOS); the file it is matched against arrives canonicalized
1013/// (`/private/var/folders/…`), so the two never meet. Each pair recorded here
1014/// is one symlinked prefix some pattern reached a location through: the
1015/// canonical form of that pattern's leading literal components, and the
1016/// spelling the pattern used for them.
1017///
1018/// Rewriting the *path* rather than the pattern leaves globset the only
1019/// authority on what a pattern means, and cannot invent a match:
1020/// `canonicalize(as_written) == canonical` together with `path == canonical +
1021/// rest` say that `as_written + rest` names that same file. Brace alternations
1022/// are expanded only to find more prefixes to canonicalize, so an expansion
1023/// that disagrees with globset can cost a spelling, never fabricate one.
1024#[derive(Debug, Default)]
1025pub struct PathAliases {
1026    /// `(canonical prefix, the spelling a pattern used for it)`.
1027    prefixes: Vec<(PathBuf, String)>,
1028}
1029
1030impl PathAliases {
1031    /// Collect the symlinked prefixes `patterns` reach locations through.
1032    ///
1033    /// Each pattern is canonicalized once here, at cache-build time, so
1034    /// per-file matching pays no syscall.
1035    pub fn new<'a>(patterns: impl IntoIterator<Item = &'a str>) -> Self {
1036        let mut prefixes: Vec<(PathBuf, String)> = Vec::new();
1037        for pattern in patterns {
1038            let pattern = expand_home_prefix(pattern);
1039            if !has_absolute_spelling(&pattern) {
1040                continue;
1041            }
1042            for spelling in expand_braces(&pattern) {
1043                let Some(as_written) = literal_path_prefix(&spelling) else {
1044                    continue;
1045                };
1046                if !is_absolute_pattern(as_written) {
1047                    continue;
1048                }
1049                let Some(canonical) = canonicalize_for_matching(Path::new(as_written)) else {
1050                    continue;
1051                };
1052                if canonical == Path::new(as_written) {
1053                    continue;
1054                }
1055                let as_written = normalize_pattern_separators(Cow::Borrowed(as_written)).into_owned();
1056                if !prefixes.iter().any(|(c, w)| c == &canonical && w == &as_written) {
1057                    prefixes.push((canonical, as_written));
1058                }
1059            }
1060        }
1061        Self { prefixes }
1062    }
1063
1064    pub fn is_empty(&self) -> bool {
1065        self.prefixes.is_empty()
1066    }
1067
1068    /// The spellings of `path` reachable through a recorded prefix, as glob
1069    /// match candidates. Empty when no pattern reached `path`'s location
1070    /// through a symlink, which is every configuration that has none.
1071    pub fn spellings_of(&self, path: &Path) -> Vec<String> {
1072        self.prefixes
1073            .iter()
1074            .filter_map(|(canonical, as_written)| {
1075                let rest = path.strip_prefix(canonical).ok()?;
1076                if rest.as_os_str().is_empty() {
1077                    return Some(as_written.clone());
1078                }
1079                let rest = normalize_pattern_separators(rest.to_string_lossy());
1080                Some(format!("{as_written}/{rest}"))
1081            })
1082            .collect()
1083    }
1084}
1085
1086impl ExcludeMatchers {
1087    /// Compile `patterns` to exclude what the discovery walk excludes.
1088    ///
1089    /// The walk applies each pattern as an `ignore` override, which reads it the
1090    /// way `.gitignore` does, so a file named directly has to be matched by the
1091    /// same rules or it is linted where the walk skips it:
1092    ///
1093    /// - A pattern with no `/` except a trailing one matches at any depth:
1094    ///   `node_modules` excludes `packages/app/node_modules/readme.md`.
1095    /// - A pattern that matches a directory excludes everything in it, including
1096    ///   one whose final component is a wildcard: `draft?` excludes
1097    ///   `drafts/note.md`.
1098    /// - `*` and `?` match within one path component: `sub/*.md` excludes
1099    ///   `sub/top.md` but not `sub/a/b.md`.
1100    ///
1101    /// Relative patterns are otherwise anchored at the root the path is relative
1102    /// to, and an absolute pattern never floats.
1103    pub fn new(patterns: &[String]) -> Self {
1104        let mut matchers = Vec::new();
1105        let mut invalid = Vec::new();
1106        for written in patterns {
1107            let floats = !written.trim_end_matches('/').contains('/');
1108            let expansions = expand_directory_pattern(written);
1109            // A literal directory name already expanded to its own `/**` entry,
1110            // which the notice names. Only a wildcard final component is left
1111            // without one, and a directory it matches still has contents.
1112            let with_contents = expansions.len() == 1;
1113            for pattern in expansions {
1114                let absolute = has_absolute_spelling(&pattern);
1115                match exclusion_globs(&pattern, with_contents, floats && !absolute) {
1116                    Ok(globs) => matchers.push(ExcludeMatcher {
1117                        pattern,
1118                        globs,
1119                        absolute,
1120                    }),
1121                    Err(e) => invalid.push((pattern, e.to_string())),
1122                }
1123            }
1124        }
1125        let aliases = PathAliases::new(matchers.iter().map(|matcher| matcher.pattern.as_str()));
1126        Self {
1127            matchers,
1128            aliases,
1129            invalid,
1130        }
1131    }
1132
1133    pub fn is_empty(&self) -> bool {
1134        self.matchers.is_empty()
1135    }
1136
1137    /// The first pattern matching `relative_path`, if any.
1138    pub fn matched_pattern(&self, relative_path: &str) -> Option<&str> {
1139        self.matchers
1140            .iter()
1141            .find(|matcher| matcher.globs.is_match(relative_path))
1142            .map(|matcher| matcher.pattern.as_str())
1143    }
1144
1145    /// The first absolute pattern matching `absolute_path`, if any.
1146    fn matched_absolute_pattern(&self, absolute_path: &str) -> Option<&str> {
1147        self.matchers
1148            .iter()
1149            .find(|matcher| matcher.absolute && matcher.globs.is_match(absolute_path))
1150            .map(|matcher| matcher.pattern.as_str())
1151    }
1152
1153    pub fn is_match(&self, relative_path: &str) -> bool {
1154        self.matched_pattern(relative_path).is_some()
1155    }
1156
1157    /// The first pattern matching a file, if any.
1158    ///
1159    /// Both forms of the file are tried: its `relative` form (how patterns are
1160    /// normally written - relative to the project or workspace root) and its
1161    /// absolute path, which is what an absolute pattern matches. Absolute
1162    /// patterns reach config either written literally or through `~` expansion,
1163    /// and the walker's overrides cannot apply them (the `ignore` crate anchors
1164    /// a leading `/` to the walk root), so this is where they take effect.
1165    ///
1166    /// Only absolute patterns are matched against the absolute path. A relative
1167    /// pattern belongs to the root its path is relative to, and one that floats
1168    /// would otherwise match a directory above that root: `docs` would exclude
1169    /// every file of a project checked out at `/home/dev/docs/site`.
1170    ///
1171    /// `absolute` is canonicalized before matching, since an expanded `~`
1172    /// resolves to a canonical location. A file that does not exist (an unsaved
1173    /// buffer, one already deleted) is resolved through its deepest existing
1174    /// ancestor (see [`resolve_for_matching`]).
1175    ///
1176    /// The path as given is tried as well, because resolving can respell a
1177    /// location the pattern names directly: on macOS `/home` canonicalizes to
1178    /// `/System/Volumes/Data/home`, which `/home/dev/**` does not match.
1179    ///
1180    /// A pattern that named its location through a symlink (`/var/folders/**`
1181    /// for a macOS temp directory) never matches that canonical form, so the
1182    /// file's other spellings are tried too (see [`PathAliases`]).
1183    pub fn matched_pattern_for_file(&self, relative: Option<&str>, absolute: &Path) -> Option<&str> {
1184        if let Some(pattern) = relative.and_then(|rel| self.matched_pattern(rel)) {
1185            return Some(pattern);
1186        }
1187        // Resolving the path costs syscalls, which a run with only relative
1188        // patterns has no use for.
1189        if !self.matchers.iter().any(|matcher| matcher.absolute) {
1190            return None;
1191        }
1192        let resolved = resolve_for_matching(absolute);
1193        if let Some(pattern) = self.matched_absolute_pattern(&normalize_pattern_separators(resolved.to_string_lossy()))
1194        {
1195            return Some(pattern);
1196        }
1197        // A rooted path is what an absolute pattern can name: a pattern is
1198        // absolute when it starts with `/` (see `is_absolute_pattern`), and on
1199        // Windows `\home\dev` has a root without being `is_absolute`.
1200        if absolute.has_root()
1201            && resolved != absolute
1202            && let Some(pattern) =
1203                self.matched_absolute_pattern(&normalize_pattern_separators(absolute.to_string_lossy()))
1204        {
1205            return Some(pattern);
1206        }
1207        self.aliases
1208            .spellings_of(&resolved)
1209            .into_iter()
1210            .find_map(|alias| self.matched_absolute_pattern(&alias))
1211    }
1212
1213    /// Whether any pattern matches the file (see [`matched_pattern_for_file`](Self::matched_pattern_for_file)).
1214    pub fn excludes_file(&self, relative: Option<&str>, absolute: &Path) -> bool {
1215        self.matched_pattern_for_file(relative, absolute).is_some()
1216    }
1217}
1218
1219/// Relativize `path` against `base` for exclude-pattern matching,
1220/// canonicalizing both sides so symlinks (e.g. macOS `/tmp`) and Windows
1221/// path-representation differences don't defeat the prefix strip. Returns
1222/// `None` when `path` is not under `base`, or when `base` does not exist.
1223///
1224/// `path` need not exist: it is resolved through its deepest existing ancestor
1225/// (see [`resolve_for_matching`]), so a file about to be created relativizes
1226/// the way it will once it is there.
1227///
1228/// Separators are normalized to `/` on Windows, following the project
1229/// convention for path strings; globset matches either form, but log
1230/// output and assertions see one canonical shape.
1231pub fn path_relative_to(path: &Path, base: &Path) -> Option<String> {
1232    let canonical_base = canonicalize_for_matching(base)?;
1233    let resolved_path = resolve_for_matching(path);
1234    resolved_path.strip_prefix(&canonical_base).ok().map(|rel| {
1235        let rel = rel.to_string_lossy();
1236        if cfg!(windows) {
1237            rel.replace('\\', "/")
1238        } else {
1239            rel.to_string()
1240        }
1241    })
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246    use super::*;
1247    use std::fs;
1248    use tempfile::tempdir;
1249
1250    #[test]
1251    fn markdown_extensions_match_case_insensitively() {
1252        for ext in ["md", "MD", "Rmd", "rmd", "MarkDown", "qmd", "mdx"] {
1253            assert!(is_markdown_extension(OsStr::new(ext)), "{ext} should match");
1254        }
1255        for ext in ["rs", "txt", "mdq", ""] {
1256            assert!(!is_markdown_extension(OsStr::new(ext)), "{ext} should not match");
1257        }
1258        assert!(has_markdown_extension(Path::new("a/b/README.md")));
1259        assert!(has_markdown_extension(Path::new("notebook.Rmd")));
1260        assert!(!has_markdown_extension(Path::new("no_extension")));
1261        assert!(!has_markdown_extension(Path::new("lib.rs")));
1262    }
1263
1264    #[test]
1265    fn lintable_selector_makes_adapter_capabilities_explicit() {
1266        let dir = tempdir().unwrap();
1267        let root = dir.path();
1268        fs::create_dir_all(root.join("docs")).unwrap();
1269        fs::create_dir_all(root.join("templates")).unwrap();
1270        fs::create_dir_all(root.join("src")).unwrap();
1271        for relative in [
1272            "docs/guide.md",
1273            "docs/notes.txt",
1274            "templates/page.md.jinja",
1275            "src/lib.rs",
1276            "src/upper.RS",
1277        ] {
1278            fs::write(root.join(relative), "content\n").unwrap();
1279        }
1280        let includes = vec![
1281            "docs/**".to_string(),
1282            "templates/**/*.md.jinja".to_string(),
1283            "src/**/*.rs".to_string(),
1284        ];
1285
1286        let markdown = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Markdown);
1287        assert!(markdown.keeps(&root.join("docs/guide.md")));
1288        assert!(markdown.keeps(&root.join("templates/page.md.jinja")));
1289        assert!(!markdown.keeps(&root.join("docs/notes.txt")));
1290        assert!(
1291            !markdown.keeps(&root.join("src/lib.rs")),
1292            "an LSP must not parse a complete Rust source file as Markdown"
1293        );
1294
1295        let rustdoc = LintablePathSelector::new(Some(root), &includes, LintableFileMode::MarkdownAndRust);
1296        assert!(rustdoc.keeps(&root.join("src/lib.rs")));
1297        assert!(!rustdoc.keeps(&root.join("src/upper.RS")));
1298        assert!(!rustdoc.keeps(&root.join("docs/notes.txt")));
1299
1300        let unrestricted = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Any);
1301        assert!(unrestricted.keeps(&root.join("docs/notes.txt")));
1302    }
1303
1304    #[test]
1305    fn workspace_scan_rejects_explicit_rust_includes() {
1306        let dir = tempdir().unwrap();
1307        let root = dir.path().to_path_buf();
1308        fs::create_dir(root.join("src")).unwrap();
1309        fs::write(root.join("src/lib.rs"), "/// # Not a document\n").unwrap();
1310        fs::write(root.join("README.md"), "# Readme\n").unwrap();
1311
1312        let options = MarkdownWalkOptions {
1313            respect_gitignore: false,
1314            skip_vendor_dirs: true,
1315        };
1316        let includes = vec!["src/**/*.rs".to_string()];
1317        let excludes = ExcludeMatchers::new(&[]);
1318        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);
1319
1320        assert!(scan.collect(std::slice::from_ref(&root)).is_empty());
1321        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("src/lib.rs")));
1322    }
1323
1324    #[test]
1325    fn workspace_scan_applies_includes_to_standard_and_explicit_files() {
1326        let dir = tempdir().unwrap();
1327        let root = dir.path().to_path_buf();
1328        fs::create_dir(root.join("docs")).unwrap();
1329        fs::create_dir(root.join("templates")).unwrap();
1330        fs::write(root.join("README.md"), "# Root\n").unwrap();
1331        fs::write(root.join("docs/guide.md"), "# Guide\n").unwrap();
1332        fs::write(root.join("templates/page.md.jinja"), "# Template\n").unwrap();
1333        fs::write(root.join("templates/page.txt"), "not markdown\n").unwrap();
1334
1335        let options = MarkdownWalkOptions {
1336            respect_gitignore: false,
1337            skip_vendor_dirs: true,
1338        };
1339        let includes = vec!["docs/**".to_string(), "templates/**/*.md.jinja".to_string()];
1340        let excludes = ExcludeMatchers::new(&[]);
1341        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);
1342
1343        // The test creates these names itself, so normalizing separators
1344        // unconditionally is safe and keeps one expected value for every platform.
1345        let names: Vec<String> = scan
1346            .collect(std::slice::from_ref(&root))
1347            .iter()
1348            .map(|path| path.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"))
1349            .collect();
1350        assert_eq!(names, vec!["docs/guide.md", "templates/page.md.jinja"]);
1351
1352        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.md.jinja")));
1353        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
1354        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.txt")));
1355    }
1356
1357    #[test]
1358    fn workspace_scan_does_not_prune_a_vendor_named_root() {
1359        let dir = tempdir().unwrap();
1360        let root = dir.path().join("target");
1361        fs::create_dir(&root).unwrap();
1362        fs::write(root.join("README.md"), "# Root\n").unwrap();
1363        fs::create_dir(root.join("target")).unwrap();
1364        fs::write(root.join("target/generated.md"), "# Generated\n").unwrap();
1365
1366        let options = MarkdownWalkOptions {
1367            respect_gitignore: false,
1368            skip_vendor_dirs: true,
1369        };
1370        let excludes = ExcludeMatchers::new(&[]);
1371        let scan = MarkdownWorkspaceScan::new(&options, &[], &excludes);
1372
1373        assert_eq!(scan.collect(std::slice::from_ref(&root)), vec![root.join("README.md")]);
1374        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
1375        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("target/generated.md")));
1376    }
1377
1378    #[test]
1379    fn the_type_glob_selects_exactly_what_counts_as_markdown() {
1380        assert_eq!(any_case_extension_glob("md"), "*.[mM][dD]");
1381
1382        // The glob stands in for `is_markdown_extension` inside a walk, so the
1383        // two have to agree on every spelling, not just the lowercase one.
1384        let mut builder = globset::GlobSetBuilder::new();
1385        for ext in MARKDOWN_EXTENSIONS {
1386            builder.add(
1387                globset::GlobBuilder::new(&any_case_extension_glob(ext))
1388                    .literal_separator(true)
1389                    .build()
1390                    .unwrap(),
1391            );
1392        }
1393        let globs = builder.build().unwrap();
1394
1395        for ext in MARKDOWN_EXTENSIONS {
1396            for spelling in [ext.to_ascii_lowercase(), ext.to_ascii_uppercase(), capitalize(ext)] {
1397                let name = format!("README.{spelling}");
1398                assert!(
1399                    globs.is_match(&name),
1400                    "{name} is markdown by extension but no type glob selects it"
1401                );
1402                assert!(is_markdown_extension(OsStr::new(&spelling)), "{spelling} should match");
1403            }
1404        }
1405
1406        // Control: the glob widens case, not the extension set.
1407        for name in ["lib.rs", "notes.txt", "README.mdq", "README.m"] {
1408            assert!(!globs.is_match(name), "{name} should not be selected");
1409        }
1410    }
1411
1412    fn capitalize(ext: &str) -> String {
1413        let mut chars = ext.chars();
1414        match chars.next() {
1415            Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
1416            None => String::new(),
1417        }
1418    }
1419
1420    #[test]
1421    fn walk_includes_hidden_files() {
1422        let temp = tempdir().unwrap();
1423        fs::create_dir_all(temp.path().join(".github")).unwrap();
1424        fs::write(temp.path().join(".github/PULL_REQUEST_TEMPLATE.md"), "# hi").unwrap();
1425        fs::write(temp.path().join("README.md"), "# hi").unwrap();
1426
1427        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
1428            .build()
1429            .flatten()
1430            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1431            .map(|e| e.path().to_path_buf())
1432            .collect();
1433        assert!(files.iter().any(|p| p.ends_with(".github/PULL_REQUEST_TEMPLATE.md")));
1434        assert!(files.iter().any(|p| p.ends_with("README.md")));
1435    }
1436
1437    #[test]
1438    fn walk_honors_gitignore_when_enabled_only() {
1439        let temp = tempdir().unwrap();
1440        fs::write(temp.path().join(".gitignore"), "ignored.md\n").unwrap();
1441        fs::write(temp.path().join("ignored.md"), "# hi").unwrap();
1442        fs::write(temp.path().join("kept.md"), "# hi").unwrap();
1443
1444        let walk = |respect: bool| -> Vec<std::path::PathBuf> {
1445            markdown_walk_builder(
1446                temp.path(),
1447                &MarkdownWalkOptions {
1448                    respect_gitignore: respect,
1449                    ..Default::default()
1450                },
1451            )
1452            .build()
1453            .flatten()
1454            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1455            .map(|e| e.path().to_path_buf())
1456            .collect()
1457        };
1458
1459        let respected = walk(true);
1460        assert!(!respected.iter().any(|p| p.ends_with("ignored.md")));
1461        assert!(respected.iter().any(|p| p.ends_with("kept.md")));
1462
1463        let unrespected = walk(false);
1464        assert!(unrespected.iter().any(|p| p.ends_with("ignored.md")));
1465    }
1466
1467    #[test]
1468    fn a_gitignore_above_the_repository_root_stays_outside_it() {
1469        let temp = tempdir().unwrap();
1470        fs::write(temp.path().join(".gitignore"), "*.md\n").unwrap();
1471        let repo = temp.path().join("repo");
1472        fs::create_dir_all(repo.join(".git")).unwrap();
1473        fs::write(repo.join("kept.md"), "# hi").unwrap();
1474
1475        let walk = |root: &Path| -> Vec<std::path::PathBuf> {
1476            markdown_walk_builder(root, &MarkdownWalkOptions::default())
1477                .build()
1478                .flatten()
1479                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1480                .map(|e| e.path().to_path_buf())
1481                .collect()
1482        };
1483
1484        assert!(
1485            walk(&repo).iter().any(|p| p.ends_with("kept.md")),
1486            "git reads no gitignore above the repository root, so neither does the walk"
1487        );
1488
1489        // Control: outside a repository there is no root to stop at, and the
1490        // ignore files above are all the walk has to go on.
1491        fs::remove_dir(repo.join(".git")).unwrap();
1492        assert!(
1493            !walk(&repo).iter().any(|p| p.ends_with("kept.md")),
1494            "with no repository to bound it, the walk keeps reading upward"
1495        );
1496    }
1497
1498    #[test]
1499    fn the_repository_boundary_needs_every_root_to_have_one() {
1500        let temp = tempdir().unwrap();
1501        let inside = temp.path().join("repo/docs");
1502        fs::create_dir_all(&inside).unwrap();
1503        fs::create_dir_all(temp.path().join("repo/.git")).unwrap();
1504        let outside = temp.path().join("plain");
1505        fs::create_dir_all(&outside).unwrap();
1506
1507        assert!(stops_at_repository_root(&[&inside]), "a root under a repository root");
1508        assert!(!stops_at_repository_root(&[&outside]), "a root under no repository");
1509
1510        // A walk has one setting for all of its roots. Bounding this one would
1511        // strip the outside root of gitignore handling altogether, which is a
1512        // worse answer than reading one file too many.
1513        assert!(!stops_at_repository_root(&[inside.as_path(), outside.as_path()]));
1514        assert!(!stops_at_repository_root(&[] as &[&Path]), "no root is no repository");
1515
1516        // A worktree and a submodule mark their root with a `.git` file rather
1517        // than a directory, and both are still repository roots.
1518        let worktree = temp.path().join("worktree");
1519        fs::create_dir_all(&worktree).unwrap();
1520        fs::write(worktree.join(".git"), "gitdir: /elsewhere/.git/worktrees/x\n").unwrap();
1521        assert!(stops_at_repository_root(&[&worktree]));
1522    }
1523
1524    #[test]
1525    fn walk_honors_markdownlintignore() {
1526        let temp = tempdir().unwrap();
1527        fs::write(temp.path().join(".markdownlintignore"), "legacy.md\n").unwrap();
1528        fs::write(temp.path().join("legacy.md"), "# hi").unwrap();
1529        fs::write(temp.path().join("kept.md"), "# hi").unwrap();
1530
1531        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
1532            .build()
1533            .flatten()
1534            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1535            .map(|e| e.path().to_path_buf())
1536            .collect();
1537        assert!(!files.iter().any(|p| p.ends_with("legacy.md")));
1538        assert!(files.iter().any(|p| p.ends_with("kept.md")));
1539    }
1540
1541    #[test]
1542    fn vendor_dirs_skipped_only_when_requested() {
1543        let temp = tempdir().unwrap();
1544        for dir in ["node_modules", "target", "src"] {
1545            fs::create_dir_all(temp.path().join(dir)).unwrap();
1546            fs::write(temp.path().join(dir).join("doc.md"), "# hi").unwrap();
1547        }
1548
1549        let walk = |skip: bool| -> Vec<std::path::PathBuf> {
1550            markdown_walk_builder(
1551                temp.path(),
1552                &MarkdownWalkOptions {
1553                    skip_vendor_dirs: skip,
1554                    // Disable gitignore handling so ambient .gitignore files in the
1555                    // temp directory's ancestry cannot mask the vendor-dir filtering
1556                    // this test exercises.
1557                    respect_gitignore: false,
1558                },
1559            )
1560            .build()
1561            .flatten()
1562            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1563            .map(|e| e.path().to_path_buf())
1564            .collect()
1565        };
1566
1567        let skipped = walk(true);
1568        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
1569        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("target")));
1570        assert!(skipped.iter().any(|p| p.ends_with("src/doc.md")));
1571
1572        let unskipped = walk(false);
1573        assert!(unskipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
1574    }
1575
1576    #[test]
1577    fn explicit_file_name_glob_extracts_literal_extensions() {
1578        assert_eq!(explicit_file_name_glob("**/*.md.jinja"), Some("*.md.jinja"));
1579        assert_eq!(explicit_file_name_glob("*.md.jinja"), Some("*.md.jinja"));
1580        assert_eq!(explicit_file_name_glob("docs/*.txt"), Some("*.txt"));
1581        assert_eq!(explicit_file_name_glob("templates/NOTES.tmpl"), Some("NOTES.tmpl"));
1582        assert_eq!(explicit_file_name_glob("*.md"), Some("*.md"));
1583        assert_eq!(explicit_file_name_glob("a/b/c/*.md.tmpl"), Some("*.md.tmpl"));
1584    }
1585
1586    #[test]
1587    fn explicit_file_name_glob_rejects_unpinned_patterns() {
1588        for pattern in [
1589            "docs/",
1590            "docs/**",
1591            "docs",
1592            "*",
1593            "**",
1594            "**/*",
1595            "*.*",
1596            "*.md*",
1597            "*.{md,jinja}",
1598            "*.md?",
1599            "data.[ch]",
1600            "!drafts/*.md.jinja",
1601            "",
1602            "**/Makefile",
1603            "*.",
1604        ] {
1605            assert_eq!(explicit_file_name_glob(pattern), None, "{pattern:?} should not qualify");
1606        }
1607    }
1608
1609    #[test]
1610    fn explicit_include_matchers_match_full_relative_paths() {
1611        let matchers = ExplicitIncludeMatchers::new(&[
1612            "**/*.md.jinja".to_string(),
1613            "docs/**".to_string(),
1614            "templates/NOTES.tmpl".to_string(),
1615        ]);
1616        assert!(!matchers.is_empty());
1617        assert!(matchers.matches_relative_path("test.md.jinja"));
1618        assert!(matchers.matches_relative_path("a/b/test.md.jinja"));
1619        assert!(matchers.matches_relative_path("templates/NOTES.tmpl"));
1620        // The directory pattern must not widen the filter to arbitrary files.
1621        assert!(!matchers.matches_relative_path("docs/anything.txt"));
1622        assert!(!matchers.matches_relative_path("test.jinja"));
1623        // A broad sibling pattern must not inherit the literal pattern's
1624        // allowance for files that merely share its name.
1625        assert!(!matchers.matches_relative_path("docs/NOTES.tmpl"));
1626        assert!(!matchers.matches_relative_path("x/templates/NOTES.tmpl"));
1627
1628        let globs: Vec<_> = matchers.file_name_globs().collect();
1629        assert_eq!(globs, vec!["*.md.jinja", "NOTES.tmpl"]);
1630    }
1631
1632    #[test]
1633    fn explicit_include_matchers_follow_gitignore_anchoring() {
1634        // No slash: matches at any depth.
1635        let unanchored = ExplicitIncludeMatchers::new(&["*.md.jinja".to_string()]);
1636        assert!(unanchored.matches_relative_path("test.md.jinja"));
1637        assert!(unanchored.matches_relative_path("a/b/test.md.jinja"));
1638
1639        // Slash: anchored to the root, and `*` does not cross separators.
1640        let anchored = ExplicitIncludeMatchers::new(&["docs/*.txt".to_string()]);
1641        assert!(anchored.matches_relative_path("docs/a.txt"));
1642        assert!(!anchored.matches_relative_path("docs/sub/a.txt"));
1643        assert!(!anchored.matches_relative_path("other/docs/a.txt"));
1644
1645        // Leading slash: anchored, slash stripped for matching.
1646        let rooted = ExplicitIncludeMatchers::new(&["/NOTES.tmpl".to_string()]);
1647        assert!(rooted.matches_relative_path("NOTES.tmpl"));
1648        assert!(!rooted.matches_relative_path("docs/NOTES.tmpl"));
1649    }
1650
1651    #[test]
1652    fn explicit_include_matchers_empty_for_directory_and_wildcard_patterns() {
1653        let matchers = ExplicitIncludeMatchers::new(&["docs/".to_string(), "**/*".to_string()]);
1654        assert!(matchers.is_empty());
1655        assert!(!matchers.matches_relative_path("x.md.jinja"));
1656    }
1657
1658    #[test]
1659    fn explicit_include_matchers_skip_invalid_globs() {
1660        // The unclosed bracket pins a literal `.tmpl` suffix but fails glob
1661        // compilation; it must be skipped without poisoning valid patterns.
1662        let matchers = ExplicitIncludeMatchers::new(&["bad[.tmpl".to_string(), "**/*.md.jinja".to_string()]);
1663        assert!(matchers.matches_relative_path("ok.md.jinja"));
1664        assert_eq!(matchers.file_name_globs().collect::<Vec<_>>(), vec!["*.md.jinja"]);
1665    }
1666
1667    #[test]
1668    fn exclude_matchers_expand_directory_patterns() {
1669        let matchers = ExcludeMatchers::new(&["drafts".to_string(), "*.tmp.md".to_string()]);
1670        assert!(matchers.is_match("drafts"));
1671        assert!(
1672            matchers.is_match("drafts/inner.md"),
1673            "directory pattern must match contents"
1674        );
1675        assert!(matchers.is_match("note.tmp.md"));
1676        assert!(!matchers.is_match("docs/guide.md"));
1677        assert_eq!(matchers.matched_pattern("drafts/inner.md"), Some("drafts/**"));
1678        assert!(matchers.invalid.is_empty());
1679    }
1680
1681    #[test]
1682    fn exclude_matchers_float_a_pattern_without_a_slash_to_any_depth() {
1683        let matchers =
1684            ExcludeMatchers::new(&["node_modules".to_string(), "build/".to_string(), "notes.md".to_string()]);
1685        for path in [
1686            "node_modules/readme.md",
1687            "packages/app/node_modules/readme.md",
1688            "build/out.md",
1689            "site/build/out.md",
1690            "notes.md",
1691            "docs/notes.md",
1692        ] {
1693            assert!(matchers.is_match(path), "{path} must be excluded");
1694        }
1695        for path in ["node_modules.md", "docs/my-notes.md", "rebuild/out.md", "docs/guide.md"] {
1696            assert!(!matchers.is_match(path), "{path} must not be excluded");
1697        }
1698        // The notice names the pattern as expanded, not the glob that floated it.
1699        assert_eq!(
1700            matchers.matched_pattern("packages/app/node_modules/readme.md"),
1701            Some("node_modules/**")
1702        );
1703    }
1704
1705    #[test]
1706    fn exclude_matchers_keep_a_pattern_containing_a_slash_anchored() {
1707        let matchers = ExcludeMatchers::new(&["docs/generated".to_string(), "sub/*.md".to_string()]);
1708        assert!(matchers.is_match("docs/generated/api.md"));
1709        assert!(!matchers.is_match("site/docs/generated/api.md"));
1710        assert!(matchers.is_match("sub/a.md"));
1711        assert!(!matchers.is_match("other/sub/a.md"));
1712    }
1713
1714    #[test]
1715    fn exclude_matchers_exclude_the_contents_of_a_directory_a_wildcard_matches() {
1716        let matchers = ExcludeMatchers::new(&["draft?".to_string(), "sub/[gh]en".to_string()]);
1717        assert!(matchers.is_match("drafts/note.md"));
1718        assert!(
1719            matchers.is_match("blog/drafts/note.md"),
1720            "a slashless wildcard floats too"
1721        );
1722        assert!(matchers.is_match("sub/gen/x.md"));
1723        assert!(matchers.is_match("sub/hen/deep/x.md"));
1724        assert!(!matchers.is_match("sub/pen/x.md"));
1725        assert!(!matchers.is_match("other/sub/gen/x.md"));
1726    }
1727
1728    #[test]
1729    fn exclude_matchers_report_an_invalid_pattern_once() {
1730        let matchers = ExcludeMatchers::new(&["[".to_string(), "docs".to_string()]);
1731        assert_eq!(matchers.invalid.len(), 1, "{:?}", matchers.invalid);
1732        assert!(matchers.is_match("docs/a.md"));
1733    }
1734
1735    #[test]
1736    fn expand_home_prefix_expands_only_a_leading_tilde() {
1737        let home = Path::new("/home/dev");
1738        assert_eq!(
1739            expand_home_prefix_impl("~/.cursor/plans", Some(home)),
1740            "/home/dev/.cursor/plans"
1741        );
1742        assert_eq!(expand_home_prefix_impl("~", Some(home)), "/home/dev");
1743        assert_eq!(expand_home_prefix_impl("~/", Some(home)), "/home/dev");
1744    }
1745
1746    #[test]
1747    fn expand_home_prefix_leaves_interior_tildes_alone() {
1748        let home = Path::new("/home/dev");
1749        // `~` is a legal filename character; only a leading `~/` is a home reference.
1750        for pattern in ["backup.md~", "docs/~drafts/**", "~user/docs", "**/*~", "!~/secret"] {
1751            assert_eq!(
1752                expand_home_prefix_impl(pattern, Some(home)),
1753                pattern,
1754                "{pattern:?} must be left as written"
1755            );
1756        }
1757    }
1758
1759    #[test]
1760    fn expand_home_prefix_without_a_home_leaves_the_pattern_as_written() {
1761        assert_eq!(expand_home_prefix_impl("~/.cursor/plans", None), "~/.cursor/plans");
1762    }
1763
1764    #[test]
1765    fn normalize_pattern_for_base_rewrites_absolute_patterns_under_the_base() {
1766        let temp = tempdir().unwrap();
1767        // Canonicalize the way production does, so the pattern has the shape an
1768        // expanded `~` produces (on Windows that means no verbatim prefix).
1769        let base = canonicalize_for_matching(temp.path()).unwrap();
1770        let pattern = format!("{}/docs/**", base.to_string_lossy().replace('\\', "/"));
1771        assert_eq!(normalize_pattern_for_base(&pattern, Some(&base)), "docs/**");
1772    }
1773
1774    #[test]
1775    fn normalize_pattern_for_base_strips_through_a_non_canonical_base() {
1776        // The base as handed to us (a symlinked `/var` on macOS, a Windows 8.3
1777        // short name) must still strip.
1778        let temp = tempdir().unwrap();
1779        let canonical = canonicalize_for_matching(temp.path()).unwrap();
1780        let pattern = format!("{}/docs/**", canonical.to_string_lossy().replace('\\', "/"));
1781        assert_eq!(normalize_pattern_for_base(&pattern, Some(temp.path())), "docs/**");
1782    }
1783
1784    #[test]
1785    fn normalize_pattern_for_base_leaves_other_patterns_alone() {
1786        let temp = tempdir().unwrap();
1787        let base = canonicalize_for_matching(temp.path()).unwrap();
1788        // Relative patterns are already base-relative.
1789        assert_eq!(normalize_pattern_for_base("docs/**", Some(&base)), "docs/**");
1790        // An absolute pattern outside the base stays absolute: nothing under
1791        // this walk can match it, which is the correct outcome.
1792        assert_eq!(
1793            normalize_pattern_for_base("/somewhere/else/**", Some(&base)),
1794            "/somewhere/else/**"
1795        );
1796        // With no base there is nothing to rewrite against.
1797        assert_eq!(normalize_pattern_for_base("/abs/docs/**", None), "/abs/docs/**");
1798    }
1799
1800    #[test]
1801    fn strip_verbatim_prefix_unwraps_windows_canonical_paths() {
1802        // The exact shape `canonicalize` returns on Windows. Left unstripped it
1803        // normalizes to `//?/C:/...`, which matches nothing.
1804        assert_eq!(
1805            strip_verbatim_prefix(r"\\?\C:\Users\dev\AppData\Local\Temp\x"),
1806            r"C:\Users\dev\AppData\Local\Temp\x"
1807        );
1808        assert_eq!(strip_verbatim_prefix(r"\\?\C:\"), r"C:\");
1809        // UNC shares unwrap to their ordinary `\\server\share` form.
1810        assert_eq!(
1811            strip_verbatim_prefix(r"\\?\UNC\server\share\docs"),
1812            r"\\server\share\docs"
1813        );
1814    }
1815
1816    #[test]
1817    fn strip_verbatim_prefix_unwraps_the_display_form() {
1818        // The same paths after display normalization has turned `\` into `/`.
1819        assert_eq!(
1820            strip_verbatim_prefix("//?/C:/Users/dev/AppData/Local/Temp/x"),
1821            "C:/Users/dev/AppData/Local/Temp/x"
1822        );
1823        assert_eq!(strip_verbatim_prefix("//?/C:/"), "C:/");
1824        assert_eq!(
1825            strip_verbatim_prefix("//?/UNC/server/share/docs"),
1826            "//server/share/docs"
1827        );
1828    }
1829
1830    #[test]
1831    fn strip_verbatim_prefix_leaves_other_paths_alone() {
1832        for path in [
1833            "/home/dev/docs",
1834            r"C:\Users\dev",
1835            "C:/Users/dev",
1836            r"\\server\share",
1837            "//server/share",
1838            // A device namespace has no ordinary equivalent to unwrap to.
1839            r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\docs",
1840            "//?/Volume{b75e2c83-0000-0000-0000-602f00000000}/docs",
1841            r"\\?\",
1842            "//?/",
1843            // A prefix written in one separator does not unwrap in the other.
1844            r"\\?/C:/Users/dev",
1845            "",
1846        ] {
1847            assert_eq!(strip_verbatim_prefix(path), path, "{path:?} must be left as written");
1848        }
1849    }
1850
1851    #[test]
1852    fn expand_directory_pattern_expands_a_literal_final_component() {
1853        // A glob earlier in the pattern must not block contents-expansion: the
1854        // final component names a directory, so its contents are excluded too.
1855        assert_eq!(
1856            expand_directory_pattern("**/.cursor/plans"),
1857            vec!["**/.cursor/plans", "**/.cursor/plans/**"]
1858        );
1859        assert_eq!(
1860            expand_directory_pattern("docs/**/drafts"),
1861            vec!["docs/**/drafts", "docs/**/drafts/**"]
1862        );
1863        // Alternation names literal directories, so it keeps its expansion.
1864        assert_eq!(
1865            expand_directory_pattern("logs/{a,b}"),
1866            vec!["logs/{a,b}", "logs/{a,b}/**"]
1867        );
1868    }
1869
1870    #[test]
1871    fn expand_directory_pattern_leaves_a_wildcard_final_component_alone() {
1872        // `docs/*` names direct children only; expanding it to `docs/*/**` would
1873        // newly exclude nested contents.
1874        for pattern in ["docs/*", "*.tmp.md", "build/**", "data.[ch]", "notes?"] {
1875            assert_eq!(
1876                expand_directory_pattern(pattern),
1877                vec![pattern.to_string()],
1878                "{pattern:?} must not gain a contents-expansion"
1879            );
1880        }
1881    }
1882
1883    #[test]
1884    fn exclude_matchers_match_an_absolute_pattern_against_an_absolute_path() {
1885        let matchers = ExcludeMatchers::new(&["/home/dev/.cursor/plans".to_string()]);
1886        let excluded = Path::new("/home/dev/.cursor/plans/plan.md");
1887        assert!(
1888            matchers.excludes_file(None, excluded),
1889            "an absolute pattern must match the absolute path when there is no relative form"
1890        );
1891        assert_eq!(
1892            matchers.matched_pattern_for_file(None, excluded),
1893            Some("/home/dev/.cursor/plans/**")
1894        );
1895        // A file inside a project root still has a relative form; the absolute
1896        // pattern must match it through the absolute path.
1897        assert!(matchers.excludes_file(Some(".cursor/plans/plan.md"), excluded));
1898        assert!(!matchers.excludes_file(Some("docs/guide.md"), Path::new("/home/dev/docs/guide.md")));
1899    }
1900
1901    #[test]
1902    fn exclude_matchers_do_not_let_relative_patterns_match_absolute_paths() {
1903        let matchers = ExcludeMatchers::new(&["drafts".to_string()]);
1904        assert!(!matchers.excludes_file(None, Path::new("/home/dev/proj/drafts/note.md")));
1905        assert!(matchers.excludes_file(Some("drafts/note.md"), Path::new("/home/dev/proj/drafts/note.md")));
1906
1907        // An absolute pattern makes the absolute path worth matching, and the
1908        // floating `drafts` must still not match a directory above the root.
1909        let matchers = ExcludeMatchers::new(&["drafts".to_string(), "/unrelated".to_string()]);
1910        let note = Path::new("/home/dev/drafts/site/note.md");
1911        assert_eq!(matchers.matched_pattern_for_file(None, note), None);
1912        assert_eq!(matchers.matched_pattern_for_file(Some("note.md"), note), None);
1913        assert_eq!(
1914            matchers.matched_pattern_for_file(Some("drafts/note.md"), Path::new("/home/dev/site/drafts/note.md")),
1915            Some("drafts/**")
1916        );
1917        assert_eq!(
1918            matchers.matched_pattern_for_file(None, Path::new("/unrelated/note.md")),
1919            Some("/unrelated/**")
1920        );
1921    }
1922
1923    #[test]
1924    fn exclude_matchers_match_a_wildcard_within_one_path_component() {
1925        let matchers = ExcludeMatchers::new(&["sub/a*b".to_string(), "notes/a?b.md".to_string()]);
1926        assert!(matchers.is_match("sub/aXb/y.md"));
1927        assert!(matchers.is_match("sub/ab/y.md"));
1928        assert!(!matchers.is_match("sub/a/keep/b/x.md"));
1929        assert!(matchers.is_match("notes/aXb.md"));
1930        assert!(!matchers.is_match("notes/a/b.md"));
1931
1932        let matchers = ExcludeMatchers::new(&["docs/**/draft.md".to_string()]);
1933        assert!(matchers.is_match("docs/draft.md"));
1934        assert!(matchers.is_match("docs/a/b/draft.md"));
1935    }
1936
1937    #[test]
1938    fn exclude_matchers_report_invalid_patterns() {
1939        let matchers = ExcludeMatchers::new(&["[".to_string(), "ok.md".to_string()]);
1940        assert_eq!(matchers.invalid.len(), 1);
1941        assert_eq!(matchers.invalid[0].0, "[");
1942        assert!(matchers.is_match("ok.md"));
1943    }
1944
1945    #[test]
1946    fn path_relative_to_strips_through_symlinked_base() {
1947        let temp = tempdir().unwrap();
1948        let base = temp.path().join("base");
1949        fs::create_dir_all(base.join("docs")).unwrap();
1950        fs::write(base.join("docs/a.md"), "# hi").unwrap();
1951
1952        assert_eq!(
1953            path_relative_to(&base.join("docs/a.md"), &base).as_deref(),
1954            Some("docs/a.md")
1955        );
1956        assert_eq!(
1957            path_relative_to(&base.join("docs/a.md"), &base.join("docs")).as_deref(),
1958            Some("a.md")
1959        );
1960        assert_eq!(path_relative_to(temp.path(), &base), None, "path outside base");
1961        assert_eq!(
1962            path_relative_to(&base.join("docs/new/ghost.md"), &base).as_deref(),
1963            Some("docs/new/ghost.md"),
1964            "a file that does not exist yet relativizes the way it will once written"
1965        );
1966        assert_eq!(
1967            path_relative_to(&base.join("docs/a.md"), &base.join("missing")),
1968            None,
1969            "a base that does not exist contains nothing"
1970        );
1971    }
1972
1973    #[test]
1974    fn resolve_for_matching_spells_a_missing_file_the_way_it_will_canonicalize() {
1975        let temp = tempdir().unwrap();
1976        let root = canonicalize_for_matching(temp.path()).unwrap();
1977        fs::create_dir_all(root.join("docs")).unwrap();
1978        fs::write(root.join("docs").join("x.md"), "# x").unwrap();
1979
1980        // `temp.path()` is not canonical on macOS (`/var` -> `/private/var`), so
1981        // every row below also proves the existing ancestor was canonicalized.
1982        let cases = [
1983            ("docs/x.md", root.join("docs").join("x.md")),
1984            ("docs/ghost.md", root.join("docs").join("ghost.md")),
1985            (
1986                "docs/new/dir/ghost.md",
1987                root.join("docs").join("new").join("dir").join("ghost.md"),
1988            ),
1989            ("missing/../docs/./x.md", root.join("docs").join("x.md")),
1990            ("docs/missing/../../top.md", root.join("top.md")),
1991        ];
1992        for (relative, expected) in cases {
1993            assert_eq!(
1994                resolve_for_matching(&temp.path().join(relative)),
1995                expected,
1996                "{relative}"
1997            );
1998        }
1999    }
2000
2001    #[test]
2002    fn resolve_for_matching_takes_a_relative_path_from_the_working_directory() {
2003        let cwd = canonicalize_for_matching(&std::env::current_dir().unwrap()).unwrap();
2004        assert_eq!(
2005            resolve_for_matching(Path::new("no-such-dir-for-matching/ghost.md")),
2006            cwd.join("no-such-dir-for-matching").join("ghost.md")
2007        );
2008        assert_eq!(resolve_for_matching(Path::new("./Cargo.toml")), cwd.join("Cargo.toml"));
2009    }
2010
2011    #[cfg(unix)]
2012    #[test]
2013    fn resolve_for_matching_follows_a_symlink_reached_through_a_missing_directory() {
2014        let temp = tempdir().unwrap();
2015        let root = canonicalize_for_matching(temp.path()).unwrap();
2016        fs::create_dir_all(root.join("real")).unwrap();
2017        std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();
2018
2019        assert_eq!(
2020            resolve_for_matching(&root.join("link").join("ghost.md")),
2021            root.join("real").join("ghost.md")
2022        );
2023        // Lexically `missing/../link/ghost.md` is `link/ghost.md`, and `link`
2024        // is only resolved by looking again once the `..` is gone.
2025        assert_eq!(
2026            resolve_for_matching(&root.join("missing").join("..").join("link").join("ghost.md")),
2027            root.join("real").join("ghost.md")
2028        );
2029    }
2030
2031    fn sorted(mut patterns: Vec<String>) -> Vec<String> {
2032        patterns.sort();
2033        patterns
2034    }
2035
2036    #[test]
2037    fn expand_braces_yields_every_alternative() {
2038        assert_eq!(
2039            sorted(expand_braces("/{var/folders,tmp}/**")),
2040            vec!["/tmp/**", "/var/folders/**"]
2041        );
2042        // Nesting expands too.
2043        assert_eq!(sorted(expand_braces("a{b,{c,d}}e")), vec!["abe", "ace", "ade"]);
2044        // An empty alternative is dropped, as globset drops it.
2045        assert_eq!(sorted(expand_braces("x{,y}")), vec!["xy"]);
2046        // Several groups multiply out.
2047        assert_eq!(
2048            sorted(expand_braces("/{a,b}/{c,d}.md")),
2049            vec!["/a/c.md", "/a/d.md", "/b/c.md", "/b/d.md"]
2050        );
2051    }
2052
2053    #[test]
2054    fn expand_braces_leaves_patterns_it_cannot_split() {
2055        // Nothing to split.
2056        assert_eq!(expand_braces("/var/folders/**"), vec!["/var/folders/**"]);
2057        // An unclosed brace is not an alternation.
2058        assert_eq!(expand_braces("/var/{a,b/**"), vec!["/var/{a,b/**"]);
2059        // A comma inside a character class is literal.
2060        assert_eq!(expand_braces("/var/[a,b]/**"), vec!["/var/[a,b]/**"]);
2061        // An alternation of nothing but empty alternatives is not a split.
2062        assert_eq!(expand_braces("x{,}"), vec!["x{,}"]);
2063        // Past the expansion cap the pattern is left alone: 2^7 = 128 > 64.
2064        let wide = "/{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}/**";
2065        assert_eq!(expand_braces(wide), vec![wide]);
2066    }
2067
2068    #[test]
2069    fn has_absolute_spelling_sees_past_a_leading_alternation() {
2070        assert!(has_absolute_spelling("/var/folders/**"));
2071        assert!(has_absolute_spelling("{/opt,/srv}/docs/**"));
2072        assert!(has_absolute_spelling("/{var/folders,tmp}/**"));
2073        assert!(!has_absolute_spelling("docs/**"));
2074        assert!(!has_absolute_spelling("{docs,notes}/**"));
2075    }
2076
2077    #[test]
2078    fn expand_braces_agrees_with_globset() {
2079        // The expansion only discovers prefixes to canonicalize, but a
2080        // disagreement with globset would mean it is describing a different
2081        // pattern than the one that decides matches.
2082        let cases = [
2083            ("/{var/folders,tmp}/**", "/tmp/note.md"),
2084            ("/{var/folders,tmp}/**", "/var/folders/x/note.md"),
2085            ("/{var/folders,tmp}/**", "/opt/note.md"),
2086            ("/{a,b}/{c,d}.md", "/b/d.md"),
2087            ("/{a,b}/{c,d}.md", "/b/e.md"),
2088            ("x{,y}", "x"),
2089            ("x{,y}", "xy"),
2090            ("/var/[a,b]/**", "/var/a/n.md"),
2091            ("/var/[a,b]/**", "/var/,/n.md"),
2092            ("/var/folders/**", "/var/folders/n.md"),
2093        ];
2094        for (pattern, path) in cases {
2095            let direct = Glob::new(pattern).unwrap().compile_matcher().is_match(path);
2096            let expanded = expand_braces(pattern)
2097                .iter()
2098                .any(|p| Glob::new(p).unwrap().compile_matcher().is_match(path));
2099            assert_eq!(direct, expanded, "pattern {pattern} against {path}");
2100        }
2101    }
2102
2103    #[test]
2104    fn literal_path_prefix_stops_at_the_first_wildcard() {
2105        assert_eq!(literal_path_prefix("/var/folders/**"), Some("/var/folders"));
2106        assert_eq!(literal_path_prefix("/var/log/app*.md"), Some("/var/log"));
2107        assert_eq!(literal_path_prefix("/var/note.md"), Some("/var/note.md"));
2108        assert_eq!(literal_path_prefix("/var/"), Some("/var"));
2109        assert_eq!(literal_path_prefix("docs/**"), Some("docs"));
2110        // Nothing literal to resolve.
2111        assert_eq!(literal_path_prefix("/**"), None);
2112        assert_eq!(literal_path_prefix("/{var,tmp}/**"), None);
2113        assert_eq!(literal_path_prefix("**/note.md"), None);
2114        // The result is always a prefix slice, so a remainder re-attaches by
2115        // byte offset.
2116        let pattern = "/var/folders/**";
2117        let prefix = literal_path_prefix(pattern).unwrap();
2118        assert_eq!(&pattern[prefix.len()..], "/**");
2119    }
2120
2121    /// `(real directory, symlink to it)` under a fresh temp dir. The symlink is
2122    /// how a pattern spells the location; the real directory is where a file
2123    /// canonicalizes to.
2124    #[cfg(unix)]
2125    fn symlinked_dir(temp: &Path) -> (PathBuf, PathBuf) {
2126        let real = temp.join("real");
2127        fs::create_dir_all(real.join("notes")).unwrap();
2128        fs::write(real.join("notes/scratch.md"), "# Note\n").unwrap();
2129        let link = temp.join("link");
2130        std::os::unix::fs::symlink(&real, &link).unwrap();
2131        (canonicalize_for_matching(&real).unwrap(), link)
2132    }
2133
2134    #[cfg(unix)]
2135    #[test]
2136    fn path_aliases_spell_a_path_the_way_a_pattern_named_it() {
2137        let temp = tempdir().unwrap();
2138        let (real, link) = symlinked_dir(temp.path());
2139        let pattern = format!("{}/notes/**", link.to_string_lossy());
2140
2141        let aliases = PathAliases::new([pattern.as_str()]);
2142        assert!(!aliases.is_empty());
2143        assert_eq!(
2144            aliases.spellings_of(&real.join("notes/scratch.md")),
2145            vec![format!("{}/notes/scratch.md", link.to_string_lossy())]
2146        );
2147        // The alias is what makes the pattern match the canonical path.
2148        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
2149        assert!(!matcher.is_match(real.join("notes/scratch.md")), "negative control");
2150        assert!(
2151            aliases
2152                .spellings_of(&real.join("notes/scratch.md"))
2153                .iter()
2154                .any(|alias| matcher.is_match(alias))
2155        );
2156        // A path outside the recorded prefix has no alias.
2157        assert!(aliases.spellings_of(Path::new("/somewhere/else/note.md")).is_empty());
2158    }
2159
2160    #[cfg(unix)]
2161    #[test]
2162    fn path_aliases_reach_through_a_brace_alternation() {
2163        // The prefix only exists once the alternation is expanded.
2164        let temp = tempdir().unwrap();
2165        let (real, link) = symlinked_dir(temp.path());
2166        let pattern = format!("{{/nowhere,{}}}/notes/**", link.to_string_lossy());
2167
2168        let aliases = PathAliases::new([pattern.as_str()]);
2169        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
2170        let note = real.join("notes/scratch.md");
2171        assert!(!matcher.is_match(&note), "negative control");
2172        assert!(aliases.spellings_of(&note).iter().any(|alias| matcher.is_match(alias)));
2173    }
2174
2175    #[test]
2176    fn path_aliases_are_empty_without_a_symlinked_prefix() {
2177        let temp = tempdir().unwrap();
2178        let canonical = canonicalize_for_matching(temp.path()).unwrap();
2179        let canonical = canonical.to_string_lossy().replace('\\', "/");
2180        // Relative patterns, absolute patterns that already name their real
2181        // location, and prefixes that do not exist all record nothing.
2182        for pattern in ["docs/**", &format!("{canonical}/docs/**"), "/nonexistent/xyz/**"] {
2183            assert!(
2184                PathAliases::new([pattern]).is_empty(),
2185                "pattern {pattern} should record no alias"
2186            );
2187        }
2188    }
2189
2190    #[cfg(unix)]
2191    #[test]
2192    fn exclude_matchers_match_a_file_a_pattern_named_through_a_symlink() {
2193        let temp = tempdir().unwrap();
2194        let (real, link) = symlinked_dir(temp.path());
2195        let note = real.join("notes/scratch.md");
2196
2197        let matchers = ExcludeMatchers::new(&[format!("{}/notes/**", link.to_string_lossy())]);
2198        assert!(matchers.excludes_file(None, &note));
2199
2200        // Negative controls: a sibling the pattern does not name, and a pattern
2201        // pointing somewhere else entirely.
2202        fs::write(real.join("other.md"), "# Other\n").unwrap();
2203        assert!(!matchers.excludes_file(None, &real.join("other.md")));
2204        let elsewhere = ExcludeMatchers::new(&[format!("{}/elsewhere/**", link.to_string_lossy())]);
2205        assert!(!elsewhere.excludes_file(None, &note));
2206    }
2207
2208    #[cfg(unix)]
2209    #[test]
2210    fn normalize_pattern_for_base_strips_a_pattern_written_through_a_symlink() {
2211        let temp = tempdir().unwrap();
2212        let (real, link) = symlinked_dir(temp.path());
2213        let pattern = format!("{}/notes/*.md", link.to_string_lossy());
2214
2215        assert_eq!(normalize_pattern_for_base(&pattern, Some(&real)), "notes/*.md");
2216        // A pattern naming a different location through the same symlink is
2217        // still outside a narrower base, and stays absolute.
2218        let outside = format!("{}/elsewhere/*.md", link.to_string_lossy());
2219        assert_eq!(normalize_pattern_for_base(&outside, Some(&real.join("notes"))), outside);
2220    }
2221}