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, GlobMatcher};
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/// Ignore-handling options applied to a markdown discovery walk.
260#[derive(Debug, Clone)]
261pub struct MarkdownWalkOptions {
262    /// Honor `.gitignore`, `.ignore`, global gitignore, `.git/info/exclude`,
263    /// and parent ignore files. Driven by `global.respect_gitignore`.
264    pub respect_gitignore: bool,
265    /// Skip `.git`, `node_modules`, and `target` directories outright, even
266    /// when gitignore handling is disabled or would not cover them.
267    pub skip_vendor_dirs: bool,
268}
269
270impl Default for MarkdownWalkOptions {
271    fn default() -> Self {
272        Self {
273            respect_gitignore: true,
274            skip_vendor_dirs: false,
275        }
276    }
277}
278
279/// Whether a walk over `roots` stops reading gitignores at the repository root.
280///
281/// Git reads no `.gitignore` above the repository root, so a walk that does hides
282/// files `git check-ignore` reports as visible. Worse, such a file can hide a
283/// whole directory, and a pruned directory is never descended into, so no include
284/// pattern gets the chance to name anything inside it.
285///
286/// Outside a repository there is no root to stop at, and ignore files are all a
287/// walk has to go on, so there they keep applying upward. One walk has one
288/// setting for all of its roots, so the boundary is only applied when every root
289/// has a repository to bound it.
290pub fn stops_at_repository_root<P: AsRef<Path>>(roots: &[P]) -> bool {
291    !roots.is_empty() && roots.iter().all(|root| in_repository(root.as_ref()))
292}
293
294/// Whether `path` sits inside a git or jujutsu repository.
295///
296/// A `.git` entry is a directory in an ordinary clone and a file in a worktree or
297/// submodule, so existence alone is the marker. This recognizes a repository the
298/// same way the walker does, which is what puts the boundary in the same place.
299fn in_repository(path: &Path) -> bool {
300    let Ok(absolute) = std::fs::canonicalize(path) else {
301        return false;
302    };
303    absolute
304        .ancestors()
305        .any(|dir| dir.join(".git").exists() || dir.join(".jj").exists())
306}
307
308/// Apply the shared ignore-handling configuration to a walker over `roots`.
309///
310/// Hidden entries are always walked (a hidden `docs/.pages.md` lints the
311/// same as a visible one); generated content is kept out by gitignore
312/// semantics and, for callers that opt in, the vendor-directory skip.
313/// `.markdownlintignore` is honored for markdownlint compatibility.
314///
315/// The roots decide where gitignore reading stops, so a caller passes the same
316/// ones it walks.
317pub fn apply_markdown_walk_options<P: AsRef<Path>>(
318    builder: &mut ignore::WalkBuilder,
319    roots: &[P],
320    options: &MarkdownWalkOptions,
321) {
322    let gitignore = options.respect_gitignore;
323    builder
324        .ignore(gitignore)
325        .git_ignore(gitignore)
326        .git_global(gitignore)
327        .git_exclude(gitignore)
328        .parents(gitignore)
329        .hidden(false)
330        // This setting does double duty in the walker: it gates gitignore
331        // handling on a repository being present, and it is what stops the walk
332        // reading gitignores above the repository root. Inside a repository both
333        // are wanted. Outside one, requiring a repository would drop `.gitignore`
334        // handling entirely, and there is no root to stop at in any case.
335        .require_git(stops_at_repository_root(roots))
336        .add_custom_ignore_filename(".markdownlintignore");
337
338    if options.skip_vendor_dirs {
339        let roots: Vec<PathBuf> = roots.iter().map(|root| root.as_ref().to_path_buf()).collect();
340        builder.filter_entry(move |entry| {
341            if roots.iter().any(|root| root == entry.path()) {
342                return true;
343            }
344            let name = entry.file_name().to_str().unwrap_or("");
345            name != ".git" && name != "node_modules" && name != "target"
346        });
347    }
348}
349
350/// Build a walker over `root` configured with the shared options.
351pub fn markdown_walk_builder(root: &Path, options: &MarkdownWalkOptions) -> ignore::WalkBuilder {
352    let mut builder = ignore::WalkBuilder::new(root);
353    apply_markdown_walk_options(&mut builder, &[root], options);
354    builder
355}
356
357/// A complete, configured Markdown workspace scan.
358///
359/// This owns the selection policy shared by full scans and incremental file
360/// events: standard Markdown extensions, explicit nonstandard file includes,
361/// include filtering, excludes, ignore files, and optional vendor-directory
362/// pruning. Adapters choose the options; they do not reconstruct the policy.
363pub struct MarkdownWorkspaceScan<'a> {
364    options: &'a MarkdownWalkOptions,
365    includes: &'a [String],
366    excludes: &'a ExcludeMatchers,
367}
368
369impl<'a> MarkdownWorkspaceScan<'a> {
370    pub fn new(options: &'a MarkdownWalkOptions, includes: &'a [String], excludes: &'a ExcludeMatchers) -> Self {
371        Self {
372            options,
373            includes,
374            excludes,
375        }
376    }
377
378    /// Collect all selected files under `roots`.
379    pub fn collect(&self, roots: &[PathBuf]) -> Vec<PathBuf> {
380        let mut files = Vec::new();
381        for root in roots {
382            let selection = RootSelection::new(root, self.includes);
383            let mut builder = markdown_walk_builder(root, self.options);
384            selection.configure_walk(&mut builder);
385
386            for result in builder.build() {
387                match result {
388                    Ok(entry)
389                        if entry.file_type().is_some_and(|file_type| file_type.is_file())
390                            && selection.is_lintable(entry.path())
391                            && !self.excluded(root, entry.path()) =>
392                    {
393                        files.push(entry.into_path());
394                    }
395                    Ok(_) => {}
396                    Err(error) => log::warn!("Error scanning {}: {error}", root.display()),
397                }
398            }
399        }
400        files.sort();
401        files.dedup();
402        files
403    }
404
405    /// Whether an incremental file event would be absent from a full scan.
406    pub fn path_is_ignored(&self, roots: &[PathBuf], path: &Path) -> bool {
407        let Some(root) = roots
408            .iter()
409            .filter(|root| path.starts_with(root))
410            .max_by_key(|root| root.components().count())
411        else {
412            return false;
413        };
414
415        let selection = RootSelection::new(root, self.includes);
416        if !selection.selects(path) || self.excluded(root, path) {
417            return true;
418        }
419
420        if self.options.skip_vendor_dirs
421            && let Ok(relative) = path.strip_prefix(root)
422            && relative.components().any(|component| {
423                matches!(component, std::path::Component::Normal(name) if name == ".git" || name == "node_modules" || name == "target")
424            })
425        {
426            return true;
427        }
428
429        let target = path.to_path_buf();
430        let mut builder = markdown_walk_builder(root, self.options);
431        selection.configure_walk(&mut builder);
432        // `filter_entry` replaces the vendor filter, which was checked above.
433        builder.filter_entry(move |entry| target.starts_with(entry.path()));
434        !builder.build().flatten().any(|entry| entry.path() == path)
435    }
436
437    fn excluded(&self, root: &Path, path: &Path) -> bool {
438        self.excludes
439            .excludes_file(path_relative_to(path, root).as_deref(), path)
440    }
441}
442
443struct RootSelection {
444    lintable: LintablePathSelector,
445    overrides: Option<ignore::overrides::Override>,
446}
447
448impl RootSelection {
449    fn new(root: &Path, includes: &[String]) -> Self {
450        let normalized: Vec<String> = includes
451            .iter()
452            .map(|pattern| normalize_pattern_for_base(pattern, Some(root)))
453            .collect();
454        let overrides = if normalized.is_empty() {
455            None
456        } else {
457            let mut builder = ignore::overrides::OverrideBuilder::new(root);
458            for pattern in &normalized {
459                if let Err(error) = builder.add(pattern) {
460                    log::warn!("Invalid include pattern '{pattern}': {error}");
461                }
462            }
463            builder.build().ok()
464        };
465        Self {
466            lintable: LintablePathSelector::new(Some(root), &normalized, LintableFileMode::Markdown),
467            overrides,
468        }
469    }
470
471    fn configure_walk(&self, builder: &mut ignore::WalkBuilder) {
472        if let Err(error) = self.lintable.configure_types(builder) {
473            log::warn!("Failed to configure workspace source types: {error}");
474        }
475        if let Some(overrides) = &self.overrides {
476            builder.overrides(overrides.clone());
477        }
478    }
479
480    fn selects(&self, path: &Path) -> bool {
481        self.overrides
482            .as_ref()
483            .is_none_or(|overrides| overrides.matched(path, false).is_whitelist())
484            && self.is_lintable(path)
485    }
486
487    fn is_lintable(&self, path: &Path) -> bool {
488        self.lintable.keeps(path)
489    }
490}
491
492/// Drop Windows' verbatim `\\?\` prefix from a canonicalized path string.
493///
494/// `std::fs::canonicalize` returns the verbatim form (`\\?\C:\Users\dev`) on
495/// Windows. That form is useless for pattern matching: it does not compare
496/// equal to the ordinary paths rumdl works with, and normalizing its
497/// separators for globbing mangles it into `//?/C:/Users/dev`, which matches
498/// nothing. Only a drive path (`\\?\C:\...`) and a UNC share
499/// (`\\?\UNC\server\share` -> `\\server\share`) are unwrapped; any other
500/// verbatim path names a device namespace that has no ordinary equivalent, so
501/// it is left alone.
502///
503/// Pure string logic, compiled on every platform so it stays under test where
504/// Windows is not available. Only the call sites are Windows-specific, and on
505/// other platforms no path ever carries this prefix.
506fn strip_verbatim_prefix(path: &str) -> Cow<'_, str> {
507    // `\\?\UNC\server\share` -> `\\server\share`. The remainder already starts
508    // with one separator, so restoring the UNC form needs one more prepended.
509    if let Some(rest) = path.strip_prefix(r"\\?\UNC")
510        && rest.starts_with('\\')
511    {
512        return Cow::Owned(format!(r"\{rest}"));
513    }
514    let Some(rest) = path.strip_prefix(r"\\?\") else {
515        return Cow::Borrowed(path);
516    };
517    let is_drive_path = rest.as_bytes().get(1) == Some(&b':');
518    if is_drive_path {
519        Cow::Borrowed(rest)
520    } else {
521        Cow::Borrowed(path)
522    }
523}
524
525/// Canonicalize `path` for pattern matching, or `None` when it cannot be
526/// resolved (a missing or unreadable file).
527///
528/// Canonical form is what patterns are matched against, so a symlinked
529/// location (`/home/dev` -> `/mnt/dev`, or a macOS `/var` -> `/private/var`)
530/// still matches. Windows' verbatim prefix is removed (see
531/// [`strip_verbatim_prefix`]).
532pub fn canonicalize_for_matching(path: &Path) -> Option<PathBuf> {
533    let canonical = path.canonicalize().ok()?;
534    if !cfg!(windows) {
535        return Some(canonical);
536    }
537    let as_str = canonical.to_string_lossy();
538    Some(PathBuf::from(strip_verbatim_prefix(&as_str).as_ref()))
539}
540
541/// The user's home directory, or `None` when it cannot be resolved.
542///
543/// Canonicalized for matching (see [`canonicalize_for_matching`]), falling
544/// back to the path as reported when it cannot be canonicalized.
545///
546/// Wasm and WASI builds have no home directory to resolve, so patterns keep
547/// their `~` there (see [`expand_home_prefix`]).
548fn home_dir() -> Option<PathBuf> {
549    #[cfg(feature = "native")]
550    {
551        use etcetera::{BaseStrategy, choose_base_strategy};
552        choose_base_strategy()
553            .ok()
554            .map(|s| canonicalize_for_matching(s.home_dir()).unwrap_or_else(|| s.home_dir().to_path_buf()))
555    }
556    #[cfg(not(feature = "native"))]
557    {
558        None
559    }
560}
561
562/// Expand a leading `~` in a path pattern to the user's home directory, so a
563/// user-level config (`~/.config/rumdl/rumdl.toml`) can name a home path
564/// without hardcoding a username.
565///
566/// Only a bare `~` and a `~/` prefix expand. `~` is a legal filename character
567/// everywhere else (editor backups like `notes.md~`, a literal `docs/~drafts`),
568/// so it is left alone there. `~user` is not expanded either: resolving another
569/// user's home needs the password database, and treating it as the current
570/// user's home would silently match the wrong directory.
571///
572/// The expansion is a glob pattern, so separators are normalized to `/` on
573/// Windows: `\` is globset's escape character, and matched paths are normalized
574/// the same way (see [`path_relative_to`]).
575pub fn expand_home_prefix(pattern: &str) -> Cow<'_, str> {
576    // Resolve the home directory only for a pattern that references it: every
577    // other pattern would otherwise pay for the lookup and its canonicalization.
578    if !has_home_prefix(pattern) {
579        return Cow::Borrowed(pattern);
580    }
581    expand_home_prefix_impl(pattern, home_dir().as_deref())
582}
583
584/// Whether `pattern` starts with a home reference (`~` or `~/`).
585fn has_home_prefix(pattern: &str) -> bool {
586    pattern == "~" || pattern.starts_with("~/")
587}
588
589fn expand_home_prefix_impl<'a>(pattern: &'a str, home: Option<&Path>) -> Cow<'a, str> {
590    let Some(suffix) = (if pattern == "~" {
591        Some("")
592    } else {
593        pattern.strip_prefix("~/")
594    }) else {
595        return Cow::Borrowed(pattern);
596    };
597    let Some(home) = home else {
598        return Cow::Borrowed(pattern);
599    };
600
601    let home = normalize_pattern_separators(home.to_string_lossy());
602    let home = home.trim_end_matches('/');
603    if suffix.is_empty() {
604        Cow::Owned(home.to_string())
605    } else {
606        Cow::Owned(format!("{home}/{suffix}"))
607    }
608}
609
610/// Normalize path separators to `/` for glob matching. On Windows `\` is
611/// globset's escape character, so a native path must be rewritten before it can
612/// be used as - or matched against - a pattern. No-op on Unix, where `\` is a
613/// legal filename character.
614fn normalize_pattern_separators(path: Cow<'_, str>) -> Cow<'_, str> {
615    if cfg!(windows) && path.contains('\\') {
616        Cow::Owned(path.replace('\\', "/"))
617    } else {
618        path
619    }
620}
621
622/// Normalize a config path pattern for matching against paths discovered under
623/// `base`: expand a leading `~`, then rewrite an absolute pattern as one
624/// relative to `base` when `base` contains it.
625///
626/// The rewrite is what makes an absolute pattern usable as a walker override:
627/// the `ignore` crate reads a leading `/` as "anchored to the walk base", so
628/// `/home/dev/docs/**` would otherwise be understood as
629/// `<base>/home/dev/docs/**` and match nothing. A pattern pointing outside
630/// `base` is left absolute - nothing under this walk can match it, which is the
631/// correct outcome.
632///
633/// A pattern can also name `base`'s location through a symlink
634/// (`/var/folders/…` for a base at `/private/var/folders/…`), which no strip of
635/// `base` in either form removes. Its leading literal components are then
636/// resolved, giving the same location in the base's own spelling. Only that
637/// prefix is rewritten and the strip consumes it, so what survives is the
638/// pattern as written. A pattern whose *first* component holds a wildcard or a
639/// brace alternation has no such prefix and stays absolute.
640pub fn normalize_pattern_for_base(pattern: &str, base: Option<&Path>) -> String {
641    let expanded = expand_home_prefix(pattern);
642    let Some(base) = base else {
643        return expanded.into_owned();
644    };
645    if !is_absolute_pattern(&expanded) {
646        return expanded.into_owned();
647    }
648
649    if let Some(relative) = strip_base_prefix(Path::new(expanded.as_ref()), base) {
650        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
651    }
652    if let Some(canonical_pattern) = canonicalize_pattern_prefix(&expanded)
653        && let Some(relative) = strip_base_prefix(Path::new(&canonical_pattern), base)
654    {
655        return normalize_pattern_separators(relative.to_string_lossy()).into_owned();
656    }
657    expanded.into_owned()
658}
659
660/// `pattern` with `base` removed, trying the base as given and canonicalized so
661/// a symlinked or non-canonical base (macOS `/var`, a Windows 8.3 short name)
662/// still strips. `None` when the pattern does not live under `base`.
663fn strip_base_prefix<'a>(pattern: &'a Path, base: &Path) -> Option<&'a Path> {
664    pattern.strip_prefix(base).ok().or_else(|| {
665        let canonical = canonicalize_for_matching(base)?;
666        pattern.strip_prefix(canonical).ok()
667    })
668}
669
670/// Expands directory-style patterns to also match files within them.
671/// Pattern "dir/path" becomes ["dir/path", "dir/path/**"] to match both
672/// the directory itself and all contents recursively. A leading `~` is
673/// expanded first (see [`expand_home_prefix`]).
674///
675/// The expansion is driven by the pattern's *final* component: it names a
676/// directory only when it holds no wildcard. `docs/*` therefore stays as
677/// written (it names direct children, and `docs/*/**` would newly exclude
678/// nested contents), while `**/.cursor/plans` gains its contents-expansion
679/// despite the wildcard earlier in the pattern.
680pub fn expand_directory_pattern(pattern: &str) -> Vec<String> {
681    let pattern = expand_home_prefix(pattern);
682    let base = pattern.trim_end_matches('/');
683    let final_component = base.rsplit('/').next().unwrap_or(base);
684
685    if final_component.is_empty() || final_component.contains(['*', '?', '[']) {
686        return vec![pattern.to_string()];
687    }
688
689    vec![
690        base.to_string(),     // Match the directory itself
691        format!("{base}/**"), // Match everything underneath
692    ]
693}
694
695/// The `ignore` override rule that excludes `pattern`.
696///
697/// The crate spells exclusion with a leading `!`; a pattern already carrying one
698/// passes through.
699pub fn exclude_override_rule(pattern: &str) -> String {
700    if pattern.starts_with('!') {
701        pattern.to_string()
702    } else {
703        format!("!{pattern}")
704    }
705}
706
707/// Whether every glob an `exclude` pattern turns into compiles.
708///
709/// An exclude pattern reaches two consumers: [`ExcludeMatchers`] compiles each
710/// expansion with `globset`, and the walker adds each as an `ignore` override.
711/// Both are mirrored here so a caller holding only the pattern can tell whether
712/// either would reject it, which is also when either would print it.
713pub fn exclude_pattern_compiles(pattern: &str) -> bool {
714    expand_directory_pattern(pattern).iter().all(|expanded| {
715        Glob::new(expanded).is_ok()
716            && ignore::overrides::OverrideBuilder::new(Path::new("."))
717                .add(&exclude_override_rule(expanded))
718                .is_ok()
719    })
720}
721
722/// Whether an `include` pattern compiles as a walker override.
723///
724/// Answers for the pattern as given, which is only the form the walker uses once
725/// [`normalize_pattern_for_base`] has run: stripping a base prefix removes
726/// whatever the base's own name held, and an absolute pattern under a directory
727/// called `notes [2019-2021]` carries a character class over a descending range
728/// until the prefix comes off. Ask this about the pattern the walker is about to
729/// add, never about the one a config file spelled.
730pub fn include_pattern_compiles(pattern: &str) -> bool {
731    ignore::overrides::OverrideBuilder::new(Path::new("."))
732        .add(&expand_home_prefix(pattern))
733        .is_ok()
734}
735
736/// Compiled `exclude` patterns with directory-pattern expansion applied.
737///
738/// Match paths through [`matched_pattern`](Self::matched_pattern) using a
739/// root-relative path (the CLI relativizes against the project root, the
740/// LSP against the containing workspace root) so patterns like
741/// `docs/drafts` behave identically everywhere.
742pub struct ExcludeMatchers {
743    matchers: Vec<(String, GlobMatcher)>,
744    /// Whether any pattern is absolute, i.e. whether matching has to consider
745    /// a file's absolute path at all. Keeps the common (all-relative) case
746    /// from paying for the canonicalization that check needs.
747    has_absolute: bool,
748    /// Spellings of a file the absolute patterns reach through a symlink.
749    aliases: PathAliases,
750    /// Patterns that failed to compile, with their errors. Callers decide
751    /// how to surface these (CLI prints to stderr, LSP logs).
752    pub invalid: Vec<(String, String)>,
753}
754
755/// Whether `pattern` names an absolute location. A leading `/` counts on every
756/// platform: patterns use `/` separators, so a Unix-style path stays absolute
757/// when the same config is read on Windows.
758pub fn is_absolute_pattern(pattern: &str) -> bool {
759    pattern.starts_with('/') || Path::new(pattern).is_absolute()
760}
761
762/// Whether `pattern` names an absolute location in any of its spellings.
763///
764/// A brace alternation can put the absolute part past the start of the pattern
765/// (`{/opt,/srv}/docs/**`), where [`is_absolute_pattern`] cannot see it. Callers
766/// deciding whether to match a file's absolute path at all must ask this, or
767/// such a pattern is never given an absolute path to match.
768pub fn has_absolute_spelling(pattern: &str) -> bool {
769    if is_absolute_pattern(pattern) {
770        return true;
771    }
772    pattern.contains('{')
773        && expand_braces(pattern)
774            .iter()
775            .any(|spelling| is_absolute_pattern(spelling))
776}
777
778/// How many literal spellings one pattern's brace alternations may produce.
779///
780/// Expansion only *discovers* directory prefixes to canonicalize (see
781/// [`PathAliases`]); it never decides whether a pattern matches. Past this
782/// point a pattern like `{a,b}{c,d}{e,f}…` is multiplying out work that buys
783/// nothing, so the pattern is left unexpanded.
784const MAX_BRACE_EXPANSIONS: usize = 64;
785
786/// Every literal spelling of `pattern`'s brace alternations:
787/// `/{var/folders,tmp}/**` yields `/var/folders/**` and `/tmp/**`.
788///
789/// Returns just `pattern` when it holds no alternation, when its braces are
790/// unbalanced, or when expanding would exceed [`MAX_BRACE_EXPANSIONS`].
791/// Character classes are opaque, so a comma inside `[...]` stays literal.
792fn expand_braces(pattern: &str) -> Vec<String> {
793    let mut pending = vec![pattern.to_string()];
794    let mut expanded: Vec<String> = Vec::new();
795    while let Some(current) = pending.pop() {
796        let Some((prefix, alternatives, suffix)) = split_first_alternation(&current) else {
797            expanded.push(current);
798            continue;
799        };
800        if pending.len() + expanded.len() + alternatives.len() > MAX_BRACE_EXPANSIONS {
801            return vec![pattern.to_string()];
802        }
803        for alternative in alternatives {
804            pending.push(format!("{prefix}{alternative}{suffix}"));
805        }
806    }
807    expanded
808}
809
810/// Split `pattern` at its first top-level brace alternation into the text
811/// before it, its alternatives, and the text after it. `None` when there is no
812/// alternation to split on, including an unclosed `{`.
813///
814/// Empty alternatives are dropped, mirroring globset: it compiles `x{,y}` to
815/// `^x(?:y)$`, so `x` is not one of that pattern's spellings.
816fn split_first_alternation(pattern: &str) -> Option<(&str, Vec<&str>, &str)> {
817    let bytes = pattern.as_bytes();
818    let mut open = None;
819    let mut depth = 0usize;
820    let mut in_class = false;
821    let mut alternatives = Vec::new();
822    let mut alternative_start = 0;
823    let mut index = 0;
824    while index < bytes.len() {
825        match bytes[index] {
826            b'\\' if !cfg!(windows) => index += 1,
827            b'[' if !in_class => in_class = true,
828            b']' if in_class => in_class = false,
829            _ if in_class => {}
830            b'{' => {
831                depth += 1;
832                if depth == 1 {
833                    open = Some(index);
834                    alternative_start = index + 1;
835                }
836            }
837            b',' if depth == 1 => {
838                alternatives.push(&pattern[alternative_start..index]);
839                alternative_start = index + 1;
840            }
841            b'}' if depth > 0 => {
842                depth -= 1;
843                if depth == 0 {
844                    alternatives.push(&pattern[alternative_start..index]);
845                    alternatives.retain(|alternative| !alternative.is_empty());
846                    if alternatives.is_empty() {
847                        return None;
848                    }
849                    return Some((&pattern[..open?], alternatives, &pattern[index + 1..]));
850                }
851            }
852            _ => {}
853        }
854        index += 1;
855    }
856    None
857}
858
859/// The leading run of `pattern`'s path components that hold no glob
860/// metacharacter: `/var/folders/**` yields `/var/folders`, `/var/log/app*.md`
861/// yields `/var/log`, and a fully literal pattern yields itself.
862///
863/// `None` when the run is empty or names only the filesystem root, neither of
864/// which can resolve to a different location. The result is always a prefix
865/// slice of `pattern`, so the remainder can be re-attached by byte offset.
866///
867/// An escaped metacharacter (`\*` on Unix) simply ends the run early. That
868/// yields a shorter prefix, never a wrong one.
869fn literal_path_prefix(pattern: &str) -> Option<&str> {
870    let mut end = 0;
871    let mut saw_component = false;
872    for component in pattern.split('/') {
873        if component.contains(GLOB_METACHARS) {
874            break;
875        }
876        saw_component |= !component.is_empty();
877        // Skip past this component and the separator that follows it.
878        end += component.len() + 1;
879    }
880    if !saw_component {
881        return None;
882    }
883    // The loop counted a separator after the final component; the pattern only
884    // has one when the run did not reach its end. A trailing separator is
885    // dropped so the remainder re-attaches with exactly one.
886    let prefix = &pattern[..(end - 1).min(pattern.len())];
887    Some(prefix.strip_suffix('/').unwrap_or(prefix))
888}
889
890/// `pattern` with its leading literal components resolved through symlinks, or
891/// `None` when there is nothing to resolve, the prefix does not exist, or
892/// resolving changes nothing.
893fn canonicalize_pattern_prefix(pattern: &str) -> Option<String> {
894    let prefix = literal_path_prefix(pattern)?;
895    let canonical = canonicalize_for_matching(Path::new(prefix))?;
896    let canonical = normalize_pattern_separators(canonical.to_string_lossy()).into_owned();
897    if canonical == prefix {
898        return None;
899    }
900    Some(format!("{canonical}{}", &pattern[prefix.len()..]))
901}
902
903/// Alternative spellings of a path, implied by the absolute patterns in a
904/// configuration.
905///
906/// A pattern names a location the way the user wrote it (`/var/folders/**` on
907/// macOS); the file it is matched against arrives canonicalized
908/// (`/private/var/folders/…`), so the two never meet. Each pair recorded here
909/// is one symlinked prefix some pattern reached a location through: the
910/// canonical form of that pattern's leading literal components, and the
911/// spelling the pattern used for them.
912///
913/// Rewriting the *path* rather than the pattern leaves globset the only
914/// authority on what a pattern means, and cannot invent a match:
915/// `canonicalize(as_written) == canonical` together with `path == canonical +
916/// rest` say that `as_written + rest` names that same file. Brace alternations
917/// are expanded only to find more prefixes to canonicalize, so an expansion
918/// that disagrees with globset can cost a spelling, never fabricate one.
919#[derive(Debug, Default)]
920pub struct PathAliases {
921    /// `(canonical prefix, the spelling a pattern used for it)`.
922    prefixes: Vec<(PathBuf, String)>,
923}
924
925impl PathAliases {
926    /// Collect the symlinked prefixes `patterns` reach locations through.
927    ///
928    /// Each pattern is canonicalized once here, at cache-build time, so
929    /// per-file matching pays no syscall.
930    pub fn new<'a>(patterns: impl IntoIterator<Item = &'a str>) -> Self {
931        let mut prefixes: Vec<(PathBuf, String)> = Vec::new();
932        for pattern in patterns {
933            let pattern = expand_home_prefix(pattern);
934            if !has_absolute_spelling(&pattern) {
935                continue;
936            }
937            for spelling in expand_braces(&pattern) {
938                let Some(as_written) = literal_path_prefix(&spelling) else {
939                    continue;
940                };
941                if !is_absolute_pattern(as_written) {
942                    continue;
943                }
944                let Some(canonical) = canonicalize_for_matching(Path::new(as_written)) else {
945                    continue;
946                };
947                if canonical == Path::new(as_written) {
948                    continue;
949                }
950                let as_written = normalize_pattern_separators(Cow::Borrowed(as_written)).into_owned();
951                if !prefixes.iter().any(|(c, w)| c == &canonical && w == &as_written) {
952                    prefixes.push((canonical, as_written));
953                }
954            }
955        }
956        Self { prefixes }
957    }
958
959    pub fn is_empty(&self) -> bool {
960        self.prefixes.is_empty()
961    }
962
963    /// The spellings of `path` reachable through a recorded prefix, as glob
964    /// match candidates. Empty when no pattern reached `path`'s location
965    /// through a symlink, which is every configuration that has none.
966    pub fn spellings_of(&self, path: &Path) -> Vec<String> {
967        self.prefixes
968            .iter()
969            .filter_map(|(canonical, as_written)| {
970                let rest = path.strip_prefix(canonical).ok()?;
971                if rest.as_os_str().is_empty() {
972                    return Some(as_written.clone());
973                }
974                let rest = normalize_pattern_separators(rest.to_string_lossy());
975                Some(format!("{as_written}/{rest}"))
976            })
977            .collect()
978    }
979}
980
981impl ExcludeMatchers {
982    pub fn new(patterns: &[String]) -> Self {
983        let mut matchers = Vec::new();
984        let mut invalid = Vec::new();
985        let mut has_absolute = false;
986        for pattern in patterns.iter().flat_map(|p| expand_directory_pattern(p)) {
987            has_absolute |= has_absolute_spelling(&pattern);
988            match Glob::new(&pattern) {
989                Ok(glob) => matchers.push((pattern, glob.compile_matcher())),
990                Err(e) => invalid.push((pattern, e.to_string())),
991            }
992        }
993        let aliases = PathAliases::new(matchers.iter().map(|(pattern, _)| pattern.as_str()));
994        Self {
995            matchers,
996            has_absolute,
997            aliases,
998            invalid,
999        }
1000    }
1001
1002    pub fn is_empty(&self) -> bool {
1003        self.matchers.is_empty()
1004    }
1005
1006    /// The first pattern matching `relative_path`, if any.
1007    pub fn matched_pattern(&self, relative_path: &str) -> Option<&str> {
1008        self.matchers
1009            .iter()
1010            .find(|(_, matcher)| matcher.is_match(relative_path))
1011            .map(|(pattern, _)| pattern.as_str())
1012    }
1013
1014    pub fn is_match(&self, relative_path: &str) -> bool {
1015        self.matched_pattern(relative_path).is_some()
1016    }
1017
1018    /// The first pattern matching a file, if any.
1019    ///
1020    /// Both forms of the file are tried: its `relative` form (how patterns are
1021    /// normally written - relative to the project or workspace root) and its
1022    /// absolute path, which is what an absolute pattern matches. Absolute
1023    /// patterns reach config either written literally or through `~` expansion,
1024    /// and the walker's overrides cannot apply them (the `ignore` crate anchors
1025    /// a leading `/` to the walk root), so this is where they take effect.
1026    ///
1027    /// Checking the absolute path cannot widen a relative pattern: globs are
1028    /// anchored at the start of the matched string, so `drafts/**` never
1029    /// matches `/home/dev/proj/drafts/note.md`.
1030    ///
1031    /// `absolute` is canonicalized before matching, since an expanded `~`
1032    /// resolves to a canonical location. Files that cannot be canonicalized
1033    /// (already deleted, unreadable) are matched as given.
1034    ///
1035    /// A pattern that named its location through a symlink (`/var/folders/**`
1036    /// for a macOS temp directory) never matches that canonical form, so the
1037    /// file's other spellings are tried too (see [`PathAliases`]).
1038    pub fn matched_pattern_for_file(&self, relative: Option<&str>, absolute: &Path) -> Option<&str> {
1039        if let Some(pattern) = relative.and_then(|rel| self.matched_pattern(rel)) {
1040            return Some(pattern);
1041        }
1042        if !self.has_absolute {
1043            return None;
1044        }
1045        let canonical = canonicalize_for_matching(absolute);
1046        let absolute = canonical.as_deref().unwrap_or(absolute);
1047        if let Some(pattern) = self.matched_pattern(&normalize_pattern_separators(absolute.to_string_lossy())) {
1048            return Some(pattern);
1049        }
1050        self.aliases
1051            .spellings_of(absolute)
1052            .into_iter()
1053            .find_map(|alias| self.matched_pattern(&alias))
1054    }
1055
1056    /// Whether any pattern matches the file (see [`matched_pattern_for_file`](Self::matched_pattern_for_file)).
1057    pub fn excludes_file(&self, relative: Option<&str>, absolute: &Path) -> bool {
1058        self.matched_pattern_for_file(relative, absolute).is_some()
1059    }
1060}
1061
1062/// Relativize `path` against `base` for exclude-pattern matching,
1063/// canonicalizing both sides so symlinks (e.g. macOS `/tmp`) and Windows
1064/// path-representation differences don't defeat the prefix strip. Returns
1065/// `None` when `path` is not under `base`.
1066///
1067/// Separators are normalized to `/` on Windows, following the project
1068/// convention for path strings; globset matches either form, but log
1069/// output and assertions see one canonical shape.
1070pub fn path_relative_to(path: &Path, base: &Path) -> Option<String> {
1071    let canonical_base = base.canonicalize().ok()?;
1072    let canonical_path = path.canonicalize().ok()?;
1073    canonical_path.strip_prefix(&canonical_base).ok().map(|rel| {
1074        let rel = rel.to_string_lossy();
1075        if cfg!(windows) {
1076            rel.replace('\\', "/")
1077        } else {
1078            rel.to_string()
1079        }
1080    })
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085    use super::*;
1086    use std::fs;
1087    use tempfile::tempdir;
1088
1089    #[test]
1090    fn markdown_extensions_match_case_insensitively() {
1091        for ext in ["md", "MD", "Rmd", "rmd", "MarkDown", "qmd", "mdx"] {
1092            assert!(is_markdown_extension(OsStr::new(ext)), "{ext} should match");
1093        }
1094        for ext in ["rs", "txt", "mdq", ""] {
1095            assert!(!is_markdown_extension(OsStr::new(ext)), "{ext} should not match");
1096        }
1097        assert!(has_markdown_extension(Path::new("a/b/README.md")));
1098        assert!(has_markdown_extension(Path::new("notebook.Rmd")));
1099        assert!(!has_markdown_extension(Path::new("no_extension")));
1100        assert!(!has_markdown_extension(Path::new("lib.rs")));
1101    }
1102
1103    #[test]
1104    fn lintable_selector_makes_adapter_capabilities_explicit() {
1105        let dir = tempdir().unwrap();
1106        let root = dir.path();
1107        fs::create_dir_all(root.join("docs")).unwrap();
1108        fs::create_dir_all(root.join("templates")).unwrap();
1109        fs::create_dir_all(root.join("src")).unwrap();
1110        for relative in [
1111            "docs/guide.md",
1112            "docs/notes.txt",
1113            "templates/page.md.jinja",
1114            "src/lib.rs",
1115            "src/upper.RS",
1116        ] {
1117            fs::write(root.join(relative), "content\n").unwrap();
1118        }
1119        let includes = vec![
1120            "docs/**".to_string(),
1121            "templates/**/*.md.jinja".to_string(),
1122            "src/**/*.rs".to_string(),
1123        ];
1124
1125        let markdown = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Markdown);
1126        assert!(markdown.keeps(&root.join("docs/guide.md")));
1127        assert!(markdown.keeps(&root.join("templates/page.md.jinja")));
1128        assert!(!markdown.keeps(&root.join("docs/notes.txt")));
1129        assert!(
1130            !markdown.keeps(&root.join("src/lib.rs")),
1131            "an LSP must not parse a complete Rust source file as Markdown"
1132        );
1133
1134        let rustdoc = LintablePathSelector::new(Some(root), &includes, LintableFileMode::MarkdownAndRust);
1135        assert!(rustdoc.keeps(&root.join("src/lib.rs")));
1136        assert!(!rustdoc.keeps(&root.join("src/upper.RS")));
1137        assert!(!rustdoc.keeps(&root.join("docs/notes.txt")));
1138
1139        let unrestricted = LintablePathSelector::new(Some(root), &includes, LintableFileMode::Any);
1140        assert!(unrestricted.keeps(&root.join("docs/notes.txt")));
1141    }
1142
1143    #[test]
1144    fn workspace_scan_rejects_explicit_rust_includes() {
1145        let dir = tempdir().unwrap();
1146        let root = dir.path().to_path_buf();
1147        fs::create_dir(root.join("src")).unwrap();
1148        fs::write(root.join("src/lib.rs"), "/// # Not a document\n").unwrap();
1149        fs::write(root.join("README.md"), "# Readme\n").unwrap();
1150
1151        let options = MarkdownWalkOptions {
1152            respect_gitignore: false,
1153            skip_vendor_dirs: true,
1154        };
1155        let includes = vec!["src/**/*.rs".to_string()];
1156        let excludes = ExcludeMatchers::new(&[]);
1157        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);
1158
1159        assert!(scan.collect(std::slice::from_ref(&root)).is_empty());
1160        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("src/lib.rs")));
1161    }
1162
1163    #[test]
1164    fn workspace_scan_applies_includes_to_standard_and_explicit_files() {
1165        let dir = tempdir().unwrap();
1166        let root = dir.path().to_path_buf();
1167        fs::create_dir(root.join("docs")).unwrap();
1168        fs::create_dir(root.join("templates")).unwrap();
1169        fs::write(root.join("README.md"), "# Root\n").unwrap();
1170        fs::write(root.join("docs/guide.md"), "# Guide\n").unwrap();
1171        fs::write(root.join("templates/page.md.jinja"), "# Template\n").unwrap();
1172        fs::write(root.join("templates/page.txt"), "not markdown\n").unwrap();
1173
1174        let options = MarkdownWalkOptions {
1175            respect_gitignore: false,
1176            skip_vendor_dirs: true,
1177        };
1178        let includes = vec!["docs/**".to_string(), "templates/**/*.md.jinja".to_string()];
1179        let excludes = ExcludeMatchers::new(&[]);
1180        let scan = MarkdownWorkspaceScan::new(&options, &includes, &excludes);
1181
1182        // The test creates these names itself, so normalizing separators
1183        // unconditionally is safe and keeps one expected value for every platform.
1184        let names: Vec<String> = scan
1185            .collect(std::slice::from_ref(&root))
1186            .iter()
1187            .map(|path| path.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"))
1188            .collect();
1189        assert_eq!(names, vec!["docs/guide.md", "templates/page.md.jinja"]);
1190
1191        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.md.jinja")));
1192        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
1193        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("templates/page.txt")));
1194    }
1195
1196    #[test]
1197    fn workspace_scan_does_not_prune_a_vendor_named_root() {
1198        let dir = tempdir().unwrap();
1199        let root = dir.path().join("target");
1200        fs::create_dir(&root).unwrap();
1201        fs::write(root.join("README.md"), "# Root\n").unwrap();
1202        fs::create_dir(root.join("target")).unwrap();
1203        fs::write(root.join("target/generated.md"), "# Generated\n").unwrap();
1204
1205        let options = MarkdownWalkOptions {
1206            respect_gitignore: false,
1207            skip_vendor_dirs: true,
1208        };
1209        let excludes = ExcludeMatchers::new(&[]);
1210        let scan = MarkdownWorkspaceScan::new(&options, &[], &excludes);
1211
1212        assert_eq!(scan.collect(std::slice::from_ref(&root)), vec![root.join("README.md")]);
1213        assert!(!scan.path_is_ignored(std::slice::from_ref(&root), &root.join("README.md")));
1214        assert!(scan.path_is_ignored(std::slice::from_ref(&root), &root.join("target/generated.md")));
1215    }
1216
1217    #[test]
1218    fn the_type_glob_selects_exactly_what_counts_as_markdown() {
1219        assert_eq!(any_case_extension_glob("md"), "*.[mM][dD]");
1220
1221        // The glob stands in for `is_markdown_extension` inside a walk, so the
1222        // two have to agree on every spelling, not just the lowercase one.
1223        let mut builder = globset::GlobSetBuilder::new();
1224        for ext in MARKDOWN_EXTENSIONS {
1225            builder.add(
1226                globset::GlobBuilder::new(&any_case_extension_glob(ext))
1227                    .literal_separator(true)
1228                    .build()
1229                    .unwrap(),
1230            );
1231        }
1232        let globs = builder.build().unwrap();
1233
1234        for ext in MARKDOWN_EXTENSIONS {
1235            for spelling in [ext.to_ascii_lowercase(), ext.to_ascii_uppercase(), capitalize(ext)] {
1236                let name = format!("README.{spelling}");
1237                assert!(
1238                    globs.is_match(&name),
1239                    "{name} is markdown by extension but no type glob selects it"
1240                );
1241                assert!(is_markdown_extension(OsStr::new(&spelling)), "{spelling} should match");
1242            }
1243        }
1244
1245        // Control: the glob widens case, not the extension set.
1246        for name in ["lib.rs", "notes.txt", "README.mdq", "README.m"] {
1247            assert!(!globs.is_match(name), "{name} should not be selected");
1248        }
1249    }
1250
1251    fn capitalize(ext: &str) -> String {
1252        let mut chars = ext.chars();
1253        match chars.next() {
1254            Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
1255            None => String::new(),
1256        }
1257    }
1258
1259    #[test]
1260    fn walk_includes_hidden_files() {
1261        let temp = tempdir().unwrap();
1262        fs::create_dir_all(temp.path().join(".github")).unwrap();
1263        fs::write(temp.path().join(".github/PULL_REQUEST_TEMPLATE.md"), "# hi").unwrap();
1264        fs::write(temp.path().join("README.md"), "# hi").unwrap();
1265
1266        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
1267            .build()
1268            .flatten()
1269            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1270            .map(|e| e.path().to_path_buf())
1271            .collect();
1272        assert!(files.iter().any(|p| p.ends_with(".github/PULL_REQUEST_TEMPLATE.md")));
1273        assert!(files.iter().any(|p| p.ends_with("README.md")));
1274    }
1275
1276    #[test]
1277    fn walk_honors_gitignore_when_enabled_only() {
1278        let temp = tempdir().unwrap();
1279        fs::write(temp.path().join(".gitignore"), "ignored.md\n").unwrap();
1280        fs::write(temp.path().join("ignored.md"), "# hi").unwrap();
1281        fs::write(temp.path().join("kept.md"), "# hi").unwrap();
1282
1283        let walk = |respect: bool| -> Vec<std::path::PathBuf> {
1284            markdown_walk_builder(
1285                temp.path(),
1286                &MarkdownWalkOptions {
1287                    respect_gitignore: respect,
1288                    ..Default::default()
1289                },
1290            )
1291            .build()
1292            .flatten()
1293            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1294            .map(|e| e.path().to_path_buf())
1295            .collect()
1296        };
1297
1298        let respected = walk(true);
1299        assert!(!respected.iter().any(|p| p.ends_with("ignored.md")));
1300        assert!(respected.iter().any(|p| p.ends_with("kept.md")));
1301
1302        let unrespected = walk(false);
1303        assert!(unrespected.iter().any(|p| p.ends_with("ignored.md")));
1304    }
1305
1306    #[test]
1307    fn a_gitignore_above_the_repository_root_stays_outside_it() {
1308        let temp = tempdir().unwrap();
1309        fs::write(temp.path().join(".gitignore"), "*.md\n").unwrap();
1310        let repo = temp.path().join("repo");
1311        fs::create_dir_all(repo.join(".git")).unwrap();
1312        fs::write(repo.join("kept.md"), "# hi").unwrap();
1313
1314        let walk = |root: &Path| -> Vec<std::path::PathBuf> {
1315            markdown_walk_builder(root, &MarkdownWalkOptions::default())
1316                .build()
1317                .flatten()
1318                .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1319                .map(|e| e.path().to_path_buf())
1320                .collect()
1321        };
1322
1323        assert!(
1324            walk(&repo).iter().any(|p| p.ends_with("kept.md")),
1325            "git reads no gitignore above the repository root, so neither does the walk"
1326        );
1327
1328        // Control: outside a repository there is no root to stop at, and the
1329        // ignore files above are all the walk has to go on.
1330        fs::remove_dir(repo.join(".git")).unwrap();
1331        assert!(
1332            !walk(&repo).iter().any(|p| p.ends_with("kept.md")),
1333            "with no repository to bound it, the walk keeps reading upward"
1334        );
1335    }
1336
1337    #[test]
1338    fn the_repository_boundary_needs_every_root_to_have_one() {
1339        let temp = tempdir().unwrap();
1340        let inside = temp.path().join("repo/docs");
1341        fs::create_dir_all(&inside).unwrap();
1342        fs::create_dir_all(temp.path().join("repo/.git")).unwrap();
1343        let outside = temp.path().join("plain");
1344        fs::create_dir_all(&outside).unwrap();
1345
1346        assert!(stops_at_repository_root(&[&inside]), "a root under a repository root");
1347        assert!(!stops_at_repository_root(&[&outside]), "a root under no repository");
1348
1349        // A walk has one setting for all of its roots. Bounding this one would
1350        // strip the outside root of gitignore handling altogether, which is a
1351        // worse answer than reading one file too many.
1352        assert!(!stops_at_repository_root(&[inside.as_path(), outside.as_path()]));
1353        assert!(!stops_at_repository_root(&[] as &[&Path]), "no root is no repository");
1354
1355        // A worktree and a submodule mark their root with a `.git` file rather
1356        // than a directory, and both are still repository roots.
1357        let worktree = temp.path().join("worktree");
1358        fs::create_dir_all(&worktree).unwrap();
1359        fs::write(worktree.join(".git"), "gitdir: /elsewhere/.git/worktrees/x\n").unwrap();
1360        assert!(stops_at_repository_root(&[&worktree]));
1361    }
1362
1363    #[test]
1364    fn walk_honors_markdownlintignore() {
1365        let temp = tempdir().unwrap();
1366        fs::write(temp.path().join(".markdownlintignore"), "legacy.md\n").unwrap();
1367        fs::write(temp.path().join("legacy.md"), "# hi").unwrap();
1368        fs::write(temp.path().join("kept.md"), "# hi").unwrap();
1369
1370        let files: Vec<_> = markdown_walk_builder(temp.path(), &MarkdownWalkOptions::default())
1371            .build()
1372            .flatten()
1373            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1374            .map(|e| e.path().to_path_buf())
1375            .collect();
1376        assert!(!files.iter().any(|p| p.ends_with("legacy.md")));
1377        assert!(files.iter().any(|p| p.ends_with("kept.md")));
1378    }
1379
1380    #[test]
1381    fn vendor_dirs_skipped_only_when_requested() {
1382        let temp = tempdir().unwrap();
1383        for dir in ["node_modules", "target", "src"] {
1384            fs::create_dir_all(temp.path().join(dir)).unwrap();
1385            fs::write(temp.path().join(dir).join("doc.md"), "# hi").unwrap();
1386        }
1387
1388        let walk = |skip: bool| -> Vec<std::path::PathBuf> {
1389            markdown_walk_builder(
1390                temp.path(),
1391                &MarkdownWalkOptions {
1392                    skip_vendor_dirs: skip,
1393                    // Disable gitignore handling so ambient .gitignore files in the
1394                    // temp directory's ancestry cannot mask the vendor-dir filtering
1395                    // this test exercises.
1396                    respect_gitignore: false,
1397                },
1398            )
1399            .build()
1400            .flatten()
1401            .filter(|e| e.file_type().is_some_and(|t| t.is_file()))
1402            .map(|e| e.path().to_path_buf())
1403            .collect()
1404        };
1405
1406        let skipped = walk(true);
1407        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
1408        assert!(!skipped.iter().any(|p| p.to_string_lossy().contains("target")));
1409        assert!(skipped.iter().any(|p| p.ends_with("src/doc.md")));
1410
1411        let unskipped = walk(false);
1412        assert!(unskipped.iter().any(|p| p.to_string_lossy().contains("node_modules")));
1413    }
1414
1415    #[test]
1416    fn explicit_file_name_glob_extracts_literal_extensions() {
1417        assert_eq!(explicit_file_name_glob("**/*.md.jinja"), Some("*.md.jinja"));
1418        assert_eq!(explicit_file_name_glob("*.md.jinja"), Some("*.md.jinja"));
1419        assert_eq!(explicit_file_name_glob("docs/*.txt"), Some("*.txt"));
1420        assert_eq!(explicit_file_name_glob("templates/NOTES.tmpl"), Some("NOTES.tmpl"));
1421        assert_eq!(explicit_file_name_glob("*.md"), Some("*.md"));
1422        assert_eq!(explicit_file_name_glob("a/b/c/*.md.tmpl"), Some("*.md.tmpl"));
1423    }
1424
1425    #[test]
1426    fn explicit_file_name_glob_rejects_unpinned_patterns() {
1427        for pattern in [
1428            "docs/",
1429            "docs/**",
1430            "docs",
1431            "*",
1432            "**",
1433            "**/*",
1434            "*.*",
1435            "*.md*",
1436            "*.{md,jinja}",
1437            "*.md?",
1438            "data.[ch]",
1439            "!drafts/*.md.jinja",
1440            "",
1441            "**/Makefile",
1442            "*.",
1443        ] {
1444            assert_eq!(explicit_file_name_glob(pattern), None, "{pattern:?} should not qualify");
1445        }
1446    }
1447
1448    #[test]
1449    fn explicit_include_matchers_match_full_relative_paths() {
1450        let matchers = ExplicitIncludeMatchers::new(&[
1451            "**/*.md.jinja".to_string(),
1452            "docs/**".to_string(),
1453            "templates/NOTES.tmpl".to_string(),
1454        ]);
1455        assert!(!matchers.is_empty());
1456        assert!(matchers.matches_relative_path("test.md.jinja"));
1457        assert!(matchers.matches_relative_path("a/b/test.md.jinja"));
1458        assert!(matchers.matches_relative_path("templates/NOTES.tmpl"));
1459        // The directory pattern must not widen the filter to arbitrary files.
1460        assert!(!matchers.matches_relative_path("docs/anything.txt"));
1461        assert!(!matchers.matches_relative_path("test.jinja"));
1462        // A broad sibling pattern must not inherit the literal pattern's
1463        // allowance for files that merely share its name.
1464        assert!(!matchers.matches_relative_path("docs/NOTES.tmpl"));
1465        assert!(!matchers.matches_relative_path("x/templates/NOTES.tmpl"));
1466
1467        let globs: Vec<_> = matchers.file_name_globs().collect();
1468        assert_eq!(globs, vec!["*.md.jinja", "NOTES.tmpl"]);
1469    }
1470
1471    #[test]
1472    fn explicit_include_matchers_follow_gitignore_anchoring() {
1473        // No slash: matches at any depth.
1474        let unanchored = ExplicitIncludeMatchers::new(&["*.md.jinja".to_string()]);
1475        assert!(unanchored.matches_relative_path("test.md.jinja"));
1476        assert!(unanchored.matches_relative_path("a/b/test.md.jinja"));
1477
1478        // Slash: anchored to the root, and `*` does not cross separators.
1479        let anchored = ExplicitIncludeMatchers::new(&["docs/*.txt".to_string()]);
1480        assert!(anchored.matches_relative_path("docs/a.txt"));
1481        assert!(!anchored.matches_relative_path("docs/sub/a.txt"));
1482        assert!(!anchored.matches_relative_path("other/docs/a.txt"));
1483
1484        // Leading slash: anchored, slash stripped for matching.
1485        let rooted = ExplicitIncludeMatchers::new(&["/NOTES.tmpl".to_string()]);
1486        assert!(rooted.matches_relative_path("NOTES.tmpl"));
1487        assert!(!rooted.matches_relative_path("docs/NOTES.tmpl"));
1488    }
1489
1490    #[test]
1491    fn explicit_include_matchers_empty_for_directory_and_wildcard_patterns() {
1492        let matchers = ExplicitIncludeMatchers::new(&["docs/".to_string(), "**/*".to_string()]);
1493        assert!(matchers.is_empty());
1494        assert!(!matchers.matches_relative_path("x.md.jinja"));
1495    }
1496
1497    #[test]
1498    fn explicit_include_matchers_skip_invalid_globs() {
1499        // The unclosed bracket pins a literal `.tmpl` suffix but fails glob
1500        // compilation; it must be skipped without poisoning valid patterns.
1501        let matchers = ExplicitIncludeMatchers::new(&["bad[.tmpl".to_string(), "**/*.md.jinja".to_string()]);
1502        assert!(matchers.matches_relative_path("ok.md.jinja"));
1503        assert_eq!(matchers.file_name_globs().collect::<Vec<_>>(), vec!["*.md.jinja"]);
1504    }
1505
1506    #[test]
1507    fn exclude_matchers_expand_directory_patterns() {
1508        let matchers = ExcludeMatchers::new(&["drafts".to_string(), "*.tmp.md".to_string()]);
1509        assert!(matchers.is_match("drafts"));
1510        assert!(
1511            matchers.is_match("drafts/inner.md"),
1512            "directory pattern must match contents"
1513        );
1514        assert!(matchers.is_match("note.tmp.md"));
1515        assert!(!matchers.is_match("docs/guide.md"));
1516        assert_eq!(matchers.matched_pattern("drafts/inner.md"), Some("drafts/**"));
1517        assert!(matchers.invalid.is_empty());
1518    }
1519
1520    #[test]
1521    fn expand_home_prefix_expands_only_a_leading_tilde() {
1522        let home = Path::new("/home/dev");
1523        assert_eq!(
1524            expand_home_prefix_impl("~/.cursor/plans", Some(home)),
1525            "/home/dev/.cursor/plans"
1526        );
1527        assert_eq!(expand_home_prefix_impl("~", Some(home)), "/home/dev");
1528        assert_eq!(expand_home_prefix_impl("~/", Some(home)), "/home/dev");
1529    }
1530
1531    #[test]
1532    fn expand_home_prefix_leaves_interior_tildes_alone() {
1533        let home = Path::new("/home/dev");
1534        // `~` is a legal filename character; only a leading `~/` is a home reference.
1535        for pattern in ["backup.md~", "docs/~drafts/**", "~user/docs", "**/*~", "!~/secret"] {
1536            assert_eq!(
1537                expand_home_prefix_impl(pattern, Some(home)),
1538                pattern,
1539                "{pattern:?} must be left as written"
1540            );
1541        }
1542    }
1543
1544    #[test]
1545    fn expand_home_prefix_without_a_home_leaves_the_pattern_as_written() {
1546        assert_eq!(expand_home_prefix_impl("~/.cursor/plans", None), "~/.cursor/plans");
1547    }
1548
1549    #[test]
1550    fn normalize_pattern_for_base_rewrites_absolute_patterns_under_the_base() {
1551        let temp = tempdir().unwrap();
1552        // Canonicalize the way production does, so the pattern has the shape an
1553        // expanded `~` produces (on Windows that means no verbatim prefix).
1554        let base = canonicalize_for_matching(temp.path()).unwrap();
1555        let pattern = format!("{}/docs/**", base.to_string_lossy().replace('\\', "/"));
1556        assert_eq!(normalize_pattern_for_base(&pattern, Some(&base)), "docs/**");
1557    }
1558
1559    #[test]
1560    fn normalize_pattern_for_base_strips_through_a_non_canonical_base() {
1561        // The base as handed to us (a symlinked `/var` on macOS, a Windows 8.3
1562        // short name) must still strip.
1563        let temp = tempdir().unwrap();
1564        let canonical = canonicalize_for_matching(temp.path()).unwrap();
1565        let pattern = format!("{}/docs/**", canonical.to_string_lossy().replace('\\', "/"));
1566        assert_eq!(normalize_pattern_for_base(&pattern, Some(temp.path())), "docs/**");
1567    }
1568
1569    #[test]
1570    fn normalize_pattern_for_base_leaves_other_patterns_alone() {
1571        let temp = tempdir().unwrap();
1572        let base = canonicalize_for_matching(temp.path()).unwrap();
1573        // Relative patterns are already base-relative.
1574        assert_eq!(normalize_pattern_for_base("docs/**", Some(&base)), "docs/**");
1575        // An absolute pattern outside the base stays absolute: nothing under
1576        // this walk can match it, which is the correct outcome.
1577        assert_eq!(
1578            normalize_pattern_for_base("/somewhere/else/**", Some(&base)),
1579            "/somewhere/else/**"
1580        );
1581        // With no base there is nothing to rewrite against.
1582        assert_eq!(normalize_pattern_for_base("/abs/docs/**", None), "/abs/docs/**");
1583    }
1584
1585    #[test]
1586    fn strip_verbatim_prefix_unwraps_windows_canonical_paths() {
1587        // The exact shape `canonicalize` returns on Windows. Left unstripped it
1588        // normalizes to `//?/C:/...`, which matches nothing.
1589        assert_eq!(
1590            strip_verbatim_prefix(r"\\?\C:\Users\dev\AppData\Local\Temp\x"),
1591            r"C:\Users\dev\AppData\Local\Temp\x"
1592        );
1593        assert_eq!(strip_verbatim_prefix(r"\\?\C:\"), r"C:\");
1594        // UNC shares unwrap to their ordinary `\\server\share` form.
1595        assert_eq!(
1596            strip_verbatim_prefix(r"\\?\UNC\server\share\docs"),
1597            r"\\server\share\docs"
1598        );
1599    }
1600
1601    #[test]
1602    fn strip_verbatim_prefix_leaves_other_paths_alone() {
1603        for path in [
1604            "/home/dev/docs",
1605            r"C:\Users\dev",
1606            r"\\server\share",
1607            // A device namespace has no ordinary equivalent to unwrap to.
1608            r"\\?\Volume{b75e2c83-0000-0000-0000-602f00000000}\docs",
1609            r"\\?\",
1610            "",
1611        ] {
1612            assert_eq!(strip_verbatim_prefix(path), path, "{path:?} must be left as written");
1613        }
1614    }
1615
1616    #[test]
1617    fn expand_directory_pattern_expands_a_literal_final_component() {
1618        // A glob earlier in the pattern must not block contents-expansion: the
1619        // final component names a directory, so its contents are excluded too.
1620        assert_eq!(
1621            expand_directory_pattern("**/.cursor/plans"),
1622            vec!["**/.cursor/plans", "**/.cursor/plans/**"]
1623        );
1624        assert_eq!(
1625            expand_directory_pattern("docs/**/drafts"),
1626            vec!["docs/**/drafts", "docs/**/drafts/**"]
1627        );
1628        // Alternation names literal directories, so it keeps its expansion.
1629        assert_eq!(
1630            expand_directory_pattern("logs/{a,b}"),
1631            vec!["logs/{a,b}", "logs/{a,b}/**"]
1632        );
1633    }
1634
1635    #[test]
1636    fn expand_directory_pattern_leaves_a_wildcard_final_component_alone() {
1637        // `docs/*` names direct children only; expanding it to `docs/*/**` would
1638        // newly exclude nested contents.
1639        for pattern in ["docs/*", "*.tmp.md", "build/**", "data.[ch]", "notes?"] {
1640            assert_eq!(
1641                expand_directory_pattern(pattern),
1642                vec![pattern.to_string()],
1643                "{pattern:?} must not gain a contents-expansion"
1644            );
1645        }
1646    }
1647
1648    #[test]
1649    fn exclude_matchers_match_an_absolute_pattern_against_an_absolute_path() {
1650        let matchers = ExcludeMatchers::new(&["/home/dev/.cursor/plans".to_string()]);
1651        let excluded = Path::new("/home/dev/.cursor/plans/plan.md");
1652        assert!(
1653            matchers.excludes_file(None, excluded),
1654            "an absolute pattern must match the absolute path when there is no relative form"
1655        );
1656        assert_eq!(
1657            matchers.matched_pattern_for_file(None, excluded),
1658            Some("/home/dev/.cursor/plans/**")
1659        );
1660        // A file inside a project root still has a relative form; the absolute
1661        // pattern must match it through the absolute path.
1662        assert!(matchers.excludes_file(Some(".cursor/plans/plan.md"), excluded));
1663        assert!(!matchers.excludes_file(Some("docs/guide.md"), Path::new("/home/dev/docs/guide.md")));
1664    }
1665
1666    #[test]
1667    fn exclude_matchers_do_not_let_relative_patterns_match_absolute_paths() {
1668        // Relative patterns are anchored at the start of the matched string, so
1669        // adding the absolute-path check must not widen them into `**/drafts`.
1670        let matchers = ExcludeMatchers::new(&["drafts".to_string()]);
1671        assert!(!matchers.excludes_file(None, Path::new("/home/dev/proj/drafts/note.md")));
1672        assert!(matchers.excludes_file(Some("drafts/note.md"), Path::new("/home/dev/proj/drafts/note.md")));
1673    }
1674
1675    #[test]
1676    fn exclude_matchers_report_invalid_patterns() {
1677        let matchers = ExcludeMatchers::new(&["[".to_string(), "ok.md".to_string()]);
1678        assert_eq!(matchers.invalid.len(), 1);
1679        assert_eq!(matchers.invalid[0].0, "[");
1680        assert!(matchers.is_match("ok.md"));
1681    }
1682
1683    #[test]
1684    fn path_relative_to_strips_through_symlinked_base() {
1685        let temp = tempdir().unwrap();
1686        let base = temp.path().join("base");
1687        fs::create_dir_all(base.join("docs")).unwrap();
1688        fs::write(base.join("docs/a.md"), "# hi").unwrap();
1689
1690        assert_eq!(
1691            path_relative_to(&base.join("docs/a.md"), &base).as_deref(),
1692            Some("docs/a.md")
1693        );
1694        assert_eq!(
1695            path_relative_to(&base.join("docs/a.md"), &base.join("docs")).as_deref(),
1696            Some("a.md")
1697        );
1698        assert_eq!(path_relative_to(temp.path(), &base), None, "path outside base");
1699    }
1700
1701    fn sorted(mut patterns: Vec<String>) -> Vec<String> {
1702        patterns.sort();
1703        patterns
1704    }
1705
1706    #[test]
1707    fn expand_braces_yields_every_alternative() {
1708        assert_eq!(
1709            sorted(expand_braces("/{var/folders,tmp}/**")),
1710            vec!["/tmp/**", "/var/folders/**"]
1711        );
1712        // Nesting expands too.
1713        assert_eq!(sorted(expand_braces("a{b,{c,d}}e")), vec!["abe", "ace", "ade"]);
1714        // An empty alternative is dropped, as globset drops it.
1715        assert_eq!(sorted(expand_braces("x{,y}")), vec!["xy"]);
1716        // Several groups multiply out.
1717        assert_eq!(
1718            sorted(expand_braces("/{a,b}/{c,d}.md")),
1719            vec!["/a/c.md", "/a/d.md", "/b/c.md", "/b/d.md"]
1720        );
1721    }
1722
1723    #[test]
1724    fn expand_braces_leaves_patterns_it_cannot_split() {
1725        // Nothing to split.
1726        assert_eq!(expand_braces("/var/folders/**"), vec!["/var/folders/**"]);
1727        // An unclosed brace is not an alternation.
1728        assert_eq!(expand_braces("/var/{a,b/**"), vec!["/var/{a,b/**"]);
1729        // A comma inside a character class is literal.
1730        assert_eq!(expand_braces("/var/[a,b]/**"), vec!["/var/[a,b]/**"]);
1731        // An alternation of nothing but empty alternatives is not a split.
1732        assert_eq!(expand_braces("x{,}"), vec!["x{,}"]);
1733        // Past the expansion cap the pattern is left alone: 2^7 = 128 > 64.
1734        let wide = "/{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}{a,b}/**";
1735        assert_eq!(expand_braces(wide), vec![wide]);
1736    }
1737
1738    #[test]
1739    fn has_absolute_spelling_sees_past_a_leading_alternation() {
1740        assert!(has_absolute_spelling("/var/folders/**"));
1741        assert!(has_absolute_spelling("{/opt,/srv}/docs/**"));
1742        assert!(has_absolute_spelling("/{var/folders,tmp}/**"));
1743        assert!(!has_absolute_spelling("docs/**"));
1744        assert!(!has_absolute_spelling("{docs,notes}/**"));
1745    }
1746
1747    #[test]
1748    fn expand_braces_agrees_with_globset() {
1749        // The expansion only discovers prefixes to canonicalize, but a
1750        // disagreement with globset would mean it is describing a different
1751        // pattern than the one that decides matches.
1752        let cases = [
1753            ("/{var/folders,tmp}/**", "/tmp/note.md"),
1754            ("/{var/folders,tmp}/**", "/var/folders/x/note.md"),
1755            ("/{var/folders,tmp}/**", "/opt/note.md"),
1756            ("/{a,b}/{c,d}.md", "/b/d.md"),
1757            ("/{a,b}/{c,d}.md", "/b/e.md"),
1758            ("x{,y}", "x"),
1759            ("x{,y}", "xy"),
1760            ("/var/[a,b]/**", "/var/a/n.md"),
1761            ("/var/[a,b]/**", "/var/,/n.md"),
1762            ("/var/folders/**", "/var/folders/n.md"),
1763        ];
1764        for (pattern, path) in cases {
1765            let direct = Glob::new(pattern).unwrap().compile_matcher().is_match(path);
1766            let expanded = expand_braces(pattern)
1767                .iter()
1768                .any(|p| Glob::new(p).unwrap().compile_matcher().is_match(path));
1769            assert_eq!(direct, expanded, "pattern {pattern} against {path}");
1770        }
1771    }
1772
1773    #[test]
1774    fn literal_path_prefix_stops_at_the_first_wildcard() {
1775        assert_eq!(literal_path_prefix("/var/folders/**"), Some("/var/folders"));
1776        assert_eq!(literal_path_prefix("/var/log/app*.md"), Some("/var/log"));
1777        assert_eq!(literal_path_prefix("/var/note.md"), Some("/var/note.md"));
1778        assert_eq!(literal_path_prefix("/var/"), Some("/var"));
1779        assert_eq!(literal_path_prefix("docs/**"), Some("docs"));
1780        // Nothing literal to resolve.
1781        assert_eq!(literal_path_prefix("/**"), None);
1782        assert_eq!(literal_path_prefix("/{var,tmp}/**"), None);
1783        assert_eq!(literal_path_prefix("**/note.md"), None);
1784        // The result is always a prefix slice, so a remainder re-attaches by
1785        // byte offset.
1786        let pattern = "/var/folders/**";
1787        let prefix = literal_path_prefix(pattern).unwrap();
1788        assert_eq!(&pattern[prefix.len()..], "/**");
1789    }
1790
1791    /// `(real directory, symlink to it)` under a fresh temp dir. The symlink is
1792    /// how a pattern spells the location; the real directory is where a file
1793    /// canonicalizes to.
1794    #[cfg(unix)]
1795    fn symlinked_dir(temp: &Path) -> (PathBuf, PathBuf) {
1796        let real = temp.join("real");
1797        fs::create_dir_all(real.join("notes")).unwrap();
1798        fs::write(real.join("notes/scratch.md"), "# Note\n").unwrap();
1799        let link = temp.join("link");
1800        std::os::unix::fs::symlink(&real, &link).unwrap();
1801        (canonicalize_for_matching(&real).unwrap(), link)
1802    }
1803
1804    #[cfg(unix)]
1805    #[test]
1806    fn path_aliases_spell_a_path_the_way_a_pattern_named_it() {
1807        let temp = tempdir().unwrap();
1808        let (real, link) = symlinked_dir(temp.path());
1809        let pattern = format!("{}/notes/**", link.to_string_lossy());
1810
1811        let aliases = PathAliases::new([pattern.as_str()]);
1812        assert!(!aliases.is_empty());
1813        assert_eq!(
1814            aliases.spellings_of(&real.join("notes/scratch.md")),
1815            vec![format!("{}/notes/scratch.md", link.to_string_lossy())]
1816        );
1817        // The alias is what makes the pattern match the canonical path.
1818        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
1819        assert!(!matcher.is_match(real.join("notes/scratch.md")), "negative control");
1820        assert!(
1821            aliases
1822                .spellings_of(&real.join("notes/scratch.md"))
1823                .iter()
1824                .any(|alias| matcher.is_match(alias))
1825        );
1826        // A path outside the recorded prefix has no alias.
1827        assert!(aliases.spellings_of(Path::new("/somewhere/else/note.md")).is_empty());
1828    }
1829
1830    #[cfg(unix)]
1831    #[test]
1832    fn path_aliases_reach_through_a_brace_alternation() {
1833        // The prefix only exists once the alternation is expanded.
1834        let temp = tempdir().unwrap();
1835        let (real, link) = symlinked_dir(temp.path());
1836        let pattern = format!("{{/nowhere,{}}}/notes/**", link.to_string_lossy());
1837
1838        let aliases = PathAliases::new([pattern.as_str()]);
1839        let matcher = Glob::new(&pattern).unwrap().compile_matcher();
1840        let note = real.join("notes/scratch.md");
1841        assert!(!matcher.is_match(&note), "negative control");
1842        assert!(aliases.spellings_of(&note).iter().any(|alias| matcher.is_match(alias)));
1843    }
1844
1845    #[test]
1846    fn path_aliases_are_empty_without_a_symlinked_prefix() {
1847        let temp = tempdir().unwrap();
1848        let canonical = canonicalize_for_matching(temp.path()).unwrap();
1849        let canonical = canonical.to_string_lossy().replace('\\', "/");
1850        // Relative patterns, absolute patterns that already name their real
1851        // location, and prefixes that do not exist all record nothing.
1852        for pattern in ["docs/**", &format!("{canonical}/docs/**"), "/nonexistent/xyz/**"] {
1853            assert!(
1854                PathAliases::new([pattern]).is_empty(),
1855                "pattern {pattern} should record no alias"
1856            );
1857        }
1858    }
1859
1860    #[cfg(unix)]
1861    #[test]
1862    fn exclude_matchers_match_a_file_a_pattern_named_through_a_symlink() {
1863        let temp = tempdir().unwrap();
1864        let (real, link) = symlinked_dir(temp.path());
1865        let note = real.join("notes/scratch.md");
1866
1867        let matchers = ExcludeMatchers::new(&[format!("{}/notes/**", link.to_string_lossy())]);
1868        assert!(matchers.excludes_file(None, &note));
1869
1870        // Negative controls: a sibling the pattern does not name, and a pattern
1871        // pointing somewhere else entirely.
1872        fs::write(real.join("other.md"), "# Other\n").unwrap();
1873        assert!(!matchers.excludes_file(None, &real.join("other.md")));
1874        let elsewhere = ExcludeMatchers::new(&[format!("{}/elsewhere/**", link.to_string_lossy())]);
1875        assert!(!elsewhere.excludes_file(None, &note));
1876    }
1877
1878    #[cfg(unix)]
1879    #[test]
1880    fn normalize_pattern_for_base_strips_a_pattern_written_through_a_symlink() {
1881        let temp = tempdir().unwrap();
1882        let (real, link) = symlinked_dir(temp.path());
1883        let pattern = format!("{}/notes/*.md", link.to_string_lossy());
1884
1885        assert_eq!(normalize_pattern_for_base(&pattern, Some(&real)), "notes/*.md");
1886        // A pattern naming a different location through the same symlink is
1887        // still outside a narrower base, and stays absolute.
1888        let outside = format!("{}/elsewhere/*.md", link.to_string_lossy());
1889        assert_eq!(normalize_pattern_for_base(&outside, Some(&real.join("notes"))), outside);
1890    }
1891}