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.
1472pub(crate) fn 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`].
1506pub(crate) fn 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
2105/// Whether `token` is a long-form magic pathspec (`:(...)`) rather than a revision name.
2106#[must_use]
2107pub fn is_long_magic_pathspec_token(token: &str) -> bool {
2108    resolve_magic_pathspec(token, "").is_some()
2109}
2110
2111fn resolve_magic_pathspec_parts(magic_prefix: &str, tail: &str, cwd_prefix: &str) -> String {
2112    if has_magic_prefix_token(magic_prefix) {
2113        return format!("{magic_prefix}{tail}");
2114    }
2115
2116    if let Some(rooted_tail) = tail.strip_prefix('/') {
2117        return format!("{magic_prefix}{}", normalize_relative_path_str(rooted_tail));
2118    }
2119
2120    if long_magic_prefix_has_top(magic_prefix) {
2121        return format!("{magic_prefix}{tail}");
2122    }
2123
2124    let combined = if cwd_prefix.is_empty() {
2125        normalize_relative_path_str(tail)
2126    } else {
2127        normalize_relative_path_str(&format!("{cwd_prefix}{tail}"))
2128    };
2129
2130    let cwd_base = normalize_relative_path_str(cwd_prefix.trim_end_matches('/'));
2131    if !cwd_base.is_empty()
2132        && (combined == cwd_base || combined.starts_with(&format!("{cwd_base}/")))
2133    {
2134        let after_base = combined
2135            .strip_prefix(&cwd_base)
2136            .unwrap_or(combined.as_str());
2137        let remainder = after_base.strip_prefix('/').unwrap_or(after_base);
2138        let magic_with_prefix = inject_magic_prefix_token(magic_prefix, &format!("{cwd_base}/"));
2139        return format!("{magic_with_prefix}{remainder}");
2140    }
2141
2142    format!("{magic_prefix}{combined}")
2143}
2144
2145fn has_magic_prefix_token(magic_prefix: &str) -> bool {
2146    let Some(inner) = magic_prefix
2147        .strip_prefix(":(")
2148        .and_then(|s| s.strip_suffix(')'))
2149    else {
2150        return false;
2151    };
2152    inner
2153        .split(',')
2154        .map(str::trim)
2155        .any(|token| token.starts_with("prefix:"))
2156}
2157
2158fn long_magic_prefix_has_top(magic_prefix: &str) -> bool {
2159    let Some(inner) = magic_prefix
2160        .strip_prefix(":(")
2161        .and_then(|s| s.strip_suffix(')'))
2162    else {
2163        return false;
2164    };
2165    inner
2166        .split(',')
2167        .map(str::trim)
2168        .any(|token| token.eq_ignore_ascii_case("top"))
2169}
2170
2171fn inject_magic_prefix_token(magic_prefix: &str, prefix: &str) -> String {
2172    let Some(inner) = magic_prefix
2173        .strip_prefix(":(")
2174        .and_then(|s| s.strip_suffix(')'))
2175    else {
2176        return magic_prefix.to_string();
2177    };
2178    if inner.trim().is_empty() {
2179        format!(":(prefix:{prefix})")
2180    } else {
2181        format!(":({inner},prefix:{prefix})")
2182    }
2183}
2184
2185/// Drop repeated leading `./` / `.//` from a repo-root pathspec (Git `prefix_path` behavior).
2186///
2187/// When stripping exposes a leading `:`, wrap with `:(literal)` so a filesystem path like
2188/// `:!foo` is not reinterpreted as short exclude magic.
2189fn normalize_repo_root_relative_pathspec(pathspec: &str) -> String {
2190    let mut spec = pathspec;
2191    let mut stripped = false;
2192    while let Some(rest) = spec.strip_prefix("./") {
2193        stripped = true;
2194        spec = rest.trim_start_matches('/');
2195    }
2196    if !stripped {
2197        return pathspec.to_owned();
2198    }
2199    if spec.is_empty() {
2200        return ".".to_owned();
2201    }
2202    if spec.starts_with(':') && !literal_pathspecs_enabled() {
2203        return format!(":(literal){spec}");
2204    }
2205    spec.to_owned()
2206}
2207
2208/// Normalize user pathspec separators on Windows (`\` → `/`) before resolution.
2209fn normalize_pathspec_separators(pathspec: &str) -> std::borrow::Cow<'_, str> {
2210    #[cfg(windows)]
2211    {
2212        if !pathspec.starts_with(':') && pathspec.contains('\\') {
2213            return std::borrow::Cow::Owned(pathspec.replace('\\', "/"));
2214        }
2215    }
2216    std::borrow::Cow::Borrowed(pathspec)
2217}
2218
2219fn normalize_relative_path_str(path: &str) -> String {
2220    let mut parts: Vec<String> = Vec::new();
2221    for component in std::path::Path::new(path).components() {
2222        match component {
2223            std::path::Component::CurDir => {}
2224            std::path::Component::ParentDir => {
2225                parts.pop();
2226            }
2227            std::path::Component::Normal(seg) => {
2228                parts.push(seg.to_string_lossy().to_string());
2229            }
2230            std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
2231        }
2232    }
2233    parts.join("/")
2234}
2235
2236/// Current directory relative to `work_tree`, or `None` if cwd is the work tree root.
2237#[must_use]
2238pub fn pathdiff(cwd: &Path, work_tree: &Path) -> Option<String> {
2239    use crate::git_path::{path_for_disk_compare, path_to_git_slash};
2240
2241    let cwd_cmp = path_for_disk_compare(cwd);
2242    let wt_cmp = path_for_disk_compare(work_tree);
2243
2244    if cwd_cmp == wt_cmp {
2245        return None;
2246    }
2247
2248    let rel = cwd_cmp.strip_prefix(&wt_cmp).ok()?;
2249    let git = path_to_git_slash(rel);
2250    if git.is_empty() {
2251        None
2252    } else {
2253        Some(git)
2254    }
2255}
2256
2257/// For short exclude magic from a subdirectory, Git applies the worktree prefix to the pattern
2258/// tail (via `prefix_path`) while keeping argv spelling. Long-form `:(exclude,prefix:…)` matches
2259/// [`resolve_worktree_pathspec`] for `:(exclude)…` under a cwd prefix.
2260fn prepend_cwd_to_short_exclude_pathspec(spec: &str, cwd: &str) -> Option<String> {
2261    let cwd = cwd.trim_end_matches('/');
2262    if cwd.is_empty() {
2263        return None;
2264    }
2265    let (elem_magic, pattern) = parse_element_magic(spec);
2266    let magic = combine_magic(elem_magic);
2267    if !magic.exclude || magic.top {
2268        return None;
2269    }
2270    if pattern.is_empty() || pattern.starts_with('/') {
2271        return None;
2272    }
2273    if magic.glob || magic.literal || magic.icase || !magic.attr_requirements.is_empty() {
2274        return None;
2275    }
2276    Some(format!(":(exclude,prefix:{cwd}/){pattern}"))
2277}
2278
2279/// Build [`PathspecMatchContext`] with optional NFC path normalization for comparisons.
2280#[must_use]
2281pub fn pathspec_match_context_with_precompose(precompose_paths: bool) -> PathspecMatchContext {
2282    PathspecMatchContext {
2283        precompose_paths,
2284        ..PathspecMatchContext::default()
2285    }
2286}
2287
2288/// Like [`matches_pathspec_list`], with an explicit `precompose_paths` flag.
2289#[must_use]
2290pub fn matches_pathspec_list_precompose(
2291    path: &str,
2292    specs: &[String],
2293    precompose_paths: bool,
2294) -> bool {
2295    matches_pathspec_list_with_context(
2296        path,
2297        specs,
2298        pathspec_match_context_with_precompose(precompose_paths),
2299    )
2300}
2301
2302/// True when argv pathspec strings must not be NFC-normalized (magic syntax).
2303#[must_use]
2304pub fn argv_pathspec_preserves_spelling(pathspec: &str) -> bool {
2305    pathspec.starts_with(":(")
2306        || pathspec.starts_with(":/")
2307        || pathspec.starts_with(":!")
2308        || pathspec.starts_with(":^")
2309}
2310
2311/// NFC-normalize a literal command-line pathspec (Git `precompose_argv_prefix`).
2312#[must_use]
2313pub fn precompose_argv_pathspec(pathspec: &str) -> Cow<'_, str> {
2314    if argv_pathspec_preserves_spelling(pathspec) {
2315        Cow::Borrowed(pathspec)
2316    } else {
2317        precompose_utf8_path(pathspec)
2318    }
2319}
2320
2321/// Resolve a pathspec string to a path relative to the repository work tree.
2322///
2323/// `prefix` is the current directory relative to the work tree (no trailing slash),
2324/// or `None` when cwd is the work tree root.
2325#[must_use]
2326pub fn resolve_pathspec(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2327    resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, false)
2328}
2329
2330/// Like [`resolve_pathspec`], but NFC-normalizes literal argv path segments when requested.
2331#[must_use]
2332pub fn resolve_pathspec_with_argv_precompose(
2333    pathspec: &str,
2334    work_tree: &Path,
2335    prefix: Option<&str>,
2336    argv_precompose: bool,
2337) -> String {
2338    let pathspec = if argv_precompose {
2339        precompose_argv_pathspec(pathspec)
2340    } else {
2341        Cow::Borrowed(pathspec)
2342    };
2343    resolve_pathspec_impl(pathspec.as_ref(), work_tree, prefix)
2344}
2345
2346fn resolve_pathspec_impl(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2347    let pathspec = normalize_pathspec_separators(pathspec);
2348    let pathspec = pathspec.as_ref();
2349    // Git: `.` at repo root means "match the whole tree" (not an empty pathspec).
2350    // An empty resolved pathspec would match nothing and breaks `grep -- . t` max-depth.
2351    if pathspec == "." {
2352        return match prefix {
2353            Some(p) if !p.is_empty() => p.to_owned(),
2354            _ => ".".to_owned(),
2355        };
2356    }
2357    if pathspec.contains("../") || pathspec.starts_with("../") {
2358        let cwd = match prefix.filter(|p| !p.is_empty()) {
2359            Some(p) => work_tree.join(p),
2360            None => work_tree.to_path_buf(),
2361        };
2362        let abs = cwd.join(pathspec);
2363        let mut parts: Vec<std::ffi::OsString> = Vec::new();
2364        for component in abs.components() {
2365            use std::path::Component;
2366            match component {
2367                Component::ParentDir => {
2368                    parts.pop();
2369                }
2370                Component::CurDir => {}
2371                other => parts.push(other.as_os_str().to_os_string()),
2372            }
2373        }
2374        let abs_norm: PathBuf = parts.iter().collect();
2375        if let Some(rel) = crate::git_path::strip_worktree_prefix(&abs_norm, work_tree) {
2376            return rel;
2377        }
2378    }
2379    if Path::new(pathspec).is_absolute() {
2380        let abs = Path::new(pathspec);
2381        if let Some(rel) = crate::git_path::strip_worktree_prefix(abs, work_tree) {
2382            return rel;
2383        }
2384        return pathspec.to_owned();
2385    }
2386
2387    if pathspec.starts_with(':') {
2388        if let Some(p) = prefix {
2389            if !p.is_empty() && !literal_pathspecs_enabled() {
2390                let cwd_ps = format!("{}/", p.trim_end_matches('/'));
2391                if pathspec.starts_with(":(") {
2392                    if pathspec_has_top(pathspec) {
2393                        return pathspec.to_owned();
2394                    }
2395                    if let Some(resolved) = resolve_magic_pathspec(pathspec, &cwd_ps) {
2396                        return resolved;
2397                    }
2398                    return pathspec.to_owned();
2399                }
2400                if pathspec_is_exclude(pathspec) {
2401                    if let Some(fixed) = prepend_cwd_to_short_exclude_pathspec(pathspec, p) {
2402                        return fixed;
2403                    }
2404                }
2405            }
2406        }
2407        if let Some(rest) = pathspec.strip_prefix(":/") {
2408            // `:/!foo` / `:/^bar` — `:/` is `:(top)`; the tail is still short magic, not a literal path.
2409            if rest.starts_with('!') || rest.starts_with('^') {
2410                return pathspec.to_owned();
2411            }
2412            return rest.to_owned();
2413        }
2414        // Long magic `:(...)` must stay intact — `:(exclude)path` is not the same as `path`
2415        // (t6132-pathspec-exclude, grep --untracked with exclude pathspecs).
2416        if pathspec.starts_with(":(") {
2417            return pathspec.to_owned();
2418        }
2419        return pathspec.to_owned();
2420    }
2421
2422    match prefix {
2423        Some(p) if !p.is_empty() => {
2424            normalize_relative_path_str(&PathBuf::from(p).join(pathspec).to_string_lossy())
2425        }
2426        _ => normalize_repo_root_relative_pathspec(pathspec),
2427    }
2428}
2429
2430/// Resolve a pathspec and ensure it lies inside `work_tree` (used by `git add`, etc.).
2431///
2432/// Returns [`PathOutsideRepository`] when resolution stays absolute, matching Git's
2433/// `'%s' is outside repository at '%s'` fatal (t7010).
2434pub fn resolve_pathspec_in_worktree(
2435    elt: &str,
2436    pathspec: &str,
2437    work_tree: &Path,
2438    prefix: Option<&str>,
2439) -> Result<String, PathOutsideRepository> {
2440    resolve_pathspec_in_worktree_with_argv_precompose(elt, pathspec, work_tree, prefix, false)
2441}
2442
2443/// Like [`resolve_pathspec_in_worktree`], NFC-normalizing `pathspec` when `argv_precompose` is set.
2444///
2445/// Callers holding a [`Repository`] should use [`Repository::resolve_worktree_pathspec`], which
2446/// computes `argv_precompose` once per handle instead of reloading config per pathspec.
2447pub(crate) fn resolve_pathspec_in_worktree_with_argv_precompose(
2448    elt: &str,
2449    pathspec: &str,
2450    work_tree: &Path,
2451    prefix: Option<&str>,
2452    argv_precompose: bool,
2453) -> Result<String, PathOutsideRepository> {
2454    let resolved =
2455        resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, argv_precompose);
2456    if Path::new(&resolved).is_absolute() {
2457        let wt = work_tree
2458            .canonicalize_simplified()
2459            .unwrap_or_else(|_| work_tree.to_path_buf());
2460        return Err(PathOutsideRepository {
2461            elt: elt.to_string(),
2462            path: resolved,
2463            work_tree: wt,
2464        });
2465    }
2466    Ok(resolved)
2467}
2468
2469/// Normalize a worktree file path for porcelain commands (`blame`, `log`, …).
2470///
2471/// Accepts repo-relative or absolute paths under `work_tree`.
2472#[must_use]
2473pub fn normalize_worktree_file_path(
2474    file_path: &str,
2475    work_tree: &Path,
2476    prefix: Option<&str>,
2477) -> String {
2478    normalize_worktree_file_path_with_git_dir(file_path, work_tree, prefix, None)
2479}
2480
2481/// Like [`normalize_worktree_file_path`], honoring `core.precomposeunicode` argv normalization for `git_dir`.
2482#[must_use]
2483pub fn normalize_worktree_file_path_with_git_dir(
2484    file_path: &str,
2485    work_tree: &Path,
2486    prefix: Option<&str>,
2487    git_dir: Option<&Path>,
2488) -> String {
2489    let argv_precompose = argv_precompose_enabled(git_dir);
2490    let resolved =
2491        resolve_pathspec_with_argv_precompose(file_path, work_tree, prefix, argv_precompose);
2492    if Path::new(&resolved).is_absolute() {
2493        file_path.to_string()
2494    } else {
2495        resolved
2496    }
2497}
2498
2499#[cfg(test)]
2500mod tree_entry_pathspec_tests {
2501    use super::*;
2502
2503    #[test]
2504    fn t6130_bracket_filename_matches_pathspec() {
2505        assert!(matches_pathspec("f[o][o]", "f[o][o]"));
2506        assert!(matches_pathspec(":(glob)f[o][o]", "f[o][o]"));
2507    }
2508
2509    #[test]
2510    fn literal_prefix_and_exact() {
2511        assert!(matches_pathspec("path1", "path1/file1"));
2512        assert!(matches_pathspec_with_context(
2513            "path1/",
2514            "path1/file1",
2515            PathspecMatchContext::default()
2516        ));
2517        assert!(matches_pathspec("file0", "file0"));
2518        assert!(!matches_pathspec("path", "path1/file1"));
2519    }
2520
2521    #[test]
2522    fn dir_prefix_needs_slash_boundary() {
2523        assert!(matches_pathspec("a/b", "a/b/c"));
2524        assert!(!matches_pathspec("a/b", "a/bc"));
2525        assert!(!matches_pathspec("a/b", "a"));
2526        assert!(matches_pathspec(":(literal)dir", "dir/x"));
2527        assert!(!matches_pathspec(":(literal)dir", "dirx"));
2528        assert!(matches_pathspec(":(icase)DIR", "dir/x"));
2529        assert!(!matches_pathspec(":(icase)DIR", "dirx"));
2530        assert!(matches_pathspec("dir/", "dir/x"));
2531        assert!(!matches_pathspec("dir/", "dir"));
2532    }
2533
2534    #[test]
2535    fn sorted_lookup_agrees_with_linear_scan() {
2536        let mut paths: Vec<&str> = vec![
2537            "a",
2538            "a-b",
2539            "a.txt",
2540            "a/b",
2541            "a/b/c.txt",
2542            "a/bc",
2543            "a0",
2544            "b/x[1].txt",
2545            "dir/sub/file",
2546            "dir-sub",
2547            "f[o][o]",
2548            "z",
2549            "caf\u{e9}/menu",
2550            "cafe\u{301}/old",
2551            "\u{212a}.txt",
2552        ];
2553        paths.sort_unstable();
2554        let specs = [
2555            "caf\u{e9}",
2556            "cafe\u{301}/",
2557            "cafe\u{301}/old",
2558            "K.txt",
2559            "\u{212a}.txt",
2560            "a",
2561            "a/",
2562            "a/b",
2563            "a/b/",
2564            "a/bc",
2565            "a-",
2566            "a-b",
2567            "a.txt",
2568            "b",
2569            "b/",
2570            "dir",
2571            "dir/sub",
2572            "dir/sub/",
2573            "dir/su",
2574            "dir-sub",
2575            "f[o][o]",
2576            "*.txt",
2577            "a/*",
2578            ":(glob)**/*.txt",
2579            ":(literal)f[o][o]",
2580            ":(icase)A/B",
2581            ":!a",
2582            ".",
2583            "./a/b",
2584            "",
2585            "z",
2586            "zz",
2587            "/",
2588            "a//",
2589        ];
2590        for ctx in [
2591            PathspecMatchContext::default(),
2592            PathspecMatchContext {
2593                precompose_paths: true,
2594                ..PathspecMatchContext::default()
2595            },
2596            PathspecMatchContext {
2597                is_directory: true,
2598                ..PathspecMatchContext::default()
2599            },
2600        ] {
2601            for spec in specs {
2602                let list = [spec.to_owned()];
2603                let linear = paths
2604                    .iter()
2605                    .any(|p| matches_pathspec_list_with_context(p, &list, ctx));
2606                assert_eq!(
2607                    sorted_paths_match_pathspec(spec, &paths, ctx),
2608                    linear,
2609                    "spec {spec:?} ctx {ctx:?}"
2610                );
2611            }
2612        }
2613        let empty: [&str; 0] = [];
2614        assert!(!sorted_paths_match_pathspec(
2615            "a",
2616            &empty,
2617            PathspecMatchContext::default()
2618        ));
2619    }
2620
2621    #[test]
2622    fn list_matcher_agrees_with_linear_matching() {
2623        let paths = [
2624            "a",
2625            "a-b",
2626            "a.txt",
2627            "a/",
2628            "a/b",
2629            "a/b/c.txt",
2630            "a/bc",
2631            "a//x",
2632            "a0",
2633            "b/x[1].txt",
2634            "dir/sub/file",
2635            "dir-sub",
2636            "f[o][o]",
2637            "z",
2638            "zz/a",
2639            "é/x",
2640            "e\u{301}/y",
2641            "\u{212a}.txt",
2642            "K.txt",
2643            "",
2644        ];
2645        let lists: &[&[&str]] = &[
2646            &[],
2647            &["a"],
2648            &["a/"],
2649            &["a//"],
2650            &["a/b", "dir/sub/", "z"],
2651            &["a/b/", "a/bc", "dir", "zz"],
2652            &["dir/su", "dir-sub", "f[o][o]"],
2653            &["é", "a-"],
2654            &["e\u{301}", "z"],
2655            &["e\u{301}/y", "K.txt"],
2656            &["\u{212a}.txt"],
2657            &["a", "*.txt"],
2658            &["dir", ":!dir/sub"],
2659            &[":!a"],
2660            &["./a", "z"],
2661            &[".", "a"],
2662            &["", "a"],
2663            &[":(icase)A/B", "z"],
2664        ];
2665        for ctx in [
2666            PathspecMatchContext::default(),
2667            PathspecMatchContext {
2668                precompose_paths: true,
2669                ..PathspecMatchContext::default()
2670            },
2671            PathspecMatchContext {
2672                is_directory: true,
2673                ..PathspecMatchContext::default()
2674            },
2675        ] {
2676            for list in lists {
2677                let specs: Vec<String> = list.iter().map(|s| (*s).to_owned()).collect();
2678                let matcher = PathspecListMatcher::new(&specs, ctx);
2679                for path in paths {
2680                    assert_eq!(
2681                        matcher.matches(path),
2682                        matches_pathspec_list_with_context(path, &specs, ctx),
2683                        "path {path:?} specs {specs:?} ctx {ctx:?}"
2684                    );
2685                }
2686            }
2687        }
2688    }
2689
2690    #[test]
2691    fn list_matcher_uses_literal_lookup_only_for_plain_lists() {
2692        let ctx = PathspecMatchContext::default();
2693        let plain = vec!["a/b".to_owned(), "dir/".to_owned()];
2694        assert!(PathspecListMatcher::new(&plain, ctx).literals.is_some());
2695        let glob = vec!["a/b".to_owned(), "*.txt".to_owned()];
2696        assert!(PathspecListMatcher::new(&glob, ctx).literals.is_none());
2697        let exclude = vec!["a/b".to_owned(), ":!a/b/c".to_owned()];
2698        assert!(PathspecListMatcher::new(&exclude, ctx).literals.is_none());
2699        assert!(PathspecListMatcher::new(&[], ctx).literals.is_none());
2700    }
2701
2702    #[test]
2703    fn precomposed_literal_specs_keep_fast_lookups() {
2704        let ctx = PathspecMatchContext {
2705            precompose_paths: true,
2706            ..PathspecMatchContext::default()
2707        };
2708        let specs: Vec<String> = (0..100).map(|i| format!("d{i}/file.txt")).collect();
2709        let matcher = PathspecListMatcher::new(&specs, ctx);
2710        assert!(
2711            matcher.literals.is_some(),
2712            "core.precomposeunicode must not force a per-spec scan of every path"
2713        );
2714        assert!(matcher.matches("d42/file.txt"));
2715        assert!(!matcher.matches("d42/other.txt"));
2716        let nfd = vec!["cafe\u{301}".to_owned()];
2717        let matcher = PathspecListMatcher::new(&nfd, ctx);
2718        assert!(matcher.literals.is_some());
2719        assert!(matcher.matches("caf\u{e9}/menu"));
2720        assert!(matcher.matches("cafe\u{301}/menu"));
2721        assert!(exact_literal_pathspec_set(&specs, ctx).is_none());
2722    }
2723
2724    #[test]
2725    fn ls_tree_bracket_in_name_is_literal_prefix() {
2726        assert!(matches_ls_tree_pathspec(
2727            "a[a]",
2728            "a[a]/three",
2729            0o100644,
2730            &[]
2731        ));
2732        assert!(!matches_pathspec_with_context(
2733            "a[a]",
2734            "a[a]/three",
2735            PathspecMatchContext::default()
2736        ));
2737    }
2738
2739    #[test]
2740    fn wildcards_cross_slash_by_default() {
2741        assert!(matches_pathspec("f*", "file0"));
2742        assert!(matches_pathspec("*file1", "path1/file1"));
2743        assert!(matches_pathspec_with_context(
2744            "path1/f*",
2745            "path1",
2746            PathspecMatchContext {
2747                is_directory: true,
2748                ..Default::default()
2749            }
2750        ));
2751        assert!(matches_pathspec("path1/*file1", "path1/file1"));
2752    }
2753
2754    #[test]
2755    fn glob_double_star_txt_at_repo_root() {
2756        assert!(pathspec_matches(":(glob)**/*.txt", "untracked.txt"));
2757        assert!(pathspec_matches(":(glob)**/*.txt", "d/untracked.txt"));
2758    }
2759
2760    #[test]
2761    fn trailing_slash_directory_only() {
2762        assert!(!matches_pathspec_with_context(
2763            "file0/",
2764            "file0",
2765            PathspecMatchContext::default()
2766        ));
2767        assert!(matches_pathspec_with_context(
2768            "file0/",
2769            "file0",
2770            PathspecMatchContext {
2771                is_directory: true,
2772                ..Default::default()
2773            }
2774        ));
2775        assert!(matches_pathspec_with_context(
2776            "submod/",
2777            "submod",
2778            PathspecMatchContext {
2779                is_git_submodule: true,
2780                ..Default::default()
2781            }
2782        ));
2783    }
2784
2785    #[test]
2786    fn exclude_top_short_magic_subtracts_from_positive() {
2787        let specs = vec!["*".to_string(), ":/!sub2".to_string()];
2788        assert!(matches_pathspec_list("sub/file", &specs));
2789        assert!(!matches_pathspec_list("sub2/file", &specs));
2790        assert!(pathspec_exclude_matches(":/!sub2", "sub2/file"));
2791    }
2792}
2793
2794#[cfg(test)]
2795mod exact_literal_pathspec_set_tests {
2796    use super::*;
2797
2798    #[test]
2799    fn exact_literal_pathspec_set_accepts_file_paths() {
2800        let ctx = PathspecMatchContext::default();
2801        let set = exact_literal_pathspec_set(&["large.txt".to_string()], ctx).expect("set");
2802        assert_eq!(set.len(), 1);
2803        assert!(set.contains("large.txt"));
2804    }
2805
2806    #[test]
2807    fn exact_literal_pathspec_set_rejects_directory_trailing_slash() {
2808        let ctx = PathspecMatchContext::default();
2809        assert!(exact_literal_pathspec_set(&["src/".to_string()], ctx).is_none());
2810    }
2811
2812    #[test]
2813    fn exact_literal_pathspec_set_rejects_glob_magic() {
2814        let ctx = PathspecMatchContext::default();
2815        assert!(exact_literal_pathspec_set(&[":(glob)*.rs".to_string()], ctx).is_none());
2816    }
2817}
2818
2819#[cfg(test)]
2820mod pathspec_list_tests {
2821    use super::*;
2822    use crate::crlf::parse_gitattributes_content;
2823
2824    #[test]
2825    fn exclude_removes_paths_matching_icase_positive() {
2826        let specs = vec![
2827            ":(icase)*.txt".to_string(),
2828            ":(exclude)submodule/subsub/*".to_string(),
2829        ];
2830        assert!(path_allowed_by_pathspec_list(&specs, "submodule/g.txt"));
2831        assert!(!path_allowed_by_pathspec_list(
2832            &specs,
2833            "submodule/subsub/e.txt"
2834        ));
2835    }
2836
2837    #[test]
2838    fn prefixed_attr_exclude_removes_matching_child_path() {
2839        let specs = vec![
2840            "sub".to_string(),
2841            ":(exclude,attr:labelB,prefix:sub/)".to_string(),
2842        ];
2843        let exclude_only = vec![":(exclude,attr:labelB,prefix:sub/)".to_string()];
2844        let attrs = parse_gitattributes_content("fileB labelB\n");
2845        assert!(!matches_pathspec_list_for_object(
2846            "sub/fileB",
2847            0o100644,
2848            &attrs,
2849            &specs,
2850        ));
2851        assert!(!matches_pathspec_list_for_object(
2852            "sub/fileB",
2853            0o100644,
2854            &attrs,
2855            &exclude_only,
2856        ));
2857    }
2858}
2859
2860#[cfg(test)]
2861mod resolve_pathspec_tests {
2862    use super::*;
2863
2864    fn wt() -> PathBuf {
2865        PathBuf::from("/tmp/grit-pathspec-worktree")
2866    }
2867
2868    #[test]
2869    fn strips_leading_dot_slash_at_repo_root() {
2870        let wt = wt();
2871        assert_eq!(resolve_pathspec("./-", &wt, None), "-");
2872        assert_eq!(resolve_pathspec("./a/b", &wt, None), "a/b");
2873        assert_eq!(resolve_pathspec("././a", &wt, None), "a");
2874        assert_eq!(resolve_pathspec(".//a", &wt, None), "a");
2875        assert_eq!(resolve_pathspec("./", &wt, None), ".");
2876        assert_eq!(resolve_pathspec(".", &wt, None), ".");
2877    }
2878
2879    #[test]
2880    fn prefixed_cwd_resolution_unchanged() {
2881        let wt = wt();
2882        assert_eq!(
2883            resolve_pathspec("file", &wt, Some("sub/dir")),
2884            "sub/dir/file"
2885        );
2886        assert_eq!(resolve_pathspec(":(glob)*.rs", &wt, None), ":(glob)*.rs");
2887    }
2888
2889    #[test]
2890    fn dot_slash_colon_filename_stays_literal_not_exclude_magic() {
2891        let wt = wt();
2892        let resolved = resolve_pathspec("./:!foo", &wt, None);
2893        assert_eq!(resolved, ":(literal):!foo");
2894        assert!(!pathspec_is_exclude(&resolved));
2895        assert!(pathspec_matches(&resolved, ":!foo"));
2896        assert!(!pathspec_matches(&resolved, "other"));
2897    }
2898
2899    #[test]
2900    fn resolve_absolute_path_under_worktree() {
2901        let tmp = tempfile::tempdir().expect("tempdir");
2902        let wt = tmp.path().join("repo");
2903        std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2904        let file = wt.join("d/b.txt");
2905        std::fs::write(&file, b"x").expect("write");
2906        let wt = wt.canonicalize_simplified().expect("canonicalize");
2907        let abs = file.canonicalize_simplified().expect("canonicalize file");
2908        let spec = abs.to_string_lossy();
2909        assert_eq!(
2910            resolve_pathspec(&spec, &wt, None),
2911            "d/b.txt",
2912            "absolute forward-slash pathspec"
2913        );
2914    }
2915
2916    #[cfg(windows)]
2917    mod windows {
2918        use super::*;
2919
2920        #[test]
2921        fn resolve_backslash_relative_and_absolute_pathspecs() {
2922            let tmp = tempfile::tempdir().expect("tempdir");
2923            let wt = tmp.path().join("repo");
2924            std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2925            let file_a = wt.join("d/a.txt");
2926            let file_b = wt.join("d/b.txt");
2927            std::fs::write(&file_a, b"a").expect("write");
2928            std::fs::write(&file_b, b"b").expect("write");
2929            let wt = wt.canonicalize_simplified().expect("canonicalize worktree");
2930
2931            assert_eq!(
2932                resolve_pathspec(r"d\a.txt", &wt, None),
2933                "d/a.txt",
2934                "backslash relative pathspec (issue #915 A)"
2935            );
2936
2937            let abs_back = file_b.canonicalize_simplified().expect("canonicalize");
2938            let abs_back_spec = abs_back.display().to_string();
2939            assert_eq!(
2940                resolve_pathspec(&abs_back_spec, &wt, None),
2941                "d/b.txt",
2942                "absolute backslash pathspec (issue #915 B)"
2943            );
2944
2945            let abs_forward = abs_back_spec.replace('\\', "/");
2946            assert_eq!(
2947                resolve_pathspec(&abs_forward, &wt, None),
2948                "d/b.txt",
2949                "absolute forward-slash pathspec (issue #915 C)"
2950            );
2951        }
2952    }
2953
2954    #[test]
2955    fn nfd_pathspec_matches_nfc_index_path_when_precompose_enabled() {
2956        let nfc_path = "caf\u{00e9}.txt";
2957        let nfd_spec = format!("cafe\u{0301}.txt");
2958        assert!(!matches_pathspec_list(&nfc_path, &[nfd_spec.clone()]));
2959        assert!(matches_pathspec_list_precompose(
2960            nfc_path,
2961            &[nfd_spec.clone()],
2962            true
2963        ));
2964    }
2965
2966    #[test]
2967    fn argv_precompose_normalizes_nfd_literal_pathspec() {
2968        let nfd = format!("cafe\u{0301}.txt");
2969        let nfc = precompose_argv_pathspec(&nfd);
2970        assert_eq!(nfc.as_ref(), "caf\u{00e9}.txt");
2971        assert!(argv_pathspec_preserves_spelling(":(glob)*.rs"));
2972        assert_eq!(
2973            precompose_argv_pathspec(":(glob)*.rs").as_ref(),
2974            ":(glob)*.rs"
2975        );
2976    }
2977}
2978
2979#[cfg(test)]
2980mod resolved_pathspecs_tests {
2981    use super::*;
2982    use crate::repo::{InitOptions, Repository};
2983
2984    fn repo_with_tree() -> (tempfile::TempDir, Repository) {
2985        let dir = tempfile::tempdir().expect("tempdir");
2986        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
2987        std::fs::write(dir.path().join("top.txt"), b"a").expect("write");
2988        std::fs::create_dir_all(dir.path().join("sub")).expect("mkdir");
2989        std::fs::write(dir.path().join("sub/inner.txt"), b"b").expect("write");
2990        (dir, repo)
2991    }
2992
2993    #[test]
2994    fn resolved_pathspecs_subdir_prefix() {
2995        let (dir, repo) = repo_with_tree();
2996        let sub = dir.path().join("sub");
2997        let resolved =
2998            ResolvedPathspecs::resolve(&repo, &sub, &["inner.txt".to_string()], None).expect("ok");
2999        assert_eq!(resolved.specs, ["sub/inner.txt"]);
3000        assert!(resolved.scoped);
3001    }
3002
3003    #[test]
3004    fn resolved_pathspecs_top_level_magic() {
3005        let (dir, repo) = repo_with_tree();
3006        let resolved =
3007            ResolvedPathspecs::resolve(&repo, dir.path(), &[":/top.txt".to_string()], None)
3008                .expect("ok");
3009        assert_eq!(resolved.specs, ["top.txt"]);
3010    }
3011
3012    #[test]
3013    fn resolved_pathspecs_parent_outside_repo() {
3014        let (dir, repo) = repo_with_tree();
3015        let outside = dir.path().parent().expect("parent").join("outside.txt");
3016        std::fs::write(&outside, b"x").expect("write outside");
3017        let spec = outside.to_string_lossy().into_owned();
3018        let err =
3019            ResolvedPathspecs::resolve(&repo, dir.path(), &[spec], None).expect_err("outside");
3020        assert!(matches!(
3021            err,
3022            PathspecResolveError::OutsideRepository { .. }
3023        ));
3024    }
3025
3026    #[test]
3027    fn resolved_pathspecs_empty_argv() {
3028        let (dir, repo) = repo_with_tree();
3029        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[String::new()], None)
3030            .expect_err("empty");
3031        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3032    }
3033
3034    #[test]
3035    fn resolved_pathspecs_from_file_lf_and_quoted() {
3036        let (dir, repo) = repo_with_tree();
3037        let input = PathspecInput::new(b"top.txt\n\"sub/inner.txt\"\n".to_vec(), false);
3038        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3039        assert_eq!(resolved.specs, ["top.txt", "sub/inner.txt"]);
3040    }
3041
3042    #[test]
3043    fn resolved_pathspecs_from_file_nul() {
3044        let (dir, repo) = repo_with_tree();
3045        let input = PathspecInput::new(b"top.txt\0sub/\0".to_vec(), true);
3046        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3047        assert_eq!(resolved.specs, ["top.txt", "sub/"]);
3048    }
3049
3050    #[test]
3051    fn resolved_pathspecs_from_file_nul_preserves_literal_bytes() {
3052        let (dir, repo) = repo_with_tree();
3053        std::fs::write(dir.path().join("  spaced  "), b"x").expect("write");
3054        let quoted_dir = dir.path().join("\"double\"");
3055        std::fs::create_dir_all(&quoted_dir).expect("mkdir");
3056        std::fs::write(quoted_dir.join("f"), b"y").expect("write");
3057        let input = PathspecInput::new(b"  spaced  \0\"double\"\0".to_vec(), true);
3058        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3059        assert_eq!(resolved.sources, ["  spaced  ", "\"double\""]);
3060    }
3061
3062    #[test]
3063    fn resolved_pathspecs_from_file_blank_line_errors() {
3064        let (dir, repo) = repo_with_tree();
3065        let input = PathspecInput::new(b"\n".to_vec(), false);
3066        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3067        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3068    }
3069
3070    #[test]
3071    fn resolved_pathspecs_from_file_nul_empty_record_errors() {
3072        let (dir, repo) = repo_with_tree();
3073        let input = PathspecInput::new(b"a\0\0b".to_vec(), true);
3074        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3075        assert_eq!(err, PathspecResolveError::EmptyPathspec);
3076    }
3077
3078    #[test]
3079    fn resolved_pathspecs_from_file_invalid_quote() {
3080        let (dir, repo) = repo_with_tree();
3081        let input = PathspecInput::new(b"\"bad\\z\"\n".to_vec(), false);
3082        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3083        assert!(matches!(
3084            err,
3085            PathspecResolveError::FromFile(
3086                PathspecFromFileParseError::InvalidEscapeSequence { .. }
3087            )
3088        ));
3089        let input = PathspecInput::new(b"\"unterminated\n".to_vec(), false);
3090        let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3091        assert!(matches!(
3092            err,
3093            PathspecResolveError::FromFile(PathspecFromFileParseError::InvalidCStyleQuoting { .. })
3094        ));
3095    }
3096
3097    #[test]
3098    fn resolved_pathspecs_entire_tree_when_unscoped() {
3099        let (dir, repo) = repo_with_tree();
3100        let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], None).expect("ok");
3101        assert!(resolved.is_entire_tree());
3102        assert!(resolved.specs.is_empty());
3103    }
3104}
3105
3106#[cfg(test)]
3107mod resolve_magic_pathspec_tests {
3108    use super::*;
3109
3110    #[test]
3111    fn long_magic_token_predicate() {
3112        assert!(is_long_magic_pathspec_token(":(attr:rust)"));
3113        assert!(!is_long_magic_pathspec_token(":0:file"));
3114        assert!(!is_long_magic_pathspec_token("main"));
3115    }
3116
3117    #[test]
3118    fn top_magic_does_not_inject_cwd_prefix() {
3119        assert_eq!(
3120            resolve_magic_pathspec(":(top)a/g.c", "a/b/").expect("magic"),
3121            ":(top)a/g.c"
3122        );
3123        assert_eq!(
3124            resolve_magic_pathspec(":(top,glob)a/**/*.c", "a/b/").expect("magic"),
3125            ":(top,glob)a/**/*.c"
3126        );
3127        assert_eq!(
3128            resolve_magic_pathspec(":(exclude,top)a/b", "a/b/").expect("magic"),
3129            ":(exclude,top)a/b"
3130        );
3131    }
3132
3133    #[test]
3134    fn non_top_magic_still_injects_prefix_from_subdirectory() {
3135        assert_eq!(
3136            resolve_magic_pathspec(":(glob)**/f.txt", "sub/").expect("magic"),
3137            ":(glob,prefix:sub/)**/f.txt"
3138        );
3139        assert_eq!(
3140            resolve_magic_pathspec(":(exclude)vendor", "sub/").expect("magic"),
3141            ":(exclude,prefix:sub/)vendor"
3142        );
3143    }
3144
3145    #[test]
3146    fn resolve_pathspec_top_from_subdirectory() {
3147        let dir = tempfile::tempdir().expect("tempdir");
3148        let wt = dir.path();
3149        std::fs::create_dir_all(wt.join("a/b")).expect("mkdir");
3150        assert_eq!(
3151            resolve_pathspec(":(top)a/g.c", wt, Some("a/b")),
3152            ":(top)a/g.c"
3153        );
3154    }
3155}
3156
3157#[cfg(test)]
3158mod rev_walk_pathspec_resolution_tests {
3159    use super::*;
3160    use crate::config::environment::{Environment, RepositoryOptions};
3161    use crate::repo::{InitOptions, Repository};
3162
3163    fn repo_from_sub(worktree: &std::path::Path, sub: &std::path::Path) -> Repository {
3164        let mut env = Environment::empty();
3165        env.cwd = sub.to_path_buf();
3166        let mut opts = RepositoryOptions::empty();
3167        opts.environment = env;
3168        Repository::discover(Some(worktree), &opts).expect("discover")
3169    }
3170
3171    #[test]
3172    fn glob_magic_from_subdirectory_gets_prefix_and_matches() {
3173        let dir = tempfile::tempdir().expect("tempdir");
3174        let wt = dir.path();
3175        std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3176        std::fs::write(wt.join("sub/f.txt"), b"x").expect("write");
3177        Repository::init(wt, &InitOptions::default()).expect("init");
3178        let repo = repo_from_sub(wt, &wt.join("sub"));
3179        let specs = repo
3180            .resolve_rev_walk_pathspecs(&[":(glob)**/f.txt".to_owned()])
3181            .expect("resolve");
3182        assert_eq!(specs, [":(glob,prefix:sub/)**/f.txt"]);
3183        assert!(pathspec_matches(&specs[0], "sub/f.txt"));
3184        assert!(!pathspec_matches(&specs[0], "other/f.txt"));
3185    }
3186
3187    #[test]
3188    fn short_exclude_from_subdirectory_uses_prefix_magic() {
3189        let dir = tempfile::tempdir().expect("tempdir");
3190        let wt = dir.path();
3191        std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3192        Repository::init(wt, &InitOptions::default()).expect("init");
3193        let repo = repo_from_sub(wt, &wt.join("sub"));
3194        let specs = repo
3195            .resolve_rev_walk_pathspecs(&[":!f.txt".to_owned()])
3196            .expect("resolve");
3197        assert_eq!(specs, [".", ":(exclude,prefix:sub/)f.txt"]);
3198        assert!(matches_pathspec_list("other/g.txt", &specs));
3199        assert!(!matches_pathspec_list("sub/f.txt", &specs));
3200    }
3201
3202    #[test]
3203    fn glob_with_prefix_descends_into_cwd_directory() {
3204        let spec = ":(glob,prefix:sub/)**/f.txt";
3205        assert!(pathspec_wants_descent_into_tree(spec, "sub"));
3206        assert!(pathspec_entry_is_relevant(
3207            "sub/f.txt",
3208            false,
3209            &[spec.to_owned()]
3210        ));
3211    }
3212
3213    #[test]
3214    fn top_magic_from_subdirectory_stays_unprefixed() {
3215        let dir = tempfile::tempdir().expect("tempdir");
3216        let wt = dir.path();
3217        std::fs::create_dir_all(wt.join("a/b")).expect("mkdir");
3218        Repository::init(wt, &InitOptions::default()).expect("init");
3219        let repo = repo_from_sub(wt, &wt.join("a/b"));
3220        let specs = repo
3221            .resolve_rev_walk_pathspecs(&[":(top)a/g.c".to_owned()])
3222            .expect("resolve");
3223        assert_eq!(specs, [":(top)a/g.c"]);
3224        assert!(pathspec_matches(&specs[0], "a/g.c"));
3225        assert!(!pathspec_matches(&specs[0], "a/b/h.c"));
3226    }
3227}