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