Skip to main content

grit_lib/
ignore.rs

1//! Ignore and exclude matching for `check-ignore`.
2//!
3//! This module implements a focused subset of Git ignore behavior:
4//! per-directory `.gitignore`, `.git/info/exclude`, and `core.excludesfile`
5//! with "last matching pattern wins" precedence. With `core.ignorecase=true`, patterns match
6//! without regard to ASCII case, as in Git.
7
8use crate::worktree::WorktreeError;
9use std::collections::HashMap;
10use std::fmt;
11use std::fs;
12use std::path::{Component, Path, PathBuf};
13
14use crate::config::parse_path;
15use crate::error::{Error, Result};
16use crate::index::{Index, MODE_GITLINK};
17use crate::objects::ObjectKind;
18use crate::repo::Repository;
19use crate::wildmatch::{wildmatch, WM_CASEFOLD, WM_PATHNAME};
20
21/// Where an ignore pattern was loaded from.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum IgnoreSource {
24    /// A per-directory exclude file (typically `.gitignore`).
25    PerDirectory(String),
26    /// Patterns from `.git/info/exclude`.
27    InfoExclude,
28    /// Patterns from `core.excludesfile` (or the XDG default).
29    CoreExcludesFile(String),
30}
31
32impl fmt::Display for IgnoreSource {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::PerDirectory(path) => f.write_str(path),
36            Self::InfoExclude => f.write_str(".git/info/exclude"),
37            Self::CoreExcludesFile(path) => f.write_str(path),
38        }
39    }
40}
41
42/// Metadata for a matching rule.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct IgnoreMatch {
45    /// Typed source of the matching pattern (see [`IgnoreSource`]).
46    pub source: IgnoreSource,
47    /// Line number in the source file (1-based).
48    pub line_number: usize,
49    /// Pattern text as written (excluding comments/blank lines).
50    pub pattern_text: String,
51    /// Whether this is a negated pattern (`!pattern`).
52    pub negative: bool,
53}
54
55/// Result of checking one path against repository ignore rules.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct IgnoreCheck {
58    /// Repository-relative path that was queried.
59    pub path: String,
60    /// Whether the path is ignored (always `false` for tracked paths).
61    pub ignored: bool,
62    /// Last matching pattern metadata, when Git would attribute one (`check-ignore -v`).
63    pub matched: Option<IgnoreMatch>,
64}
65
66/// Patterns parsed from one exclude file (such as a `.gitignore`), for matching single paths.
67///
68/// Unlike [`IgnoreMatcher`], a list is not tied to a repository: the caller decides which
69/// files apply to a path and in what order, as tools that layer their own ignore handling on
70/// top of Git's file format need to. Matching follows Git's `last_matching_pattern_from_list`
71/// for one path: patterns without a slash match the path's last component, other patterns match
72/// the whole path relative to the list's base directory, and directory-only patterns (`foo/`)
73/// match only when the path is a directory. Parent directories are not consulted; callers that
74/// walk a tree stop descending into ignored directories, as Git does.
75///
76/// # Examples
77///
78/// ```
79/// use grit_lib::worktree::ignore::IgnorePatternList;
80///
81/// let list = IgnorePatternList::parse(b"*.log\n!keep.log\nbuild/\n", "");
82/// assert!(list.is_ignored("debug.log", false, false).unwrap());
83/// assert!(!list.is_ignored("keep.log", false, false).unwrap());
84/// assert!(list.is_ignored("build", true, false).unwrap());
85/// assert_eq!(list.is_ignored("build", false, false), None);
86/// ```
87#[derive(Debug, Clone, Default)]
88#[allow(dead_code)] // integration / re-export use only
89pub struct IgnorePatternList {
90    rules: Vec<IgnoreRule>,
91}
92
93/// The pattern that decided an [`IgnorePatternList::last_match`] query.
94#[derive(Debug, Clone, PartialEq, Eq)]
95#[allow(dead_code)] // integration / re-export use only
96pub struct IgnorePatternMatch {
97    /// Line number of the pattern in the parsed content (1-based).
98    pub line_number: usize,
99    /// Pattern text as written (without trailing whitespace).
100    pub pattern_text: String,
101    /// Whether this is a negated pattern (`!pattern`), which re-includes the path.
102    pub negative: bool,
103}
104
105#[allow(dead_code)] // used from integration tests via `ignore` re-exports
106impl IgnorePatternList {
107    /// Parse exclude-file `content` whose patterns are relative to `base_dir`.
108    ///
109    /// `base_dir` is the slash-separated directory holding the file, relative to the root
110    /// paths are matched against (`""` for the root). Blank lines and comments are skipped,
111    /// a UTF-8 byte order mark on the first line is dropped, and invalid UTF-8 is replaced
112    /// as in [`String::from_utf8_lossy`].
113    #[must_use]
114    pub fn parse(content: &[u8], base_dir: &str) -> Self {
115        let content = String::from_utf8_lossy(content);
116        let base_dir = base_dir.trim_matches('/');
117        let source = IgnoreSource::PerDirectory(if base_dir.is_empty() {
118            ".gitignore".to_owned()
119        } else {
120            format!("{base_dir}/.gitignore")
121        });
122        let mut warnings = Vec::new();
123        let rules =
124            parse_gitignore_content(&content, source, base_dir, &mut warnings).unwrap_or_default();
125        Self { rules }
126    }
127
128    /// Whether the list has no patterns.
129    #[must_use]
130    pub fn is_empty(&self) -> bool {
131        self.rules.is_empty()
132    }
133
134    /// Number of patterns in the list.
135    #[must_use]
136    pub fn len(&self) -> usize {
137        self.rules.len()
138    }
139
140    /// The last pattern matching `path`, if any.
141    ///
142    /// `path` is slash-separated and relative to the root the list's base directory is
143    /// relative to. Paths outside the base directory never match. With `ignore_case`,
144    /// patterns compare without regard to ASCII case (`core.ignorecase`).
145    #[must_use]
146    pub fn last_match(
147        &self,
148        path: &str,
149        is_dir: bool,
150        ignore_case: bool,
151    ) -> Option<IgnorePatternMatch> {
152        self.rules
153            .iter()
154            .rev()
155            .find(|rule| rule_matches(rule, path, is_dir, ignore_case))
156            .map(|rule| IgnorePatternMatch {
157                line_number: rule.line_number,
158                pattern_text: rule.pattern_text.clone(),
159                negative: rule.negative,
160            })
161    }
162
163    /// Whether the last matching pattern ignores `path` (`Some(false)` when it re-includes
164    /// it), or `None` when no pattern matches. See [`Self::last_match`].
165    #[must_use]
166    pub fn is_ignored(&self, path: &str, is_dir: bool, ignore_case: bool) -> Option<bool> {
167        self.last_match(path, is_dir, ignore_case)
168            .map(|m| !m.negative)
169    }
170}
171
172#[derive(Debug, Clone)]
173enum IgnorePatternKind {
174    Wild,
175    Literal(String),
176    Prefix(String),
177    Suffix(String),
178}
179
180#[derive(Debug, Clone)]
181struct IgnoreRule {
182    source: IgnoreSource,
183    line_number: usize,
184    pattern_text: String,
185    negative: bool,
186    directory_only: bool,
187    anchored: bool,
188    has_slash: bool,
189    body: String,
190    base_dir: String,
191    match_kind: IgnorePatternKind,
192}
193
194/// Patterns of one per-directory exclude file; every rule's `base_dir` is `base_dir`.
195#[derive(Debug, Clone)]
196struct DirRuleSet {
197    base_dir: String,
198    rules: Vec<IgnoreRule>,
199}
200
201/// What the per-directory exclude stack looks like inside one work-tree directory.
202#[derive(Debug, Clone)]
203struct DirState {
204    /// Ids into `IgnoreMatcher::rule_sets` of the exclude files that apply, root first.
205    stack: Vec<usize>,
206    /// Whether deeper directories may still add their own exclude file; `false` once an
207    /// ancestor turned out to be a file (or per-directory files are not read at all).
208    extendable: bool,
209    /// The pattern excluding this directory or one of its ancestors, which excludes everything
210    /// below it (`prep_exclude` stops descending at an excluded directory).
211    excluded: Option<IgnoreMatch>,
212}
213
214impl From<&IgnoreRule> for IgnoreMatch {
215    fn from(rule: &IgnoreRule) -> Self {
216        Self {
217            source: rule.source.clone(),
218            line_number: rule.line_number,
219            pattern_text: rule.pattern_text.clone(),
220            negative: rule.negative,
221        }
222    }
223}
224
225/// Engine used to evaluate ignore patterns against repository-relative paths.
226#[derive(Debug, Default, Clone)]
227pub struct IgnoreMatcher {
228    /// Patterns from `git ls-files -x` / `--exclude` (Git `EXC_CMDL`), evaluated first.
229    cli_rules: Vec<IgnoreRule>,
230    global_rules: Vec<IgnoreRule>,
231    info_rules: Vec<IgnoreRule>,
232    /// Patterns from `git ls-files -X` / `--exclude-from` (Git `EXC_FILE`, after global/info).
233    exclude_from_rules: Vec<IgnoreRule>,
234    /// Per-directory exclude files read so far, keyed by directory, as ids into `rule_sets`.
235    gitignore_cache: HashMap<String, usize>,
236    rule_sets: Vec<DirRuleSet>,
237    /// Per-directory exclude filename (`ls-files --exclude-per-directory`, default `.gitignore`).
238    per_directory_name: Option<String>,
239    /// Whether per-directory exclude files are read at all (Git `EXC_DIRS`).
240    ///
241    /// `from_repository` (standard excludes) and an explicit `--exclude-per-directory`/`--ignored`
242    /// enable this; a matcher built only for `-x`/`-X` does not consult per-directory files.
243    read_per_directory: bool,
244    /// Warnings emitted while loading in-tree `.gitignore` (e.g. symlink paths).
245    pub warnings: Vec<String>,
246    /// Exclude state of each queried parent directory, keyed by directory, as ids into
247    /// `dir_states`. Built once per directory from its parent's state.
248    dir_state_ids: HashMap<String, usize>,
249    dir_states: Vec<DirState>,
250    /// The directory of the previous query, which consecutive sibling paths share.
251    last_dir: Option<(String, usize)>,
252    /// Fold ASCII case when comparing patterns and base directories (`core.ignorecase`).
253    ignore_case: bool,
254    /// Repository-relative directories entered during a depth-first walk (skip restat in EXC_DIRS).
255    known_worktree_directories: std::collections::HashSet<String>,
256}
257
258impl IgnoreMatcher {
259    /// Build a matcher from repository exclude sources.
260    ///
261    /// Honors `core.ignorecase`: when it is `true`, patterns match paths without regard to
262    /// ASCII case (`Build/` ignores `build/`, `*.LOG` ignores `debug.log`), as Git does.
263    ///
264    /// # Parameters
265    ///
266    /// - `repo` - open repository.
267    ///
268    /// # Errors
269    ///
270    /// Returns [`Error::Io`] if configured pattern files cannot be read, or a config error if
271    /// the repository configuration cannot be loaded.
272    pub fn from_repository(repo: &Repository) -> Result<Self> {
273        let ignore_case = repo.config().snapshot()?.ignore_case();
274        Ok(Self {
275            global_rules: load_global_excludes(repo)?,
276            info_rules: load_info_excludes(repo)?,
277            // Standard excludes include the per-directory `.gitignore` set (Git `EXC_DIRS`).
278            read_per_directory: true,
279            ignore_case,
280            ..Self::default()
281        })
282    }
283
284    /// Set whether patterns match case-insensitively (Git's `core.ignorecase`).
285    ///
286    /// [`Self::from_repository`] reads this from configuration; use this to override it, or to
287    /// opt in on a matcher built with [`Default::default`]. Only ASCII letters are folded, like
288    /// Git.
289    ///
290    /// # Parameters
291    ///
292    /// - `ignore_case` - `true` to fold ASCII case when matching.
293    ///
294    /// # Returns
295    ///
296    /// The matcher with the setting applied.
297    #[must_use]
298    pub fn with_ignore_case(mut self, ignore_case: bool) -> Self {
299        self.ignore_case = ignore_case;
300        self.clear_dir_states();
301        self
302    }
303
304    /// Forget per-directory exclude states, which depend on every pattern source and on case
305    /// folding; call after changing either.
306    fn clear_dir_states(&mut self) {
307        self.dir_state_ids.clear();
308        self.dir_states.clear();
309        self.last_dir = None;
310    }
311
312    /// Whether patterns match case-insensitively (see [`Self::with_ignore_case`]).
313    #[must_use]
314    pub fn ignore_case(&self) -> bool {
315        self.ignore_case
316    }
317
318    /// Append patterns from `ls-files --exclude-from` / `-X` files (relative paths resolve from `cwd`).
319    ///
320    /// Matches Git's `EXC_FILE` lists loaded after `core.excludesfile` and `.git/info/exclude`.
321    pub fn add_exclude_from_files(&mut self, paths: &[PathBuf], cwd: &Path) -> Result<()> {
322        for path in paths {
323            let resolved = if path.is_absolute() {
324                path.clone()
325            } else {
326                cwd.join(path)
327            };
328            let display = path.display().to_string();
329            let mut more = load_rules_from_file(
330                &resolved,
331                IgnoreSource::CoreExcludesFile(display),
332                String::new(),
333                false,
334                &mut self.warnings,
335            )?;
336            self.exclude_from_rules.append(&mut more);
337        }
338        self.clear_dir_states();
339        Ok(())
340    }
341
342    /// Override the per-directory exclude filename (`ls-files --exclude-per-directory=<file>`).
343    ///
344    /// When unset, per-directory excludes are read from `.gitignore` (Git's standard name).
345    pub fn set_per_directory_name(&mut self, name: &str) {
346        self.per_directory_name = Some(name.to_owned());
347        self.read_per_directory = true;
348        // The cache is keyed by directory only; clear it so a new filename is honored.
349        self.gitignore_cache.clear();
350        self.rule_sets.clear();
351        self.clear_dir_states();
352    }
353
354    /// Append patterns from `ls-files --exclude` / `-x` (Git command-line exclude list).
355    pub fn add_cli_excludes(&mut self, patterns: &[String]) {
356        for pat in patterns {
357            if let Some(rule) = parse_rule_line(
358                pat,
359                1,
360                IgnoreSource::PerDirectory("--exclude option".into()),
361                "",
362            ) {
363                self.cli_rules.push(rule);
364            }
365        }
366        self.clear_dir_states();
367    }
368
369    /// Take any warnings accumulated while loading ignore files (caller prints to stderr).
370    #[must_use]
371    pub fn take_warnings(&mut self) -> Vec<String> {
372        std::mem::take(&mut self.warnings)
373    }
374
375    /// Whether `repo_rel_path` is ignored, without computing verbose `-v` match metadata.
376    ///
377    /// Prefer this on hot paths (for example untracked directory walks) that only need the
378    /// boolean result.
379    pub fn is_path_ignored(
380        &mut self,
381        repo: &Repository,
382        index: Option<&Index>,
383        repo_rel_path: &str,
384        is_dir: bool,
385    ) -> Result<bool> {
386        if is_tracked(index, repo_rel_path) {
387            return Ok(false);
388        }
389        let state = self.dir_state_id(repo, index, parent_dir(repo_rel_path), false)?;
390        let state = &self.dir_states[state];
391        if state.excluded.is_some() {
392            return Ok(true);
393        }
394        Ok(self
395            .last_matching_rule(repo_rel_path, is_dir, &state.stack)
396            .is_some_and(|rule| !rule.negative))
397    }
398
399    /// Check whether a repository-relative path is ignored.
400    ///
401    /// # Parameters
402    ///
403    /// - `repo` - repository handle.
404    /// - `index` - optional index; when present, tracked entries are not ignored. The lookup is
405    ///   exact-case even under `core.ignorecase`, like `git check-ignore`; work-tree walks that
406    ///   must treat case variants of tracked paths as tracked check that before asking.
407    /// - `repo_rel_path` - normalized repository-relative path with `/` separators.
408    /// - `is_dir` - whether the queried path is a directory.
409    ///
410    /// # Returns
411    ///
412    /// Tuple `(ignored, match_info)` where `match_info` is the last matching
413    /// pattern (including negated matches).
414    ///
415    /// # Errors
416    ///
417    /// Returns [`Error::Io`] when a relevant `.gitignore` cannot be read.
418    pub fn check_path(
419        &mut self,
420        repo: &Repository,
421        index: Option<&Index>,
422        repo_rel_path: &str,
423        is_dir: bool,
424    ) -> Result<(bool, Option<IgnoreMatch>)> {
425        self.check_path_with_ancestors(repo, index, repo_rel_path, is_dir, false)
426    }
427
428    /// [`Self::check_path`], where `ancestors_are_dirs` records that the caller already
429    /// knows no ancestor of `repo_rel_path` is a regular file (because `stat` of the path
430    /// succeeded or failed with "not found"), so new directories need no `stat` of their own.
431    fn check_path_with_ancestors(
432        &mut self,
433        repo: &Repository,
434        index: Option<&Index>,
435        repo_rel_path: &str,
436        is_dir: bool,
437        ancestors_are_dirs: bool,
438    ) -> Result<(bool, Option<IgnoreMatch>)> {
439        if is_tracked(index, repo_rel_path) {
440            return Ok((false, None));
441        }
442        let parent = parent_dir(repo_rel_path);
443        let state = self.dir_state_id(repo, index, parent, ancestors_are_dirs)?;
444        let state = &self.dir_states[state];
445        // A path under an excluded directory stays excluded: a later `!dir/file` cannot
446        // re-include it (gitignore(5)).
447        if let Some(ancestor_match) = &state.excluded {
448            return Ok((true, Some(ancestor_match.clone())));
449        }
450        let Some(rule) = self.last_matching_rule(repo_rel_path, is_dir, &state.stack) else {
451            return Ok((false, None));
452        };
453        if rule.negative {
454            return Ok((false, Some(rule.into())));
455        }
456        let attributed = self
457            .rules_in_priority_order(&state.stack)
458            .filter(|candidate| candidate.directory_only)
459            .filter(|candidate| rule_matches(candidate, repo_rel_path, is_dir, self.ignore_case))
460            .reduce(|best, candidate| {
461                let key = |r: &IgnoreRule| (base_dir_depth(&r.base_dir), r.line_number);
462                if key(candidate) < key(best) {
463                    candidate
464                } else {
465                    best
466                }
467            })
468            .unwrap_or(rule);
469        Ok((true, Some(attributed.into())))
470    }
471
472    /// The rule deciding `path`, given the per-directory exclude `stack` (root first) of its
473    /// parent directory.
474    ///
475    /// Pattern groups are consulted in Git's priority order: command-line excludes, then the
476    /// per-directory files from the deepest directory up, then `--exclude-from`,
477    /// `core.excludesfile` and `info/exclude` as one group. The first group with a match
478    /// decides, and within a group the last matching line wins.
479    fn last_matching_rule(&self, path: &str, is_dir: bool, stack: &[usize]) -> Option<&IgnoreRule> {
480        let fold = self.ignore_case;
481        last_match_in("", &self.cli_rules, path, is_dir, fold)
482            .or_else(|| {
483                stack.iter().rev().find_map(|&id| {
484                    let set = self.rule_sets.get(id)?;
485                    last_match_in(&set.base_dir, &set.rules, path, is_dir, fold)
486                })
487            })
488            .or_else(|| last_match_in("", &self.info_rules, path, is_dir, fold))
489            .or_else(|| last_match_in("", &self.global_rules, path, is_dir, fold))
490            .or_else(|| last_match_in("", &self.exclude_from_rules, path, is_dir, fold))
491    }
492
493    /// Every rule that can apply under `stack`, in the order Git's `check-ignore -v` scans
494    /// them: command-line excludes, per-directory files deepest first, then the file group.
495    fn rules_in_priority_order<'a>(
496        &'a self,
497        stack: &'a [usize],
498    ) -> impl Iterator<Item = &'a IgnoreRule> + 'a {
499        let per_dir = stack
500            .iter()
501            .rev()
502            .filter_map(|&id| self.rule_sets.get(id))
503            .flat_map(|set| set.rules.iter());
504        self.cli_rules
505            .iter()
506            .chain(per_dir)
507            .chain(self.exclude_from_rules.iter())
508            .chain(self.global_rules.iter())
509            .chain(self.info_rules.iter())
510    }
511
512    /// Load per-directory exclude files for `dir_rel` when depth-first walking the work tree.
513    ///
514    /// Idempotent: repeated calls for the same directory reuse the in-memory cache.
515    pub fn note_directory_entered(
516        &mut self,
517        repo: &Repository,
518        index: Option<&Index>,
519        dir_rel: &str,
520    ) -> Result<()> {
521        if !self.read_per_directory {
522            return Ok(());
523        }
524        if self.gitignore_cache.contains_key(dir_rel) {
525            return Ok(());
526        }
527        self.known_worktree_directories.insert(dir_rel.to_owned());
528        self.rule_set_id(repo, index, dir_rel)?;
529        Ok(())
530    }
531
532    /// Record that the walk entered work-tree directory `dir_rel` without reading its
533    /// per-directory exclude file yet.
534    ///
535    /// The file is read by the first query for a path inside the directory, so a directory
536    /// whose entries are all tracked never opens it (as in Git, where exclude rules are only
537    /// consulted for untracked paths).
538    pub(crate) fn note_directory_known(&mut self, dir_rel: &str) {
539        if self.read_per_directory
540            && !self.gitignore_cache.contains_key(dir_rel)
541            && !self.known_worktree_directories.contains(dir_rel)
542        {
543            self.known_worktree_directories.insert(dir_rel.to_owned());
544        }
545    }
546
547    /// Id of the parsed per-directory exclude file of `dir`, reading it on first use.
548    fn rule_set_id(
549        &mut self,
550        repo: &Repository,
551        index: Option<&Index>,
552        dir: &str,
553    ) -> Result<usize> {
554        if let Some(&id) = self.gitignore_cache.get(dir) {
555            return Ok(id);
556        }
557        let per_dir_name = self.per_directory_name.as_deref();
558        let rules = load_gitignore_for_dir(repo, index, dir, per_dir_name, &mut self.warnings)?;
559        let id = self.rule_sets.len();
560        self.rule_sets.push(DirRuleSet {
561            base_dir: dir.to_owned(),
562            rules,
563        });
564        self.gitignore_cache.insert(dir.to_owned(), id);
565        Ok(id)
566    }
567
568    /// Id of the exclude state of directory `dir` (`""` for the root), building it on first use.
569    ///
570    /// Sibling paths share their parent's state, so a batch of queries reads each exclude
571    /// file, stats each directory and probes each directory against the patterns once.
572    /// `ancestors_are_dirs` skips that `stat` when no ancestor can be a regular file.
573    fn dir_state_id(
574        &mut self,
575        repo: &Repository,
576        index: Option<&Index>,
577        dir: &str,
578        ancestors_are_dirs: bool,
579    ) -> Result<usize> {
580        if let Some((last, id)) = &self.last_dir {
581            if last == dir {
582                return Ok(*id);
583            }
584        }
585        let id = match self.dir_state_ids.get(dir) {
586            Some(&id) => id,
587            None => self.build_dir_state(repo, index, dir, ancestors_are_dirs)?,
588        };
589        match &mut self.last_dir {
590            Some((last, last_id)) => {
591                last.clear();
592                last.push_str(dir);
593                *last_id = id;
594            }
595            None => self.last_dir = Some((dir.to_owned(), id)),
596        }
597        Ok(id)
598    }
599
600    /// Build the state of `dir` from its parent's, as Git's `prep_exclude` does when it
601    /// descends one level: probe `dir` itself against the patterns loaded so far, then push
602    /// `dir`'s own exclude file.
603    fn build_dir_state(
604        &mut self,
605        repo: &Repository,
606        index: Option<&Index>,
607        dir: &str,
608        ancestors_are_dirs: bool,
609    ) -> Result<usize> {
610        let state = if dir.is_empty() {
611            let stack = if self.read_per_directory {
612                vec![self.rule_set_id(repo, index, "")?]
613            } else {
614                Vec::new()
615            };
616            DirState {
617                stack,
618                extendable: self.read_per_directory,
619                excluded: None,
620            }
621        } else {
622            let parent = parent_dir(dir);
623            let parent_id = match self.dir_state_ids.get(parent) {
624                Some(&id) => id,
625                None => self.build_dir_state(repo, index, parent, ancestors_are_dirs)?,
626            };
627            let parent_state = &self.dir_states[parent_id];
628            let excluded = parent_state.excluded.clone().or_else(|| {
629                self.last_matching_rule(dir, true, &parent_state.stack)
630                    .filter(|rule| !rule.negative)
631                    .map(IgnoreMatch::from)
632            });
633            let mut stack = parent_state.stack.clone();
634            let mut extendable = parent_state.extendable;
635            // Git does not treat a file as a directory when loading per-directory excludes
636            // (`tracked.txt/.gitignore` must not be probed), nor anything below it.
637            if extendable
638                && (self.known_worktree_directories.contains(dir)
639                    || ancestors_are_dirs
640                    || !worktree_path_is_existing_file(repo, dir))
641            {
642                stack.push(self.rule_set_id(repo, index, dir)?);
643            } else {
644                extendable = false;
645            }
646            DirState {
647                stack,
648                extendable,
649                excluded,
650            }
651        };
652        let id = self.dir_states.len();
653        self.dir_states.push(state);
654        self.dir_state_ids.insert(dir.to_owned(), id);
655        Ok(id)
656    }
657}
658
659fn load_global_excludes(repo: &Repository) -> Result<Vec<IgnoreRule>> {
660    let config = repo.config().snapshot()?;
661    let env = repo.environment();
662    let (resolved, display_path) = if let Some(raw_path) = config.value("core.excludesfile") {
663        let expanded = parse_path(env, &raw_path);
664        let resolved = if Path::new(&expanded).is_absolute() {
665            PathBuf::from(&expanded)
666        } else if let Some(work_tree) = &repo.work_tree() {
667            work_tree.join(&expanded)
668        } else {
669            repo.git_dir().join(&expanded)
670        };
671        (resolved, raw_path)
672    } else if let Some(path) = env.default_xdg_config_git_file("ignore") {
673        let display = path.display().to_string();
674        (path, display)
675    } else {
676        return Ok(Vec::new());
677    };
678
679    let mut sink = Vec::new();
680    load_rules_from_file(
681        &resolved,
682        IgnoreSource::CoreExcludesFile(display_path),
683        String::new(),
684        false,
685        &mut sink,
686    )
687}
688
689fn load_info_excludes(repo: &Repository) -> Result<Vec<IgnoreRule>> {
690    let path = repo.git_dir().join("info/exclude");
691    let mut sink = Vec::new();
692    load_rules_from_file(
693        &path,
694        IgnoreSource::InfoExclude,
695        String::new(),
696        false,
697        &mut sink,
698    )
699}
700
701fn load_gitignore_for_dir(
702    repo: &Repository,
703    index: Option<&Index>,
704    dir: &str,
705    per_dir_name: Option<&str>,
706    warnings: &mut Vec<String>,
707) -> Result<Vec<IgnoreRule>> {
708    let Some(work_tree) = &repo.work_tree() else {
709        return Ok(Vec::new());
710    };
711    let file_name = per_dir_name.unwrap_or(".gitignore");
712    let path = if dir.is_empty() {
713        work_tree.join(file_name)
714    } else {
715        work_tree.join(dir).join(file_name)
716    };
717    let source_display = if dir.is_empty() {
718        file_name.to_owned()
719    } else {
720        format!("{dir}/{file_name}")
721    };
722    let source = IgnoreSource::PerDirectory(source_display.clone());
723    let rel_key = if dir.is_empty() {
724        file_name.to_owned()
725    } else {
726        format!("{dir}/{file_name}")
727    };
728
729    // In-tree `.gitignore` must not be a symlink (Git follows symlinks for global/info excludes
730    // only). Match Git's warning and skip the file (t0008).
731    match read_in_tree_pattern_file(&path)? {
732        InTreePatternFile::Symlink => {
733            warnings.push(crate::diagnostics::warning_line(&format!(
734                "unable to access '{source_display}': Too many levels of symbolic links"
735            )));
736            return Ok(Vec::new());
737        }
738        InTreePatternFile::Content(content) => {
739            return parse_gitignore_content(&content, source, dir, warnings);
740        }
741        InTreePatternFile::Missing => {}
742    }
743
744    if let Some(ix) = index {
745        if let Some(entry) = ix.get(rel_key.as_bytes(), 0) {
746            if let Ok(obj) = repo.odb().read(&entry.oid) {
747                if obj.kind == ObjectKind::Blob {
748                    if let Ok(text) = std::str::from_utf8(&obj.data) {
749                        return parse_gitignore_content(text, source, dir, warnings);
750                    }
751                }
752            }
753        }
754    }
755
756    Ok(Vec::new())
757}
758
759fn parse_gitignore_content(
760    content: &str,
761    source: IgnoreSource,
762    base_dir: &str,
763    _warnings: &mut Vec<String>,
764) -> Result<Vec<IgnoreRule>> {
765    let mut rules = Vec::new();
766    // Split on LF only: like Git's `add_patterns_from_buffer`, a line loses at most one
767    // trailing CR (in `parse_rule_line`), so `a\r\r` names the file `a\r`.
768    for (idx, line) in content.split('\n').enumerate() {
769        let line = if idx == 0 {
770            line.strip_prefix('\u{feff}').unwrap_or(line)
771        } else {
772            line
773        };
774        if let Some(rule) = parse_rule_line(line, idx + 1, source.clone(), base_dir) {
775            rules.push(rule);
776        }
777    }
778    Ok(rules)
779}
780
781fn load_rules_from_file(
782    path: &Path,
783    source: IgnoreSource,
784    base_dir: String,
785    deny_symlink_gitignore: bool,
786    warnings: &mut Vec<String>,
787) -> Result<Vec<IgnoreRule>> {
788    if deny_symlink_gitignore && path.exists() {
789        if let Ok(meta) = fs::symlink_metadata(path) {
790            if meta.file_type().is_symlink() {
791                warnings.push(crate::diagnostics::warning_line(&format!(
792                    "unable to access '{}': Too many levels of symbolic links",
793                    source
794                )));
795                return Ok(Vec::new());
796            }
797        }
798    }
799    if path.exists() {
800        crate::worktree_rules::record_ignore_pattern_file_read(path);
801    }
802    let Some(content) = read_optional_text(path)? else {
803        return Ok(Vec::new());
804    };
805    parse_gitignore_content(&content, source, &base_dir, warnings)
806}
807
808/// Trims only *unescaped* trailing spaces, matching Git's `trim_trailing_spaces` in `dir.c`.
809///
810/// A backslash escapes the following byte; a run of spaces ending the line is removed only
811/// when it is not part of an escape sequence (see t0008 "trailing whitespace is ignored").
812fn trim_trailing_spaces_git(line: &str) -> &str {
813    let bytes = line.as_bytes();
814    let mut last_space_start: Option<usize> = None;
815    let mut i = 0usize;
816    while let Some(&byte) = bytes.get(i) {
817        match byte {
818            b' ' => {
819                last_space_start.get_or_insert(i);
820                i += 1;
821            }
822            b'\\' => {
823                last_space_start = None;
824                i += 2;
825            }
826            _ => {
827                last_space_start = None;
828                i += 1;
829            }
830        }
831    }
832    // Spaces are ASCII, so `start` is a char boundary.
833    last_space_start.map_or(line, |start| &line[..start])
834}
835
836fn parse_rule_line(
837    line: &str,
838    line_number: usize,
839    source: IgnoreSource,
840    base_dir: &str,
841) -> Option<IgnoreRule> {
842    let pattern_text = trim_trailing_spaces_git(line.strip_suffix('\r').unwrap_or(line));
843    if pattern_text.is_empty() || pattern_text.starts_with('#') {
844        return None;
845    }
846    let (negative, raw) = match pattern_text.strip_prefix('!') {
847        Some(rest) => (true, rest),
848        None => (false, pattern_text),
849    };
850    let (anchored, raw) = match raw.strip_prefix('/') {
851        Some(rest) => (true, rest),
852        None => (false, raw),
853    };
854    let (directory_only, body) = match raw.strip_suffix('/') {
855        Some(rest) => (true, rest),
856        None => (false, raw),
857    };
858    if raw.is_empty() || body.is_empty() {
859        return None;
860    }
861    Some(IgnoreRule {
862        source,
863        line_number,
864        pattern_text: pattern_text.to_owned(),
865        negative,
866        directory_only,
867        anchored,
868        has_slash: body.contains('/'),
869        body: body.to_owned(),
870        base_dir: base_dir.to_owned(),
871        match_kind: classify_ignore_pattern(body),
872    })
873}
874
875fn classify_ignore_pattern(body: &str) -> IgnorePatternKind {
876    // Backslashes are wildmatch escapes (`foo\ bar` matches a literal space); never treat as
877    // a plain literal string.
878    if body.contains('\\') || body.contains(['?', '[']) {
879        return IgnorePatternKind::Wild;
880    }
881    if !body.contains('*') {
882        return IgnorePatternKind::Literal(body.to_owned());
883    }
884    if let Some(rest) = body.strip_prefix('*') {
885        if !rest.contains('*') && !rest.contains('/') {
886            return IgnorePatternKind::Suffix(rest.to_owned());
887        }
888    }
889    if let Some(rest) = body.strip_suffix('*') {
890        if !rest.contains('*') && !rest.contains('/') {
891            return IgnorePatternKind::Prefix(rest.to_owned());
892        }
893    }
894    IgnorePatternKind::Wild
895}
896
897fn base_dir_depth(base: &str) -> usize {
898    if base.is_empty() {
899        return 0;
900    }
901    base.split('/').count()
902}
903
904fn rule_matches(rule: &IgnoreRule, repo_rel_path: &str, is_dir: bool, ignore_case: bool) -> bool {
905    let Some(target) = MatchTarget::new(&rule.base_dir, repo_rel_path, ignore_case) else {
906        return false;
907    };
908    if ignore_case {
909        target.matches::<true>(rule, is_dir)
910    } else {
911        target.matches::<false>(rule, is_dir)
912    }
913}
914
915/// The last rule in `rules` (all relative to `base_dir`) that matches `path`.
916///
917/// Strips the base directory and finds the basename once for the whole list, and scans
918/// from the last line so the first hit is the winner.
919fn last_match_in<'a>(
920    base_dir: &str,
921    rules: &'a [IgnoreRule],
922    path: &str,
923    is_dir: bool,
924    ignore_case: bool,
925) -> Option<&'a IgnoreRule> {
926    if rules.is_empty() {
927        return None;
928    }
929    let target = MatchTarget::new(base_dir, path, ignore_case)?;
930    if ignore_case {
931        rules
932            .iter()
933            .rev()
934            .find(|rule| target.matches::<true>(rule, is_dir))
935    } else {
936        rules
937            .iter()
938            .rev()
939            .find(|rule| target.matches::<false>(rule, is_dir))
940    }
941}
942
943/// A queried path as seen from one exclude file's directory, borrowed from the query.
944struct MatchTarget<'p> {
945    /// The path relative to the exclude file's directory (never empty).
946    rel: &'p str,
947    /// The last component of `rel`.
948    basename: &'p str,
949}
950
951impl<'p> MatchTarget<'p> {
952    /// `None` when `path` is not strictly inside `base_dir`, so no rule there can match.
953    fn new(base_dir: &str, path: &'p str, ignore_case: bool) -> Option<Self> {
954        let rel = strip_base(base_dir, path, ignore_case)?;
955        if rel.is_empty() {
956            return None;
957        }
958        let basename = rel.rsplit_once('/').map_or(rel, |(_, name)| name);
959        Some(Self { rel, basename })
960    }
961
962    /// Whether `rule` matches, specialized on case folding so the default case-sensitive
963    /// path carries no per-comparison `core.ignorecase` checks.
964    ///
965    /// Only the queried path itself is tested: slash-free patterns match its basename,
966    /// patterns with a slash match the whole path relative to the rule's directory. A path
967    /// under an excluded directory inherits that exclusion from its parent directory's
968    /// state, which probes each ancestor with the same test, so `tags` followed by `!tags/`
969    /// leaves `tags/a.txt` unignored while `tags` alone ignores it through its parent.
970    fn matches<const FOLD: bool>(&self, rule: &IgnoreRule, is_dir: bool) -> bool {
971        // Directory-only patterns (`foo/`) never match files, so `!pkg/` cannot re-include
972        // files under `pkg/` that `*` still ignores (issue #1650).
973        if rule.directory_only && !is_dir {
974            return false;
975        }
976        if rule.has_slash || rule.anchored {
977            return rule_body_matches(rule, self.rel, true, FOLD);
978        }
979        rule_body_matches(rule, self.basename, false, FOLD)
980    }
981}
982
983fn is_tracked(index: Option<&Index>, repo_rel_path: &str) -> bool {
984    let Some(index) = index else {
985        return false;
986    };
987    // Trailing `/` is a directory query; Git does not apply the index tracked exemption
988    // (`tracked.txt/` can match exclude rules even when `tracked.txt` is staged).
989    if repo_rel_path.ends_with('/') {
990        return false;
991    }
992    index.get(repo_rel_path.as_bytes(), 0).is_some()
993}
994
995/// True when `repo_rel_path` exists in the work tree as a regular file (not a directory).
996fn worktree_path_is_existing_file(repo: &Repository, repo_rel_path: &str) -> bool {
997    let Some(work_tree) = repo.work_tree() else {
998        return false;
999    };
1000    let path = work_tree.join(repo_rel_path);
1001    path.metadata().map(|m| m.is_file()).unwrap_or(false)
1002}
1003
1004/// Whether a queried path names a directory: it ends in `/` or is one in the work tree.
1005///
1006/// `scratch` is reused across a batch so each query costs one `stat` and no allocation.
1007///
1008/// Returns `(is_dir, ancestors_are_dirs)`. The second is `true` when the `stat` shows that no
1009/// ancestor of the path is a regular file: it succeeded, or failed because a component is
1010/// missing (a file ancestor fails with "not a directory" instead).
1011fn probe_query_path(
1012    work_tree: Option<&Path>,
1013    repo_rel_path: &str,
1014    scratch: &mut PathBuf,
1015) -> (bool, bool) {
1016    if repo_rel_path.ends_with('/') {
1017        return (true, false);
1018    }
1019    let Some(work_tree) = work_tree else {
1020        return (false, false);
1021    };
1022    scratch.as_mut_os_string().clear();
1023    scratch.push(work_tree);
1024    scratch.push(repo_rel_path);
1025    match scratch.metadata() {
1026        Ok(meta) => (meta.is_dir(), true),
1027        // Windows reports a file ancestor as "path not found", so only Unix can tell.
1028        Err(err) => (
1029            false,
1030            cfg!(unix) && err.kind() == std::io::ErrorKind::NotFound,
1031        ),
1032    }
1033}
1034
1035impl Repository {
1036    /// Check whether paths are ignored, reusing one [`IgnoreMatcher`] for the whole batch.
1037    ///
1038    /// Tracked index entries are never reported as ignored. Each result includes verbose-style
1039    /// match metadata compatible with `git check-ignore -v`.
1040    ///
1041    /// # Parameters
1042    ///
1043    /// - `paths` - repository-relative paths with `/` separators (as returned by
1044    ///   [`normalize_repo_relative`]).
1045    /// - `index` - current index; tracked paths are treated as not ignored.
1046    ///
1047    /// # Errors
1048    ///
1049    /// Returns [`Error::Io`] when loading exclude files fails.
1050    pub fn ignore_check(&self, paths: &[String], index: &Index) -> Result<Vec<IgnoreCheck>> {
1051        let mut matcher = IgnoreMatcher::from_repository(self)?;
1052        let mut out = Vec::with_capacity(paths.len());
1053        let mut scratch = PathBuf::new();
1054        for path in paths {
1055            let (is_dir, ancestors_are_dirs) =
1056                probe_query_path(self.work_tree(), path, &mut scratch);
1057            let (ignored, matched) = matcher.check_path_with_ancestors(
1058                self,
1059                Some(index),
1060                path,
1061                is_dir,
1062                ancestors_are_dirs,
1063            )?;
1064            out.push(IgnoreCheck {
1065                path: path.clone(),
1066                ignored,
1067                matched,
1068            });
1069        }
1070        Ok(out)
1071    }
1072}
1073
1074/// Outcome of reading a per-directory pattern file that Git refuses to follow as a symlink.
1075enum InTreePatternFile {
1076    Missing,
1077    Symlink,
1078    Content(String),
1079}
1080
1081/// Read `path` without following a final symlink, so a link (dangling, or to a FIFO or
1082/// device) is reported instead of opened. A missing file costs a single failed open on Unix.
1083fn read_in_tree_pattern_file(path: &Path) -> Result<InTreePatternFile> {
1084    #[cfg(unix)]
1085    let opened = {
1086        use std::os::unix::fs::OpenOptionsExt;
1087        fs::OpenOptions::new()
1088            .read(true)
1089            .custom_flags(libc::O_NOFOLLOW)
1090            .open(path)
1091    };
1092    #[cfg(not(unix))]
1093    let opened = match fs::symlink_metadata(path) {
1094        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1095            return Ok(InTreePatternFile::Missing);
1096        }
1097        Err(err) => return Err(Error::Io(err)),
1098        Ok(meta) if meta.file_type().is_symlink() => return Ok(InTreePatternFile::Symlink),
1099        Ok(_) => fs::File::open(path),
1100    };
1101    let mut file = match opened {
1102        Ok(file) => file,
1103        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1104            return Ok(InTreePatternFile::Missing);
1105        }
1106        Err(_) if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) => {
1107            return Ok(InTreePatternFile::Symlink);
1108        }
1109        Err(err) => return Err(Error::Io(err)),
1110    };
1111    let mut content = String::new();
1112    std::io::Read::read_to_string(&mut file, &mut content).map_err(Error::Io)?;
1113    Ok(InTreePatternFile::Content(content))
1114}
1115
1116fn read_optional_text(path: &Path) -> Result<Option<String>> {
1117    match fs::read_to_string(path) {
1118        Ok(content) => Ok(Some(content)),
1119        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
1120        Err(err) => Err(Error::Io(err)),
1121    }
1122}
1123
1124/// Path of `path` relative to the `.gitignore` directory `base`, or `None` when `path` is not
1125/// inside it. With `ignore_case`, the base compares without regard to ASCII case.
1126fn strip_base<'a>(base: &str, path: &'a str, ignore_case: bool) -> Option<&'a str> {
1127    if base.is_empty() {
1128        return Some(path);
1129    }
1130    if !starts_with_fold(path, base, ignore_case) {
1131        return None;
1132    }
1133    match path.as_bytes().get(base.len()) {
1134        None => Some(""),
1135        // `base.len()` is a char boundary: the byte there is ASCII `/`.
1136        Some(b'/') => path.get(base.len() + 1..),
1137        Some(_) => None,
1138    }
1139}
1140
1141fn eq_fold(text: &str, pattern: &str, ignore_case: bool) -> bool {
1142    if ignore_case {
1143        text.eq_ignore_ascii_case(pattern)
1144    } else {
1145        text == pattern
1146    }
1147}
1148
1149fn starts_with_fold(text: &str, prefix: &str, ignore_case: bool) -> bool {
1150    if !ignore_case {
1151        return text.starts_with(prefix);
1152    }
1153    text.as_bytes()
1154        .get(..prefix.len())
1155        .is_some_and(|head| head.eq_ignore_ascii_case(prefix.as_bytes()))
1156}
1157
1158fn ends_with_fold(text: &str, suffix: &str, ignore_case: bool) -> bool {
1159    if !ignore_case {
1160        return text.ends_with(suffix);
1161    }
1162    text.len()
1163        .checked_sub(suffix.len())
1164        .and_then(|start| text.as_bytes().get(start..))
1165        .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix.as_bytes()))
1166}
1167
1168fn parent_dir(path: &str) -> &str {
1169    match path.rsplit_once('/') {
1170        Some((parent, _)) => parent,
1171        None => "",
1172    }
1173}
1174
1175fn pattern_matches_kind(
1176    kind: &IgnorePatternKind,
1177    pattern: &str,
1178    text: &str,
1179    pathname: bool,
1180    ignore_case: bool,
1181) -> bool {
1182    match kind {
1183        IgnorePatternKind::Literal(lit) => eq_fold(text, lit, ignore_case),
1184        IgnorePatternKind::Prefix(prefix) => {
1185            if !starts_with_fold(text, prefix, ignore_case) {
1186                return false;
1187            }
1188            !pathname || !text[prefix.len()..].contains('/')
1189        }
1190        IgnorePatternKind::Suffix(suffix) => {
1191            if !ends_with_fold(text, suffix, ignore_case) {
1192                return false;
1193            }
1194            if !pathname {
1195                return true;
1196            }
1197            let Some(head_len) = text.len().checked_sub(suffix.len()) else {
1198                return true;
1199            };
1200            !text[..head_len].contains('/')
1201        }
1202        IgnorePatternKind::Wild => {
1203            let mut flags = if pathname { WM_PATHNAME } else { 0 };
1204            if ignore_case {
1205                flags |= WM_CASEFOLD;
1206            }
1207            wildmatch(pattern.as_bytes(), text.as_bytes(), flags)
1208        }
1209    }
1210}
1211
1212fn rule_body_matches(rule: &IgnoreRule, text: &str, pathname: bool, ignore_case: bool) -> bool {
1213    pattern_matches_kind(&rule.match_kind, &rule.body, text, pathname, ignore_case)
1214}
1215
1216/// One line from a sparse-checkout specification blob (`--filter=sparse:oid=…`).
1217#[derive(Debug, Clone)]
1218struct SparsePattern {
1219    negative: bool,
1220    directory_only: bool,
1221    anchored: bool,
1222    has_slash: bool,
1223    body: String,
1224}
1225
1226impl SparsePattern {
1227    fn from_line(line: &str) -> Option<Self> {
1228        let raw_line = trim_trailing_spaces_git(line.strip_suffix('\r').unwrap_or(line));
1229        if raw_line.is_empty() || raw_line.starts_with('#') {
1230            return None;
1231        }
1232
1233        let mut raw = raw_line.to_owned();
1234
1235        let mut negative = false;
1236        if let Some(rest) = raw.strip_prefix('!') {
1237            negative = true;
1238            raw = rest.to_owned();
1239        }
1240        if raw.is_empty() {
1241            return None;
1242        }
1243
1244        // Git `parse_path_pattern`: trailing `/` sets `PATTERN_FLAG_MUSTBEDIR` and shortens the
1245        // active pattern length without turning `/*` into an empty body (that would drop the rule).
1246        let mut directory_only = false;
1247        if raw.len() > 1 && raw.ends_with('/') {
1248            directory_only = true;
1249            raw.pop();
1250        }
1251        if raw.is_empty() {
1252            return None;
1253        }
1254
1255        let mut anchored = false;
1256        if let Some(rest) = raw.strip_prefix('/') {
1257            anchored = true;
1258            raw = rest.to_owned();
1259        }
1260        // After `/*` → pop `/` we get `"/"` then strip leading `/` → empty. Git keeps this as the
1261        // root glob `*` (include all top-level names in non-cone sparse files).
1262        if raw.is_empty() && anchored && directory_only {
1263            raw = "*".to_owned();
1264            directory_only = false;
1265        } else if raw.is_empty() {
1266            return None;
1267        }
1268
1269        let has_slash = raw.contains('/');
1270        Some(Self {
1271            negative,
1272            directory_only,
1273            anchored,
1274            has_slash,
1275            body: raw,
1276        })
1277    }
1278}
1279
1280/// Whether `p` matches `pathname` for sparse-checkout evaluation.
1281///
1282/// `as_directory` mirrors Git's `dtype == DT_DIR` pass when walking parent paths:
1283/// patterns with a trailing `/` in the sparse file (`PATTERN_FLAG_MUSTBEDIR`) only
1284/// participate in those iterations.
1285fn sparse_pattern_matches(p: &SparsePattern, pathname: &str, as_directory: bool) -> bool {
1286    // Git never gates basename (NODIR) or anchored `/*` patterns on dtype: `match_basename` /
1287    // `match_pathname` run regardless of `DT_DIR` (dir.c). Earlier code rejected `nodir`
1288    // patterns on the parent-directory pass, which wrongly excluded `subsub/added` under
1289    // `/*` + `!sub` + `sub/added` (t1011 subtest 9). The `!/*/` directory-only rule still
1290    // shadows `/*` for nested dirs via reverse-order first-match (t7817/t1091 preserved).
1291    if p.directory_only && !as_directory {
1292        return false;
1293    }
1294    // On-disk `!/*/` parses as directory-only anchored `*`. For regular files we exclude nested
1295    // paths only (`dir/c`, not `a`). When walking parents (`as_directory`), Git still matches this
1296    // pattern against directory paths like `dir` so `dir/c` can be excluded (t7817).
1297    if p.directory_only && p.anchored && !p.has_slash && p.body == "*" {
1298        // Git `match_pathname` for MUSTBEDIR `/*` / `!/*/`: only top-level directory names
1299        // (no `/` in the pathname), including on the parent-directory pass — not every
1300        // `as_directory` path (dir.c / filter_sparse).
1301        let trimmed = pathname.trim_end_matches('/');
1302        return !trimmed.contains('/');
1303    }
1304    if !p.has_slash && !p.anchored {
1305        sparse_unanchored_basename_matches(&p.body, pathname)
1306    } else if p.anchored && !p.has_slash && p.body == "*" && !p.directory_only {
1307        // Sparse line `/*`: include only top-level paths (one segment). `WM_PATHNAME` keeps `*`
1308        // from matching `/`, but we match against the bare pathname; require no `/` so `dir/c` is
1309        // not included by `/*` alone (t7817 — excluded via `!/*/` on the parent directory pass).
1310        !pathname.contains('/')
1311    } else {
1312        wildmatch(p.body.as_bytes(), pathname.as_bytes(), WM_PATHNAME)
1313    }
1314}
1315
1316fn sparse_pattern_matches_path(p: &SparsePattern, pathname: &str) -> bool {
1317    sparse_pattern_matches(p, pathname, false)
1318}
1319
1320/// Parse sparse-checkout lines from a blob (same syntax as `info/sparse-checkout`).
1321#[must_use]
1322pub fn parse_sparse_patterns_from_blob(content: &str) -> Vec<String> {
1323    let mut patterns = Vec::new();
1324    for line in content.lines() {
1325        let t = line.trim_end_matches('\r');
1326        if t.is_empty() || t.starts_with('#') {
1327            continue;
1328        }
1329        patterns.push(t.to_owned());
1330    }
1331    patterns
1332}
1333
1334fn sparse_list_last_match(
1335    pathname: &str,
1336    as_directory: bool,
1337    parsed: &[SparsePattern],
1338) -> Option<bool> {
1339    for p in parsed.iter().rev() {
1340        if sparse_pattern_matches(p, pathname, as_directory) {
1341            return Some(!p.negative);
1342        }
1343    }
1344    None
1345}
1346
1347/// Non-cone sparse-checkout inclusion, matching Git's `path_in_sparse_checkout`.
1348///
1349/// Walks from the full path toward parents (as in `dir.c:path_in_sparse_checkout_1`):
1350/// each step uses last-match-wins over patterns; `UNDECIDED` falls back to the parent
1351/// directory until the decision is made or the path is rejected at the top level.
1352#[must_use]
1353#[allow(dead_code)] // integration / re-export use only
1354pub(crate) fn path_in_sparse_checkout(
1355    path: &str,
1356    lines: &[String],
1357    work_tree: Option<&Path>,
1358) -> bool {
1359    ParsedSparsePatterns::parse(lines).includes(path, work_tree)
1360}
1361
1362/// Non-cone sparse-checkout lines parsed once, for repeated [`path_in_sparse_checkout`] checks.
1363#[derive(Debug, Clone)]
1364pub(crate) struct ParsedSparsePatterns(Vec<SparsePattern>);
1365
1366impl ParsedSparsePatterns {
1367    /// Parse sparse-checkout lines; blank lines and comments are dropped.
1368    pub fn parse(lines: &[String]) -> Self {
1369        Self(
1370            lines
1371                .iter()
1372                .filter_map(|l| SparsePattern::from_line(l))
1373                .collect(),
1374        )
1375    }
1376
1377    /// Whether `path` is included; `work_tree` lets on-disk directories match directory-only rules.
1378    pub(crate) fn includes(&self, path: &str, work_tree: Option<&Path>) -> bool {
1379        if path.is_empty() || self.0.is_empty() {
1380            return true;
1381        }
1382
1383        let mut end = path.len();
1384        let mut as_directory = false;
1385
1386        loop {
1387            let pathname = &path[..end];
1388            let dtype_is_dir =
1389                work_tree.is_some_and(|wt| wt.join(pathname).is_dir()) || as_directory;
1390
1391            match sparse_list_last_match(pathname, dtype_is_dir, &self.0) {
1392                Some(true) => return true,
1393                Some(false) => return false,
1394                None => {
1395                    let Some(slash) = path[..end].rfind('/') else {
1396                        // Top-level path with no matching rule: Git stops here (UNDECIDED → excluded),
1397                        // not at an empty pathname.
1398                        return false;
1399                    };
1400                    end = slash;
1401                    as_directory = true;
1402                }
1403            }
1404        }
1405    }
1406}
1407
1408/// Last-match-wins sparse semantics for `rev-list --filter=sparse:oid=…` (non-cone).
1409///
1410/// Unanchored patterns without `/` use Git-style basename rules: `pat` matches `pat`,
1411/// `pat.ext`, and `pat/…` paths. Anchored patterns and patterns containing `/` use
1412/// pathname wildmatch with `WM_PATHNAME`.
1413///
1414/// Returns `None` if no pattern matched (`UNDECIDED`).
1415#[must_use]
1416#[allow(dead_code)] // integration / re-export use only
1417pub fn path_matches_sparse_pattern_list(pathname: &str, lines: &[String]) -> Option<bool> {
1418    let parsed: Vec<SparsePattern> = lines
1419        .iter()
1420        .filter_map(|l| SparsePattern::from_line(l))
1421        .collect();
1422    if parsed.is_empty() {
1423        return None;
1424    }
1425    for p in parsed.iter().rev() {
1426        if sparse_pattern_matches_path(p, pathname) {
1427            return Some(!p.negative);
1428        }
1429    }
1430    None
1431}
1432
1433fn sparse_unanchored_basename_matches(pat: &str, path: &str) -> bool {
1434    let basename = path.rsplit('/').next().unwrap_or(path);
1435    wildmatch(pat.as_bytes(), basename.as_bytes(), 0)
1436}
1437
1438/// Returns the submodule path if `repo_rel_path` names something inside a gitlink entry.
1439#[must_use]
1440#[allow(dead_code)] // integration / re-export use only
1441pub(crate) fn submodule_containing_path(repo_rel_path: &str, index: &Index) -> Option<String> {
1442    let bytes = repo_rel_path.as_bytes();
1443    if bytes.is_empty() {
1444        return None;
1445    }
1446    let mut best: Option<String> = None;
1447    let mut end = 0usize;
1448    while end < bytes.len() {
1449        let Some(slash) = bytes[end..].iter().position(|&b| b == b'/') else {
1450            break;
1451        };
1452        end += slash;
1453        if let Some(entry) = index.get(&bytes[..end], 0) {
1454            if entry.mode == MODE_GITLINK {
1455                best = Some(String::from_utf8_lossy(&bytes[..end]).into_owned());
1456            }
1457        }
1458        end += 1;
1459    }
1460    best
1461}
1462
1463/// Convert a user-supplied path into a normalized repository-relative path.
1464///
1465/// For many paths from the same directory, build one [`RepoPathNormalizer`] instead.
1466///
1467/// # Parameters
1468///
1469/// - `repo` - repository handle.
1470/// - `cwd` - current working directory.
1471/// - `path` - user input path string.
1472///
1473/// # Errors
1474///
1475/// Returns [`crate::worktree::WorktreeError::Path`] if the repository has no work tree or the path resolves
1476/// outside it.
1477pub fn normalize_repo_relative(repo: &Repository, cwd: &Path, path: &str) -> Result<String> {
1478    RepoPathNormalizer::new(repo, cwd)?.normalize(path)
1479}
1480
1481/// Converts user-supplied paths, relative to one working directory, into normalized
1482/// repository-relative paths (as [`normalize_repo_relative`] does for a single path).
1483///
1484/// The working directory's position in the work tree is resolved once, so each relative path
1485/// is normalized lexically on its `/`-separated components with a single allocation for the
1486/// result. Absolute paths and paths that climb above the work tree root take the general
1487/// route, which also recognizes alternate spellings of the work tree (such as macOS
1488/// `/private/tmp` for `/tmp`).
1489///
1490/// # Examples
1491///
1492/// ```no_run
1493/// use std::path::Path;
1494/// use grit_lib::config::environment::RepositoryOptions;
1495/// use grit_lib::repo::Repository;
1496/// use grit_lib::worktree::ignore::RepoPathNormalizer;
1497///
1498/// # fn main() -> grit_lib::error::Result<()> {
1499/// let repo = Repository::discover(None, &RepositoryOptions::empty())?;
1500/// let cwd = repo.work_tree().unwrap_or(Path::new(".")).join("src");
1501/// let normalizer = RepoPathNormalizer::new(&repo, &cwd)?;
1502/// assert_eq!(normalizer.normalize("./lib/../main.rs")?, "src/main.rs");
1503/// assert_eq!(normalizer.normalize("../docs/")?, "docs/");
1504/// # Ok(())
1505/// # }
1506/// ```
1507#[derive(Debug)]
1508pub struct RepoPathNormalizer<'a> {
1509    work_tree: &'a Path,
1510    cwd: &'a Path,
1511    /// `cwd` relative to the work tree root with `/` separators, when it lies inside it.
1512    cwd_rel: Option<String>,
1513}
1514
1515impl<'a> RepoPathNormalizer<'a> {
1516    /// Prepare to normalize paths given relative to `cwd`.
1517    ///
1518    /// # Parameters
1519    ///
1520    /// - `repo` - repository whose work tree paths are made relative to.
1521    /// - `cwd` - directory relative input paths start from (usually the process's current
1522    ///   directory); it may lie outside the work tree.
1523    ///
1524    /// # Errors
1525    ///
1526    /// Returns [`crate::worktree::WorktreeError::Path`] when `repo` has no work tree.
1527    pub fn new(repo: &'a Repository, cwd: &'a Path) -> Result<Self> {
1528        let Some(work_tree) = repo.work_tree() else {
1529            return Err(Error::Worktree(WorktreeError::Path {
1530                detail: "this operation must be run in a work tree".to_owned(),
1531            }));
1532        };
1533        let cwd_rel = normalize_path(cwd)
1534            .strip_prefix(work_tree)
1535            .ok()
1536            .map(crate::git_path::path_to_git_slash);
1537        Ok(Self {
1538            work_tree,
1539            cwd,
1540            cwd_rel,
1541        })
1542    }
1543
1544    /// Normalize one user-supplied path.
1545    ///
1546    /// `.` and `..` components are resolved lexically, a trailing `/` (a directory query) is
1547    /// kept, the work tree root itself becomes `""`, and paths starting with `:` are returned
1548    /// unchanged.
1549    ///
1550    /// # Parameters
1551    ///
1552    /// - `path` - path as the user typed it, relative to the normalizer's directory or
1553    ///   absolute.
1554    ///
1555    /// # Returns
1556    ///
1557    /// The repository-relative path with `/` separators.
1558    ///
1559    /// # Errors
1560    ///
1561    /// Returns [`crate::worktree::WorktreeError::Path`] if the path resolves outside the work tree.
1562    pub fn normalize(&self, path: &str) -> Result<String> {
1563        if path.starts_with(':') {
1564            return Ok(path.to_owned());
1565        }
1566        match self.normalize_lexically(path) {
1567            Some(rel) => Ok(rel),
1568            None => self.normalize_via_filesystem_paths(path),
1569        }
1570    }
1571
1572    /// The fast route: a relative path that stays inside the work tree, resolved from the
1573    /// precomputed working directory prefix. `None` sends the path down the general route.
1574    fn normalize_lexically(&self, path: &str) -> Option<String> {
1575        let cwd_rel = self.cwd_rel.as_deref()?;
1576        if cfg!(windows) || Path::new(path).is_absolute() {
1577            return None;
1578        }
1579        let mut rel = String::with_capacity(cwd_rel.len() + path.len() + 1);
1580        rel.push_str(cwd_rel);
1581        for component in path.split('/') {
1582            match component {
1583                "" | "." => {}
1584                ".." => {
1585                    if rel.is_empty() {
1586                        return None;
1587                    }
1588                    rel.truncate(rel.rfind('/').unwrap_or(0));
1589                }
1590                name => {
1591                    if !rel.is_empty() {
1592                        rel.push('/');
1593                    }
1594                    rel.push_str(name);
1595                }
1596            }
1597        }
1598        if path.ends_with('/') && !rel.is_empty() {
1599            rel.push('/');
1600        }
1601        Some(rel)
1602    }
1603
1604    fn normalize_via_filesystem_paths(&self, path: &str) -> Result<String> {
1605        let work_tree = self.work_tree;
1606        let query_as_dir = path.ends_with('/');
1607        let input = Path::new(path);
1608        let combined = if input.is_absolute() {
1609            input.to_path_buf()
1610        } else {
1611            self.cwd.join(input)
1612        };
1613        let normalized = normalize_path(&combined);
1614        // Repository opening already resolves the worktree root. Most queries share that
1615        // spelling, so avoid canonicalizing the same root again for every path in a batch.
1616        // Keep the filesystem-alias fallback for spellings such as macOS /tmp and /private/tmp.
1617        let mut rel = match normalized.strip_prefix(work_tree) {
1618            Ok(relative) => crate::git_path::path_to_git_slash(relative),
1619            Err(_) => {
1620                crate::git_path::strip_worktree_prefix(&normalized, work_tree).ok_or_else(|| {
1621                    Error::Worktree(WorktreeError::Path {
1622                        detail: format!("path '{path}' is outside repository work tree"),
1623                    })
1624                })?
1625            }
1626        };
1627        if query_as_dir && !rel.is_empty() && !rel.ends_with('/') {
1628            rel.push('/');
1629        }
1630        Ok(rel)
1631    }
1632}
1633
1634fn normalize_path(path: &Path) -> PathBuf {
1635    let mut out = PathBuf::new();
1636    for component in path.components() {
1637        match component {
1638            Component::CurDir => {}
1639            Component::ParentDir => {
1640                out.pop();
1641            }
1642            other => out.push(other.as_os_str()),
1643        }
1644    }
1645    out
1646}
1647
1648#[cfg(test)]
1649mod normalization_tests {
1650    use super::*;
1651
1652    #[test]
1653    fn bare_repository_queries_return_a_path_error() {
1654        let dir = tempfile::tempdir().unwrap();
1655        let repo = crate::repo::init_repository(
1656            dir.path(),
1657            true,
1658            "main",
1659            None,
1660            crate::RefStorageFormat::Files,
1661        )
1662        .unwrap();
1663        assert!(matches!(
1664            normalize_repo_relative(&repo, dir.path(), "missing/file"),
1665            Err(Error::Worktree(WorktreeError::Path { .. }))
1666        ));
1667    }
1668
1669    #[test]
1670    fn lexical_route_agrees_with_filesystem_route() {
1671        let dir = tempfile::tempdir().unwrap();
1672        let root = dir.path();
1673        crate::repo::init_repository(root, false, "main", None, crate::RefStorageFormat::Files)
1674            .unwrap();
1675        let options = crate::environment::RepositoryOptions::empty().with_work_tree(root);
1676        let repo = Repository::open(&root.join(".git"), &options).unwrap();
1677        let root = repo.work_tree().unwrap().to_path_buf();
1678        let inputs = [
1679            "",
1680            ".",
1681            "./",
1682            "a",
1683            "a/",
1684            "a//b",
1685            "./a/./b/",
1686            "a/../b",
1687            "a/b/../../c",
1688            "..",
1689            "../",
1690            "../x",
1691            "../../x/y/",
1692            "x/../../y",
1693            "café/new.txt",
1694            "...",
1695            ".hidden/..x",
1696        ];
1697        for cwd in [root.clone(), root.join("sub"), root.join("sub/deeper")] {
1698            let normalizer = RepoPathNormalizer::new(&repo, &cwd).unwrap();
1699            assert!(normalizer.cwd_rel.is_some());
1700            for input in inputs {
1701                let general = normalizer.normalize_via_filesystem_paths(input);
1702                let lexical = normalizer.normalize_lexically(input);
1703                match (&general, lexical) {
1704                    (Ok(expected), Some(got)) => assert_eq!(&got, expected, "{cwd:?} {input}"),
1705                    (_, None) => {}
1706                    (Err(e), Some(got)) => panic!("{cwd:?} {input}: lexical {got}, general {e}"),
1707                }
1708                assert_eq!(
1709                    normalizer.normalize(input).ok(),
1710                    general.ok(),
1711                    "{cwd:?} {input}"
1712                );
1713            }
1714        }
1715        let from_root = RepoPathNormalizer::new(&repo, &root).unwrap();
1716        assert_eq!(from_root.normalize("a/../b/").unwrap(), "b/");
1717        assert_eq!(from_root.normalize(":(glob)x").unwrap(), ":(glob)x");
1718        assert!(from_root.normalize("../x").is_err());
1719        let absolute = root.join("sub/f");
1720        assert_eq!(
1721            from_root.normalize(absolute.to_str().unwrap()).unwrap(),
1722            "sub/f"
1723        );
1724
1725        let outside = dir.path().parent().unwrap();
1726        let normalizer = RepoPathNormalizer::new(&repo, outside).unwrap();
1727        assert!(normalizer.cwd_rel.is_none());
1728        let name = root.file_name().unwrap().to_str().unwrap();
1729        assert_eq!(normalizer.normalize(&format!("{name}/x/")).unwrap(), "x/");
1730        assert!(normalizer.normalize("elsewhere").is_err());
1731    }
1732}
1733
1734#[cfg(test)]
1735mod per_directory_load_tests {
1736    use super::*;
1737
1738    #[test]
1739    fn known_directory_reads_its_exclude_file_on_first_query() {
1740        let dir = tempfile::tempdir().unwrap();
1741        let root = dir.path();
1742        let repo =
1743            crate::repo::init_repository(root, false, "main", None, crate::RefStorageFormat::Files)
1744                .unwrap();
1745        fs::create_dir_all(root.join("d/sub")).unwrap();
1746        fs::write(root.join("d/.gitignore"), "*.tmp\n").unwrap();
1747
1748        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
1749        matcher.note_directory_known("d");
1750        matcher.note_directory_known("d/sub");
1751        assert!(
1752            matcher.gitignore_cache.is_empty(),
1753            "entering a directory must not read its exclude file"
1754        );
1755        assert!(matcher.known_worktree_directories.contains("d/sub"));
1756
1757        assert!(matcher
1758            .is_path_ignored(&repo, None, "d/sub/x.tmp", false)
1759            .unwrap());
1760        assert!(!matcher
1761            .is_path_ignored(&repo, None, "d/sub/x.txt", false)
1762            .unwrap());
1763        assert!(matcher.gitignore_cache.contains_key("d"));
1764        assert!(matcher.gitignore_cache.contains_key("d/sub"));
1765    }
1766}
1767
1768#[cfg(test)]
1769mod sparse_checkout_tests {
1770    use super::*;
1771
1772    #[test]
1773    fn non_cone_default_init_patterns() {
1774        let lines = vec!["/*".into(), "!/*/".into()];
1775        assert!(path_in_sparse_checkout("a", &lines, None));
1776        assert!(!path_in_sparse_checkout("folder1/a", &lines, None));
1777        let wt = std::env::temp_dir().join("grit-sparse-wt-test");
1778        let _ = std::fs::create_dir_all(wt.join("folder1"));
1779        let _ = std::fs::write(wt.join("a"), b"x");
1780        assert!(!path_in_sparse_checkout("folder1/a", &lines, Some(&wt)));
1781        assert!(!path_in_sparse_checkout("folder1", &lines, Some(&wt)));
1782    }
1783
1784    #[test]
1785    fn unanchored_glob_matches_path_components() {
1786        let lines = vec!["/*".into(), "!/*/".into(), "*folder*".into()];
1787        assert!(path_in_sparse_checkout("folder1/a", &lines, None));
1788        assert!(path_in_sparse_checkout("folder2/a", &lines, None));
1789        assert!(!path_in_sparse_checkout("deep/a", &lines, None));
1790    }
1791
1792    #[test]
1793    fn non_cone_src_nested_under_included_dir_with_negated_slash_slash() {
1794        let lines = vec!["/*".into(), "!/*/".into(), "/src/".into()];
1795        assert!(path_in_sparse_checkout("a.txt", &lines, None));
1796        assert!(path_in_sparse_checkout("src/z", &lines, None));
1797        assert!(path_in_sparse_checkout("src/deep/w", &lines, None));
1798        assert!(!path_in_sparse_checkout("d1/x", &lines, None));
1799        assert!(!path_in_sparse_checkout("d1/sub/y", &lines, None));
1800    }
1801
1802    #[test]
1803    fn unanchored_star_with_negated_other_includes_other_slash_q() {
1804        let lines = vec!["*".into(), "!other".into()];
1805        assert!(path_in_sparse_checkout("other/q", &lines, None));
1806        assert!(!path_in_sparse_checkout("other", &lines, None));
1807    }
1808}
1809
1810#[cfg(test)]
1811mod gitignore_glob_tests {
1812    use super::*;
1813
1814    fn pathname_pattern_matches(pattern: &str, text: &str) -> bool {
1815        pattern_matches_kind(
1816            &classify_ignore_pattern(pattern),
1817            pattern,
1818            text,
1819            true,
1820            false,
1821        )
1822    }
1823
1824    fn rule(line: &str, base_dir: &str) -> IgnoreRule {
1825        parse_rule_line(line, 1, IgnoreSource::InfoExclude, base_dir).unwrap()
1826    }
1827
1828    #[test]
1829    fn lines_lose_at_most_one_trailing_cr() {
1830        let rules = |content: &str| {
1831            parse_gitignore_content(content, IgnoreSource::InfoExclude, "", &mut Vec::new())
1832                .unwrap()
1833        };
1834        let [crlf] = rules("a\r\n").try_into().unwrap();
1835        assert!(rule_matches(&crlf, "a", false, false));
1836        let [double_cr] = rules("a\r\r\n").try_into().unwrap();
1837        assert!(rule_matches(&double_cr, "a\r", false, false));
1838        assert!(!rule_matches(&double_cr, "a", false, false));
1839        let [leading_cr] = rules("\ra\n").try_into().unwrap();
1840        assert!(rule_matches(&leading_cr, "\ra", false, false));
1841        assert!(rules("a\nb").len() == 2);
1842    }
1843
1844    #[test]
1845    fn trailing_spaces_are_trimmed_unless_escaped() {
1846        for (line, expected) in [
1847            ("a  ", "a"),
1848            ("a\\ ", "a\\ "),
1849            ("a\\  ", "a\\ "),
1850            ("a\\", "a\\"),
1851            ("é b ", "é b"),
1852            ("   ", ""),
1853            ("a \\\\ ", "a \\\\"),
1854        ] {
1855            assert_eq!(trim_trailing_spaces_git(line), expected, "{line:?}");
1856        }
1857        for empty in ["!", "/", "!/", "//", "# x", " ", "\r"] {
1858            let parsed = parse_rule_line(empty, 1, IgnoreSource::InfoExclude, "");
1859            assert!(parsed.is_none(), "{empty:?}");
1860        }
1861        let r = rule("!/a/b/ ", "");
1862        assert!(r.negative && r.anchored && r.directory_only && r.has_slash);
1863        assert_eq!(
1864            (r.pattern_text.as_str(), r.body.as_str()),
1865            ("!/a/b/", "a/b")
1866        );
1867    }
1868
1869    #[test]
1870    fn every_pattern_kind_folds_ascii_case_only_with_ignore_case() {
1871        for (pattern, kind, path) in [
1872            ("README", "literal", "readme"),
1873            ("Target*", "prefix", "target-debug"),
1874            ("*.LOG", "suffix", "debug.log"),
1875            ("[Dd]EBUG?.txt", "wild", "debug1.TXT"),
1876        ] {
1877            let r = rule(pattern, "");
1878            assert!(!rule_matches(&r, path, false, false), "{kind}: {pattern}");
1879            assert!(rule_matches(&r, path, false, true), "{kind}: {pattern}");
1880            assert!(rule_matches(&r, &format!("sub/{path}"), false, true));
1881        }
1882        assert!(!rule_matches(&rule("*.LOG", ""), "x.lag", false, true));
1883        assert!(!rule_matches(&rule("Target*", ""), "tar", false, true));
1884        assert!(!rule_matches(&rule("*.LOG", ""), "LOG", false, true));
1885        // Git folds ASCII only; non-ASCII letters keep their case.
1886        assert!(!rule_matches(&rule("*É", ""), "é", false, true));
1887        assert!(!rule_matches(&rule("Über", ""), "über", false, true));
1888        assert!(rule_matches(&rule("Über", ""), "ÜBER", false, true));
1889    }
1890
1891    #[test]
1892    fn directory_and_anchored_rules_fold_case() {
1893        let dir_only = rule("Build/", "");
1894        assert!(rule_matches(&dir_only, "build", true, true));
1895        assert!(rule_matches(&dir_only, "src/BUILD", true, true));
1896        assert!(!rule_matches(&dir_only, "build", true, false));
1897        assert!(!rule_matches(&dir_only, "build", false, true));
1898        let anchored = rule("/Docs/*.PDF", "");
1899        assert!(rule_matches(&anchored, "docs/manual.pdf", false, true));
1900        assert!(!rule_matches(&anchored, "docs/sub/manual.pdf", false, true));
1901        assert!(!rule_matches(&anchored, "docs/manual.pdf", false, false));
1902    }
1903
1904    #[test]
1905    fn nested_gitignore_base_dir_folds_case() {
1906        let nested = rule("*.tmp", "Sub/Dir");
1907        assert!(rule_matches(&nested, "Sub/Dir/a.tmp", false, false));
1908        assert!(!rule_matches(&nested, "sub/dir/a.tmp", false, false));
1909        assert!(rule_matches(&nested, "sub/dir/a.tmp", false, true));
1910        assert!(!rule_matches(&nested, "sub/dirx/a.tmp", false, true));
1911        assert!(!rule_matches(&nested, "sub/di", false, true));
1912        assert_eq!(strip_base("Sub", "sub", true), Some(""));
1913        assert_eq!(strip_base("Sub", "SUB/x", true), Some("x"));
1914        assert_eq!(strip_base("Sub", "subway/x", true), None);
1915        assert_eq!(strip_base("Sub", "sub/x", false), None);
1916    }
1917
1918    #[test]
1919    fn precompiled_literal_prefix_suffix_patterns() {
1920        assert!(matches!(
1921            classify_ignore_pattern("build"),
1922            IgnorePatternKind::Literal(_)
1923        ));
1924        assert!(matches!(
1925            classify_ignore_pattern("target*"),
1926            IgnorePatternKind::Prefix(_)
1927        ));
1928        assert!(matches!(
1929            classify_ignore_pattern("*.o"),
1930            IgnorePatternKind::Suffix(_)
1931        ));
1932        assert!(matches!(
1933            classify_ignore_pattern("a*b"),
1934            IgnorePatternKind::Wild
1935        ));
1936        assert!(matches!(
1937            classify_ignore_pattern(r"foo\ bar"),
1938            IgnorePatternKind::Wild
1939        ));
1940        assert!(matches!(
1941            classify_ignore_pattern("foo/*"),
1942            IgnorePatternKind::Wild
1943        ));
1944        assert!(!pathname_pattern_matches("foo/*", "foo/bar/baz"));
1945        assert!(rule_body_matches(
1946            &IgnoreRule {
1947                source: IgnoreSource::InfoExclude,
1948                line_number: 1,
1949                pattern_text: "*.log".into(),
1950                negative: false,
1951                directory_only: false,
1952                anchored: false,
1953                has_slash: false,
1954                body: "*.log".into(),
1955                base_dir: String::new(),
1956                match_kind: IgnorePatternKind::Suffix(".log".into()),
1957            },
1958            "app.log",
1959            false,
1960            false
1961        ));
1962    }
1963
1964    #[test]
1965    fn dir_star_extension_matches_nested_path() {
1966        // Slash in pattern → WM_PATHNAME: `*` does not cross `/` (gitignore(5)).
1967        assert!(!pathname_pattern_matches("doc/*.pdf", "doc/sub/manual.pdf"));
1968        assert!(pathname_pattern_matches("doc/*.pdf", "doc/manual.pdf"));
1969        assert!(!pathname_pattern_matches("doc/*.pdf", "other/manual.pdf"));
1970        assert!(pathname_pattern_matches(
1971            "doc/**/*.pdf",
1972            "doc/sub/manual.pdf"
1973        ));
1974    }
1975
1976    #[test]
1977    fn dir_star_extension_unexpanded_when_parent_has_glob() {
1978        assert!(!pathname_pattern_matches("*/foo/*.pdf", "a/foo/sub/x.pdf"));
1979    }
1980
1981    #[test]
1982    fn nested_dir_star_extension() {
1983        assert!(!pathname_pattern_matches("foo/bar/*.c", "foo/bar/baz/x.c"));
1984    }
1985
1986    #[test]
1987    fn pathname_suffix_star_does_not_cross_slashes() {
1988        assert!(pathname_pattern_matches("*.log", "root.log"));
1989        assert!(!pathname_pattern_matches("*.log", "sub/nested.log"));
1990    }
1991
1992    #[test]
1993    fn root_anchored_suffix_patterns_match_one_segment() {
1994        let rule = |line: &str| rule(line, "");
1995        assert!(rule_matches(&rule("/*.log"), "root.log", false, false));
1996        assert!(!rule_matches(
1997            &rule("/*.log"),
1998            "sub/nested.log",
1999            false,
2000            false
2001        ));
2002        assert!(rule_matches(&rule("/*"), "only", false, false));
2003        assert!(!rule_matches(&rule("/*"), "sub/nested", false, false));
2004        assert!(rule_matches(&rule("/keep*"), "keep-out", false, false));
2005        assert!(!rule_matches(&rule("/keep*"), "keep/out", false, false));
2006        assert!(rule_matches(&rule("/*.LOG"), "root.log", false, true));
2007        assert!(!rule_matches(
2008            &rule("/*.LOG"),
2009            "sub/nested.log",
2010            false,
2011            true
2012        ));
2013    }
2014}
2015
2016#[cfg(all(test, unix))]
2017mod per_directory_gitignore_tests {
2018    use super::*;
2019    use crate::repo::init_repository;
2020    use crate::RefStorageFormat;
2021    use std::os::unix::ffi::OsStringExt;
2022    use std::os::unix::fs::symlink;
2023    use tempfile::TempDir;
2024
2025    fn ignored_with_warnings(repo: &Repository, path: &str) -> (bool, Vec<String>) {
2026        let mut matcher = IgnoreMatcher::from_repository(repo).unwrap();
2027        let ignored = matcher.is_path_ignored(repo, None, path, false).unwrap();
2028        (ignored, matcher.take_warnings())
2029    }
2030
2031    #[test]
2032    fn symlinked_gitignore_is_skipped_with_warning_and_plain_one_applies() {
2033        let dir = TempDir::new().unwrap();
2034        let root = dir.path();
2035        let repo = init_repository(root, false, "main", None, RefStorageFormat::Files).unwrap();
2036        fs::create_dir_all(root.join("plain")).unwrap();
2037        fs::create_dir_all(root.join("to_file")).unwrap();
2038        fs::create_dir_all(root.join("to_dir")).unwrap();
2039        fs::create_dir_all(root.join("none")).unwrap();
2040        fs::write(root.join("plain/.gitignore"), "*.log\n").unwrap();
2041        fs::write(root.join("rules"), "*.log\n").unwrap();
2042        symlink(root.join("rules"), root.join("to_file/.gitignore")).unwrap();
2043        symlink(root.join("plain"), root.join("to_dir/.gitignore")).unwrap();
2044        fs::create_dir_all(root.join("dangling")).unwrap();
2045        symlink(root.join("no-such-rules"), root.join("dangling/.gitignore")).unwrap();
2046        fs::create_dir_all(root.join("to_fifo")).unwrap();
2047        let fifo = std::ffi::CString::new(root.join("fifo").into_os_string().into_vec()).unwrap();
2048        // SAFETY: `fifo` is a NUL-terminated path that outlives the call.
2049        assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o644) }, 0);
2050        symlink(root.join("fifo"), root.join("to_fifo/.gitignore")).unwrap();
2051
2052        assert_eq!(ignored_with_warnings(&repo, "plain/a.log"), (true, vec![]));
2053        assert_eq!(ignored_with_warnings(&repo, "none/a.log"), (false, vec![]));
2054        let (done_tx, done_rx) = std::sync::mpsc::channel();
2055        let fifo_root = root.to_path_buf();
2056        std::thread::spawn(move || {
2057            let options = crate::environment::RepositoryOptions::empty().with_work_tree(&fifo_root);
2058            let repo = Repository::open(&fifo_root.join(".git"), &options).unwrap();
2059            let _ = done_tx.send(ignored_with_warnings(&repo, "to_fifo/a.log"));
2060        });
2061        let (ignored, warnings) = done_rx
2062            .recv_timeout(std::time::Duration::from_secs(5))
2063            .expect("a .gitignore symlink to a FIFO must be rejected without opening it");
2064        assert!(!ignored);
2065        assert_eq!(warnings.len(), 1, "{warnings:?}");
2066        for dir in ["to_file", "to_dir", "dangling"] {
2067            let (ignored, warnings) = ignored_with_warnings(&repo, &format!("{dir}/a.log"));
2068            assert!(!ignored, "{dir}: symlinked .gitignore must not apply");
2069            assert_eq!(warnings.len(), 1, "{dir}: {warnings:?}");
2070            assert!(warnings[0].contains(&format!("{dir}/.gitignore")));
2071        }
2072    }
2073}
2074
2075#[cfg(test)]
2076mod ignore_case_matcher_tests {
2077    use super::*;
2078    use crate::repo::init_repository;
2079    use crate::RefStorageFormat;
2080    use tempfile::TempDir;
2081
2082    fn issue_repo(ignore_case: bool) -> (TempDir, Repository) {
2083        let dir = TempDir::new().unwrap();
2084        let root = dir.path();
2085        init_repository(root, false, "main", None, RefStorageFormat::Files).unwrap();
2086        let mut config = fs::read_to_string(root.join(".git/config")).unwrap();
2087        config.push_str(&format!("[core]\n\tignorecase = {ignore_case}\n"));
2088        fs::write(root.join(".git/config"), config).unwrap();
2089        fs::write(root.join(".gitignore"), "Build/\n*.LOG\n!keep.log\n").unwrap();
2090        fs::create_dir_all(root.join("build")).unwrap();
2091        for file in ["build/x.o", "debug.log", "keep.log", "README"] {
2092            fs::write(root.join(file), "x\n").unwrap();
2093        }
2094        let options = crate::environment::RepositoryOptions::empty().with_work_tree(root);
2095        let repo = Repository::open(&root.join(".git"), &options).unwrap();
2096        (dir, repo)
2097    }
2098
2099    fn ignored(matcher: &mut IgnoreMatcher, repo: &Repository, path: &str, is_dir: bool) -> bool {
2100        let fast = matcher.is_path_ignored(repo, None, path, is_dir).unwrap();
2101        let (verbose, _) = matcher.check_path(repo, None, path, is_dir).unwrap();
2102        assert_eq!(fast, verbose, "{path}");
2103        fast
2104    }
2105
2106    #[test]
2107    fn from_repository_honors_core_ignorecase() {
2108        let (_dir, repo) = issue_repo(true);
2109        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2110        assert!(matcher.ignore_case());
2111        assert!(ignored(&mut matcher, &repo, "build", true));
2112        assert!(ignored(&mut matcher, &repo, "build/x.o", false));
2113        assert!(ignored(&mut matcher, &repo, "debug.log", false));
2114        assert!(!ignored(&mut matcher, &repo, "keep.log", false));
2115        assert!(!ignored(&mut matcher, &repo, "KEEP.LOG", false));
2116        assert!(!ignored(&mut matcher, &repo, "README", false));
2117        let (_, matched) = matcher.check_path(&repo, None, "build/x.o", false).unwrap();
2118        assert_eq!(matched.unwrap().pattern_text, "Build/");
2119    }
2120
2121    #[test]
2122    fn case_sensitive_by_default_and_overridable() {
2123        let (_dir, repo) = issue_repo(false);
2124        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2125        assert!(!matcher.ignore_case());
2126        assert!(!ignored(&mut matcher, &repo, "build/x.o", false));
2127        assert!(!ignored(&mut matcher, &repo, "debug.log", false));
2128        assert!(ignored(&mut matcher, &repo, "Build/x.o", false));
2129
2130        let mut folded = matcher.with_ignore_case(true);
2131        assert!(ignored(&mut folded, &repo, "build/x.o", false));
2132        assert!(ignored(&mut folded, &repo, "debug.log", false));
2133        assert!(!IgnoreMatcher::default().ignore_case());
2134    }
2135}
2136
2137#[cfg(test)]
2138mod index_lookup_scaling_tests {
2139    use super::*;
2140    use crate::index::{index_path_cmp, Index, IndexEntry, MODE_REGULAR};
2141    use crate::objects::ObjectId;
2142    use crate::repo::init_repository;
2143    use crate::RefStorageFormat;
2144    use tempfile::TempDir;
2145
2146    fn dummy_oid() -> ObjectId {
2147        ObjectId::from_bytes(&[0u8; 20]).unwrap()
2148    }
2149
2150    fn make_entry(path: &str) -> IndexEntry {
2151        IndexEntry {
2152            ctime_sec: 0,
2153            ctime_nsec: 0,
2154            mtime_sec: 0,
2155            mtime_nsec: 0,
2156            dev: 0,
2157            ino: 0,
2158            mode: MODE_REGULAR,
2159            uid: 0,
2160            gid: 0,
2161            size: 0,
2162            oid: dummy_oid(),
2163            flags: path.len().min(0xFFF) as u16,
2164            flags_extended: None,
2165            path: path.as_bytes().to_vec(),
2166            base_index_pos: 0,
2167        }
2168    }
2169
2170    #[test]
2171    fn tracked_check_path_index_lookups_sublinear_in_index_size() {
2172        const N: usize = 100_000;
2173        const M: usize = 1_000;
2174        let dir = TempDir::new().unwrap();
2175        let repo =
2176            init_repository(dir.path(), false, "main", None, RefStorageFormat::Files).unwrap();
2177        let mut index = Index::new();
2178        for i in 0..N {
2179            index.add_or_replace(make_entry(&format!("tracked/{i:06}.txt")));
2180        }
2181        let mut matcher = IgnoreMatcher::default();
2182        index_path_cmp::reset();
2183        for i in 0..M {
2184            let path = format!("untracked/{i:06}.txt");
2185            let (ignored, _) = matcher
2186                .check_path(&repo, Some(&index), &path, false)
2187                .unwrap();
2188            assert!(!ignored, "untracked path must not be ignored");
2189        }
2190        let cmps = index_path_cmp::take();
2191        let log_n = (N as f64).log2().ceil() as usize;
2192        let bound = 100 * M * log_n;
2193        assert!(
2194            cmps < bound,
2195            "index path comparisons {cmps} should stay under {bound} (N={N}, M={M})"
2196        );
2197    }
2198}
2199
2200#[cfg(test)]
2201mod pattern_list_tests {
2202    use super::IgnorePatternList;
2203
2204    fn ignored(content: &str, path: &str, is_dir: bool) -> bool {
2205        IgnorePatternList::parse(content.as_bytes(), "")
2206            .is_ignored(path, is_dir, false)
2207            .unwrap_or(false)
2208    }
2209
2210    #[test]
2211    fn basename_patterns_match_last_component_only() {
2212        assert!(ignored("foo\n", "foo", false));
2213        assert!(ignored("foo\n", "dir/foo", false));
2214        assert!(!ignored("foo\n", "foo/bar", false));
2215        assert!(ignored("*.o\n", "a/b/c.o", false));
2216    }
2217
2218    #[test]
2219    fn slash_patterns_match_whole_path() {
2220        assert!(ignored("/foo\n", "foo", false));
2221        assert!(!ignored("/foo\n", "dir/foo", false));
2222        assert!(ignored("dir/foo\n", "dir/foo", false));
2223        assert!(!ignored("dir/foo\n", "x/dir/foo", false));
2224        assert!(ignored("dir/*.o\n", "dir/a.o", false));
2225        assert!(!ignored("dir/*.o\n", "dir/sub/a.o", false));
2226        assert!(ignored("**/foo\n", "a/b/foo", false));
2227        assert!(ignored("a/**/b\n", "a/x/y/b", false));
2228    }
2229
2230    #[test]
2231    fn directory_only_patterns_need_a_directory() {
2232        assert!(ignored("foo/\n", "foo", true));
2233        assert!(!ignored("foo/\n", "foo", false));
2234        assert!(!ignored("foo/\n", "foo/bar", false));
2235    }
2236
2237    #[test]
2238    fn last_matching_pattern_wins() {
2239        let list = IgnorePatternList::parse(b"*.log\n!keep.log\n", "");
2240        assert_eq!(list.is_ignored("a.log", false, false), Some(true));
2241        assert_eq!(list.is_ignored("keep.log", false, false), Some(false));
2242        assert_eq!(list.is_ignored("a.txt", false, false), None);
2243        let m = list.last_match("keep.log", false, false).unwrap();
2244        assert_eq!((m.line_number, m.pattern_text.as_str()), (2, "!keep.log"));
2245    }
2246
2247    #[test]
2248    fn comments_blank_lines_and_trailing_spaces() {
2249        let list = IgnorePatternList::parse(b"\xef\xbb\xbf# comment\n\nfoo  \nbar\\ \n\\#x\n", "");
2250        assert_eq!(list.len(), 3);
2251        assert!(ignored("foo  \n", "foo", false));
2252        assert!(list.is_ignored("bar ", false, false).unwrap());
2253        assert!(list.is_ignored("#x", false, false).unwrap());
2254    }
2255
2256    #[test]
2257    fn base_directory_scopes_patterns() {
2258        let list = IgnorePatternList::parse(b"foo\n/bar\n", "sub");
2259        assert_eq!(list.is_ignored("sub/foo", false, false), Some(true));
2260        assert_eq!(list.is_ignored("sub/x/foo", false, false), Some(true));
2261        assert_eq!(list.is_ignored("sub/bar", false, false), Some(true));
2262        assert_eq!(list.is_ignored("sub/x/bar", false, false), None);
2263        assert_eq!(list.is_ignored("foo", false, false), None);
2264        assert_eq!(list.is_ignored("subfoo", false, false), None);
2265    }
2266
2267    #[test]
2268    fn ignore_case() {
2269        let list = IgnorePatternList::parse(b"*.LOG\nBuild/\n", "");
2270        assert_eq!(list.is_ignored("debug.log", false, false), None);
2271        assert_eq!(list.is_ignored("debug.log", false, true), Some(true));
2272        assert_eq!(list.is_ignored("build", true, true), Some(true));
2273    }
2274
2275    #[test]
2276    fn root_anchored_star_suffix_in_pattern_list() {
2277        let list = IgnorePatternList::parse(b"/*.log\n", "");
2278        assert_eq!(list.is_ignored("root.log", false, false), Some(true));
2279        assert_eq!(list.is_ignored("sub/nested.log", false, false), None);
2280        assert_eq!(list.is_ignored("sub/keep.txt", false, false), None);
2281    }
2282
2283    #[test]
2284    fn nested_gitignore_root_anchored_suffix() {
2285        let list = IgnorePatternList::parse(b"/*.dat\n", "sub");
2286        assert_eq!(list.is_ignored("sub/a.dat", false, false), Some(true));
2287        assert_eq!(list.is_ignored("sub/deeper/b.dat", false, false), None);
2288    }
2289
2290    #[test]
2291    fn negated_root_anchored_suffix() {
2292        let list = IgnorePatternList::parse(b"*.log\n!/*.log\n", "");
2293        assert_eq!(list.is_ignored("root.log", false, false), Some(false));
2294        assert_eq!(list.is_ignored("sub/nested.log", false, false), Some(true));
2295    }
2296}
2297
2298#[cfg(test)]
2299mod dir_state_cache_tests {
2300    use super::*;
2301    use crate::repo::init_repository;
2302    use crate::RefStorageFormat;
2303    use tempfile::TempDir;
2304
2305    fn repo_with(files: &[(&str, &str)]) -> (TempDir, Repository) {
2306        let dir = TempDir::new().unwrap();
2307        let root = dir.path();
2308        init_repository(root, false, "main", None, RefStorageFormat::Files).unwrap();
2309        for (path, content) in files {
2310            let path = root.join(path);
2311            fs::create_dir_all(path.parent().unwrap()).unwrap();
2312            fs::write(path, content).unwrap();
2313        }
2314        let options = crate::environment::RepositoryOptions::empty().with_work_tree(root);
2315        let repo = Repository::open(&root.join(".git"), &options).unwrap();
2316        (dir, repo)
2317    }
2318
2319    #[test]
2320    fn each_directory_state_and_exclude_file_is_built_once() {
2321        let (_dir, repo) = repo_with(&[
2322            (".gitignore", "*.o\n"),
2323            ("a/x/.gitignore", "*.tmp\n"),
2324            ("a/y/.gitignore", "*.bak\n"),
2325        ]);
2326        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2327        for round in 0..3 {
2328            for (path, expected) in [
2329                ("a/x/f.tmp", true),
2330                ("a/y/f.tmp", false),
2331                ("a/y/f.bak", true),
2332                ("a/x/f.o", true),
2333                ("a/x/f.rs", false),
2334                ("top.o", true),
2335            ] {
2336                let (ignored, _) = matcher.check_path(&repo, None, path, false).unwrap();
2337                assert_eq!(ignored, expected, "round {round}: {path}");
2338                assert_eq!(
2339                    matcher.is_path_ignored(&repo, None, path, false).unwrap(),
2340                    expected
2341                );
2342            }
2343        }
2344        // Root, `a`, `a/x` and `a/y`, each stat'd, read and probed once across all rounds.
2345        assert_eq!(matcher.dir_states.len(), 4);
2346        assert_eq!(matcher.rule_sets.len(), 4);
2347        let x = &matcher.dir_states[matcher.dir_state_ids["a/x"]];
2348        assert_eq!(x.stack.len(), 3);
2349        assert!(x.extendable && x.excluded.is_none());
2350    }
2351
2352    #[test]
2353    fn excluded_directory_is_recorded_on_its_descendants_states() {
2354        let (_dir, repo) = repo_with(&[(".gitignore", "build/\n!build/keep.txt\n")]);
2355        fs::create_dir_all(repo.work_tree().unwrap().join("build/deep")).unwrap();
2356        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2357        for path in ["build/keep.txt", "build/deep/a.c"] {
2358            let (ignored, matched) = matcher.check_path(&repo, None, path, false).unwrap();
2359            assert!(ignored, "{path}");
2360            assert_eq!(matched.unwrap().pattern_text, "build/");
2361        }
2362        assert!(matcher.dir_states[matcher.dir_state_ids["build"]]
2363            .excluded
2364            .is_some());
2365        assert!(matcher.dir_states[matcher.dir_state_ids["build/deep"]]
2366            .excluded
2367            .is_some());
2368        assert!(
2369            !matcher
2370                .check_path(&repo, None, "keep.txt", false)
2371                .unwrap()
2372                .0
2373        );
2374    }
2375
2376    #[test]
2377    fn a_file_ancestor_ends_the_per_directory_stack() {
2378        let (_dir, repo) = repo_with(&[(".gitignore", "*.o\n"), ("plain", "x\n")]);
2379        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2380        assert!(
2381            matcher
2382                .check_path(&repo, None, "plain/sub/x.o", false)
2383                .unwrap()
2384                .0
2385        );
2386        let plain = &matcher.dir_states[matcher.dir_state_ids["plain"]];
2387        assert_eq!(plain.stack.len(), 1);
2388        assert!(!plain.extendable);
2389        assert_eq!(
2390            matcher.dir_states[matcher.dir_state_ids["plain/sub"]]
2391                .stack
2392                .len(),
2393            1
2394        );
2395        assert!(!matcher.gitignore_cache.contains_key("plain"));
2396    }
2397
2398    #[test]
2399    fn batch_check_skips_directory_stats_only_when_the_path_stat_allows_it() {
2400        let (_dir, repo) = repo_with(&[
2401            (".gitignore", "*.o\n"),
2402            ("plain", "x\n"),
2403            ("real/.gitignore", "*.tmp\n"),
2404        ]);
2405        let index = Index::new();
2406        let paths = [
2407            "plain/sub/x.o",
2408            "plain/x.tmp",
2409            "real/x.tmp",
2410            "missing/deeper/x.tmp",
2411            "real/",
2412        ]
2413        .map(str::to_owned);
2414        let checks = repo.ignore_check(&paths, &index).unwrap();
2415        let ignored: Vec<bool> = checks.iter().map(|c| c.ignored).collect();
2416        assert_eq!(ignored, [true, false, true, false, false]);
2417        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2418        let wt = repo.work_tree().unwrap();
2419        let mut scratch = PathBuf::new();
2420        assert_eq!(
2421            probe_query_path(Some(wt), "real", &mut scratch),
2422            (true, true)
2423        );
2424        assert_eq!(
2425            probe_query_path(Some(wt), "missing/x", &mut scratch),
2426            (false, cfg!(unix))
2427        );
2428        assert_eq!(
2429            probe_query_path(Some(wt), "plain/x", &mut scratch),
2430            (false, false)
2431        );
2432        assert_eq!(
2433            probe_query_path(Some(wt), "real/", &mut scratch),
2434            (true, false)
2435        );
2436        matcher
2437            .check_path_with_ancestors(&repo, None, "plain/x.tmp", false, false)
2438            .unwrap();
2439        assert!(!matcher.dir_states[matcher.dir_state_ids["plain"]].extendable);
2440    }
2441
2442    #[test]
2443    fn adding_pattern_sources_refreshes_cached_directory_states() {
2444        let (_dir, repo) = repo_with(&[("d/.gitignore", "*.tmp\n")]);
2445        let mut matcher = IgnoreMatcher::from_repository(&repo).unwrap();
2446        assert!(!matcher
2447            .is_path_ignored(&repo, None, "d/x.log", false)
2448            .unwrap());
2449        assert!(!matcher
2450            .is_path_ignored(&repo, None, "d/sub/x.c", false)
2451            .unwrap());
2452        matcher.add_cli_excludes(&["*.log".to_owned(), "sub".to_owned()]);
2453        assert!(matcher
2454            .is_path_ignored(&repo, None, "d/x.log", false)
2455            .unwrap());
2456        assert!(matcher
2457            .is_path_ignored(&repo, None, "d/sub/x.c", false)
2458            .unwrap());
2459
2460        let mut folded = matcher.with_ignore_case(true);
2461        assert!(folded
2462            .is_path_ignored(&repo, None, "d/X.TMP", false)
2463            .unwrap());
2464
2465        folded.set_per_directory_name(".other");
2466        assert!(!folded
2467            .is_path_ignored(&repo, None, "d/x.tmp", false)
2468            .unwrap());
2469    }
2470
2471    #[test]
2472    fn last_match_in_picks_the_last_matching_line_for_the_base_directory() {
2473        let source = IgnoreSource::PerDirectory("sub/.gitignore".into());
2474        let rules =
2475            parse_gitignore_content("*.log\n!keep.log\nkeep*\n", source, "sub", &mut Vec::new())
2476                .unwrap();
2477        let hit = |path| last_match_in("sub", &rules, path, false, false).map(|r| r.line_number);
2478        assert_eq!(hit("sub/a.log"), Some(1));
2479        assert_eq!(hit("sub/deep/keep.log"), Some(3));
2480        assert_eq!(hit("sub/keep.txt"), Some(3));
2481        assert_eq!(hit("other/a.log"), None);
2482        assert_eq!(hit("sub"), None);
2483        assert_eq!(hit("subx/a.log"), None);
2484        assert_eq!(
2485            last_match_in("", &[], "a.log", false, false).map(|r| r.line_number),
2486            None
2487        );
2488    }
2489}