Skip to main content

grit_lib/
pathspec.rs

1//! Git-compatible pathspec matching (magic tokens and global flags).
2//!
3//! ```rust
4//! use grit_lib::worktree::pathspec::parse_pathspecs_from_source;
5//!
6//! let specs = parse_pathspecs_from_source(b"README.md\n", false).expect("parse");
7//! assert_eq!(specs, ["README.md"]);
8//! ```
9//!
10//! Global flags are read from the same environment variables as Git:
11//! `GIT_LITERAL_PATHSPECS`, `GIT_GLOB_PATHSPECS`, `GIT_NOGLOB_PATHSPECS`,
12//! `GIT_ICASE_PATHSPECS`. The `grit` binary sets these from CLI flags such as
13//! `--literal-pathspecs` before dispatching subcommands.
14
15use crate::git_path::CanonicalizeExt;
16use std::borrow::Cow;
17use std::path::{Path, PathBuf};
18
19use hashbrown::HashSet;
20
21use crate::attributes::MacroTable;
22use crate::crlf::path_gitattribute_values;
23use crate::crlf::AttrRule;
24pub use crate::error::{AttrPathspecError, PathspecFromFileParseError, PathspecResolveError};
25use crate::precompose_config::argv_precompose_enabled;
26use crate::repo::Repository;
27use crate::unicode_normalization::precompose_utf8_path;
28use crate::wildmatch::{wildmatch, WM_CASEFOLD, WM_PATHNAME};
29
30/// Returns the length of the leading literal segment before the first glob metacharacter,
31/// matching Git's `simple_length()` (`*` `?` `[` `\`) on bytes.
32#[must_use]
33pub fn simple_length(match_str: &str) -> usize {
34    let b = match_str.as_bytes();
35    let mut len = 0usize;
36    for &c in b {
37        if matches!(c, b'*' | b'?' | b'[' | b'\\') {
38            break;
39        }
40        len += 1;
41    }
42    len
43}
44
45/// Whether the pattern uses wildcards after Git pathspec escaping rules.
46#[must_use]
47pub fn has_glob_chars(s: &str) -> bool {
48    simple_length(s) < s.len()
49}
50
51/// Read pathspec entries from raw file bytes (stdin or file), matching Git's
52/// `--pathspec-from-file` / `--pathspec-file-nul` rules.
53///
54/// * **NUL mode:** entries are separated by `NUL`; each segment is taken literally
55///   (no trimming or C-style unquoting).
56/// * **Line mode:** entries are separated by `LF`; optional `CR` before `LF`
57///   is stripped; optional trailing line without a final newline is included;
58///   double-quoted lines are C-unquoted (including octal escapes).
59pub fn parse_pathspecs_from_source(
60    data: &[u8],
61    nul_terminated: bool,
62) -> Result<Vec<String>, PathspecFromFileParseError> {
63    if nul_terminated {
64        let mut chunks: Vec<&[u8]> = data.split(|b| *b == 0).collect();
65        if chunks.last().copied() == Some(&[] as &[u8]) {
66            chunks.pop();
67        }
68        let mut out = Vec::with_capacity(chunks.len());
69        for chunk in chunks {
70            if chunk.is_empty() {
71                out.push(String::new());
72                continue;
73            }
74            let entry = std::str::from_utf8(chunk)
75                .map_err(|_| PathspecFromFileParseError::InvalidUtf8InNulRecord)?;
76            out.push(entry.to_string());
77        }
78        return Ok(out);
79    }
80
81    let text = String::from_utf8_lossy(data);
82    let mut out = Vec::new();
83    for raw in text.split_inclusive('\n') {
84        let line = raw.trim_end_matches('\n').trim_end_matches('\r');
85        if line.is_empty() {
86            out.push(String::new());
87            continue;
88        }
89        if line.starts_with('"') {
90            if line.ends_with('"') && line.len() >= 2 {
91                out.push(unquote_c_style_pathspec_line(line)?);
92            } else {
93                return Err(PathspecFromFileParseError::InvalidCStyleQuoting {
94                    line: line.to_string(),
95                });
96            }
97        } else {
98            out.push(line.to_string());
99        }
100    }
101    Ok(out)
102}
103
104/// Unquote a single `--pathspec-from-file` line that is wrapped in double quotes.
105fn unquote_c_style_pathspec_line(s: &str) -> Result<String, PathspecFromFileParseError> {
106    let bytes = s.as_bytes();
107    if bytes.first() != Some(&b'"') || bytes.last() != Some(&b'"') || bytes.len() < 2 {
108        return Err(PathspecFromFileParseError::InvalidCStyleQuoting {
109            line: s.to_string(),
110        });
111    }
112
113    let inner = &bytes[1..bytes.len() - 1];
114    let mut out = Vec::with_capacity(inner.len());
115    let mut i = 0;
116    while i < inner.len() {
117        if inner[i] != b'\\' {
118            out.push(inner[i]);
119            i += 1;
120            continue;
121        }
122        i += 1;
123        if i >= inner.len() {
124            return Err(PathspecFromFileParseError::InvalidEscapeAtEnd);
125        }
126        match inner[i] {
127            b'\\' => out.push(b'\\'),
128            b'"' => out.push(b'"'),
129            b'a' => out.push(7),
130            b'b' => out.push(8),
131            b'f' => out.push(12),
132            b'n' => out.push(b'\n'),
133            b'r' => out.push(b'\r'),
134            b't' => out.push(b'\t'),
135            b'v' => out.push(11),
136            c if c.is_ascii_digit() => {
137                if i + 2 >= inner.len() {
138                    return Err(PathspecFromFileParseError::TruncatedOctalEscape);
139                }
140                let oct = std::str::from_utf8(&inner[i..i + 3])
141                    .map_err(|_| PathspecFromFileParseError::InvalidOctalBytes)?;
142                out.push(
143                    u8::from_str_radix(oct, 8)
144                        .map_err(|_| PathspecFromFileParseError::InvalidOctalValue)?,
145                );
146                i += 2;
147            }
148            other => {
149                return Err(PathspecFromFileParseError::InvalidEscapeSequence {
150                    escape: char::from(other),
151                });
152            }
153        }
154        i += 1;
155    }
156    String::from_utf8(out).map_err(|_| PathspecFromFileParseError::InvalidUtf8InQuotedLine)
157}
158
159/// Raw bytes for [`ResolvedPathspecs::resolve`] from `--pathspec-from-file` (read by the caller).
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct PathspecInput {
162    /// File or stdin contents.
163    pub data: Vec<u8>,
164    /// When true, entries are NUL-separated (`--pathspec-file-nul`).
165    pub nul_terminated: bool,
166}
167
168impl PathspecInput {
169    /// Build input from bytes already read from a file or stdin.
170    #[must_use]
171    pub fn new(data: Vec<u8>, nul_terminated: bool) -> Self {
172        Self {
173            data,
174            nul_terminated,
175        }
176    }
177}
178
179/// Pathspec argv fragments resolved against a repository work tree.
180#[derive(Debug, Clone, Default, PartialEq, Eq)]
181pub struct ResolvedPathspecs {
182    /// Work-tree-relative pathspec strings for matching.
183    pub specs: Vec<String>,
184    /// User-facing spellings aligned with `specs` (argv or file lines).
185    pub sources: Vec<String>,
186    /// True when the caller supplied argv paths and/or a from-file (not "whole tree").
187    pub scoped: bool,
188}
189
190impl ResolvedPathspecs {
191    /// Resolve `raw` argv pathspecs and optional `--pathspec-from-file` bytes against `repo`.
192    ///
193    /// `cwd` is the process working directory used for relative pathspec prefixes (never read
194    /// from the environment inside the library).
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use grit_lib::worktree::pathspec::{PathspecInput, ResolvedPathspecs};
200    /// use grit_lib::repo::{InitOptions, Repository};
201    /// use std::fs;
202    ///
203    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
204    /// let dir = tempfile::tempdir()?;
205    /// let repo = Repository::init(dir.path(), &InitOptions::default())?;
206    /// fs::write(dir.path().join("a.txt"), b"x")?;
207    /// let resolved = ResolvedPathspecs::resolve(
208    ///     &repo,
209    ///     dir.path(),
210    ///     &["a.txt".to_string()],
211    ///     None,
212    /// )?;
213    /// assert_eq!(resolved.specs, ["a.txt"]);
214    /// let from_file = PathspecInput::new(b"a.txt\n".to_vec(), false);
215    /// let from_file = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(from_file))?;
216    /// assert_eq!(from_file.specs, ["a.txt"]);
217    /// # Ok(())
218    /// # }
219    /// ```
220    pub fn resolve(
221        repo: &Repository,
222        cwd: &Path,
223        raw: &[String],
224        from_file: Option<PathspecInput>,
225    ) -> Result<Self, PathspecResolveError> {
226        let work_tree = repo
227            .work_tree()
228            .ok_or(PathspecResolveError::NeedsWorkTree)?;
229        let prefix = pathdiff(cwd, work_tree);
230        let scoped = from_file.is_some() || !raw.is_empty();
231
232        let mut sources = Vec::new();
233        if let Some(input) = from_file {
234            let parsed = parse_pathspecs_from_source(&input.data, input.nul_terminated)?;
235            sources.extend(parsed);
236        }
237        for sel in raw {
238            sources.push(sel.clone());
239        }
240
241        if scoped && sources.is_empty() {
242            return Err(PathspecResolveError::EmptyPathspec);
243        }
244        for sel in &sources {
245            if sel.is_empty() {
246                return Err(PathspecResolveError::EmptyPathspec);
247            }
248        }
249
250        let argv_precompose = repo.pathspec_precompose_enabled();
251        let specs = sources
252            .iter()
253            .map(|sel| {
254                resolve_pathspec_in_worktree_with_argv_precompose(
255                    sel,
256                    sel,
257                    work_tree,
258                    prefix.as_deref(),
259                    argv_precompose,
260                )
261            })
262            .collect::<Result<Vec<_>, _>>()?;
263
264        Ok(Self {
265            specs,
266            sources,
267            scoped,
268        })
269    }
270
271    /// Whether the invocation targets the entire work tree (no path arguments or from-file).
272    #[must_use]
273    pub fn is_entire_tree(&self) -> bool {
274        !self.scoped
275    }
276
277    /// Consume `self` and return resolved specs and user-facing sources.
278    ///
279    /// When [`Self::is_entire_tree`] is true, both vectors are empty (match legacy
280    /// "stage/remove/clean the whole tree" call sites).
281    #[must_use]
282    pub fn into_pathspec_lists(self) -> (Vec<String>, Vec<String>) {
283        if self.scoped {
284            (self.specs, self.sources)
285        } else {
286            (Vec::new(), Vec::new())
287        }
288    }
289
290    /// Resolved pathspec strings only; empty when the invocation is unscoped.
291    #[must_use]
292    pub fn into_specs(self) -> Vec<String> {
293        if self.scoped {
294            self.specs
295        } else {
296            Vec::new()
297        }
298    }
299}
300
301#[derive(Debug, Clone, Default)]
302struct PathspecMagic {
303    literal: bool,
304    glob: bool,
305    icase: bool,
306    exclude: bool,
307    /// `:(top)` / short `:/` — paths are relative to repo root.
308    top: bool,
309    prefix: Option<String>,
310    /// `:(attr:...)` requirements.
311    attr_requirements: Vec<AttrRequirement>,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
315enum AttrRequirement {
316    Set(String),
317    Unset(String),
318    Unspecified(String),
319    Value(String, String),
320}
321
322impl AttrRequirement {
323    fn name(&self) -> &str {
324        match self {
325            AttrRequirement::Set(name)
326            | AttrRequirement::Unset(name)
327            | AttrRequirement::Unspecified(name)
328            | AttrRequirement::Value(name, _) => name,
329        }
330    }
331}
332
333/// The library never reads the process environment, so Git's `GIT_*_PATHSPECS` globals are
334/// always unset here and every global flag takes its default. This runs on every pathspec
335/// comparison, so it must stay allocation-free.
336fn git_env_bool(_key: &str, default: bool) -> bool {
337    default
338}
339
340fn literal_global() -> bool {
341    git_env_bool("GIT_LITERAL_PATHSPECS", false)
342}
343
344/// Whether `GIT_LITERAL_PATHSPECS` is enabled (shell `*` and `?` are literal, not globs).
345#[must_use]
346pub fn literal_pathspecs_enabled() -> bool {
347    literal_global()
348}
349
350fn glob_global() -> bool {
351    git_env_bool("GIT_GLOB_PATHSPECS", false)
352}
353
354fn noglob_global() -> bool {
355    git_env_bool("GIT_NOGLOB_PATHSPECS", false)
356}
357
358fn icase_global() -> bool {
359    git_env_bool("GIT_ICASE_PATHSPECS", false)
360}
361
362/// Validates global pathspec environment flags the same way Git does.
363///
364/// Returns an error message suitable for `bail!` when flags are incompatible.
365pub fn validate_global_pathspec_flags() -> Result<(), String> {
366    let lit = literal_global();
367    let glob = glob_global();
368    let noglob = noglob_global();
369    let icase = icase_global();
370
371    if glob && noglob {
372        return Err("global 'glob' and 'noglob' pathspec settings are incompatible".to_string());
373    }
374    if lit && (glob || noglob || icase) {
375        return Err(
376            "global 'literal' pathspec setting is incompatible with all other global pathspec settings"
377                .to_string(),
378        );
379    }
380    Ok(())
381}
382
383fn is_valid_attr_name(name: &str) -> bool {
384    !name.is_empty()
385        && name
386            .bytes()
387            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
388}
389
390fn split_attr_expr(expr: &str) -> Result<Vec<String>, AttrPathspecError> {
391    let mut parts = Vec::new();
392    let mut cur = String::new();
393    let mut in_value = false;
394    let mut escaped = false;
395
396    for ch in expr.chars() {
397        if escaped {
398            if ch.is_ascii_whitespace() {
399                return Err(AttrPathspecError::DanglingEscape);
400            }
401            if ch != ',' {
402                return Err(AttrPathspecError::UnsupportedEscape);
403            }
404            cur.push(ch);
405            escaped = false;
406            continue;
407        }
408        if in_value && ch == '\\' {
409            escaped = true;
410            continue;
411        }
412        if ch == '=' {
413            in_value = true;
414            cur.push(ch);
415            continue;
416        }
417        if ch.is_ascii_whitespace() {
418            if !cur.is_empty() {
419                parts.push(cur);
420                cur = String::new();
421            }
422            in_value = false;
423            continue;
424        }
425        cur.push(ch);
426    }
427
428    if escaped {
429        return Err(AttrPathspecError::DanglingEscape);
430    }
431    if !cur.is_empty() {
432        parts.push(cur);
433    }
434    Ok(parts)
435}
436
437fn parse_attr_requirements(expr: &str) -> Result<Vec<AttrRequirement>, AttrPathspecError> {
438    let name_only = |name: &str| {
439        if name.contains('=') || !is_valid_attr_name(name) {
440            Err(AttrPathspecError::InvalidName(name.to_owned()))
441        } else {
442            Ok(name.to_owned())
443        }
444    };
445    let mut out = Vec::new();
446    for token in split_attr_expr(expr)? {
447        let req = if let Some(name) = token.strip_prefix('-') {
448            AttrRequirement::Unset(name_only(name)?)
449        } else if let Some(name) = token.strip_prefix('!') {
450            AttrRequirement::Unspecified(name_only(name)?)
451        } else if let Some((name, value)) = token.split_once('=') {
452            AttrRequirement::Value(name_only(name)?, value.to_owned())
453        } else {
454            AttrRequirement::Set(name_only(&token)?)
455        };
456        out.push(req);
457    }
458    if out.is_empty() {
459        return Err(AttrPathspecError::Empty);
460    }
461    Ok(out)
462}
463
464/// The `attr:` clauses inside a long-form `:(...)` magic prefix (none for other specs).
465fn attr_clauses(spec: &str) -> Vec<String> {
466    if literal_global() {
467        return Vec::new();
468    }
469    let Some(rest) = spec.strip_prefix(":(") else {
470        return Vec::new();
471    };
472    let Some(close) = rest.find(')') else {
473        return Vec::new();
474    };
475    split_long_magic_tokens_raw(&rest[..close])
476        .into_iter()
477        .filter_map(|token| token.trim_start().strip_prefix("attr:").map(str::to_owned))
478        .collect()
479}
480
481/// Validate the `:(attr:...)` magic of every spec in `specs`.
482///
483/// Specs without attr magic are always accepted. A spec is rejected when it has more than one
484/// `attr:` clause or a clause that does not parse (empty clause, invalid attribute name, bad
485/// escape). A clause of only whitespace has no requirements and is accepted.
486///
487/// # Errors
488///
489/// [`crate::error::Error::InvalidAttrPathspec`] naming the first rejected spec and its
490/// [`AttrPathspecError`].
491pub fn validate_attr_pathspecs(specs: &[String]) -> crate::error::Result<()> {
492    for spec in specs {
493        let invalid = |reason| crate::error::Error::InvalidAttrPathspec {
494            spec: spec.clone(),
495            reason,
496        };
497        let clauses = attr_clauses(spec);
498        if clauses.len() > 1 {
499            return Err(invalid(AttrPathspecError::MultipleAttrClauses));
500        }
501        match clauses.first() {
502            Some(expr) if expr.is_empty() => return Err(invalid(AttrPathspecError::Empty)),
503            // Whitespace alone is an attr clause with no requirements, which Git accepts.
504            Some(expr) if expr.trim().is_empty() => {}
505            Some(expr) => {
506                parse_attr_requirements(expr).map_err(invalid)?;
507            }
508            None => {}
509        }
510    }
511    Ok(())
512}
513
514fn split_long_magic_tokens(magic_part: &str) -> Vec<String> {
515    split_long_magic_tokens_raw(magic_part)
516        .into_iter()
517        .map(|token| token.trim().to_string())
518        .collect()
519}
520
521/// Split long magic on unescaped `,`, keeping surrounding whitespace.
522fn split_long_magic_tokens_raw(magic_part: &str) -> Vec<String> {
523    let mut tokens = Vec::new();
524    let mut cur = String::new();
525    let mut escaped = false;
526    for ch in magic_part.chars() {
527        if escaped {
528            cur.push('\\');
529            cur.push(ch);
530            escaped = false;
531            continue;
532        }
533        if ch == '\\' {
534            escaped = true;
535            continue;
536        }
537        if ch == ',' {
538            tokens.push(std::mem::take(&mut cur));
539            continue;
540        }
541        cur.push(ch);
542    }
543    if escaped {
544        cur.push('\\');
545    }
546    tokens.push(cur);
547    tokens
548}
549
550fn parse_long_magic(rest_after_paren: &str) -> Option<(PathspecMagic, &str)> {
551    let close = rest_after_paren.find(')')?;
552    let magic_part = &rest_after_paren[..close];
553    let tail = &rest_after_paren[close + 1..];
554    let mut magic = PathspecMagic::default();
555    for raw in split_long_magic_tokens(magic_part) {
556        let token = raw.trim();
557        if token.is_empty() {
558            continue;
559        }
560        if let Some(p) = token.strip_prefix("prefix:") {
561            magic.prefix = Some(p.to_string());
562            continue;
563        }
564        if let Some(expr) = token.strip_prefix("attr:") {
565            if let Ok(reqs) = parse_attr_requirements(expr) {
566                magic.attr_requirements = reqs;
567            }
568            continue;
569        }
570        if token.eq_ignore_ascii_case("literal") {
571            magic.literal = true;
572        } else if token.eq_ignore_ascii_case("glob") {
573            magic.glob = true;
574        } else if token.eq_ignore_ascii_case("icase") {
575            magic.icase = true;
576        } else if token.eq_ignore_ascii_case("exclude") {
577            magic.exclude = true;
578        } else if token.eq_ignore_ascii_case("top") {
579            magic.top = true;
580        }
581    }
582    Some((magic, tail))
583}
584
585/// `elem` is the full pathspec beginning with `:` (short magic form, not `:(...)`).
586fn parse_short_magic(elem: &str) -> (PathspecMagic, &str) {
587    let bytes = elem.as_bytes();
588    let mut i = 1usize;
589    let mut magic = PathspecMagic::default();
590    while i < bytes.len() && bytes[i] != b':' {
591        let ch = bytes[i];
592        if ch == b'^' {
593            magic.exclude = true;
594            i += 1;
595            continue;
596        }
597        let is_magic = match ch {
598            b'!' => {
599                magic.exclude = true;
600                true
601            }
602            b'/' => {
603                magic.top = true;
604                true
605            } // short `:/` = top
606            _ => false,
607        };
608        if is_magic {
609            i += 1;
610            continue;
611        }
612        break;
613    }
614    if i < bytes.len() && bytes[i] == b':' {
615        i += 1;
616    }
617    (magic, &elem[i..])
618}
619
620/// Strip `:(magic)` / `:magic` prefix when not in literal-global mode.
621fn parse_element_magic(elem: &str) -> (PathspecMagic, &str) {
622    if !elem.starts_with(':') || literal_global() {
623        return (PathspecMagic::default(), elem);
624    }
625    if let Some(rest) = elem.strip_prefix(":(") {
626        return parse_long_magic(rest).unwrap_or((PathspecMagic::default(), elem));
627    }
628    parse_short_magic(elem)
629}
630
631fn combine_magic(element: PathspecMagic) -> PathspecMagic {
632    let mut m = element;
633    if literal_global() {
634        m.literal = true;
635    }
636    if glob_global() && !m.literal {
637        m.glob = true;
638    }
639    if icase_global() {
640        m.icase = true;
641    }
642    if noglob_global() && !m.glob {
643        m.literal = true;
644    }
645    m
646}
647
648fn strip_top_magic(mut pattern: &str) -> &str {
649    if let Some(r) = pattern.strip_prefix(":/") {
650        pattern = r;
651    }
652    pattern
653}
654
655/// Path prefix used for Bloom-filter lookups (`revision.c` `convert_pathspec_to_bloom_keyvec`).
656///
657/// `cwd_from_repo_root` is the path from the repository work tree to the process cwd, using `/`
658/// separators and no leading slash (empty string at repo root). Used for `:(top)` / `:/`.
659#[must_use]
660pub fn bloom_lookup_prefix_with_cwd(
661    spec: &str,
662    cwd_from_repo_root: Option<&str>,
663) -> Option<String> {
664    let (elem_magic, raw_pattern) = parse_element_magic(spec);
665    let magic = combine_magic(elem_magic);
666    if magic.exclude || magic.icase {
667        return None;
668    }
669    let pattern = strip_top_magic(raw_pattern);
670    if pattern.is_empty() {
671        return None;
672    }
673    let combined = if magic.top {
674        let cwd = cwd_from_repo_root.unwrap_or("").trim_end_matches('/');
675        if cwd.is_empty() {
676            pattern.to_string()
677        } else {
678            format!("{cwd}/{pattern}")
679        }
680    } else if let Some(prefix) = magic.prefix.as_deref() {
681        let base = prefix.trim_end_matches('/');
682        if base.is_empty() {
683            pattern.to_string()
684        } else {
685            normalize_relative_path_str(&format!("{base}/{pattern}"))
686        }
687    } else {
688        pattern.to_string()
689    };
690    let pattern = combined.as_str();
691    let mut len = simple_length(pattern);
692    if len != pattern.len() {
693        while len > 0 && pattern.as_bytes()[len - 1] != b'/' {
694            len -= 1;
695        }
696    }
697    while len > 0 && pattern.as_bytes()[len - 1] == b'/' {
698        len -= 1;
699    }
700    if len == 0 {
701        return None;
702    }
703    Some(combined[..len].to_string())
704}
705
706/// Bloom filter lookup prefix for a pathspec at the repository root.
707#[must_use]
708pub fn bloom_lookup_prefix(spec: &str) -> Option<String> {
709    bloom_lookup_prefix_with_cwd(spec, None)
710}
711
712/// Whether every pathspec can participate in Bloom precomputation (Git `forbid_bloom_filters`).
713#[must_use]
714pub fn pathspecs_allow_bloom(specs: &[String]) -> bool {
715    specs.iter().all(|s| {
716        !s.is_empty() && !pathspec_is_exclude(s) && bloom_lookup_prefix_with_cwd(s, None).is_some()
717    })
718}
719
720/// Whether `path` is included when Git applies a pathspec list with optional `:(exclude)` entries.
721///
722/// A path is rejected if any exclude pathspec matches it. When at least one non-exclude pathspec is
723/// present, the path must also match one of those positives (`OR` semantics).
724#[must_use]
725pub fn path_allowed_by_pathspec_list(specs: &[String], path: &str) -> bool {
726    let mut has_positive = false;
727    let mut positive_match = false;
728    for s in specs {
729        let (elem, raw_pattern) = parse_element_magic(s);
730        let magic = combine_magic(elem);
731        if magic.exclude {
732            if path_matches_pathspec_tail(raw_pattern, path, magic) {
733                return false;
734            }
735            continue;
736        }
737        has_positive = true;
738        if pathspec_matches(s, path) {
739            positive_match = true;
740        }
741    }
742    !has_positive || positive_match
743}
744
745/// True when `spec` matches `path` for pathspec bookkeeping (positive match or exclude hit).
746#[must_use]
747pub fn pathspec_contributes_match(spec: &str, path: &str) -> bool {
748    pathspec_matches(spec, path) || pathspec_exclude_matches(spec, path)
749}
750
751/// Path under `prefix:` magic (e.g. `sub/`) for repository-relative `path`, including the
752/// directory entry `sub` when the prefix is `sub/`.
753fn path_for_match_under_magic_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
754    let base = prefix.trim_end_matches('/');
755    if base.is_empty() {
756        return Some(path);
757    }
758    if path == base {
759        return Some("");
760    }
761    if let Some(rest) = path.strip_prefix(prefix) {
762        return Some(rest);
763    }
764    let anchored = if prefix.ends_with('/') {
765        prefix.to_string()
766    } else {
767        format!("{prefix}/")
768    };
769    path.starts_with(&anchored).then(|| &path[anchored.len()..])
770}
771
772fn path_matches_pathspec_tail(raw_pattern: &str, path: &str, magic: PathspecMagic) -> bool {
773    if magic.literal && magic.glob {
774        return false;
775    }
776    let pattern = strip_top_magic(raw_pattern);
777    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
778        match path_for_match_under_magic_prefix(path, prefix) {
779            Some(rest) => rest,
780            None => return false,
781        }
782    } else {
783        path
784    };
785    pathspec_matches_tail(pattern, path_for_match, magic)
786}
787
788/// True if `path` is matched by `spec` (Git pathspec syntax, including magic and globals).
789///
790/// Same as [`matches_pathspec`] (default file context; exclude specs never match positively here).
791/// See [`matches_pathspec_list`].
792#[must_use]
793pub fn pathspec_matches(spec: &str, path: &str) -> bool {
794    matches_pathspec(spec, path)
795}
796
797/// Returns whether `spec` uses Git's exclude magic (`:(exclude)`, `:!`, `:^`, etc.).
798#[must_use]
799pub fn pathspec_is_exclude(spec: &str) -> bool {
800    let (elem_magic, _) = parse_element_magic(spec);
801    combine_magic(elem_magic).exclude
802}
803
804/// Whether a path-limited revision tree walk should recurse into directory `path`.
805///
806/// Uses [`pathspec_wants_descent_into_tree`] for non-exclude specs. Exclude-only lists never
807/// trigger that helper alone, but Git's implicit match-all still requires walking non-excluded
808/// directories so nested paths can match [`matches_pathspec_list`].
809#[must_use]
810pub fn pathspec_wants_descent_for_rev_tree(path: &str, specs: &[String]) -> bool {
811    if specs.is_empty() {
812        return true;
813    }
814    for spec in specs {
815        if !pathspec_is_exclude(spec) && pathspec_wants_descent_into_tree(spec, path) {
816            return true;
817        }
818    }
819    if !specs.iter().any(|s| pathspec_is_exclude(s)) {
820        return false;
821    }
822    let ctx = PathspecMatchContext {
823        is_directory: true,
824        is_git_submodule: false,
825        precompose_paths: false,
826    };
827    for spec in specs {
828        if pathspec_is_exclude(spec)
829            && pathspec_exclude_element_matches_with_context(spec, path, ctx)
830        {
831            return false;
832        }
833    }
834    !specs.iter().any(|s| !pathspec_is_exclude(s))
835}
836
837/// Whether a path-limited tree walk must look at entry `path`: it matches `specs`, or it is a
838/// directory that [`pathspec_wants_descent_for_rev_tree`] says may hold a match.
839pub(crate) fn pathspec_entry_is_relevant(path: &str, is_tree: bool, specs: &[String]) -> bool {
840    matches_pathspec_list(path, specs)
841        || (is_tree && pathspec_wants_descent_for_rev_tree(path, specs))
842}
843
844/// Whether a path-limited tree walk should recurse into directory `full_name` for pathspec `spec`.
845///
846/// Used by revision history path limiting ([`crate::revwalk::rev_list`]) and diff tree pruning.
847/// Matches Git `tree-walk.c` `do_match` recursive
848/// directory interest: a directory is entered when a positive spec's leading literal segment
849/// matches it, or when the pattern begins with a glob metacharacter (`simple_length` zero).
850///
851/// Exclude-only patterns never trigger descent alone.
852#[must_use]
853pub fn pathspec_wants_descent_into_tree(spec: &str, full_name: &str) -> bool {
854    if pathspec_is_exclude(spec) {
855        return false;
856    }
857    let (elem_magic, raw_pattern) = parse_element_magic(spec);
858    let magic = combine_magic(elem_magic);
859    if magic.exclude {
860        return false;
861    }
862    let pattern = strip_top_magic(raw_pattern);
863    let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
864    if pattern.is_empty() || pattern == "." {
865        return true;
866    }
867    if let Some(prefix) = magic.prefix.as_deref() {
868        let base = prefix.trim_end_matches('/');
869        if !base.is_empty() && (full_name == base || base.starts_with(&format!("{full_name}/"))) {
870            return true;
871        }
872    }
873    let dir_prefix = format!("{full_name}/");
874    if pattern.starts_with(&dir_prefix) {
875        return true;
876    }
877    if ps_str_eq(pattern, full_name, magic.icase) {
878        return true;
879    }
880    pathspec_recursive_descent_wanted(pattern, magic, full_name)
881}
882
883fn pathspec_literal_descent_wanted(pattern: &str, dir: &str) -> bool {
884    if pattern.is_empty() {
885        return false;
886    }
887    if let Some(prefix) = pattern.strip_suffix('/') {
888        return dir == prefix || path_is_under_dir(dir, prefix, false);
889    }
890    if dir == pattern {
891        return false;
892    }
893    dir.len() < pattern.len()
894        && path_starts_with(pattern, dir, false)
895        && pattern.as_bytes()[dir.len()] == b'/'
896}
897
898fn pathspec_recursive_descent_wanted(pattern: &str, magic: PathspecMagic, dir: &str) -> bool {
899    if magic.literal {
900        return pathspec_literal_descent_wanted(pattern, dir);
901    }
902    if simple_length(pattern) == 0 {
903        return true;
904    }
905
906    let icase = magic.icase;
907    let glob = magic.glob;
908    let components: Vec<&str> = dir.split('/').filter(|c| !c.is_empty()).collect();
909    pathspec_descent_match_components(pattern, icase, glob, &components)
910}
911
912fn pathspec_first_component(pat: &str) -> (&str, &str) {
913    match pat.find('/') {
914        Some(i) => (&pat[..i], &pat[i + 1..]),
915        None => (pat, ""),
916    }
917}
918
919fn pathspec_dir_name_matches_component(
920    pat_comp: &str,
921    dir_name: &str,
922    icase: bool,
923    glob: bool,
924) -> bool {
925    if pat_comp.is_empty() {
926        return true;
927    }
928    let nwl = simple_length(pat_comp);
929    if nwl == 0 {
930        return true;
931    }
932    if nwl >= pat_comp.len() {
933        return ps_str_eq(pat_comp, dir_name, icase);
934    }
935    let lit = &pat_comp[..nwl];
936    let lit_bytes = lit.as_bytes();
937    let dir_bytes = dir_name.as_bytes();
938    if icase {
939        if dir_bytes.len() < lit_bytes.len()
940            || !dir_bytes[..lit_bytes.len()].eq_ignore_ascii_case(lit_bytes)
941        {
942            return false;
943        }
944    } else if dir_bytes.len() < lit_bytes.len() || &dir_bytes[..lit_bytes.len()] != lit_bytes {
945        return false;
946    }
947    let flags = if icase { WM_CASEFOLD } else { 0 };
948    let wm_flags = if glob { flags | WM_PATHNAME } else { flags };
949    wildmatch(pat_comp.as_bytes(), dir_name.as_bytes(), wm_flags)
950}
951
952fn pathspec_descent_match_components(
953    pat: &str,
954    icase: bool,
955    glob: bool,
956    dir_components: &[&str],
957) -> bool {
958    if dir_components.is_empty() {
959        return simple_length(pat) == 0 || !pat.is_empty();
960    }
961    if simple_length(pat) == 0 {
962        return true;
963    }
964    let (pat_comp, pat_rest) = pathspec_first_component(pat);
965    if !pathspec_dir_name_matches_component(pat_comp, dir_components[0], icase, glob) {
966        return false;
967    }
968    pathspec_descent_match_components(pat_rest, icase, glob, &dir_components[1..])
969}
970
971#[cfg(test)]
972mod pathspec_descent_tests {
973    use super::*;
974
975    #[test]
976    fn descent_wildcard_non_final_component() {
977        assert!(pathspec_wants_descent_into_tree("*/g.c", "a"));
978        assert!(pathspec_wants_descent_into_tree("a/*/f.c", "a"));
979        assert!(pathspec_wants_descent_into_tree("a/*/f.c", "a/b"));
980        assert!(pathspec_wants_descent_into_tree(":(glob)**/f.c", "a"));
981        assert!(pathspec_wants_descent_into_tree(":(glob)*/g.c", "a"));
982        assert!(pathspec_wants_descent_into_tree(":(icase)A/g.c", "a"));
983        assert!(!pathspec_wants_descent_into_tree(":(literal)*g.c", "a"));
984        assert!(!pathspec_wants_descent_into_tree("a/*.c", "b"));
985        assert!(pathspec_wants_descent_into_tree("b*/log.c", "builtin"));
986        assert!(!pathspec_wants_descent_into_tree("b*/log.c", "other"));
987        assert!(pathspec_wants_descent_into_tree("bu?ltin/log.c", "builtin"));
988        assert!(pathspec_wants_descent_into_tree(
989            ":(icase)B*/LOG.C",
990            "builtin"
991        ));
992        assert!(!pathspec_wants_descent_into_tree(":(icase)b*/log.c", "é"));
993    }
994
995    #[test]
996    fn glob_doublestar_path_matches_nested_file() {
997        let specs = vec![":(glob)**/f.c".to_owned()];
998        assert!(matches_pathspec_list("a/b/f.c", &specs));
999    }
1000}
1001
1002/// Like [`matches_pathspec_set_for_object`], but uses [`matches_ls_tree_pathspec`] for each
1003/// element so `ls-files` / index filtering agrees with `ls-tree` on patterns such as `a[a]`.
1004#[must_use]
1005pub fn matches_pathspec_set_for_object_ls_tree(
1006    specs: &[String],
1007    path: &str,
1008    mode: u32,
1009    attr_rules: &[AttrRule],
1010) -> bool {
1011    if specs.is_empty() {
1012        return true;
1013    }
1014    let mut positives: Vec<&str> = Vec::new();
1015    let mut excludes: Vec<&str> = Vec::new();
1016    for s in specs {
1017        if pathspec_is_exclude(s) {
1018            excludes.push(s.as_str());
1019        } else {
1020            positives.push(s.as_str());
1021        }
1022    }
1023    let positive_ok = if positives.is_empty() {
1024        true
1025    } else {
1026        positives
1027            .iter()
1028            .any(|s| matches_ls_tree_pathspec(s, path, mode, attr_rules))
1029    };
1030    if !positive_ok {
1031        return false;
1032    }
1033    for ex in excludes {
1034        if matches_ls_tree_pathspec(ex, path, mode, attr_rules) {
1035            return false;
1036        }
1037    }
1038    true
1039}
1040
1041/// True if `path` matches the combined pathspec list: any positive spec (or all paths when there
1042/// are only excludes, matching Git `parse_pathspec`), and not matched by any exclude spec.
1043#[must_use]
1044pub fn matches_pathspec_set_for_object(
1045    specs: &[String],
1046    path: &str,
1047    mode: u32,
1048    attr_rules: &[AttrRule],
1049) -> bool {
1050    if specs.is_empty() {
1051        return true;
1052    }
1053    let mut positives: Vec<&str> = Vec::new();
1054    let mut excludes: Vec<&str> = Vec::new();
1055    for s in specs {
1056        if pathspec_is_exclude(s) {
1057            excludes.push(s.as_str());
1058        } else {
1059            positives.push(s.as_str());
1060        }
1061    }
1062    let positive_ok = if positives.is_empty() {
1063        true
1064    } else {
1065        positives
1066            .iter()
1067            .any(|s| matches_pathspec_for_object(s, path, mode, attr_rules))
1068    };
1069    if !positive_ok {
1070        return false;
1071    }
1072    for ex in excludes {
1073        if matches_pathspec_for_object(ex, path, mode, attr_rules) {
1074            return false;
1075        }
1076    }
1077    true
1078}
1079
1080/// True if `spec` uses `:(top)` or short `:/` (repo-root-relative) magic.
1081#[must_use]
1082pub fn pathspec_has_top(spec: &str) -> bool {
1083    let (elem_magic, _) = parse_element_magic(spec);
1084    combine_magic(elem_magic).top
1085}
1086
1087/// True if `spec` carries an `attr:` clause in long-form `:(...)` magic, so matching it needs
1088/// `.gitattributes` rules. Malformed clauses count too; [`validate_attr_pathspecs`] rejects them.
1089///
1090/// Such specs only match through the attribute-aware entry points:
1091/// [`crate::repo::Repository::pathspec_matcher`], which loads the repository's attributes and
1092/// validates the clauses, or [`matches_pathspec_list_for_object`] with caller-supplied rules.
1093#[must_use]
1094pub fn pathspec_has_attr_magic(spec: &str) -> bool {
1095    // Attr magic only exists in long form; skip the allocating parse for every other spec.
1096    spec.starts_with(":(") && spec.contains("attr:") && !attr_clauses(spec).is_empty()
1097}
1098
1099/// A resolved pathspec list bound to one repository's matching rules, built by
1100/// [`crate::repo::Repository::pathspec_matcher`].
1101///
1102/// Holds the repository's attributes when a spec carries `:(attr:...)` magic, so testing many
1103/// paths reads them once. Attr requirements see `[attr]` macro expansion and match attribute
1104/// patterns case-insensitively when `core.ignorecase` is set, as Git does. Paths are treated as regular files: a spec ending in `/` does not match
1105/// a path equal to its directory, and `builtin_objectmode` reads as `100644`. Use
1106/// [`matches_pathspec_list_for_object`] when the entry mode matters.
1107#[derive(Debug, Clone)]
1108pub struct PathspecMatcher<'s> {
1109    specs: Cow<'s, [String]>,
1110    precompose: bool,
1111    attrs: Option<std::sync::Arc<crate::attributes::ParsedGitAttributes>>,
1112    /// Match attribute patterns case-insensitively (`core.ignorecase`).
1113    attr_icase: bool,
1114}
1115
1116impl<'s> PathspecMatcher<'s> {
1117    pub(crate) fn new(
1118        specs: &'s [String],
1119        precompose: bool,
1120        attrs: Option<std::sync::Arc<crate::attributes::ParsedGitAttributes>>,
1121        attr_icase: bool,
1122    ) -> Self {
1123        // The attribute-aware matcher has no precompose context, so normalize the specs up front.
1124        let specs = if precompose && attrs.is_some() {
1125            Cow::Owned(
1126                specs
1127                    .iter()
1128                    .map(|spec| precompose_utf8_path(spec).into_owned())
1129                    .collect(),
1130            )
1131        } else {
1132            Cow::Borrowed(specs)
1133        };
1134        Self {
1135            specs,
1136            precompose,
1137            attrs,
1138            attr_icase,
1139        }
1140    }
1141
1142    /// Whether `path` is selected: it matches at least one positive spec (any path when there
1143    /// are none or the list is empty) and no `:(exclude)` spec.
1144    #[must_use]
1145    pub fn matches(&self, path: &str) -> bool {
1146        const REGULAR_FILE: u32 = 0o100644;
1147        self.matches_entry(path, REGULAR_FILE)
1148    }
1149
1150    /// Like [`Self::matches`], but uses Git tree/index entry `mode` for trailing-slash and
1151    /// submodule pathspec semantics.
1152    ///
1153    /// Required for path-limited history walks and staging when specs include `:(attr:...)` magic.
1154    #[must_use]
1155    pub fn matches_entry(&self, path: &str, mode: u32) -> bool {
1156        let ctx = context_from_mode_bits(mode);
1157        let match_ctx = PathspecMatchContext {
1158            is_directory: ctx.is_directory,
1159            is_git_submodule: ctx.is_git_submodule,
1160            precompose_paths: self.precompose,
1161        };
1162        let Some(attrs) = &self.attrs else {
1163            return matches_pathspec_list_with_context(path, &self.specs, match_ctx);
1164        };
1165        let path = if self.precompose {
1166            precompose_utf8_path(path)
1167        } else {
1168            Cow::Borrowed(path)
1169        };
1170        let lookup = AttrLookup::new(&attrs.rules, &attrs.macros, self.attr_icase);
1171        matches_pathspec_list_with_attrs(&path, mode, lookup, &self.specs)
1172    }
1173
1174    /// Whether a changed file is selected, checking its current `path` and, for a rename or
1175    /// copy, its `old_path` too (Git limits diffs on either side of a rename).
1176    #[must_use]
1177    pub fn matches_change(&self, path: &str, old_path: Option<&str>) -> bool {
1178        self.specs.is_empty()
1179            || self.matches(path)
1180            || old_path.is_some_and(|old| old != path && self.matches(old))
1181    }
1182
1183    /// Whether the list is empty (every path is selected).
1184    #[must_use]
1185    pub fn is_empty(&self) -> bool {
1186        self.specs.is_empty()
1187    }
1188}
1189
1190fn pathspec_match_one_positive(path: &str, magic: PathspecMagic, raw_pattern: &str) -> bool {
1191    if magic.literal && magic.glob {
1192        return false;
1193    }
1194    let pattern = strip_top_magic(raw_pattern);
1195    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1196        match path_for_match_under_magic_prefix(path, prefix) {
1197            Some(rest) => rest,
1198            None => return false,
1199        }
1200    } else {
1201        path
1202    };
1203    pathspec_matches_tail(pattern, path_for_match, magic)
1204}
1205
1206/// Attribute state that `:(attr:...)` requirements are evaluated against.
1207#[derive(Clone, Copy)]
1208pub(crate) struct AttrLookup<'a> {
1209    rules: &'a [AttrRule],
1210    /// `[attr]` macro definitions; `None` means no macros are defined.
1211    macros: Option<&'a MacroTable>,
1212    /// Match attribute patterns case-insensitively (`core.ignorecase`).
1213    icase: bool,
1214}
1215
1216impl<'a> AttrLookup<'a> {
1217    pub(crate) fn new(rules: &'a [AttrRule], macros: &'a MacroTable, icase: bool) -> Self {
1218        Self {
1219            rules,
1220            macros: Some(macros),
1221            icase,
1222        }
1223    }
1224
1225    fn rules_only(rules: &'a [AttrRule]) -> Self {
1226        Self {
1227            rules,
1228            macros: None,
1229            icase: false,
1230        }
1231    }
1232}
1233
1234fn attr_requirements_match(
1235    requirements: &[AttrRequirement],
1236    attrs: AttrLookup<'_>,
1237    path: &str,
1238    is_dir: bool,
1239    mode: u32,
1240) -> bool {
1241    let no_macros = MacroTable::default();
1242    let assigned = path_gitattribute_values(
1243        attrs.rules,
1244        attrs.macros.unwrap_or(&no_macros),
1245        attrs.icase,
1246        path,
1247        is_dir,
1248    );
1249    requirements.iter().all(|req| {
1250        let value: Option<Cow<'_, str>> = if req.name() == "builtin_objectmode" {
1251            (mode != 0).then(|| Cow::Owned(format!("{mode:06o}")))
1252        } else {
1253            assigned
1254                .get(req.name())
1255                .map(|v| Cow::Borrowed(v.display()))
1256                .filter(|v| v != "unspecified")
1257        };
1258        match req {
1259            AttrRequirement::Set(_) => value.as_deref() == Some("set"),
1260            AttrRequirement::Unset(_) => value.as_deref() == Some("unset"),
1261            AttrRequirement::Unspecified(_) => value.is_none(),
1262            AttrRequirement::Value(_, expected) => value.as_deref() == Some(expected.as_str()),
1263        }
1264    })
1265}
1266
1267fn matches_pathspec_element_with_context(
1268    spec: &str,
1269    path: &str,
1270    ctx: PathspecMatchContext,
1271) -> bool {
1272    let (elem_magic, raw_pattern) = parse_element_magic(spec);
1273    let magic = combine_magic(elem_magic);
1274    if magic.exclude {
1275        return false;
1276    }
1277    if magic.literal && magic.glob {
1278        return false;
1279    }
1280    if !magic.attr_requirements.is_empty() {
1281        return false;
1282    }
1283    if magic.literal || magic.glob || magic.icase {
1284        return pathspec_matches(spec, path);
1285    }
1286    let pattern = strip_top_magic(raw_pattern);
1287    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1288        match path_for_match_under_magic_prefix(path, prefix) {
1289            Some(rest) => rest,
1290            None => return false,
1291        }
1292    } else {
1293        path
1294    };
1295    matches_pathspec_with_context(pattern, path_for_match, ctx)
1296}
1297
1298fn pathspec_exclude_element_matches_with_context(
1299    spec: &str,
1300    path: &str,
1301    ctx: PathspecMatchContext,
1302) -> bool {
1303    let (elem_magic, raw_pattern) = parse_element_magic(spec);
1304    let mut magic = combine_magic(elem_magic);
1305    if !magic.exclude {
1306        return false;
1307    }
1308    magic.exclude = false;
1309    if magic.literal && magic.glob {
1310        return false;
1311    }
1312    if !magic.attr_requirements.is_empty() {
1313        // Attribute pathspecs need `.gitattributes` context; use
1314        // [`matches_pathspec_list_for_object`] for those.
1315        return false;
1316    }
1317    if magic.literal || magic.glob || magic.icase {
1318        return pathspec_match_one_positive(path, magic, raw_pattern);
1319    }
1320    let pattern = strip_top_magic(raw_pattern);
1321    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1322        match path_for_match_under_magic_prefix(path, prefix) {
1323            Some(rest) => rest,
1324            None => return false,
1325        }
1326    } else {
1327        path
1328    };
1329    matches_pathspec_with_context(pattern, path_for_match, ctx)
1330}
1331
1332/// True if `path` is matched by an exclude pathspec's pattern. Returns `false` if `spec` is not
1333/// an exclude pathspec.
1334#[must_use]
1335pub fn pathspec_exclude_matches(spec: &str, path: &str) -> bool {
1336    pathspec_exclude_element_matches_with_context(spec, path, PathspecMatchContext::default())
1337}
1338
1339/// When every pathspec is an exclude and none use `:(top)` / `:/`, Git prepends an implicit
1340/// positive that matches only under the process cwd (relative to the work tree), not the whole
1341/// repository (`PATHSPEC_PREFER_CWD` in `pathspec.c`). `cwd_from_repo_root` is that prefix
1342/// without a trailing slash, or empty at the work tree root.
1343#[must_use]
1344pub fn extend_pathspec_list_implicit_cwd(
1345    specs: &[String],
1346    cwd_from_repo_root: Option<&str>,
1347) -> Vec<String> {
1348    if specs.is_empty() {
1349        return specs.to_vec();
1350    }
1351    if !specs.iter().all(|s| pathspec_is_exclude(s)) {
1352        return specs.to_vec();
1353    }
1354    let any_top = specs.iter().any(|s| pathspec_has_top(s));
1355    if any_top {
1356        return specs.to_vec();
1357    }
1358    let Some(cwd) = cwd_from_repo_root.map(str::trim).filter(|s| !s.is_empty()) else {
1359        return specs.to_vec();
1360    };
1361    let cwd = cwd.trim_end_matches('/');
1362    if cwd.is_empty() {
1363        return specs.to_vec();
1364    }
1365    let mut out = Vec::with_capacity(specs.len() + 1);
1366    // Git `parse_pathspec` with `PATHSPEC_PREFER_CWD` adds `.` (see pathspec.c), not `{cwd}/`.
1367    out.push(".".to_owned());
1368    out.extend_from_slice(specs);
1369    out
1370}
1371
1372/// Git `match_pathspec` semantics over a pathspec list: OR of positive specs minus OR of exclude
1373/// specs. If every element is exclude-only, Git implicitly prepends `.` (match all); this
1374/// function does the same.
1375///
1376/// No `.gitattributes` rules are available here, so a positive `:(attr:...)` spec never matches
1377/// and an exclude `:(exclude,attr:...)` spec never excludes. Use
1378/// [`crate::repo::Repository::paths_match_pathspecs`] or [`matches_pathspec_list_for_object`]
1379/// when specs may carry attr magic (see [`pathspec_has_attr_magic`]).
1380#[must_use]
1381pub fn matches_pathspec_list(path: &str, specs: &[String]) -> bool {
1382    matches_pathspec_list_with_context(path, specs, PathspecMatchContext::default())
1383}
1384
1385/// Like [`matches_pathspec_list`], but uses `ctx` for non-magic pathspec elements (trailing `/`).
1386///
1387/// Like [`matches_pathspec_list`], this does not evaluate `:(attr:...)` magic: positive attr specs
1388/// never match and attr excludes never exclude.
1389#[must_use]
1390pub fn matches_pathspec_list_with_context(
1391    path: &str,
1392    specs: &[String],
1393    ctx: PathspecMatchContext,
1394) -> bool {
1395    if specs.is_empty() {
1396        return true;
1397    }
1398    let mut has_exclude = false;
1399    let mut has_positive = false;
1400    let mut positive = false;
1401    for spec in specs {
1402        if pathspec_is_exclude(spec) {
1403            has_exclude = true;
1404        } else {
1405            has_positive = true;
1406            positive = positive || matches_pathspec_element_with_context(spec, path, ctx);
1407        }
1408    }
1409    if has_positive && !positive {
1410        return false;
1411    }
1412    if !has_exclude {
1413        return true;
1414    }
1415    let excluded = specs.iter().any(|s| {
1416        pathspec_is_exclude(s) && pathspec_exclude_element_matches_with_context(s, path, ctx)
1417    });
1418    !excluded
1419}
1420
1421/// Whether any of `sorted_paths` matches the single pathspec `spec`.
1422///
1423/// Same result as testing every path with [`matches_pathspec_list_with_context`] and `[spec]`,
1424/// but a plain literal pathspec (no magic, no wildcards, no `./`) is answered with a binary
1425/// search instead of a scan, so checking many pathspecs against a large index stays cheap.
1426///
1427/// `sorted_paths` must be sorted in byte order (the [`str`] ordering) for the result to be
1428/// correct; duplicates are allowed.
1429pub(crate) fn sorted_paths_match_pathspec<S: AsRef<str>>(
1430    spec: &str,
1431    sorted_paths: &[S],
1432    ctx: PathspecMatchContext,
1433) -> bool {
1434    let list = [spec.to_owned()];
1435    let matches_linearly = |p: &S| matches_pathspec_list_with_context(p.as_ref(), &list, ctx);
1436    if !is_plain_literal_pathspec(spec, ctx) {
1437        return sorted_paths.iter().any(matches_linearly);
1438    }
1439    let spec_nfc = literal_spec_for_lookup(spec, ctx);
1440    if sorted_literal_lookup(&spec_nfc, sorted_paths) {
1441        return true;
1442    }
1443    // A hit on the NFC spelling is always a match; a path stored in another normalization form
1444    // can only match through a non-ASCII segment, so a miss rechecks just those paths.
1445    ctx.precompose_paths
1446        && sorted_paths
1447            .iter()
1448            .filter(|p| !p.as_ref().is_ascii())
1449            .any(matches_linearly)
1450}
1451
1452/// Binary-search `sorted_paths` for the plain literal `spec` (exact path or directory prefix).
1453fn sorted_literal_lookup<S: AsRef<str>>(spec: &str, sorted_paths: &[S]) -> bool {
1454    let has_path_with_prefix = |prefix: &str| {
1455        let at = sorted_paths.partition_point(|p| p.as_ref() < prefix);
1456        sorted_paths
1457            .get(at)
1458            .is_some_and(|p| p.as_ref().starts_with(prefix))
1459    };
1460    if spec.ends_with('/') {
1461        return has_path_with_prefix(spec);
1462    }
1463    let at = sorted_paths.partition_point(|p| p.as_ref() < spec);
1464    if sorted_paths.get(at).is_some_and(|p| p.as_ref() == spec) {
1465        return true;
1466    }
1467    has_path_with_prefix(&format!("{spec}/"))
1468}
1469
1470/// The spelling of a plain literal `spec` that [`matches_pathspec_with_context`] compares paths
1471/// against: NFC when the context precomposes paths, else `spec` itself.
1472fn literal_spec_for_lookup(spec: &str, ctx: PathspecMatchContext) -> Cow<'_, str> {
1473    if ctx.precompose_paths {
1474        precompose_utf8_path(spec)
1475    } else {
1476        Cow::Borrowed(spec)
1477    }
1478}
1479
1480/// Repository-relative paths when every spec is a plain literal file path (no trailing `/`).
1481///
1482/// Used to narrow index/worktree diffs to a small path set without scanning the full index.
1483/// Returns `None` when `ctx` precomposes paths: another normalization form of a spec could also
1484/// match, and only a scan of the candidate paths can find it.
1485pub(crate) fn exact_literal_pathspec_set(
1486    specs: &[String],
1487    ctx: PathspecMatchContext,
1488) -> Option<std::collections::BTreeSet<String>> {
1489    if specs.is_empty() || ctx.precompose_paths {
1490        return None;
1491    }
1492    if !specs
1493        .iter()
1494        .all(|s| is_plain_literal_pathspec(s, ctx) && !s.ends_with('/'))
1495    {
1496        return None;
1497    }
1498    Some(specs.iter().cloned().collect())
1499}
1500
1501/// Whether `spec` matches exactly the path `spec` and everything under directory `spec`
1502/// (no magic, no wildcards, no `./`, and no context that changes trailing-`/` handling).
1503///
1504/// With [`PathspecMatchContext::precompose_paths`], "the path `spec`" means equality after NFC
1505/// normalization of both sides; see [`literal_spec_for_lookup`].
1506fn is_plain_literal_pathspec(spec: &str, ctx: PathspecMatchContext) -> bool {
1507    !ctx.is_directory
1508        && !ctx.is_git_submodule
1509        && !spec.is_empty()
1510        && spec != "."
1511        && !spec.starts_with("./")
1512        && !spec.starts_with(':')
1513        && simple_length(spec) == spec.len()
1514        && !(literal_global() || glob_global() || noglob_global() || icase_global())
1515}
1516
1517/// A pathspec list prepared once for matching many paths with the same context.
1518///
1519/// Gives the same answers as [`matches_pathspec_list_with_context`] with the list and context
1520/// it was built from. When every element is a plain literal (see
1521/// [`sorted_paths_match_pathspec`]), a path is answered with hash lookups of the path and its
1522/// leading directories instead of comparing it against every element, which keeps matching a
1523/// large index against many pathspecs linear in the index size.
1524pub(crate) struct PathspecListMatcher<'a> {
1525    specs: &'a [String],
1526    ctx: PathspecMatchContext,
1527    literals: Option<LiteralPathspecSet>,
1528}
1529
1530/// Plain literal pathspecs split by how they match, spelled as [`literal_spec_for_lookup`] does.
1531struct LiteralPathspecSet {
1532    /// Specs without a trailing `/`: they match the path itself.
1533    exact: HashSet<String>,
1534    /// Directories whose contents match: every spec, with one trailing `/` removed.
1535    dirs: HashSet<String>,
1536}
1537
1538impl<'a> PathspecListMatcher<'a> {
1539    /// Prepare `specs` for repeated matching under `ctx`.
1540    pub(crate) fn new(specs: &'a [String], ctx: PathspecMatchContext) -> Self {
1541        let all_plain =
1542            !specs.is_empty() && specs.iter().all(|s| is_plain_literal_pathspec(s, ctx));
1543        let literals = all_plain.then(|| {
1544            let mut set = LiteralPathspecSet {
1545                exact: HashSet::with_capacity(specs.len()),
1546                dirs: HashSet::with_capacity(specs.len()),
1547            };
1548            for spec in specs {
1549                let spec = literal_spec_for_lookup(spec, ctx);
1550                match spec.strip_suffix('/') {
1551                    Some(dir) => {
1552                        set.dirs.insert(dir.to_owned());
1553                    }
1554                    None => {
1555                        set.exact.insert(spec.to_string());
1556                        set.dirs.insert(spec.into_owned());
1557                    }
1558                }
1559            }
1560            set
1561        });
1562        Self {
1563            specs,
1564            ctx,
1565            literals,
1566        }
1567    }
1568
1569    /// Whether `path` matches the pathspec list.
1570    pub(crate) fn matches(&self, path: &str) -> bool {
1571        let Some(set) = &self.literals else {
1572            return matches_pathspec_list_with_context(path, self.specs, self.ctx);
1573        };
1574        let path = literal_spec_for_lookup(path, self.ctx);
1575        let path = path.as_ref();
1576        if set.exact.contains(path) {
1577            return true;
1578        }
1579        path.bytes()
1580            .enumerate()
1581            .any(|(i, b)| b == b'/' && set.dirs.contains(&path[..i]))
1582    }
1583}
1584
1585/// `matches_pathspec_list` for tree/index objects with mode and `.gitattributes` rules.
1586///
1587/// `attr_rules` are applied without `[attr]` macro definitions and with case-sensitive
1588/// patterns; [`crate::repo::Repository::pathspec_matcher`] also honors macros and
1589/// `core.ignorecase`.
1590#[must_use]
1591pub fn matches_pathspec_list_for_object(
1592    path: &str,
1593    mode: u32,
1594    attr_rules: &[AttrRule],
1595    specs: &[String],
1596) -> bool {
1597    matches_pathspec_list_with_attrs(path, mode, AttrLookup::rules_only(attr_rules), specs)
1598}
1599
1600pub(crate) fn matches_pathspec_list_with_attrs(
1601    path: &str,
1602    mode: u32,
1603    attrs: AttrLookup<'_>,
1604    specs: &[String],
1605) -> bool {
1606    if specs.is_empty() {
1607        return true;
1608    }
1609    let mut has_exclude = false;
1610    let mut has_positive = false;
1611    let mut positive = false;
1612    for spec in specs {
1613        if pathspec_is_exclude(spec) {
1614            has_exclude = true;
1615        } else {
1616            has_positive = true;
1617            positive = positive || matches_pathspec_for_object_with_attrs(spec, path, mode, attrs);
1618        }
1619    }
1620    if has_positive && !positive {
1621        return false;
1622    }
1623    if !has_exclude {
1624        return true;
1625    }
1626    !specs.iter().any(|s| {
1627        pathspec_is_exclude(s) && matches_pathspec_exclude_for_object(s, path, mode, attrs)
1628    })
1629}
1630
1631fn matches_pathspec_exclude_for_object(
1632    spec: &str,
1633    path: &str,
1634    mode: u32,
1635    attrs: AttrLookup<'_>,
1636) -> bool {
1637    let (elem_magic, raw_pattern) = parse_element_magic(spec);
1638    let mut magic = combine_magic(elem_magic);
1639    if !magic.exclude {
1640        return false;
1641    }
1642    magic.exclude = false;
1643    if magic.literal && magic.glob {
1644        return false;
1645    }
1646    let ctx = context_from_mode_bits(mode);
1647    let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
1648    if !magic.attr_requirements.is_empty()
1649        && !attr_requirements_match(&magic.attr_requirements, attrs, path, is_dir_for_attr, mode)
1650    {
1651        return false;
1652    }
1653    let pattern = strip_top_magic(raw_pattern);
1654    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1655        match path_for_match_under_magic_prefix(path, prefix) {
1656            Some(rest) => rest,
1657            None => return false,
1658        }
1659    } else {
1660        path
1661    };
1662    if magic.literal || magic.glob || magic.icase {
1663        pathspec_matches_tail(pattern, path_for_match, magic)
1664    } else {
1665        matches_pathspec_with_context(pattern, path_for_match, ctx)
1666    }
1667}
1668
1669fn pathspec_matches_tail(pattern: &str, path: &str, magic: PathspecMagic) -> bool {
1670    if pattern.is_empty() {
1671        return true;
1672    }
1673
1674    let flags = if magic.icase { WM_CASEFOLD } else { 0 };
1675
1676    if magic.literal {
1677        return literal_prefix_match(pattern, path);
1678    }
1679
1680    let wm_flags = if magic.glob {
1681        flags | WM_PATHNAME
1682    } else {
1683        flags
1684    };
1685
1686    let pattern_bytes = pattern.as_bytes();
1687    let path_bytes = path.as_bytes();
1688    let simple = simple_length(pattern);
1689
1690    // Git `match_pathspec_item`: exact / directory prefix before `git_fnmatch`.
1691    // Only when the pattern has no glob metacharacters (`simple_length` spans the whole pattern);
1692    // otherwise a pattern like `a[a]` must not match children via `a[a]/` prefix (t6130 vs ls-tree).
1693    if ps_str_eq(pattern, path, magic.icase) {
1694        return true;
1695    }
1696    if simple == pattern.len() {
1697        if let Some(prefix) = pattern.strip_suffix('/') {
1698            if ps_str_eq(prefix, path, magic.icase) {
1699                return true;
1700            }
1701            if path_is_under_dir(path, prefix, magic.icase) {
1702                return true;
1703            }
1704        } else if path_is_under_dir(path, pattern, magic.icase) {
1705            return true;
1706        }
1707    }
1708
1709    // `:(glob)**/*.txt` at repo root: Git matches `untracked.txt` (leading `**/` is optional).
1710    if magic.glob && !path.contains('/') && pattern.starts_with("**/") {
1711        if wildmatch(pattern_bytes, path_bytes, wm_flags) {
1712            return true;
1713        }
1714        if let Some(suffix) = pattern.strip_prefix("**/") {
1715            if wildmatch(suffix.as_bytes(), path_bytes, wm_flags) {
1716                return true;
1717            }
1718        }
1719    }
1720
1721    // Wildcard: require literal bytes up to `simple_length`, then wildmatch the tail only.
1722    if simple < pattern.len() {
1723        if path_bytes.len() < simple {
1724            return false;
1725        }
1726        let path_lit = &path_bytes[..simple];
1727        let pat_lit = &pattern_bytes[..simple];
1728        let same = if magic.icase {
1729            path_lit.eq_ignore_ascii_case(pat_lit)
1730        } else {
1731            path_lit == pat_lit
1732        };
1733        if !same {
1734            return false;
1735        }
1736        let pat_rest = &pattern[simple..];
1737        let path_rest = &path[simple..];
1738        return wildmatch(pat_rest.as_bytes(), path_rest.as_bytes(), wm_flags);
1739    }
1740
1741    ps_str_eq(pattern, path, magic.icase) || path_is_under_dir(path, pattern, magic.icase)
1742}
1743
1744fn ps_str_eq(a: &str, b: &str, icase: bool) -> bool {
1745    if icase {
1746        a.eq_ignore_ascii_case(b)
1747    } else {
1748        a == b
1749    }
1750}
1751
1752fn path_starts_with(path: &str, prefix: &str, icase: bool) -> bool {
1753    if icase {
1754        path.get(..prefix.len())
1755            .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
1756    } else {
1757        path.starts_with(prefix)
1758    }
1759}
1760
1761/// Whether `path` starts with `dir` followed by `/` (the path lies inside directory `dir`).
1762fn path_is_under_dir(path: &str, dir: &str, icase: bool) -> bool {
1763    path.as_bytes().get(dir.len()) == Some(&b'/') && path_starts_with(path, dir, icase)
1764}
1765
1766fn literal_prefix_match(pattern: &str, path: &str) -> bool {
1767    if let Some(prefix) = pattern.strip_suffix('/') {
1768        return path == prefix || path_is_under_dir(path, prefix, false);
1769    }
1770    path == pattern || path_is_under_dir(path, pattern, false)
1771}
1772
1773/// Literal pathspec match for `ls-tree` when the pattern has no `*`/`?` (brackets stay literal).
1774fn ls_tree_literal_match(pattern: &str, path: &str, ctx: PathspecMatchContext) -> bool {
1775    if let Some(prefix) = pattern.strip_suffix('/') {
1776        if path_is_under_dir(path, prefix, false) {
1777            return true;
1778        }
1779        if path == prefix {
1780            return ctx.is_directory || ctx.is_git_submodule;
1781        }
1782        return false;
1783    }
1784    path == pattern || path_is_under_dir(path, pattern, false)
1785}
1786
1787/// Optional path metadata for literal pathspecs with a trailing `/` (tree-walk / diff-tree).
1788///
1789/// Git treats `dir/` as “directory or git submodule only”: a regular file `dir`
1790/// does not match, but a tree entry `dir` or gitlink `dir` does.
1791#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1792pub struct PathspecMatchContext {
1793    /// The index/tree entry is a directory (mode `040000`).
1794    pub is_directory: bool,
1795    /// The entry is a git submodule / gitlink (`160000`).
1796    pub is_git_submodule: bool,
1797    /// NFC-normalize pathspec and path when matching (per-repository `core.precomposeunicode`).
1798    pub precompose_paths: bool,
1799}
1800
1801/// Returns whether `path` matches the pathspec `spec` with default (file) context.
1802///
1803/// For pathspecs ending in `/`, a path equal to the prefix matches only when
1804/// [`PathspecMatchContext`] indicates a directory or submodule; see
1805/// [`matches_pathspec_with_context`].
1806///
1807/// `:(attr:...)` requirements are not evaluated here (only the pattern part is matched); use
1808/// [`matches_pathspec_for_object`] or [`crate::repo::Repository::paths_match_pathspecs`] for
1809/// specs where [`pathspec_has_attr_magic`] is true.
1810#[must_use]
1811pub fn matches_pathspec(spec: &str, path: &str) -> bool {
1812    matches_pathspec_with_context(spec, path, PathspecMatchContext::default())
1813}
1814
1815/// Like [`matches_pathspec`], but uses `ctx` for trailing-`/` literal pathspecs and for
1816/// wildcard pathspecs where the pattern continues after a directory boundary (Git
1817/// `matches_pathspec` + directory semantics).
1818#[must_use]
1819pub fn matches_pathspec_with_context(spec: &str, path: &str, ctx: PathspecMatchContext) -> bool {
1820    let spec_nfc: Cow<'_, str> = if ctx.precompose_paths {
1821        precompose_utf8_path(spec)
1822    } else {
1823        Cow::Borrowed(spec)
1824    };
1825    let path_nfc: Cow<'_, str> = if ctx.precompose_paths {
1826        precompose_utf8_path(path)
1827    } else {
1828        Cow::Borrowed(path)
1829    };
1830    let spec = spec_nfc.as_ref();
1831    let path = path_nfc.as_ref();
1832
1833    let trimmed = spec.strip_prefix("./").unwrap_or(spec);
1834    if trimmed == "." || trimmed.is_empty() {
1835        return true;
1836    }
1837
1838    let (elem_magic, raw_pattern) = parse_element_magic(trimmed);
1839    let magic = combine_magic(elem_magic);
1840
1841    if magic.literal && magic.glob {
1842        return false;
1843    }
1844    if magic.exclude {
1845        return false;
1846    }
1847
1848    let pattern = strip_top_magic(raw_pattern);
1849    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1850        match path_for_match_under_magic_prefix(path, prefix) {
1851            Some(rest) => rest,
1852            None => return false,
1853        }
1854    } else {
1855        path
1856    };
1857
1858    if magic.literal {
1859        if let Some(prefix) = pattern.strip_suffix('/') {
1860            if path_is_under_dir(path_for_match, prefix, false) {
1861                return true;
1862            }
1863            if path_for_match == prefix {
1864                return ctx.is_directory || ctx.is_git_submodule;
1865            }
1866            return false;
1867        }
1868        return path_for_match == pattern || path_is_under_dir(path_for_match, pattern, false);
1869    }
1870
1871    // No wildcards and trailing `/`: directory-only semantics (Git `matches_pathspec`).
1872    if let Some(prefix) = pattern.strip_suffix('/') {
1873        if simple_length(pattern) == pattern.len() {
1874            if path_is_under_dir(path_for_match, prefix, false) {
1875                return true;
1876            }
1877            if path_for_match == prefix {
1878                return ctx.is_directory || ctx.is_git_submodule;
1879            }
1880            return false;
1881        }
1882    }
1883
1884    if pathspec_matches_tail(pattern, path_for_match, magic) {
1885        return true;
1886    }
1887
1888    if (ctx.is_directory || ctx.is_git_submodule)
1889        && !path_for_match.is_empty()
1890        && pattern.len() > path_for_match.len()
1891        && pattern.as_bytes().get(path_for_match.len()) == Some(&b'/')
1892        && pattern.starts_with(path_for_match)
1893        && simple_length(pattern) < pattern.len()
1894    {
1895        return true;
1896    }
1897
1898    false
1899}
1900
1901/// Parse a Git mode string (e.g. `100644`, `040000`) into a [`PathspecMatchContext`].
1902#[must_use]
1903pub fn context_from_mode_octal(mode: &str) -> PathspecMatchContext {
1904    let Ok(bits) = u32::from_str_radix(mode, 8) else {
1905        return PathspecMatchContext::default();
1906    };
1907    context_from_mode_bits(bits)
1908}
1909
1910/// Classify a raw Git mode (e.g. from an index or tree entry) for pathspec matching.
1911#[must_use]
1912pub fn context_from_mode_bits(mode: u32) -> PathspecMatchContext {
1913    let ty = mode & 0o170000;
1914    PathspecMatchContext {
1915        is_directory: ty == 0o040000,
1916        is_git_submodule: ty == 0o160000,
1917        precompose_paths: false,
1918    }
1919}
1920
1921/// Pathspec matching for `ls-tree` after Git forces `pathspec.has_wildcard = 0` (`ls-tree.c`).
1922///
1923/// Metacharacters `*` / `?` still participate in [`wildmatch`]; `[` and `\\` are **not** glob
1924/// starters unless a `*` or `?` appears — so `a[a]` matches the literal directory `a[a]` (t3102),
1925/// while `a*` matches `a/one`, `aa/two`, `a[a]/three`, …
1926#[must_use]
1927pub fn matches_ls_tree_pathspec(
1928    spec: &str,
1929    path: &str,
1930    mode: u32,
1931    attr_rules: &[AttrRule],
1932) -> bool {
1933    let (elem_magic, raw_pattern) = parse_element_magic(spec);
1934    let mut magic = combine_magic(elem_magic);
1935    magic.exclude = false;
1936
1937    if magic.literal && magic.glob {
1938        return false;
1939    }
1940
1941    let ctx = context_from_mode_bits(mode);
1942    let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
1943
1944    if !magic.attr_requirements.is_empty()
1945        && !attr_requirements_match(
1946            &magic.attr_requirements,
1947            AttrLookup::rules_only(attr_rules),
1948            path,
1949            is_dir_for_attr,
1950            mode,
1951        )
1952    {
1953        return false;
1954    }
1955
1956    let pattern = strip_top_magic(raw_pattern);
1957    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1958        match path_for_match_under_magic_prefix(path, prefix) {
1959            Some(rest) => rest,
1960            None => return false,
1961        }
1962    } else {
1963        path
1964    };
1965
1966    if magic.literal || magic.glob || magic.icase {
1967        return pathspec_matches_tail(pattern, path_for_match, magic);
1968    }
1969
1970    let spec_nfc: Cow<'_, str> = Cow::Borrowed(pattern);
1971    let path_nfc: Cow<'_, str> = Cow::Borrowed(path_for_match);
1972    let pattern = spec_nfc.as_ref();
1973    let path = path_nfc.as_ref();
1974
1975    let trimmed = pattern.strip_prefix("./").unwrap_or(pattern);
1976    if trimmed == "." || trimmed.is_empty() {
1977        return true;
1978    }
1979
1980    let uses_star_or_question = trimmed.contains('*') || trimmed.contains('?');
1981    if !uses_star_or_question {
1982        return ls_tree_literal_match(trimmed, path, ctx);
1983    }
1984
1985    let nwl = simple_length(trimmed);
1986    let flags = 0u32;
1987    if nwl == trimmed.len() {
1988        return wildmatch(trimmed.as_bytes(), path.as_bytes(), flags);
1989    }
1990    let lit = trimmed.as_bytes().get(..nwl).unwrap_or_default();
1991    let path_b = path.as_bytes();
1992    if path_b.len() < nwl {
1993        return false;
1994    }
1995    if &path_b[..nwl] != lit {
1996        return false;
1997    }
1998    let pat_rest = &trimmed[nwl..];
1999    let path_rest = &path[nwl..];
2000    wildmatch(pat_rest.as_bytes(), path_rest.as_bytes(), flags)
2001}
2002
2003/// Match a pathspec against a tree path, using `.gitattributes` for `:(attr:...)`.
2004///
2005/// `mode` supplies directory/gitlink context for literal pathspecs ending in `/`.
2006#[must_use]
2007pub fn matches_pathspec_for_object(
2008    spec: &str,
2009    path: &str,
2010    mode: u32,
2011    attr_rules: &[AttrRule],
2012) -> bool {
2013    matches_pathspec_for_object_with_attrs(spec, path, mode, AttrLookup::rules_only(attr_rules))
2014}
2015
2016fn matches_pathspec_for_object_with_attrs(
2017    spec: &str,
2018    path: &str,
2019    mode: u32,
2020    attrs: AttrLookup<'_>,
2021) -> bool {
2022    let (elem_magic, raw_pattern) = parse_element_magic(spec);
2023    let mut magic = combine_magic(elem_magic);
2024    magic.exclude = false;
2025
2026    if magic.literal && magic.glob {
2027        return false;
2028    }
2029
2030    let ctx = context_from_mode_bits(mode);
2031    let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
2032
2033    if !magic.attr_requirements.is_empty()
2034        && !attr_requirements_match(&magic.attr_requirements, attrs, path, is_dir_for_attr, mode)
2035    {
2036        return false;
2037    }
2038
2039    let pattern = strip_top_magic(raw_pattern);
2040    let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
2041        match path_for_match_under_magic_prefix(path, prefix) {
2042            Some(rest) => rest,
2043            None => return false,
2044        }
2045    } else {
2046        path
2047    };
2048    if magic.literal || magic.glob || magic.icase {
2049        pathspec_matches_tail(pattern, path_for_match, magic)
2050    } else {
2051        matches_pathspec_with_context(pattern, path_for_match, ctx)
2052    }
2053}
2054
2055/// Resolved path lies outside the repository work tree (Git `prefix_path_gently` failure).
2056#[derive(Debug, Clone)]
2057pub struct PathOutsideRepository {
2058    /// User-facing pathspec token (argv element).
2059    pub elt: String,
2060    /// Resolved absolute path outside the work tree.
2061    pub path: String,
2062    /// Canonical work tree root.
2063    pub work_tree: PathBuf,
2064}
2065
2066impl std::fmt::Display for PathOutsideRepository {
2067    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2068        write!(
2069            f,
2070            "{}: '{}' is outside repository at '{}'",
2071            self.elt,
2072            self.path,
2073            self.work_tree.display()
2074        )
2075    }
2076}
2077
2078impl From<PathOutsideRepository> for PathspecResolveError {
2079    fn from(outside: PathOutsideRepository) -> Self {
2080        Self::OutsideRepository {
2081            elt: outside.elt,
2082            path: outside.path,
2083            work_tree: outside.work_tree.display().to_string(),
2084        }
2085    }
2086}
2087
2088/// Resolve a magic pathspec relative to a current-directory prefix.
2089///
2090/// This keeps the `cwd` prefix case-sensitive (via an internal `prefix:` magic
2091/// token) while still honoring magic options like `icase` for the tail.
2092/// Specs that include `top` (or short `:/`) stay repo-root-relative: the tail is
2093/// not prefixed with the process cwd and no `prefix:` token is injected.
2094/// Returns `None` when `spec` is not a parseable magic pathspec.
2095pub fn resolve_magic_pathspec(spec: &str, cwd_prefix: &str) -> Option<String> {
2096    if !spec.starts_with(":(") {
2097        return None;
2098    }
2099    let close_idx = spec.find(')')?;
2100    let magic_prefix = &spec[..=close_idx];
2101    let tail = &spec[close_idx + 1..];
2102    Some(resolve_magic_pathspec_parts(magic_prefix, tail, cwd_prefix))
2103}
2104
2105fn resolve_magic_pathspec_parts(magic_prefix: &str, tail: &str, cwd_prefix: &str) -> String {
2106    if has_magic_prefix_token(magic_prefix) {
2107        return format!("{magic_prefix}{tail}");
2108    }
2109
2110    if let Some(rooted_tail) = tail.strip_prefix('/') {
2111        return format!("{magic_prefix}{}", normalize_relative_path_str(rooted_tail));
2112    }
2113
2114    if long_magic_prefix_has_top(magic_prefix) {
2115        return format!("{magic_prefix}{tail}");
2116    }
2117
2118    let combined = if cwd_prefix.is_empty() {
2119        normalize_relative_path_str(tail)
2120    } else {
2121        normalize_relative_path_str(&format!("{cwd_prefix}{tail}"))
2122    };
2123
2124    let cwd_base = normalize_relative_path_str(cwd_prefix.trim_end_matches('/'));
2125    if !cwd_base.is_empty()
2126        && (combined == cwd_base || combined.starts_with(&format!("{cwd_base}/")))
2127    {
2128        let after_base = combined
2129            .strip_prefix(&cwd_base)
2130            .unwrap_or(combined.as_str());
2131        let remainder = after_base.strip_prefix('/').unwrap_or(after_base);
2132        let magic_with_prefix = inject_magic_prefix_token(magic_prefix, &format!("{cwd_base}/"));
2133        return format!("{magic_with_prefix}{remainder}");
2134    }
2135
2136    format!("{magic_prefix}{combined}")
2137}
2138
2139fn has_magic_prefix_token(magic_prefix: &str) -> bool {
2140    let Some(inner) = magic_prefix
2141        .strip_prefix(":(")
2142        .and_then(|s| s.strip_suffix(')'))
2143    else {
2144        return false;
2145    };
2146    inner
2147        .split(',')
2148        .map(str::trim)
2149        .any(|token| token.starts_with("prefix:"))
2150}
2151
2152fn long_magic_prefix_has_top(magic_prefix: &str) -> bool {
2153    let Some(inner) = magic_prefix
2154        .strip_prefix(":(")
2155        .and_then(|s| s.strip_suffix(')'))
2156    else {
2157        return false;
2158    };
2159    inner
2160        .split(',')
2161        .map(str::trim)
2162        .any(|token| token.eq_ignore_ascii_case("top"))
2163}
2164
2165fn inject_magic_prefix_token(magic_prefix: &str, prefix: &str) -> String {
2166    let Some(inner) = magic_prefix
2167        .strip_prefix(":(")
2168        .and_then(|s| s.strip_suffix(')'))
2169    else {
2170        return magic_prefix.to_string();
2171    };
2172    if inner.trim().is_empty() {
2173        format!(":(prefix:{prefix})")
2174    } else {
2175        format!(":({inner},prefix:{prefix})")
2176    }
2177}
2178
2179/// Drop repeated leading `./` / `.//` from a repo-root pathspec (Git `prefix_path` behavior).
2180///
2181/// When stripping exposes a leading `:`, wrap with `:(literal)` so a filesystem path like
2182/// `:!foo` is not reinterpreted as short exclude magic.
2183fn normalize_repo_root_relative_pathspec(pathspec: &str) -> String {
2184    let mut spec = pathspec;
2185    let mut stripped = false;
2186    while let Some(rest) = spec.strip_prefix("./") {
2187        stripped = true;
2188        spec = rest.trim_start_matches('/');
2189    }
2190    if !stripped {
2191        return pathspec.to_owned();
2192    }
2193    if spec.is_empty() {
2194        return ".".to_owned();
2195    }
2196    if spec.starts_with(':') && !literal_pathspecs_enabled() {
2197        return format!(":(literal){spec}");
2198    }
2199    spec.to_owned()
2200}
2201
2202/// Normalize user pathspec separators on Windows (`\` → `/`) before resolution.
2203fn normalize_pathspec_separators(pathspec: &str) -> std::borrow::Cow<'_, str> {
2204    #[cfg(windows)]
2205    {
2206        if !pathspec.starts_with(':') && pathspec.contains('\\') {
2207            return std::borrow::Cow::Owned(pathspec.replace('\\', "/"));
2208        }
2209    }
2210    std::borrow::Cow::Borrowed(pathspec)
2211}
2212
2213fn normalize_relative_path_str(path: &str) -> String {
2214    let mut parts: Vec<String> = Vec::new();
2215    for component in std::path::Path::new(path).components() {
2216        match component {
2217            std::path::Component::CurDir => {}
2218            std::path::Component::ParentDir => {
2219                parts.pop();
2220            }
2221            std::path::Component::Normal(seg) => {
2222                parts.push(seg.to_string_lossy().to_string());
2223            }
2224            std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
2225        }
2226    }
2227    parts.join("/")
2228}
2229
2230/// Current directory relative to `work_tree`, or `None` if cwd is the work tree root.
2231#[must_use]
2232pub fn pathdiff(cwd: &Path, work_tree: &Path) -> Option<String> {
2233    use crate::git_path::{path_for_disk_compare, path_to_git_slash};
2234
2235    let cwd_cmp = path_for_disk_compare(cwd);
2236    let wt_cmp = path_for_disk_compare(work_tree);
2237
2238    if cwd_cmp == wt_cmp {
2239        return None;
2240    }
2241
2242    let rel = cwd_cmp.strip_prefix(&wt_cmp).ok()?;
2243    let git = path_to_git_slash(rel);
2244    if git.is_empty() {
2245        None
2246    } else {
2247        Some(git)
2248    }
2249}
2250
2251/// For short exclude magic from a subdirectory, Git applies the worktree prefix to the pattern
2252/// tail (via `prefix_path`) while keeping argv spelling. Long-form `:(exclude,prefix:…)` matches
2253/// [`resolve_worktree_pathspec`] for `:(exclude)…` under a cwd prefix.
2254fn prepend_cwd_to_short_exclude_pathspec(spec: &str, cwd: &str) -> Option<String> {
2255    let cwd = cwd.trim_end_matches('/');
2256    if cwd.is_empty() {
2257        return None;
2258    }
2259    let (elem_magic, pattern) = parse_element_magic(spec);
2260    let magic = combine_magic(elem_magic);
2261    if !magic.exclude || magic.top {
2262        return None;
2263    }
2264    if pattern.is_empty() || pattern.starts_with('/') {
2265        return None;
2266    }
2267    if magic.glob || magic.literal || magic.icase || !magic.attr_requirements.is_empty() {
2268        return None;
2269    }
2270    Some(format!(":(exclude,prefix:{cwd}/){pattern}"))
2271}
2272
2273/// Build [`PathspecMatchContext`] with optional NFC path normalization for comparisons.
2274#[must_use]
2275pub fn pathspec_match_context_with_precompose(precompose_paths: bool) -> PathspecMatchContext {
2276    PathspecMatchContext {
2277        precompose_paths,
2278        ..PathspecMatchContext::default()
2279    }
2280}
2281
2282/// Like [`matches_pathspec_list`], with an explicit `precompose_paths` flag.
2283#[must_use]
2284pub fn matches_pathspec_list_precompose(
2285    path: &str,
2286    specs: &[String],
2287    precompose_paths: bool,
2288) -> bool {
2289    matches_pathspec_list_with_context(
2290        path,
2291        specs,
2292        pathspec_match_context_with_precompose(precompose_paths),
2293    )
2294}
2295
2296/// True when argv pathspec strings must not be NFC-normalized (magic syntax).
2297#[must_use]
2298pub fn argv_pathspec_preserves_spelling(pathspec: &str) -> bool {
2299    pathspec.starts_with(":(")
2300        || pathspec.starts_with(":/")
2301        || pathspec.starts_with(":!")
2302        || pathspec.starts_with(":^")
2303}
2304
2305/// NFC-normalize a literal command-line pathspec (Git `precompose_argv_prefix`).
2306#[must_use]
2307pub fn precompose_argv_pathspec(pathspec: &str) -> Cow<'_, str> {
2308    if argv_pathspec_preserves_spelling(pathspec) {
2309        Cow::Borrowed(pathspec)
2310    } else {
2311        precompose_utf8_path(pathspec)
2312    }
2313}
2314
2315/// Resolve a pathspec string to a path relative to the repository work tree.
2316///
2317/// `prefix` is the current directory relative to the work tree (no trailing slash),
2318/// or `None` when cwd is the work tree root.
2319#[must_use]
2320pub fn resolve_pathspec(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2321    resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, false)
2322}
2323
2324/// Like [`resolve_pathspec`], but NFC-normalizes literal argv path segments when requested.
2325#[must_use]
2326pub fn resolve_pathspec_with_argv_precompose(
2327    pathspec: &str,
2328    work_tree: &Path,
2329    prefix: Option<&str>,
2330    argv_precompose: bool,
2331) -> String {
2332    let pathspec = if argv_precompose {
2333        precompose_argv_pathspec(pathspec)
2334    } else {
2335        Cow::Borrowed(pathspec)
2336    };
2337    resolve_pathspec_impl(pathspec.as_ref(), work_tree, prefix)
2338}
2339
2340fn resolve_pathspec_impl(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2341    let pathspec = normalize_pathspec_separators(pathspec);
2342    let pathspec = pathspec.as_ref();
2343    // Git: `.` at repo root means "match the whole tree" (not an empty pathspec).
2344    // An empty resolved pathspec would match nothing and breaks `grep -- . t` max-depth.
2345    if pathspec == "." {
2346        return match prefix {
2347            Some(p) if !p.is_empty() => p.to_owned(),
2348            _ => ".".to_owned(),
2349        };
2350    }
2351    if pathspec.contains("../") || pathspec.starts_with("../") {
2352        let cwd = match prefix.filter(|p| !p.is_empty()) {
2353            Some(p) => work_tree.join(p),
2354            None => work_tree.to_path_buf(),
2355        };
2356        let abs = cwd.join(pathspec);
2357        let mut parts: Vec<std::ffi::OsString> = Vec::new();
2358        for component in abs.components() {
2359            use std::path::Component;
2360            match component {
2361                Component::ParentDir => {
2362                    parts.pop();
2363                }
2364                Component::CurDir => {}
2365                other => parts.push(other.as_os_str().to_os_string()),
2366            }
2367        }
2368        let abs_norm: PathBuf = parts.iter().collect();
2369        if let Some(rel) = crate::git_path::strip_worktree_prefix(&abs_norm, work_tree) {
2370            return rel;
2371        }
2372    }
2373    if Path::new(pathspec).is_absolute() {
2374        let abs = Path::new(pathspec);
2375        if let Some(rel) = crate::git_path::strip_worktree_prefix(abs, work_tree) {
2376            return rel;
2377        }
2378        return pathspec.to_owned();
2379    }
2380
2381    if pathspec.starts_with(':') {
2382        if let Some(p) = prefix {
2383            if !p.is_empty() && !literal_pathspecs_enabled() {
2384                let cwd_ps = format!("{}/", p.trim_end_matches('/'));
2385                if pathspec.starts_with(":(") {
2386                    if pathspec_has_top(pathspec) {
2387                        return pathspec.to_owned();
2388                    }
2389                    if let Some(resolved) = resolve_magic_pathspec(pathspec, &cwd_ps) {
2390                        return resolved;
2391                    }
2392                    return pathspec.to_owned();
2393                }
2394                if pathspec_is_exclude(pathspec) {
2395                    if let Some(fixed) = prepend_cwd_to_short_exclude_pathspec(pathspec, p) {
2396                        return fixed;
2397                    }
2398                }
2399            }
2400        }
2401        if let Some(rest) = pathspec.strip_prefix(":/") {
2402            // `:/!foo` / `:/^bar` — `:/` is `:(top)`; the tail is still short magic, not a literal path.
2403            if rest.starts_with('!') || rest.starts_with('^') {
2404                return pathspec.to_owned();
2405            }
2406            return rest.to_owned();
2407        }
2408        // Long magic `:(...)` must stay intact — `:(exclude)path` is not the same as `path`
2409        // (t6132-pathspec-exclude, grep --untracked with exclude pathspecs).
2410        if pathspec.starts_with(":(") {
2411            return pathspec.to_owned();
2412        }
2413        return pathspec.to_owned();
2414    }
2415
2416    match prefix {
2417        Some(p) if !p.is_empty() => {
2418            normalize_relative_path_str(&PathBuf::from(p).join(pathspec).to_string_lossy())
2419        }
2420        _ => normalize_repo_root_relative_pathspec(pathspec),
2421    }
2422}
2423
2424/// Resolve a pathspec and ensure it lies inside `work_tree` (used by `git add`, etc.).
2425///
2426/// Returns [`PathOutsideRepository`] when resolution stays absolute, matching Git's
2427/// `'%s' is outside repository at '%s'` fatal (t7010).
2428pub fn resolve_pathspec_in_worktree(
2429    elt: &str,
2430    pathspec: &str,
2431    work_tree: &Path,
2432    prefix: Option<&str>,
2433) -> Result<String, PathOutsideRepository> {
2434    resolve_pathspec_in_worktree_with_argv_precompose(elt, pathspec, work_tree, prefix, false)
2435}
2436
2437/// Like [`resolve_pathspec_in_worktree`], NFC-normalizing `pathspec` when `argv_precompose` is set.
2438///
2439/// Callers holding a [`Repository`] should use [`Repository::resolve_worktree_pathspec`], which
2440/// computes `argv_precompose` once per handle instead of reloading config per pathspec.
2441pub(crate) fn resolve_pathspec_in_worktree_with_argv_precompose(
2442    elt: &str,
2443    pathspec: &str,
2444    work_tree: &Path,
2445    prefix: Option<&str>,
2446    argv_precompose: bool,
2447) -> Result<String, PathOutsideRepository> {
2448    let resolved =
2449        resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, argv_precompose);
2450    if Path::new(&resolved).is_absolute() {
2451        let wt = work_tree
2452            .canonicalize_simplified()
2453            .unwrap_or_else(|_| work_tree.to_path_buf());
2454        return Err(PathOutsideRepository {
2455            elt: elt.to_string(),
2456            path: resolved,
2457            work_tree: wt,
2458        });
2459    }
2460    Ok(resolved)
2461}
2462
2463/// Normalize a worktree file path for porcelain commands (`blame`, `log`, …).
2464///
2465/// Accepts repo-relative or absolute paths under `work_tree`.
2466#[must_use]
2467pub fn normalize_worktree_file_path(
2468    file_path: &str,
2469    work_tree: &Path,
2470    prefix: Option<&str>,
2471) -> String {
2472    normalize_worktree_file_path_with_git_dir(file_path, work_tree, prefix, None)
2473}
2474
2475/// Like [`normalize_worktree_file_path`], honoring `core.precomposeunicode` argv normalization for `git_dir`.
2476#[must_use]
2477pub fn normalize_worktree_file_path_with_git_dir(
2478    file_path: &str,
2479    work_tree: &Path,
2480    prefix: Option<&str>,
2481    git_dir: Option<&Path>,
2482) -> String {
2483    let argv_precompose = argv_precompose_enabled(git_dir);
2484    let resolved =
2485        resolve_pathspec_with_argv_precompose(file_path, work_tree, prefix, argv_precompose);
2486    if Path::new(&resolved).is_absolute() {
2487        file_path.to_string()
2488    } else {
2489        resolved
2490    }
2491}
2492
2493#[cfg(test)]
2494mod tree_entry_pathspec_tests {
2495    use super::*;
2496
2497    #[test]
2498    fn t6130_bracket_filename_matches_pathspec() {
2499        assert!(matches_pathspec("f[o][o]", "f[o][o]"));
2500        assert!(matches_pathspec(":(glob)f[o][o]", "f[o][o]"));
2501    }
2502
2503    #[test]
2504    fn literal_prefix_and_exact() {
2505        assert!(matches_pathspec("path1", "path1/file1"));
2506        assert!(matches_pathspec_with_context(
2507            "path1/",
2508            "path1/file1",
2509            PathspecMatchContext::default()
2510        ));
2511        assert!(matches_pathspec("file0", "file0"));
2512        assert!(!matches_pathspec("path", "path1/file1"));
2513    }
2514
2515    #[test]
2516    fn dir_prefix_needs_slash_boundary() {
2517        assert!(matches_pathspec("a/b", "a/b/c"));
2518        assert!(!matches_pathspec("a/b", "a/bc"));
2519        assert!(!matches_pathspec("a/b", "a"));
2520        assert!(matches_pathspec(":(literal)dir", "dir/x"));
2521        assert!(!matches_pathspec(":(literal)dir", "dirx"));
2522        assert!(matches_pathspec(":(icase)DIR", "dir/x"));
2523        assert!(!matches_pathspec(":(icase)DIR", "dirx"));
2524        assert!(matches_pathspec("dir/", "dir/x"));
2525        assert!(!matches_pathspec("dir/", "dir"));
2526    }
2527
2528    #[test]
2529    fn sorted_lookup_agrees_with_linear_scan() {
2530        let mut paths: Vec<&str> = vec![
2531            "a",
2532            "a-b",
2533            "a.txt",
2534            "a/b",
2535            "a/b/c.txt",
2536            "a/bc",
2537            "a0",
2538            "b/x[1].txt",
2539            "dir/sub/file",
2540            "dir-sub",
2541            "f[o][o]",
2542            "z",
2543            "caf\u{e9}/menu",
2544            "cafe\u{301}/old",
2545            "\u{212a}.txt",
2546        ];
2547        paths.sort_unstable();
2548        let specs = [
2549            "caf\u{e9}",
2550            "cafe\u{301}/",
2551            "cafe\u{301}/old",
2552            "K.txt",
2553            "\u{212a}.txt",
2554            "a",
2555            "a/",
2556            "a/b",
2557            "a/b/",
2558            "a/bc",
2559            "a-",
2560            "a-b",
2561            "a.txt",
2562            "b",
2563            "b/",
2564            "dir",
2565            "dir/sub",
2566            "dir/sub/",
2567            "dir/su",
2568            "dir-sub",
2569            "f[o][o]",
2570            "*.txt",
2571            "a/*",
2572            ":(glob)**/*.txt",
2573            ":(literal)f[o][o]",
2574            ":(icase)A/B",
2575            ":!a",
2576            ".",
2577            "./a/b",
2578            "",
2579            "z",
2580            "zz",
2581            "/",
2582            "a//",
2583        ];
2584        for ctx in [
2585            PathspecMatchContext::default(),
2586            PathspecMatchContext {
2587                precompose_paths: true,
2588                ..PathspecMatchContext::default()
2589            },
2590            PathspecMatchContext {
2591                is_directory: true,
2592                ..PathspecMatchContext::default()
2593            },
2594        ] {
2595            for spec in specs {
2596                let list = [spec.to_owned()];
2597                let linear = paths
2598                    .iter()
2599                    .any(|p| matches_pathspec_list_with_context(p, &list, ctx));
2600                assert_eq!(
2601                    sorted_paths_match_pathspec(spec, &paths, ctx),
2602                    linear,
2603                    "spec {spec:?} ctx {ctx:?}"
2604                );
2605            }
2606        }
2607        let empty: [&str; 0] = [];
2608        assert!(!sorted_paths_match_pathspec(
2609            "a",
2610            &empty,
2611            PathspecMatchContext::default()
2612        ));
2613    }
2614
2615    #[test]
2616    fn list_matcher_agrees_with_linear_matching() {
2617        let paths = [
2618            "a",
2619            "a-b",
2620            "a.txt",
2621            "a/",
2622            "a/b",
2623            "a/b/c.txt",
2624            "a/bc",
2625            "a//x",
2626            "a0",
2627            "b/x[1].txt",
2628            "dir/sub/file",
2629            "dir-sub",
2630            "f[o][o]",
2631            "z",
2632            "zz/a",
2633            "é/x",
2634            "e\u{301}/y",
2635            "\u{212a}.txt",
2636            "K.txt",
2637            "",
2638        ];
2639        let lists: &[&[&str]] = &[
2640            &[],
2641            &["a"],
2642            &["a/"],
2643            &["a//"],
2644            &["a/b", "dir/sub/", "z"],
2645            &["a/b/", "a/bc", "dir", "zz"],
2646            &["dir/su", "dir-sub", "f[o][o]"],
2647            &["é", "a-"],
2648            &["e\u{301}", "z"],
2649            &["e\u{301}/y", "K.txt"],
2650            &["\u{212a}.txt"],
2651            &["a", "*.txt"],
2652            &["dir", ":!dir/sub"],
2653            &[":!a"],
2654            &["./a", "z"],
2655            &[".", "a"],
2656            &["", "a"],
2657            &[":(icase)A/B", "z"],
2658        ];
2659        for ctx in [
2660            PathspecMatchContext::default(),
2661            PathspecMatchContext {
2662                precompose_paths: true,
2663                ..PathspecMatchContext::default()
2664            },
2665            PathspecMatchContext {
2666                is_directory: true,
2667                ..PathspecMatchContext::default()
2668            },
2669        ] {
2670            for list in lists {
2671                let specs: Vec<String> = list.iter().map(|s| (*s).to_owned()).collect();
2672                let matcher = PathspecListMatcher::new(&specs, ctx);
2673                for path in paths {
2674                    assert_eq!(
2675                        matcher.matches(path),
2676                        matches_pathspec_list_with_context(path, &specs, ctx),
2677                        "path {path:?} specs {specs:?} ctx {ctx:?}"
2678                    );
2679                }
2680            }
2681        }
2682    }
2683
2684    #[test]
2685    fn list_matcher_uses_literal_lookup_only_for_plain_lists() {
2686        let ctx = PathspecMatchContext::default();
2687        let plain = vec!["a/b".to_owned(), "dir/".to_owned()];
2688        assert!(PathspecListMatcher::new(&plain, ctx).literals.is_some());
2689        let glob = vec!["a/b".to_owned(), "*.txt".to_owned()];
2690        assert!(PathspecListMatcher::new(&glob, ctx).literals.is_none());
2691        let exclude = vec!["a/b".to_owned(), ":!a/b/c".to_owned()];
2692        assert!(PathspecListMatcher::new(&exclude, ctx).literals.is_none());
2693        assert!(PathspecListMatcher::new(&[], ctx).literals.is_none());
2694    }
2695
2696    #[test]
2697    fn precomposed_literal_specs_keep_fast_lookups() {
2698        let ctx = PathspecMatchContext {
2699            precompose_paths: true,
2700            ..PathspecMatchContext::default()
2701        };
2702        let specs: Vec<String> = (0..100).map(|i| format!("d{i}/file.txt")).collect();
2703        let matcher = PathspecListMatcher::new(&specs, ctx);
2704        assert!(
2705            matcher.literals.is_some(),
2706            "core.precomposeunicode must not force a per-spec scan of every path"
2707        );
2708        assert!(matcher.matches("d42/file.txt"));
2709        assert!(!matcher.matches("d42/other.txt"));
2710        let nfd = vec!["cafe\u{301}".to_owned()];
2711        let matcher = PathspecListMatcher::new(&nfd, ctx);
2712        assert!(matcher.literals.is_some());
2713        assert!(matcher.matches("caf\u{e9}/menu"));
2714        assert!(matcher.matches("cafe\u{301}/menu"));
2715        assert!(exact_literal_pathspec_set(&specs, ctx).is_none());
2716    }
2717
2718    #[test]
2719    fn ls_tree_bracket_in_name_is_literal_prefix() {
2720        assert!(matches_ls_tree_pathspec(
2721            "a[a]",
2722            "a[a]/three",
2723            0o100644,
2724            &[]
2725        ));
2726        assert!(!matches_pathspec_with_context(
2727            "a[a]",
2728            "a[a]/three",
2729            PathspecMatchContext::default()
2730        ));
2731    }
2732
2733    #[test]
2734    fn wildcards_cross_slash_by_default() {
2735        assert!(matches_pathspec("f*", "file0"));
2736        assert!(matches_pathspec("*file1", "path1/file1"));
2737        assert!(matches_pathspec_with_context(
2738            "path1/f*",
2739            "path1",
2740            PathspecMatchContext {
2741                is_directory: true,
2742                ..Default::default()
2743            }
2744        ));
2745        assert!(matches_pathspec("path1/*file1", "path1/file1"));
2746    }
2747
2748    #[test]
2749    fn glob_double_star_txt_at_repo_root() {
2750        assert!(pathspec_matches(":(glob)**/*.txt", "untracked.txt"));
2751        assert!(pathspec_matches(":(glob)**/*.txt", "d/untracked.txt"));
2752    }
2753
2754    #[test]
2755    fn trailing_slash_directory_only() {
2756        assert!(!matches_pathspec_with_context(
2757            "file0/",
2758            "file0",
2759            PathspecMatchContext::default()
2760        ));
2761        assert!(matches_pathspec_with_context(
2762            "file0/",
2763            "file0",
2764            PathspecMatchContext {
2765                is_directory: true,
2766                ..Default::default()
2767            }
2768        ));
2769        assert!(matches_pathspec_with_context(
2770            "submod/",
2771            "submod",
2772            PathspecMatchContext {
2773                is_git_submodule: true,
2774                ..Default::default()
2775            }
2776        ));
2777    }
2778
2779    #[test]
2780    fn exclude_top_short_magic_subtracts_from_positive() {
2781        let specs = vec!["*".to_string(), ":/!sub2".to_string()];
2782        assert!(matches_pathspec_list("sub/file", &specs));
2783        assert!(!matches_pathspec_list("sub2/file", &specs));
2784        assert!(pathspec_exclude_matches(":/!sub2", "sub2/file"));
2785    }
2786}
2787
2788#[cfg(test)]
2789mod exact_literal_pathspec_set_tests {
2790    use super::*;
2791
2792    #[test]
2793    fn exact_literal_pathspec_set_accepts_file_paths() {
2794        let ctx = PathspecMatchContext::default();
2795        let set = exact_literal_pathspec_set(&["large.txt".to_string()], ctx).expect("set");
2796        assert_eq!(set.len(), 1);
2797        assert!(set.contains("large.txt"));
2798    }
2799
2800    #[test]
2801    fn exact_literal_pathspec_set_rejects_directory_trailing_slash() {
2802        let ctx = PathspecMatchContext::default();
2803        assert!(exact_literal_pathspec_set(&["src/".to_string()], ctx).is_none());
2804    }
2805
2806    #[test]
2807    fn exact_literal_pathspec_set_rejects_glob_magic() {
2808        let ctx = PathspecMatchContext::default();
2809        assert!(exact_literal_pathspec_set(&[":(glob)*.rs".to_string()], ctx).is_none());
2810    }
2811}
2812
2813#[cfg(test)]
2814mod pathspec_list_tests {
2815    use super::*;
2816    use crate::crlf::parse_gitattributes_content;
2817
2818    #[test]
2819    fn exclude_removes_paths_matching_icase_positive() {
2820        let specs = vec![
2821            ":(icase)*.txt".to_string(),
2822            ":(exclude)submodule/subsub/*".to_string(),
2823        ];
2824        assert!(path_allowed_by_pathspec_list(&specs, "submodule/g.txt"));
2825        assert!(!path_allowed_by_pathspec_list(
2826            &specs,
2827            "submodule/subsub/e.txt"
2828        ));
2829    }
2830
2831    #[test]
2832    fn prefixed_attr_exclude_removes_matching_child_path() {
2833        let specs = vec![
2834            "sub".to_string(),
2835            ":(exclude,attr:labelB,prefix:sub/)".to_string(),
2836        ];
2837        let exclude_only = vec![":(exclude,attr:labelB,prefix:sub/)".to_string()];
2838        let attrs = parse_gitattributes_content("fileB labelB\n");
2839        assert!(!matches_pathspec_list_for_object(
2840            "sub/fileB",
2841            0o100644,
2842            &attrs,
2843            &specs,
2844        ));
2845        assert!(!matches_pathspec_list_for_object(
2846            "sub/fileB",
2847            0o100644,
2848            &attrs,
2849            &exclude_only,
2850        ));
2851    }
2852}
2853
2854#[cfg(test)]
2855mod resolve_pathspec_tests {
2856    use super::*;
2857
2858    fn wt() -> PathBuf {
2859        PathBuf::from("/tmp/grit-pathspec-worktree")
2860    }
2861
2862    #[test]
2863    fn strips_leading_dot_slash_at_repo_root() {
2864        let wt = wt();
2865        assert_eq!(resolve_pathspec("./-", &wt, None), "-");
2866        assert_eq!(resolve_pathspec("./a/b", &wt, None), "a/b");
2867        assert_eq!(resolve_pathspec("././a", &wt, None), "a");
2868        assert_eq!(resolve_pathspec(".//a", &wt, None), "a");
2869        assert_eq!(resolve_pathspec("./", &wt, None), ".");
2870        assert_eq!(resolve_pathspec(".", &wt, None), ".");
2871    }
2872
2873    #[test]
2874    fn prefixed_cwd_resolution_unchanged() {
2875        let wt = wt();
2876        assert_eq!(
2877            resolve_pathspec("file", &wt, Some("sub/dir")),
2878            "sub/dir/file"
2879        );
2880        assert_eq!(resolve_pathspec(":(glob)*.rs", &wt, None), ":(glob)*.rs");
2881    }
2882
2883    #[test]
2884    fn dot_slash_colon_filename_stays_literal_not_exclude_magic() {
2885        let wt = wt();
2886        let resolved = resolve_pathspec("./:!foo", &wt, None);
2887        assert_eq!(resolved, ":(literal):!foo");
2888        assert!(!pathspec_is_exclude(&resolved));
2889        assert!(pathspec_matches(&resolved, ":!foo"));
2890        assert!(!pathspec_matches(&resolved, "other"));
2891    }
2892
2893    #[test]
2894    fn resolve_absolute_path_under_worktree() {
2895        let tmp = tempfile::tempdir().expect("tempdir");
2896        let wt = tmp.path().join("repo");
2897        std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2898        let file = wt.join("d/b.txt");
2899        std::fs::write(&file, b"x").expect("write");
2900        let wt = wt.canonicalize_simplified().expect("canonicalize");
2901        let abs = file.canonicalize_simplified().expect("canonicalize file");
2902        let spec = abs.to_string_lossy();
2903        assert_eq!(
2904            resolve_pathspec(&spec, &wt, None),
2905            "d/b.txt",
2906            "absolute forward-slash pathspec"
2907        );
2908    }
2909
2910    #[cfg(windows)]
2911    mod windows {
2912        use super::*;
2913
2914        #[test]
2915        fn resolve_backslash_relative_and_absolute_pathspecs() {
2916            let tmp = tempfile::tempdir().expect("tempdir");
2917            let wt = tmp.path().join("repo");
2918            std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2919            let file_a = wt.join("d/a.txt");
2920            let file_b = wt.join("d/b.txt");
2921            std::fs::write(&file_a, b"a").expect("write");
2922            std::fs::write(&file_b, b"b").expect("write");
2923            let wt = wt.canonicalize_simplified().expect("canonicalize worktree");
2924
2925            assert_eq!(
2926                resolve_pathspec(r"d\a.txt", &wt, None),
2927                "d/a.txt",
2928                "backslash relative pathspec (issue #915 A)"
2929            );
2930
2931            let abs_back = file_b.canonicalize_simplified().expect("canonicalize");
2932            let abs_back_spec = abs_back.display().to_string();
2933            assert_eq!(
2934                resolve_pathspec(&abs_back_spec, &wt, None),
2935                "d/b.txt",
2936                "absolute backslash pathspec (issue #915 B)"
2937            );
2938
2939            let abs_forward = abs_back_spec.replace('\\', "/");
2940            assert_eq!(
2941                resolve_pathspec(&abs_forward, &wt, None),
2942                "d/b.txt",
2943                "absolute forward-slash pathspec (issue #915 C)"
2944            );
2945        }
2946    }
2947
2948    #[test]
2949    fn nfd_pathspec_matches_nfc_index_path_when_precompose_enabled() {
2950        let nfc_path = "caf\u{00e9}.txt";
2951        let nfd_spec = format!("cafe\u{0301}.txt");
2952        assert!(!matches_pathspec_list(&nfc_path, &[nfd_spec.clone()]));
2953        assert!(matches_pathspec_list_precompose(
2954            nfc_path,
2955            &[nfd_spec.clone()],
2956            true
2957        ));
2958    }
2959
2960    #[test]
2961    fn argv_precompose_normalizes_nfd_literal_pathspec() {
2962        let nfd = format!("cafe\u{0301}.txt");
2963        let nfc = precompose_argv_pathspec(&nfd);
2964        assert_eq!(nfc.as_ref(), "caf\u{00e9}.txt");
2965        assert!(argv_pathspec_preserves_spelling(":(glob)*.rs"));
2966        assert_eq!(
2967            precompose_argv_pathspec(":(glob)*.rs").as_ref(),
2968            ":(glob)*.rs"
2969        );
2970    }
2971}
2972
2973#[cfg(test)]
2974mod resolved_pathspecs_tests {
2975    use super::*;
2976    use crate::repo::{InitOptions, Repository};
2977
2978    fn repo_with_tree() -> (tempfile::TempDir, Repository) {
2979        let dir = tempfile::tempdir().expect("tempdir");
2980        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
2981        std::fs::write(dir.path().join("top.txt"), b"a").expect("write");
2982        std::fs::create_dir_all(dir.path().join("sub")).expect("mkdir");
2983        std::fs::write(dir.path().join("sub/inner.txt"), b"b").expect("write");
2984        (dir, repo)
2985    }
2986
2987    #[test]
2988    fn resolved_pathspecs_subdir_prefix() {
2989        let (dir, repo) = repo_with_tree();
2990        let sub = dir.path().join("sub");
2991        let resolved =
2992            ResolvedPathspecs::resolve(&repo, &sub, &["inner.txt".to_string()], None).expect("ok");
2993        assert_eq!(resolved.specs, ["sub/inner.txt"]);
2994        assert!(resolved.scoped);
2995    }
2996
2997    #[test]
2998    fn resolved_pathspecs_top_level_magic() {
2999        let (dir, repo) = repo_with_tree();
3000        let resolved =
3001            ResolvedPathspecs::resolve(&repo, dir.path(), &[":/top.txt".to_string()], None)
3002                .expect("ok");
3003        assert_eq!(resolved.specs, ["top.txt"]);
3004    }
3005
3006    #[test]
3007    fn resolved_pathspecs_parent_outside_repo() {
3008        let (dir, repo) = repo_with_tree();
3009        let outside = dir.path().parent().expect("parent").join("outside.txt");
3010        std::fs::write(&outside, b"x").expect("write outside");
3011        let spec = outside.to_string_lossy().into_owned();
3012        let err =
3013            ResolvedPathspecs::resolve(&repo, dir.path(), &[spec], None).expect_err("outside");
3014        assert!(matches!(
3015            err,
3016            PathspecResolveError::OutsideRepository { .. }
3017        ));
3018    }
3019
3020    #[test]
3021    fn resolved_pathspecs_empty_argv() {
3022        let (dir, repo) = repo_with_tree();
3023        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[String::new()], None)
3024            .expect_err("empty");
3025        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3026    }
3027
3028    #[test]
3029    fn resolved_pathspecs_from_file_lf_and_quoted() {
3030        let (dir, repo) = repo_with_tree();
3031        let input = PathspecInput::new(b"top.txt\n\"sub/inner.txt\"\n".to_vec(), false);
3032        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3033        assert_eq!(resolved.specs, ["top.txt", "sub/inner.txt"]);
3034    }
3035
3036    #[test]
3037    fn resolved_pathspecs_from_file_nul() {
3038        let (dir, repo) = repo_with_tree();
3039        let input = PathspecInput::new(b"top.txt\0sub/\0".to_vec(), true);
3040        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3041        assert_eq!(resolved.specs, ["top.txt", "sub/"]);
3042    }
3043
3044    #[test]
3045    fn resolved_pathspecs_from_file_nul_preserves_literal_bytes() {
3046        let (dir, repo) = repo_with_tree();
3047        std::fs::write(dir.path().join("  spaced  "), b"x").expect("write");
3048        let quoted_dir = dir.path().join("\"double\"");
3049        std::fs::create_dir_all(&quoted_dir).expect("mkdir");
3050        std::fs::write(quoted_dir.join("f"), b"y").expect("write");
3051        let input = PathspecInput::new(b"  spaced  \0\"double\"\0".to_vec(), true);
3052        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3053        assert_eq!(resolved.sources, ["  spaced  ", "\"double\""]);
3054    }
3055
3056    #[test]
3057    fn resolved_pathspecs_from_file_blank_line_errors() {
3058        let (dir, repo) = repo_with_tree();
3059        let input = PathspecInput::new(b"\n".to_vec(), false);
3060        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3061        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3062    }
3063
3064    #[test]
3065    fn resolved_pathspecs_from_file_nul_empty_record_errors() {
3066        let (dir, repo) = repo_with_tree();
3067        let input = PathspecInput::new(b"a\0\0b".to_vec(), true);
3068        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3069        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3070    }
3071
3072    #[test]
3073    fn resolved_pathspecs_from_file_invalid_quote() {
3074        let (dir, repo) = repo_with_tree();
3075        let input = PathspecInput::new(b"\"bad\\z\"\n".to_vec(), false);
3076        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3077        assert!(matches!(
3078            err,
3079            PathspecResolveError::FromFile(
3080                PathspecFromFileParseError::InvalidEscapeSequence { .. }
3081            )
3082        ));
3083        let input = PathspecInput::new(b"\"unterminated\n".to_vec(), false);
3084        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3085        assert!(matches!(
3086            err,
3087            PathspecResolveError::FromFile(PathspecFromFileParseError::InvalidCStyleQuoting { .. })
3088        ));
3089    }
3090
3091    #[test]
3092    fn resolved_pathspecs_entire_tree_when_unscoped() {
3093        let (dir, repo) = repo_with_tree();
3094        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], None).expect("ok");
3095        assert!(resolved.is_entire_tree());
3096        assert!(resolved.specs.is_empty());
3097    }
3098}
3099
3100#[cfg(test)]
3101mod resolve_magic_pathspec_tests {
3102    use super::*;
3103
3104    #[test]
3105    fn top_magic_does_not_inject_cwd_prefix() {
3106        assert_eq!(
3107            resolve_magic_pathspec(":(top)a/g.c", "a/b/").expect("magic"),
3108            ":(top)a/g.c"
3109        );
3110        assert_eq!(
3111            resolve_magic_pathspec(":(top,glob)a/**/*.c", "a/b/").expect("magic"),
3112            ":(top,glob)a/**/*.c"
3113        );
3114        assert_eq!(
3115            resolve_magic_pathspec(":(exclude,top)a/b", "a/b/").expect("magic"),
3116            ":(exclude,top)a/b"
3117        );
3118    }
3119
3120    #[test]
3121    fn non_top_magic_still_injects_prefix_from_subdirectory() {
3122        assert_eq!(
3123            resolve_magic_pathspec(":(glob)**/f.txt", "sub/").expect("magic"),
3124            ":(glob,prefix:sub/)**/f.txt"
3125        );
3126        assert_eq!(
3127            resolve_magic_pathspec(":(exclude)vendor", "sub/").expect("magic"),
3128            ":(exclude,prefix:sub/)vendor"
3129        );
3130    }
3131
3132    #[test]
3133    fn resolve_pathspec_top_from_subdirectory() {
3134        let dir = tempfile::tempdir().expect("tempdir");
3135        let wt = dir.path();
3136        std::fs::create_dir_all(wt.join("a/b")).expect("mkdir");
3137        assert_eq!(
3138            resolve_pathspec(":(top)a/g.c", wt, Some("a/b")),
3139            ":(top)a/g.c"
3140        );
3141    }
3142}
3143
3144#[cfg(test)]
3145mod rev_walk_pathspec_resolution_tests {
3146    use super::*;
3147    use crate::config::environment::{Environment, RepositoryOptions};
3148    use crate::repo::{InitOptions, Repository};
3149
3150    fn repo_from_sub(worktree: &std::path::Path, sub: &std::path::Path) -> Repository {
3151        let mut env = Environment::empty();
3152        env.cwd = sub.to_path_buf();
3153        let mut opts = RepositoryOptions::empty();
3154        opts.environment = env;
3155        Repository::discover(Some(worktree), &opts).expect("discover")
3156    }
3157
3158    #[test]
3159    fn glob_magic_from_subdirectory_gets_prefix_and_matches() {
3160        let dir = tempfile::tempdir().expect("tempdir");
3161        let wt = dir.path();
3162        std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3163        std::fs::write(wt.join("sub/f.txt"), b"x").expect("write");
3164        Repository::init(wt, &InitOptions::default()).expect("init");
3165        let repo = repo_from_sub(wt, &wt.join("sub"));
3166        let specs = repo
3167            .resolve_rev_walk_pathspecs(&[":(glob)**/f.txt".to_owned()])
3168            .expect("resolve");
3169        assert_eq!(specs, [":(glob,prefix:sub/)**/f.txt"]);
3170        assert!(pathspec_matches(&specs[0], "sub/f.txt"));
3171        assert!(!pathspec_matches(&specs[0], "other/f.txt"));
3172    }
3173
3174    #[test]
3175    fn short_exclude_from_subdirectory_uses_prefix_magic() {
3176        let dir = tempfile::tempdir().expect("tempdir");
3177        let wt = dir.path();
3178        std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3179        Repository::init(wt, &InitOptions::default()).expect("init");
3180        let repo = repo_from_sub(wt, &wt.join("sub"));
3181        let specs = repo
3182            .resolve_rev_walk_pathspecs(&[":!f.txt".to_owned()])
3183            .expect("resolve");
3184        assert_eq!(specs, [".", ":(exclude,prefix:sub/)f.txt"]);
3185        assert!(matches_pathspec_list("other/g.txt", &specs));
3186        assert!(!matches_pathspec_list("sub/f.txt", &specs));
3187    }
3188
3189    #[test]
3190    fn glob_with_prefix_descends_into_cwd_directory() {
3191        let spec = ":(glob,prefix:sub/)**/f.txt";
3192        assert!(pathspec_wants_descent_into_tree(spec, "sub"));
3193        assert!(pathspec_entry_is_relevant(
3194            "sub/f.txt",
3195            false,
3196            &[spec.to_owned()]
3197        ));
3198    }
3199
3200    #[test]
3201    fn top_magic_from_subdirectory_stays_unprefixed() {
3202        let dir = tempfile::tempdir().expect("tempdir");
3203        let wt = dir.path();
3204        std::fs::create_dir_all(wt.join("a/b")).expect("mkdir");
3205        Repository::init(wt, &InitOptions::default()).expect("init");
3206        let repo = repo_from_sub(wt, &wt.join("a/b"));
3207        let specs = repo
3208            .resolve_rev_walk_pathspecs(&[":(top)a/g.c".to_owned()])
3209            .expect("resolve");
3210        assert_eq!(specs, [":(top)a/g.c"]);
3211        assert!(pathspec_matches(&specs[0], "a/g.c"));
3212        assert!(!pathspec_matches(&specs[0], "a/b/h.c"));
3213    }
3214}