1use crate::git_path::CanonicalizeExt;
16use std::borrow::Cow;
17use std::path::{Path, PathBuf};
18
19use hashbrown::HashSet;
20
21use crate::attributes::MacroTable;
22use crate::crlf::path_gitattribute_values;
23use crate::crlf::AttrRule;
24pub use crate::error::{AttrPathspecError, PathspecFromFileParseError, PathspecResolveError};
25use crate::precompose_config::argv_precompose_enabled;
26use crate::repo::Repository;
27use crate::unicode_normalization::precompose_utf8_path;
28use crate::wildmatch::{wildmatch, WM_CASEFOLD, WM_PATHNAME};
29
30#[must_use]
33pub fn simple_length(match_str: &str) -> usize {
34 let b = match_str.as_bytes();
35 let mut len = 0usize;
36 for &c in b {
37 if matches!(c, b'*' | b'?' | b'[' | b'\\') {
38 break;
39 }
40 len += 1;
41 }
42 len
43}
44
45#[must_use]
47pub fn has_glob_chars(s: &str) -> bool {
48 simple_length(s) < s.len()
49}
50
51pub fn parse_pathspecs_from_source(
60 data: &[u8],
61 nul_terminated: bool,
62) -> Result<Vec<String>, PathspecFromFileParseError> {
63 if nul_terminated {
64 let mut chunks: Vec<&[u8]> = data.split(|b| *b == 0).collect();
65 if chunks.last().copied() == Some(&[] as &[u8]) {
66 chunks.pop();
67 }
68 let mut out = Vec::with_capacity(chunks.len());
69 for chunk in chunks {
70 if chunk.is_empty() {
71 out.push(String::new());
72 continue;
73 }
74 let entry = std::str::from_utf8(chunk)
75 .map_err(|_| PathspecFromFileParseError::InvalidUtf8InNulRecord)?;
76 out.push(entry.to_string());
77 }
78 return Ok(out);
79 }
80
81 let text = String::from_utf8_lossy(data);
82 let mut out = Vec::new();
83 for raw in text.split_inclusive('\n') {
84 let line = raw.trim_end_matches('\n').trim_end_matches('\r');
85 if line.is_empty() {
86 out.push(String::new());
87 continue;
88 }
89 if line.starts_with('"') {
90 if line.ends_with('"') && line.len() >= 2 {
91 out.push(unquote_c_style_pathspec_line(line)?);
92 } else {
93 return Err(PathspecFromFileParseError::InvalidCStyleQuoting {
94 line: line.to_string(),
95 });
96 }
97 } else {
98 out.push(line.to_string());
99 }
100 }
101 Ok(out)
102}
103
104fn unquote_c_style_pathspec_line(s: &str) -> Result<String, PathspecFromFileParseError> {
106 let bytes = s.as_bytes();
107 if bytes.first() != Some(&b'"') || bytes.last() != Some(&b'"') || bytes.len() < 2 {
108 return Err(PathspecFromFileParseError::InvalidCStyleQuoting {
109 line: s.to_string(),
110 });
111 }
112
113 let inner = &bytes[1..bytes.len() - 1];
114 let mut out = Vec::with_capacity(inner.len());
115 let mut i = 0;
116 while i < inner.len() {
117 if inner[i] != b'\\' {
118 out.push(inner[i]);
119 i += 1;
120 continue;
121 }
122 i += 1;
123 if i >= inner.len() {
124 return Err(PathspecFromFileParseError::InvalidEscapeAtEnd);
125 }
126 match inner[i] {
127 b'\\' => out.push(b'\\'),
128 b'"' => out.push(b'"'),
129 b'a' => out.push(7),
130 b'b' => out.push(8),
131 b'f' => out.push(12),
132 b'n' => out.push(b'\n'),
133 b'r' => out.push(b'\r'),
134 b't' => out.push(b'\t'),
135 b'v' => out.push(11),
136 c if c.is_ascii_digit() => {
137 if i + 2 >= inner.len() {
138 return Err(PathspecFromFileParseError::TruncatedOctalEscape);
139 }
140 let oct = std::str::from_utf8(&inner[i..i + 3])
141 .map_err(|_| PathspecFromFileParseError::InvalidOctalBytes)?;
142 out.push(
143 u8::from_str_radix(oct, 8)
144 .map_err(|_| PathspecFromFileParseError::InvalidOctalValue)?,
145 );
146 i += 2;
147 }
148 other => {
149 return Err(PathspecFromFileParseError::InvalidEscapeSequence {
150 escape: char::from(other),
151 });
152 }
153 }
154 i += 1;
155 }
156 String::from_utf8(out).map_err(|_| PathspecFromFileParseError::InvalidUtf8InQuotedLine)
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct PathspecInput {
162 pub data: Vec<u8>,
164 pub nul_terminated: bool,
166}
167
168impl PathspecInput {
169 #[must_use]
171 pub fn new(data: Vec<u8>, nul_terminated: bool) -> Self {
172 Self {
173 data,
174 nul_terminated,
175 }
176 }
177}
178
179#[derive(Debug, Clone, Default, PartialEq, Eq)]
181pub struct ResolvedPathspecs {
182 pub specs: Vec<String>,
184 pub sources: Vec<String>,
186 pub scoped: bool,
188}
189
190impl ResolvedPathspecs {
191 pub fn resolve(
221 repo: &Repository,
222 cwd: &Path,
223 raw: &[String],
224 from_file: Option<PathspecInput>,
225 ) -> Result<Self, PathspecResolveError> {
226 let work_tree = repo
227 .work_tree()
228 .ok_or(PathspecResolveError::NeedsWorkTree)?;
229 let prefix = pathdiff(cwd, work_tree);
230 let scoped = from_file.is_some() || !raw.is_empty();
231
232 let mut sources = Vec::new();
233 if let Some(input) = from_file {
234 let parsed = parse_pathspecs_from_source(&input.data, input.nul_terminated)?;
235 sources.extend(parsed);
236 }
237 for sel in raw {
238 sources.push(sel.clone());
239 }
240
241 if scoped && sources.is_empty() {
242 return Err(PathspecResolveError::EmptyPathspec);
243 }
244 for sel in &sources {
245 if sel.is_empty() {
246 return Err(PathspecResolveError::EmptyPathspec);
247 }
248 }
249
250 let argv_precompose = repo.pathspec_precompose_enabled();
251 let specs = sources
252 .iter()
253 .map(|sel| {
254 resolve_pathspec_in_worktree_with_argv_precompose(
255 sel,
256 sel,
257 work_tree,
258 prefix.as_deref(),
259 argv_precompose,
260 )
261 })
262 .collect::<Result<Vec<_>, _>>()?;
263
264 Ok(Self {
265 specs,
266 sources,
267 scoped,
268 })
269 }
270
271 #[must_use]
273 pub fn is_entire_tree(&self) -> bool {
274 !self.scoped
275 }
276
277 #[must_use]
282 pub fn into_pathspec_lists(self) -> (Vec<String>, Vec<String>) {
283 if self.scoped {
284 (self.specs, self.sources)
285 } else {
286 (Vec::new(), Vec::new())
287 }
288 }
289
290 #[must_use]
292 pub fn into_specs(self) -> Vec<String> {
293 if self.scoped {
294 self.specs
295 } else {
296 Vec::new()
297 }
298 }
299}
300
301#[derive(Debug, Clone, Default)]
302struct PathspecMagic {
303 literal: bool,
304 glob: bool,
305 icase: bool,
306 exclude: bool,
307 top: bool,
309 prefix: Option<String>,
310 attr_requirements: Vec<AttrRequirement>,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq)]
315enum AttrRequirement {
316 Set(String),
317 Unset(String),
318 Unspecified(String),
319 Value(String, String),
320}
321
322impl AttrRequirement {
323 fn name(&self) -> &str {
324 match self {
325 AttrRequirement::Set(name)
326 | AttrRequirement::Unset(name)
327 | AttrRequirement::Unspecified(name)
328 | AttrRequirement::Value(name, _) => name,
329 }
330 }
331}
332
333fn git_env_bool(_key: &str, default: bool) -> bool {
337 default
338}
339
340fn literal_global() -> bool {
341 git_env_bool("GIT_LITERAL_PATHSPECS", false)
342}
343
344#[must_use]
346pub fn literal_pathspecs_enabled() -> bool {
347 literal_global()
348}
349
350fn glob_global() -> bool {
351 git_env_bool("GIT_GLOB_PATHSPECS", false)
352}
353
354fn noglob_global() -> bool {
355 git_env_bool("GIT_NOGLOB_PATHSPECS", false)
356}
357
358fn icase_global() -> bool {
359 git_env_bool("GIT_ICASE_PATHSPECS", false)
360}
361
362pub fn validate_global_pathspec_flags() -> Result<(), String> {
366 let lit = literal_global();
367 let glob = glob_global();
368 let noglob = noglob_global();
369 let icase = icase_global();
370
371 if glob && noglob {
372 return Err("global 'glob' and 'noglob' pathspec settings are incompatible".to_string());
373 }
374 if lit && (glob || noglob || icase) {
375 return Err(
376 "global 'literal' pathspec setting is incompatible with all other global pathspec settings"
377 .to_string(),
378 );
379 }
380 Ok(())
381}
382
383fn is_valid_attr_name(name: &str) -> bool {
384 !name.is_empty()
385 && name
386 .bytes()
387 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
388}
389
390fn split_attr_expr(expr: &str) -> Result<Vec<String>, AttrPathspecError> {
391 let mut parts = Vec::new();
392 let mut cur = String::new();
393 let mut in_value = false;
394 let mut escaped = false;
395
396 for ch in expr.chars() {
397 if escaped {
398 if ch.is_ascii_whitespace() {
399 return Err(AttrPathspecError::DanglingEscape);
400 }
401 if ch != ',' {
402 return Err(AttrPathspecError::UnsupportedEscape);
403 }
404 cur.push(ch);
405 escaped = false;
406 continue;
407 }
408 if in_value && ch == '\\' {
409 escaped = true;
410 continue;
411 }
412 if ch == '=' {
413 in_value = true;
414 cur.push(ch);
415 continue;
416 }
417 if ch.is_ascii_whitespace() {
418 if !cur.is_empty() {
419 parts.push(cur);
420 cur = String::new();
421 }
422 in_value = false;
423 continue;
424 }
425 cur.push(ch);
426 }
427
428 if escaped {
429 return Err(AttrPathspecError::DanglingEscape);
430 }
431 if !cur.is_empty() {
432 parts.push(cur);
433 }
434 Ok(parts)
435}
436
437fn parse_attr_requirements(expr: &str) -> Result<Vec<AttrRequirement>, AttrPathspecError> {
438 let name_only = |name: &str| {
439 if name.contains('=') || !is_valid_attr_name(name) {
440 Err(AttrPathspecError::InvalidName(name.to_owned()))
441 } else {
442 Ok(name.to_owned())
443 }
444 };
445 let mut out = Vec::new();
446 for token in split_attr_expr(expr)? {
447 let req = if let Some(name) = token.strip_prefix('-') {
448 AttrRequirement::Unset(name_only(name)?)
449 } else if let Some(name) = token.strip_prefix('!') {
450 AttrRequirement::Unspecified(name_only(name)?)
451 } else if let Some((name, value)) = token.split_once('=') {
452 AttrRequirement::Value(name_only(name)?, value.to_owned())
453 } else {
454 AttrRequirement::Set(name_only(&token)?)
455 };
456 out.push(req);
457 }
458 if out.is_empty() {
459 return Err(AttrPathspecError::Empty);
460 }
461 Ok(out)
462}
463
464fn attr_clauses(spec: &str) -> Vec<String> {
466 if literal_global() {
467 return Vec::new();
468 }
469 let Some(rest) = spec.strip_prefix(":(") else {
470 return Vec::new();
471 };
472 let Some(close) = rest.find(')') else {
473 return Vec::new();
474 };
475 split_long_magic_tokens_raw(&rest[..close])
476 .into_iter()
477 .filter_map(|token| token.trim_start().strip_prefix("attr:").map(str::to_owned))
478 .collect()
479}
480
481pub fn validate_attr_pathspecs(specs: &[String]) -> crate::error::Result<()> {
492 for spec in specs {
493 let invalid = |reason| crate::error::Error::InvalidAttrPathspec {
494 spec: spec.clone(),
495 reason,
496 };
497 let clauses = attr_clauses(spec);
498 if clauses.len() > 1 {
499 return Err(invalid(AttrPathspecError::MultipleAttrClauses));
500 }
501 match clauses.first() {
502 Some(expr) if expr.is_empty() => return Err(invalid(AttrPathspecError::Empty)),
503 Some(expr) if expr.trim().is_empty() => {}
505 Some(expr) => {
506 parse_attr_requirements(expr).map_err(invalid)?;
507 }
508 None => {}
509 }
510 }
511 Ok(())
512}
513
514fn split_long_magic_tokens(magic_part: &str) -> Vec<String> {
515 split_long_magic_tokens_raw(magic_part)
516 .into_iter()
517 .map(|token| token.trim().to_string())
518 .collect()
519}
520
521fn split_long_magic_tokens_raw(magic_part: &str) -> Vec<String> {
523 let mut tokens = Vec::new();
524 let mut cur = String::new();
525 let mut escaped = false;
526 for ch in magic_part.chars() {
527 if escaped {
528 cur.push('\\');
529 cur.push(ch);
530 escaped = false;
531 continue;
532 }
533 if ch == '\\' {
534 escaped = true;
535 continue;
536 }
537 if ch == ',' {
538 tokens.push(std::mem::take(&mut cur));
539 continue;
540 }
541 cur.push(ch);
542 }
543 if escaped {
544 cur.push('\\');
545 }
546 tokens.push(cur);
547 tokens
548}
549
550fn parse_long_magic(rest_after_paren: &str) -> Option<(PathspecMagic, &str)> {
551 let close = rest_after_paren.find(')')?;
552 let magic_part = &rest_after_paren[..close];
553 let tail = &rest_after_paren[close + 1..];
554 let mut magic = PathspecMagic::default();
555 for raw in split_long_magic_tokens(magic_part) {
556 let token = raw.trim();
557 if token.is_empty() {
558 continue;
559 }
560 if let Some(p) = token.strip_prefix("prefix:") {
561 magic.prefix = Some(p.to_string());
562 continue;
563 }
564 if let Some(expr) = token.strip_prefix("attr:") {
565 if let Ok(reqs) = parse_attr_requirements(expr) {
566 magic.attr_requirements = reqs;
567 }
568 continue;
569 }
570 if token.eq_ignore_ascii_case("literal") {
571 magic.literal = true;
572 } else if token.eq_ignore_ascii_case("glob") {
573 magic.glob = true;
574 } else if token.eq_ignore_ascii_case("icase") {
575 magic.icase = true;
576 } else if token.eq_ignore_ascii_case("exclude") {
577 magic.exclude = true;
578 } else if token.eq_ignore_ascii_case("top") {
579 magic.top = true;
580 }
581 }
582 Some((magic, tail))
583}
584
585fn parse_short_magic(elem: &str) -> (PathspecMagic, &str) {
587 let bytes = elem.as_bytes();
588 let mut i = 1usize;
589 let mut magic = PathspecMagic::default();
590 while i < bytes.len() && bytes[i] != b':' {
591 let ch = bytes[i];
592 if ch == b'^' {
593 magic.exclude = true;
594 i += 1;
595 continue;
596 }
597 let is_magic = match ch {
598 b'!' => {
599 magic.exclude = true;
600 true
601 }
602 b'/' => {
603 magic.top = true;
604 true
605 } _ => false,
607 };
608 if is_magic {
609 i += 1;
610 continue;
611 }
612 break;
613 }
614 if i < bytes.len() && bytes[i] == b':' {
615 i += 1;
616 }
617 (magic, &elem[i..])
618}
619
620fn parse_element_magic(elem: &str) -> (PathspecMagic, &str) {
622 if !elem.starts_with(':') || literal_global() {
623 return (PathspecMagic::default(), elem);
624 }
625 if let Some(rest) = elem.strip_prefix(":(") {
626 return parse_long_magic(rest).unwrap_or((PathspecMagic::default(), elem));
627 }
628 parse_short_magic(elem)
629}
630
631fn combine_magic(element: PathspecMagic) -> PathspecMagic {
632 let mut m = element;
633 if literal_global() {
634 m.literal = true;
635 }
636 if glob_global() && !m.literal {
637 m.glob = true;
638 }
639 if icase_global() {
640 m.icase = true;
641 }
642 if noglob_global() && !m.glob {
643 m.literal = true;
644 }
645 m
646}
647
648fn strip_top_magic(mut pattern: &str) -> &str {
649 if let Some(r) = pattern.strip_prefix(":/") {
650 pattern = r;
651 }
652 pattern
653}
654
655#[must_use]
660pub fn bloom_lookup_prefix_with_cwd(
661 spec: &str,
662 cwd_from_repo_root: Option<&str>,
663) -> Option<String> {
664 let (elem_magic, raw_pattern) = parse_element_magic(spec);
665 let magic = combine_magic(elem_magic);
666 if magic.exclude || magic.icase {
667 return None;
668 }
669 let pattern = strip_top_magic(raw_pattern);
670 if pattern.is_empty() {
671 return None;
672 }
673 let combined = if magic.top {
674 let cwd = cwd_from_repo_root.unwrap_or("").trim_end_matches('/');
675 if cwd.is_empty() {
676 pattern.to_string()
677 } else {
678 format!("{cwd}/{pattern}")
679 }
680 } else if let Some(prefix) = magic.prefix.as_deref() {
681 let base = prefix.trim_end_matches('/');
682 if base.is_empty() {
683 pattern.to_string()
684 } else {
685 normalize_relative_path_str(&format!("{base}/{pattern}"))
686 }
687 } else {
688 pattern.to_string()
689 };
690 let pattern = combined.as_str();
691 let mut len = simple_length(pattern);
692 if len != pattern.len() {
693 while len > 0 && pattern.as_bytes()[len - 1] != b'/' {
694 len -= 1;
695 }
696 }
697 while len > 0 && pattern.as_bytes()[len - 1] == b'/' {
698 len -= 1;
699 }
700 if len == 0 {
701 return None;
702 }
703 Some(combined[..len].to_string())
704}
705
706#[must_use]
708pub fn bloom_lookup_prefix(spec: &str) -> Option<String> {
709 bloom_lookup_prefix_with_cwd(spec, None)
710}
711
712#[must_use]
714pub fn pathspecs_allow_bloom(specs: &[String]) -> bool {
715 specs.iter().all(|s| {
716 !s.is_empty() && !pathspec_is_exclude(s) && bloom_lookup_prefix_with_cwd(s, None).is_some()
717 })
718}
719
720#[must_use]
725pub fn path_allowed_by_pathspec_list(specs: &[String], path: &str) -> bool {
726 let mut has_positive = false;
727 let mut positive_match = false;
728 for s in specs {
729 let (elem, raw_pattern) = parse_element_magic(s);
730 let magic = combine_magic(elem);
731 if magic.exclude {
732 if path_matches_pathspec_tail(raw_pattern, path, magic) {
733 return false;
734 }
735 continue;
736 }
737 has_positive = true;
738 if pathspec_matches(s, path) {
739 positive_match = true;
740 }
741 }
742 !has_positive || positive_match
743}
744
745#[must_use]
747pub fn pathspec_contributes_match(spec: &str, path: &str) -> bool {
748 pathspec_matches(spec, path) || pathspec_exclude_matches(spec, path)
749}
750
751fn path_for_match_under_magic_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
754 let base = prefix.trim_end_matches('/');
755 if base.is_empty() {
756 return Some(path);
757 }
758 if path == base {
759 return Some("");
760 }
761 if let Some(rest) = path.strip_prefix(prefix) {
762 return Some(rest);
763 }
764 let anchored = if prefix.ends_with('/') {
765 prefix.to_string()
766 } else {
767 format!("{prefix}/")
768 };
769 path.starts_with(&anchored).then(|| &path[anchored.len()..])
770}
771
772fn path_matches_pathspec_tail(raw_pattern: &str, path: &str, magic: PathspecMagic) -> bool {
773 if magic.literal && magic.glob {
774 return false;
775 }
776 let pattern = strip_top_magic(raw_pattern);
777 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
778 match path_for_match_under_magic_prefix(path, prefix) {
779 Some(rest) => rest,
780 None => return false,
781 }
782 } else {
783 path
784 };
785 pathspec_matches_tail(pattern, path_for_match, magic)
786}
787
788#[must_use]
793pub fn pathspec_matches(spec: &str, path: &str) -> bool {
794 matches_pathspec(spec, path)
795}
796
797#[must_use]
799pub fn pathspec_is_exclude(spec: &str) -> bool {
800 let (elem_magic, _) = parse_element_magic(spec);
801 combine_magic(elem_magic).exclude
802}
803
804#[must_use]
810pub fn pathspec_wants_descent_for_rev_tree(path: &str, specs: &[String]) -> bool {
811 if specs.is_empty() {
812 return true;
813 }
814 for spec in specs {
815 if !pathspec_is_exclude(spec) && pathspec_wants_descent_into_tree(spec, path) {
816 return true;
817 }
818 }
819 if !specs.iter().any(|s| pathspec_is_exclude(s)) {
820 return false;
821 }
822 let ctx = PathspecMatchContext {
823 is_directory: true,
824 is_git_submodule: false,
825 precompose_paths: false,
826 };
827 for spec in specs {
828 if pathspec_is_exclude(spec)
829 && pathspec_exclude_element_matches_with_context(spec, path, ctx)
830 {
831 return false;
832 }
833 }
834 !specs.iter().any(|s| !pathspec_is_exclude(s))
835}
836
837pub(crate) fn pathspec_entry_is_relevant(path: &str, is_tree: bool, specs: &[String]) -> bool {
840 matches_pathspec_list(path, specs)
841 || (is_tree && pathspec_wants_descent_for_rev_tree(path, specs))
842}
843
844#[must_use]
853pub fn pathspec_wants_descent_into_tree(spec: &str, full_name: &str) -> bool {
854 if pathspec_is_exclude(spec) {
855 return false;
856 }
857 let (elem_magic, raw_pattern) = parse_element_magic(spec);
858 let magic = combine_magic(elem_magic);
859 if magic.exclude {
860 return false;
861 }
862 let pattern = strip_top_magic(raw_pattern);
863 let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
864 if pattern.is_empty() || pattern == "." {
865 return true;
866 }
867 if let Some(prefix) = magic.prefix.as_deref() {
868 let base = prefix.trim_end_matches('/');
869 if !base.is_empty() && (full_name == base || base.starts_with(&format!("{full_name}/"))) {
870 return true;
871 }
872 }
873 let dir_prefix = format!("{full_name}/");
874 if pattern.starts_with(&dir_prefix) {
875 return true;
876 }
877 if ps_str_eq(pattern, full_name, magic.icase) {
878 return true;
879 }
880 pathspec_recursive_descent_wanted(pattern, magic, full_name)
881}
882
883fn pathspec_literal_descent_wanted(pattern: &str, dir: &str) -> bool {
884 if pattern.is_empty() {
885 return false;
886 }
887 if let Some(prefix) = pattern.strip_suffix('/') {
888 return dir == prefix || path_is_under_dir(dir, prefix, false);
889 }
890 if dir == pattern {
891 return false;
892 }
893 dir.len() < pattern.len()
894 && path_starts_with(pattern, dir, false)
895 && pattern.as_bytes()[dir.len()] == b'/'
896}
897
898fn pathspec_recursive_descent_wanted(pattern: &str, magic: PathspecMagic, dir: &str) -> bool {
899 if magic.literal {
900 return pathspec_literal_descent_wanted(pattern, dir);
901 }
902 if simple_length(pattern) == 0 {
903 return true;
904 }
905
906 let icase = magic.icase;
907 let glob = magic.glob;
908 let components: Vec<&str> = dir.split('/').filter(|c| !c.is_empty()).collect();
909 pathspec_descent_match_components(pattern, icase, glob, &components)
910}
911
912fn pathspec_first_component(pat: &str) -> (&str, &str) {
913 match pat.find('/') {
914 Some(i) => (&pat[..i], &pat[i + 1..]),
915 None => (pat, ""),
916 }
917}
918
919fn pathspec_dir_name_matches_component(
920 pat_comp: &str,
921 dir_name: &str,
922 icase: bool,
923 glob: bool,
924) -> bool {
925 if pat_comp.is_empty() {
926 return true;
927 }
928 let nwl = simple_length(pat_comp);
929 if nwl == 0 {
930 return true;
931 }
932 if nwl >= pat_comp.len() {
933 return ps_str_eq(pat_comp, dir_name, icase);
934 }
935 let lit = &pat_comp[..nwl];
936 let lit_bytes = lit.as_bytes();
937 let dir_bytes = dir_name.as_bytes();
938 if icase {
939 if dir_bytes.len() < lit_bytes.len()
940 || !dir_bytes[..lit_bytes.len()].eq_ignore_ascii_case(lit_bytes)
941 {
942 return false;
943 }
944 } else if dir_bytes.len() < lit_bytes.len() || &dir_bytes[..lit_bytes.len()] != lit_bytes {
945 return false;
946 }
947 let flags = if icase { WM_CASEFOLD } else { 0 };
948 let wm_flags = if glob { flags | WM_PATHNAME } else { flags };
949 wildmatch(pat_comp.as_bytes(), dir_name.as_bytes(), wm_flags)
950}
951
952fn pathspec_descent_match_components(
953 pat: &str,
954 icase: bool,
955 glob: bool,
956 dir_components: &[&str],
957) -> bool {
958 if dir_components.is_empty() {
959 return simple_length(pat) == 0 || !pat.is_empty();
960 }
961 if simple_length(pat) == 0 {
962 return true;
963 }
964 let (pat_comp, pat_rest) = pathspec_first_component(pat);
965 if !pathspec_dir_name_matches_component(pat_comp, dir_components[0], icase, glob) {
966 return false;
967 }
968 pathspec_descent_match_components(pat_rest, icase, glob, &dir_components[1..])
969}
970
971#[cfg(test)]
972mod pathspec_descent_tests {
973 use super::*;
974
975 #[test]
976 fn descent_wildcard_non_final_component() {
977 assert!(pathspec_wants_descent_into_tree("*/g.c", "a"));
978 assert!(pathspec_wants_descent_into_tree("a/*/f.c", "a"));
979 assert!(pathspec_wants_descent_into_tree("a/*/f.c", "a/b"));
980 assert!(pathspec_wants_descent_into_tree(":(glob)**/f.c", "a"));
981 assert!(pathspec_wants_descent_into_tree(":(glob)*/g.c", "a"));
982 assert!(pathspec_wants_descent_into_tree(":(icase)A/g.c", "a"));
983 assert!(!pathspec_wants_descent_into_tree(":(literal)*g.c", "a"));
984 assert!(!pathspec_wants_descent_into_tree("a/*.c", "b"));
985 assert!(pathspec_wants_descent_into_tree("b*/log.c", "builtin"));
986 assert!(!pathspec_wants_descent_into_tree("b*/log.c", "other"));
987 assert!(pathspec_wants_descent_into_tree("bu?ltin/log.c", "builtin"));
988 assert!(pathspec_wants_descent_into_tree(
989 ":(icase)B*/LOG.C",
990 "builtin"
991 ));
992 assert!(!pathspec_wants_descent_into_tree(":(icase)b*/log.c", "é"));
993 }
994
995 #[test]
996 fn glob_doublestar_path_matches_nested_file() {
997 let specs = vec![":(glob)**/f.c".to_owned()];
998 assert!(matches_pathspec_list("a/b/f.c", &specs));
999 }
1000}
1001
1002#[must_use]
1005pub fn matches_pathspec_set_for_object_ls_tree(
1006 specs: &[String],
1007 path: &str,
1008 mode: u32,
1009 attr_rules: &[AttrRule],
1010) -> bool {
1011 if specs.is_empty() {
1012 return true;
1013 }
1014 let mut positives: Vec<&str> = Vec::new();
1015 let mut excludes: Vec<&str> = Vec::new();
1016 for s in specs {
1017 if pathspec_is_exclude(s) {
1018 excludes.push(s.as_str());
1019 } else {
1020 positives.push(s.as_str());
1021 }
1022 }
1023 let positive_ok = if positives.is_empty() {
1024 true
1025 } else {
1026 positives
1027 .iter()
1028 .any(|s| matches_ls_tree_pathspec(s, path, mode, attr_rules))
1029 };
1030 if !positive_ok {
1031 return false;
1032 }
1033 for ex in excludes {
1034 if matches_ls_tree_pathspec(ex, path, mode, attr_rules) {
1035 return false;
1036 }
1037 }
1038 true
1039}
1040
1041#[must_use]
1044pub fn matches_pathspec_set_for_object(
1045 specs: &[String],
1046 path: &str,
1047 mode: u32,
1048 attr_rules: &[AttrRule],
1049) -> bool {
1050 if specs.is_empty() {
1051 return true;
1052 }
1053 let mut positives: Vec<&str> = Vec::new();
1054 let mut excludes: Vec<&str> = Vec::new();
1055 for s in specs {
1056 if pathspec_is_exclude(s) {
1057 excludes.push(s.as_str());
1058 } else {
1059 positives.push(s.as_str());
1060 }
1061 }
1062 let positive_ok = if positives.is_empty() {
1063 true
1064 } else {
1065 positives
1066 .iter()
1067 .any(|s| matches_pathspec_for_object(s, path, mode, attr_rules))
1068 };
1069 if !positive_ok {
1070 return false;
1071 }
1072 for ex in excludes {
1073 if matches_pathspec_for_object(ex, path, mode, attr_rules) {
1074 return false;
1075 }
1076 }
1077 true
1078}
1079
1080#[must_use]
1082pub fn pathspec_has_top(spec: &str) -> bool {
1083 let (elem_magic, _) = parse_element_magic(spec);
1084 combine_magic(elem_magic).top
1085}
1086
1087#[must_use]
1094pub fn pathspec_has_attr_magic(spec: &str) -> bool {
1095 spec.starts_with(":(") && spec.contains("attr:") && !attr_clauses(spec).is_empty()
1097}
1098
1099#[derive(Debug, Clone)]
1108pub struct PathspecMatcher<'s> {
1109 specs: Cow<'s, [String]>,
1110 precompose: bool,
1111 attrs: Option<std::sync::Arc<crate::attributes::ParsedGitAttributes>>,
1112 attr_icase: bool,
1114}
1115
1116impl<'s> PathspecMatcher<'s> {
1117 pub(crate) fn new(
1118 specs: &'s [String],
1119 precompose: bool,
1120 attrs: Option<std::sync::Arc<crate::attributes::ParsedGitAttributes>>,
1121 attr_icase: bool,
1122 ) -> Self {
1123 let specs = if precompose && attrs.is_some() {
1125 Cow::Owned(
1126 specs
1127 .iter()
1128 .map(|spec| precompose_utf8_path(spec).into_owned())
1129 .collect(),
1130 )
1131 } else {
1132 Cow::Borrowed(specs)
1133 };
1134 Self {
1135 specs,
1136 precompose,
1137 attrs,
1138 attr_icase,
1139 }
1140 }
1141
1142 #[must_use]
1145 pub fn matches(&self, path: &str) -> bool {
1146 const REGULAR_FILE: u32 = 0o100644;
1147 let Some(attrs) = &self.attrs else {
1148 return matches_pathspec_list_with_context(
1149 path,
1150 &self.specs,
1151 pathspec_match_context_with_precompose(self.precompose),
1152 );
1153 };
1154 let path = if self.precompose {
1155 precompose_utf8_path(path)
1156 } else {
1157 Cow::Borrowed(path)
1158 };
1159 let lookup = AttrLookup::new(&attrs.rules, &attrs.macros, self.attr_icase);
1160 matches_pathspec_list_with_attrs(&path, REGULAR_FILE, lookup, &self.specs)
1161 }
1162
1163 #[must_use]
1166 pub fn matches_change(&self, path: &str, old_path: Option<&str>) -> bool {
1167 self.specs.is_empty()
1168 || self.matches(path)
1169 || old_path.is_some_and(|old| old != path && self.matches(old))
1170 }
1171
1172 #[must_use]
1174 pub fn is_empty(&self) -> bool {
1175 self.specs.is_empty()
1176 }
1177}
1178
1179fn pathspec_match_one_positive(path: &str, magic: PathspecMagic, raw_pattern: &str) -> bool {
1180 if magic.literal && magic.glob {
1181 return false;
1182 }
1183 let pattern = strip_top_magic(raw_pattern);
1184 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1185 match path_for_match_under_magic_prefix(path, prefix) {
1186 Some(rest) => rest,
1187 None => return false,
1188 }
1189 } else {
1190 path
1191 };
1192 pathspec_matches_tail(pattern, path_for_match, magic)
1193}
1194
1195#[derive(Clone, Copy)]
1197pub(crate) struct AttrLookup<'a> {
1198 rules: &'a [AttrRule],
1199 macros: Option<&'a MacroTable>,
1201 icase: bool,
1203}
1204
1205impl<'a> AttrLookup<'a> {
1206 pub(crate) fn new(rules: &'a [AttrRule], macros: &'a MacroTable, icase: bool) -> Self {
1207 Self {
1208 rules,
1209 macros: Some(macros),
1210 icase,
1211 }
1212 }
1213
1214 fn rules_only(rules: &'a [AttrRule]) -> Self {
1215 Self {
1216 rules,
1217 macros: None,
1218 icase: false,
1219 }
1220 }
1221}
1222
1223fn attr_requirements_match(
1224 requirements: &[AttrRequirement],
1225 attrs: AttrLookup<'_>,
1226 path: &str,
1227 is_dir: bool,
1228 mode: u32,
1229) -> bool {
1230 let no_macros = MacroTable::default();
1231 let assigned = path_gitattribute_values(
1232 attrs.rules,
1233 attrs.macros.unwrap_or(&no_macros),
1234 attrs.icase,
1235 path,
1236 is_dir,
1237 );
1238 requirements.iter().all(|req| {
1239 let value: Option<Cow<'_, str>> = if req.name() == "builtin_objectmode" {
1240 (mode != 0).then(|| Cow::Owned(format!("{mode:06o}")))
1241 } else {
1242 assigned
1243 .get(req.name())
1244 .map(|v| Cow::Borrowed(v.display()))
1245 .filter(|v| v != "unspecified")
1246 };
1247 match req {
1248 AttrRequirement::Set(_) => value.as_deref() == Some("set"),
1249 AttrRequirement::Unset(_) => value.as_deref() == Some("unset"),
1250 AttrRequirement::Unspecified(_) => value.is_none(),
1251 AttrRequirement::Value(_, expected) => value.as_deref() == Some(expected.as_str()),
1252 }
1253 })
1254}
1255
1256fn matches_pathspec_element_with_context(
1257 spec: &str,
1258 path: &str,
1259 ctx: PathspecMatchContext,
1260) -> bool {
1261 let (elem_magic, raw_pattern) = parse_element_magic(spec);
1262 let magic = combine_magic(elem_magic);
1263 if magic.exclude {
1264 return false;
1265 }
1266 if magic.literal && magic.glob {
1267 return false;
1268 }
1269 if !magic.attr_requirements.is_empty() {
1270 return false;
1271 }
1272 if magic.literal || magic.glob || magic.icase {
1273 return pathspec_matches(spec, path);
1274 }
1275 let pattern = strip_top_magic(raw_pattern);
1276 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1277 match path_for_match_under_magic_prefix(path, prefix) {
1278 Some(rest) => rest,
1279 None => return false,
1280 }
1281 } else {
1282 path
1283 };
1284 matches_pathspec_with_context(pattern, path_for_match, ctx)
1285}
1286
1287fn pathspec_exclude_element_matches_with_context(
1288 spec: &str,
1289 path: &str,
1290 ctx: PathspecMatchContext,
1291) -> bool {
1292 let (elem_magic, raw_pattern) = parse_element_magic(spec);
1293 let mut magic = combine_magic(elem_magic);
1294 if !magic.exclude {
1295 return false;
1296 }
1297 magic.exclude = false;
1298 if magic.literal && magic.glob {
1299 return false;
1300 }
1301 if !magic.attr_requirements.is_empty() {
1302 return false;
1305 }
1306 if magic.literal || magic.glob || magic.icase {
1307 return pathspec_match_one_positive(path, magic, raw_pattern);
1308 }
1309 let pattern = strip_top_magic(raw_pattern);
1310 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1311 match path_for_match_under_magic_prefix(path, prefix) {
1312 Some(rest) => rest,
1313 None => return false,
1314 }
1315 } else {
1316 path
1317 };
1318 matches_pathspec_with_context(pattern, path_for_match, ctx)
1319}
1320
1321#[must_use]
1324pub fn pathspec_exclude_matches(spec: &str, path: &str) -> bool {
1325 pathspec_exclude_element_matches_with_context(spec, path, PathspecMatchContext::default())
1326}
1327
1328#[must_use]
1333pub fn extend_pathspec_list_implicit_cwd(
1334 specs: &[String],
1335 cwd_from_repo_root: Option<&str>,
1336) -> Vec<String> {
1337 if specs.is_empty() {
1338 return specs.to_vec();
1339 }
1340 if !specs.iter().all(|s| pathspec_is_exclude(s)) {
1341 return specs.to_vec();
1342 }
1343 let any_top = specs.iter().any(|s| pathspec_has_top(s));
1344 if any_top {
1345 return specs.to_vec();
1346 }
1347 let Some(cwd) = cwd_from_repo_root.map(str::trim).filter(|s| !s.is_empty()) else {
1348 return specs.to_vec();
1349 };
1350 let cwd = cwd.trim_end_matches('/');
1351 if cwd.is_empty() {
1352 return specs.to_vec();
1353 }
1354 let mut out = Vec::with_capacity(specs.len() + 1);
1355 out.push(".".to_owned());
1357 out.extend_from_slice(specs);
1358 out
1359}
1360
1361#[must_use]
1370pub fn matches_pathspec_list(path: &str, specs: &[String]) -> bool {
1371 matches_pathspec_list_with_context(path, specs, PathspecMatchContext::default())
1372}
1373
1374#[must_use]
1379pub fn matches_pathspec_list_with_context(
1380 path: &str,
1381 specs: &[String],
1382 ctx: PathspecMatchContext,
1383) -> bool {
1384 if specs.is_empty() {
1385 return true;
1386 }
1387 let mut has_exclude = false;
1388 let mut has_positive = false;
1389 let mut positive = false;
1390 for spec in specs {
1391 if pathspec_is_exclude(spec) {
1392 has_exclude = true;
1393 } else {
1394 has_positive = true;
1395 positive = positive || matches_pathspec_element_with_context(spec, path, ctx);
1396 }
1397 }
1398 if has_positive && !positive {
1399 return false;
1400 }
1401 if !has_exclude {
1402 return true;
1403 }
1404 let excluded = specs.iter().any(|s| {
1405 pathspec_is_exclude(s) && pathspec_exclude_element_matches_with_context(s, path, ctx)
1406 });
1407 !excluded
1408}
1409
1410pub(crate) fn sorted_paths_match_pathspec<S: AsRef<str>>(
1419 spec: &str,
1420 sorted_paths: &[S],
1421 ctx: PathspecMatchContext,
1422) -> bool {
1423 let list = [spec.to_owned()];
1424 let matches_linearly = |p: &S| matches_pathspec_list_with_context(p.as_ref(), &list, ctx);
1425 if !is_plain_literal_pathspec(spec, ctx) {
1426 return sorted_paths.iter().any(matches_linearly);
1427 }
1428 let spec_nfc = literal_spec_for_lookup(spec, ctx);
1429 if sorted_literal_lookup(&spec_nfc, sorted_paths) {
1430 return true;
1431 }
1432 ctx.precompose_paths
1435 && sorted_paths
1436 .iter()
1437 .filter(|p| !p.as_ref().is_ascii())
1438 .any(matches_linearly)
1439}
1440
1441fn sorted_literal_lookup<S: AsRef<str>>(spec: &str, sorted_paths: &[S]) -> bool {
1443 let has_path_with_prefix = |prefix: &str| {
1444 let at = sorted_paths.partition_point(|p| p.as_ref() < prefix);
1445 sorted_paths
1446 .get(at)
1447 .is_some_and(|p| p.as_ref().starts_with(prefix))
1448 };
1449 if spec.ends_with('/') {
1450 return has_path_with_prefix(spec);
1451 }
1452 let at = sorted_paths.partition_point(|p| p.as_ref() < spec);
1453 if sorted_paths.get(at).is_some_and(|p| p.as_ref() == spec) {
1454 return true;
1455 }
1456 has_path_with_prefix(&format!("{spec}/"))
1457}
1458
1459fn literal_spec_for_lookup(spec: &str, ctx: PathspecMatchContext) -> Cow<'_, str> {
1462 if ctx.precompose_paths {
1463 precompose_utf8_path(spec)
1464 } else {
1465 Cow::Borrowed(spec)
1466 }
1467}
1468
1469pub(crate) fn exact_literal_pathspec_set(
1475 specs: &[String],
1476 ctx: PathspecMatchContext,
1477) -> Option<std::collections::BTreeSet<String>> {
1478 if specs.is_empty() || ctx.precompose_paths {
1479 return None;
1480 }
1481 if !specs
1482 .iter()
1483 .all(|s| is_plain_literal_pathspec(s, ctx) && !s.ends_with('/'))
1484 {
1485 return None;
1486 }
1487 Some(specs.iter().cloned().collect())
1488}
1489
1490fn is_plain_literal_pathspec(spec: &str, ctx: PathspecMatchContext) -> bool {
1496 !ctx.is_directory
1497 && !ctx.is_git_submodule
1498 && !spec.is_empty()
1499 && spec != "."
1500 && !spec.starts_with("./")
1501 && !spec.starts_with(':')
1502 && simple_length(spec) == spec.len()
1503 && !(literal_global() || glob_global() || noglob_global() || icase_global())
1504}
1505
1506pub(crate) struct PathspecListMatcher<'a> {
1514 specs: &'a [String],
1515 ctx: PathspecMatchContext,
1516 literals: Option<LiteralPathspecSet>,
1517}
1518
1519struct LiteralPathspecSet {
1521 exact: HashSet<String>,
1523 dirs: HashSet<String>,
1525}
1526
1527impl<'a> PathspecListMatcher<'a> {
1528 pub(crate) fn new(specs: &'a [String], ctx: PathspecMatchContext) -> Self {
1530 let all_plain =
1531 !specs.is_empty() && specs.iter().all(|s| is_plain_literal_pathspec(s, ctx));
1532 let literals = all_plain.then(|| {
1533 let mut set = LiteralPathspecSet {
1534 exact: HashSet::with_capacity(specs.len()),
1535 dirs: HashSet::with_capacity(specs.len()),
1536 };
1537 for spec in specs {
1538 let spec = literal_spec_for_lookup(spec, ctx);
1539 match spec.strip_suffix('/') {
1540 Some(dir) => {
1541 set.dirs.insert(dir.to_owned());
1542 }
1543 None => {
1544 set.exact.insert(spec.to_string());
1545 set.dirs.insert(spec.into_owned());
1546 }
1547 }
1548 }
1549 set
1550 });
1551 Self {
1552 specs,
1553 ctx,
1554 literals,
1555 }
1556 }
1557
1558 pub(crate) fn matches(&self, path: &str) -> bool {
1560 let Some(set) = &self.literals else {
1561 return matches_pathspec_list_with_context(path, self.specs, self.ctx);
1562 };
1563 let path = literal_spec_for_lookup(path, self.ctx);
1564 let path = path.as_ref();
1565 if set.exact.contains(path) {
1566 return true;
1567 }
1568 path.bytes()
1569 .enumerate()
1570 .any(|(i, b)| b == b'/' && set.dirs.contains(&path[..i]))
1571 }
1572}
1573
1574#[must_use]
1580pub fn matches_pathspec_list_for_object(
1581 path: &str,
1582 mode: u32,
1583 attr_rules: &[AttrRule],
1584 specs: &[String],
1585) -> bool {
1586 matches_pathspec_list_with_attrs(path, mode, AttrLookup::rules_only(attr_rules), specs)
1587}
1588
1589pub(crate) fn matches_pathspec_list_with_attrs(
1590 path: &str,
1591 mode: u32,
1592 attrs: AttrLookup<'_>,
1593 specs: &[String],
1594) -> bool {
1595 if specs.is_empty() {
1596 return true;
1597 }
1598 let mut has_exclude = false;
1599 let mut has_positive = false;
1600 let mut positive = false;
1601 for spec in specs {
1602 if pathspec_is_exclude(spec) {
1603 has_exclude = true;
1604 } else {
1605 has_positive = true;
1606 positive = positive || matches_pathspec_for_object_with_attrs(spec, path, mode, attrs);
1607 }
1608 }
1609 if has_positive && !positive {
1610 return false;
1611 }
1612 if !has_exclude {
1613 return true;
1614 }
1615 !specs.iter().any(|s| {
1616 pathspec_is_exclude(s) && matches_pathspec_exclude_for_object(s, path, mode, attrs)
1617 })
1618}
1619
1620fn matches_pathspec_exclude_for_object(
1621 spec: &str,
1622 path: &str,
1623 mode: u32,
1624 attrs: AttrLookup<'_>,
1625) -> bool {
1626 let (elem_magic, raw_pattern) = parse_element_magic(spec);
1627 let mut magic = combine_magic(elem_magic);
1628 if !magic.exclude {
1629 return false;
1630 }
1631 magic.exclude = false;
1632 if magic.literal && magic.glob {
1633 return false;
1634 }
1635 let ctx = context_from_mode_bits(mode);
1636 let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
1637 if !magic.attr_requirements.is_empty()
1638 && !attr_requirements_match(&magic.attr_requirements, attrs, path, is_dir_for_attr, mode)
1639 {
1640 return false;
1641 }
1642 let pattern = strip_top_magic(raw_pattern);
1643 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1644 match path_for_match_under_magic_prefix(path, prefix) {
1645 Some(rest) => rest,
1646 None => return false,
1647 }
1648 } else {
1649 path
1650 };
1651 if magic.literal || magic.glob || magic.icase {
1652 pathspec_matches_tail(pattern, path_for_match, magic)
1653 } else {
1654 matches_pathspec_with_context(pattern, path_for_match, ctx)
1655 }
1656}
1657
1658fn pathspec_matches_tail(pattern: &str, path: &str, magic: PathspecMagic) -> bool {
1659 if pattern.is_empty() {
1660 return true;
1661 }
1662
1663 let flags = if magic.icase { WM_CASEFOLD } else { 0 };
1664
1665 if magic.literal {
1666 return literal_prefix_match(pattern, path);
1667 }
1668
1669 let wm_flags = if magic.glob {
1670 flags | WM_PATHNAME
1671 } else {
1672 flags
1673 };
1674
1675 let pattern_bytes = pattern.as_bytes();
1676 let path_bytes = path.as_bytes();
1677 let simple = simple_length(pattern);
1678
1679 if ps_str_eq(pattern, path, magic.icase) {
1683 return true;
1684 }
1685 if simple == pattern.len() {
1686 if let Some(prefix) = pattern.strip_suffix('/') {
1687 if ps_str_eq(prefix, path, magic.icase) {
1688 return true;
1689 }
1690 if path_is_under_dir(path, prefix, magic.icase) {
1691 return true;
1692 }
1693 } else if path_is_under_dir(path, pattern, magic.icase) {
1694 return true;
1695 }
1696 }
1697
1698 if magic.glob && !path.contains('/') && pattern.starts_with("**/") {
1700 if wildmatch(pattern_bytes, path_bytes, wm_flags) {
1701 return true;
1702 }
1703 if let Some(suffix) = pattern.strip_prefix("**/") {
1704 if wildmatch(suffix.as_bytes(), path_bytes, wm_flags) {
1705 return true;
1706 }
1707 }
1708 }
1709
1710 if simple < pattern.len() {
1712 if path_bytes.len() < simple {
1713 return false;
1714 }
1715 let path_lit = &path_bytes[..simple];
1716 let pat_lit = &pattern_bytes[..simple];
1717 let same = if magic.icase {
1718 path_lit.eq_ignore_ascii_case(pat_lit)
1719 } else {
1720 path_lit == pat_lit
1721 };
1722 if !same {
1723 return false;
1724 }
1725 let pat_rest = &pattern[simple..];
1726 let path_rest = &path[simple..];
1727 return wildmatch(pat_rest.as_bytes(), path_rest.as_bytes(), wm_flags);
1728 }
1729
1730 ps_str_eq(pattern, path, magic.icase) || path_is_under_dir(path, pattern, magic.icase)
1731}
1732
1733fn ps_str_eq(a: &str, b: &str, icase: bool) -> bool {
1734 if icase {
1735 a.eq_ignore_ascii_case(b)
1736 } else {
1737 a == b
1738 }
1739}
1740
1741fn path_starts_with(path: &str, prefix: &str, icase: bool) -> bool {
1742 if icase {
1743 path.get(..prefix.len())
1744 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
1745 } else {
1746 path.starts_with(prefix)
1747 }
1748}
1749
1750fn path_is_under_dir(path: &str, dir: &str, icase: bool) -> bool {
1752 path.as_bytes().get(dir.len()) == Some(&b'/') && path_starts_with(path, dir, icase)
1753}
1754
1755fn literal_prefix_match(pattern: &str, path: &str) -> bool {
1756 if let Some(prefix) = pattern.strip_suffix('/') {
1757 return path == prefix || path_is_under_dir(path, prefix, false);
1758 }
1759 path == pattern || path_is_under_dir(path, pattern, false)
1760}
1761
1762fn ls_tree_literal_match(pattern: &str, path: &str, ctx: PathspecMatchContext) -> bool {
1764 if let Some(prefix) = pattern.strip_suffix('/') {
1765 if path_is_under_dir(path, prefix, false) {
1766 return true;
1767 }
1768 if path == prefix {
1769 return ctx.is_directory || ctx.is_git_submodule;
1770 }
1771 return false;
1772 }
1773 path == pattern || path_is_under_dir(path, pattern, false)
1774}
1775
1776#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1781pub struct PathspecMatchContext {
1782 pub is_directory: bool,
1784 pub is_git_submodule: bool,
1786 pub precompose_paths: bool,
1788}
1789
1790#[must_use]
1800pub fn matches_pathspec(spec: &str, path: &str) -> bool {
1801 matches_pathspec_with_context(spec, path, PathspecMatchContext::default())
1802}
1803
1804#[must_use]
1808pub fn matches_pathspec_with_context(spec: &str, path: &str, ctx: PathspecMatchContext) -> bool {
1809 let spec_nfc: Cow<'_, str> = if ctx.precompose_paths {
1810 precompose_utf8_path(spec)
1811 } else {
1812 Cow::Borrowed(spec)
1813 };
1814 let path_nfc: Cow<'_, str> = if ctx.precompose_paths {
1815 precompose_utf8_path(path)
1816 } else {
1817 Cow::Borrowed(path)
1818 };
1819 let spec = spec_nfc.as_ref();
1820 let path = path_nfc.as_ref();
1821
1822 let trimmed = spec.strip_prefix("./").unwrap_or(spec);
1823 if trimmed == "." || trimmed.is_empty() {
1824 return true;
1825 }
1826
1827 let (elem_magic, raw_pattern) = parse_element_magic(trimmed);
1828 let magic = combine_magic(elem_magic);
1829
1830 if magic.literal && magic.glob {
1831 return false;
1832 }
1833 if magic.exclude {
1834 return false;
1835 }
1836
1837 let pattern = strip_top_magic(raw_pattern);
1838 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1839 match path_for_match_under_magic_prefix(path, prefix) {
1840 Some(rest) => rest,
1841 None => return false,
1842 }
1843 } else {
1844 path
1845 };
1846
1847 if magic.literal {
1848 if let Some(prefix) = pattern.strip_suffix('/') {
1849 if path_is_under_dir(path_for_match, prefix, false) {
1850 return true;
1851 }
1852 if path_for_match == prefix {
1853 return ctx.is_directory || ctx.is_git_submodule;
1854 }
1855 return false;
1856 }
1857 return path_for_match == pattern || path_is_under_dir(path_for_match, pattern, false);
1858 }
1859
1860 if let Some(prefix) = pattern.strip_suffix('/') {
1862 if simple_length(pattern) == pattern.len() {
1863 if path_is_under_dir(path_for_match, prefix, false) {
1864 return true;
1865 }
1866 if path_for_match == prefix {
1867 return ctx.is_directory || ctx.is_git_submodule;
1868 }
1869 return false;
1870 }
1871 }
1872
1873 if pathspec_matches_tail(pattern, path_for_match, magic) {
1874 return true;
1875 }
1876
1877 if (ctx.is_directory || ctx.is_git_submodule)
1878 && !path_for_match.is_empty()
1879 && pattern.len() > path_for_match.len()
1880 && pattern.as_bytes().get(path_for_match.len()) == Some(&b'/')
1881 && pattern.starts_with(path_for_match)
1882 && simple_length(pattern) < pattern.len()
1883 {
1884 return true;
1885 }
1886
1887 false
1888}
1889
1890#[must_use]
1892pub fn context_from_mode_octal(mode: &str) -> PathspecMatchContext {
1893 let Ok(bits) = u32::from_str_radix(mode, 8) else {
1894 return PathspecMatchContext::default();
1895 };
1896 context_from_mode_bits(bits)
1897}
1898
1899#[must_use]
1901pub fn context_from_mode_bits(mode: u32) -> PathspecMatchContext {
1902 let ty = mode & 0o170000;
1903 PathspecMatchContext {
1904 is_directory: ty == 0o040000,
1905 is_git_submodule: ty == 0o160000,
1906 precompose_paths: false,
1907 }
1908}
1909
1910#[must_use]
1916pub fn matches_ls_tree_pathspec(
1917 spec: &str,
1918 path: &str,
1919 mode: u32,
1920 attr_rules: &[AttrRule],
1921) -> bool {
1922 let (elem_magic, raw_pattern) = parse_element_magic(spec);
1923 let mut magic = combine_magic(elem_magic);
1924 magic.exclude = false;
1925
1926 if magic.literal && magic.glob {
1927 return false;
1928 }
1929
1930 let ctx = context_from_mode_bits(mode);
1931 let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
1932
1933 if !magic.attr_requirements.is_empty()
1934 && !attr_requirements_match(
1935 &magic.attr_requirements,
1936 AttrLookup::rules_only(attr_rules),
1937 path,
1938 is_dir_for_attr,
1939 mode,
1940 )
1941 {
1942 return false;
1943 }
1944
1945 let pattern = strip_top_magic(raw_pattern);
1946 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
1947 match path_for_match_under_magic_prefix(path, prefix) {
1948 Some(rest) => rest,
1949 None => return false,
1950 }
1951 } else {
1952 path
1953 };
1954
1955 if magic.literal || magic.glob || magic.icase {
1956 return pathspec_matches_tail(pattern, path_for_match, magic);
1957 }
1958
1959 let spec_nfc: Cow<'_, str> = Cow::Borrowed(pattern);
1960 let path_nfc: Cow<'_, str> = Cow::Borrowed(path_for_match);
1961 let pattern = spec_nfc.as_ref();
1962 let path = path_nfc.as_ref();
1963
1964 let trimmed = pattern.strip_prefix("./").unwrap_or(pattern);
1965 if trimmed == "." || trimmed.is_empty() {
1966 return true;
1967 }
1968
1969 let uses_star_or_question = trimmed.contains('*') || trimmed.contains('?');
1970 if !uses_star_or_question {
1971 return ls_tree_literal_match(trimmed, path, ctx);
1972 }
1973
1974 let nwl = simple_length(trimmed);
1975 let flags = 0u32;
1976 if nwl == trimmed.len() {
1977 return wildmatch(trimmed.as_bytes(), path.as_bytes(), flags);
1978 }
1979 let lit = trimmed.as_bytes().get(..nwl).unwrap_or_default();
1980 let path_b = path.as_bytes();
1981 if path_b.len() < nwl {
1982 return false;
1983 }
1984 if &path_b[..nwl] != lit {
1985 return false;
1986 }
1987 let pat_rest = &trimmed[nwl..];
1988 let path_rest = &path[nwl..];
1989 wildmatch(pat_rest.as_bytes(), path_rest.as_bytes(), flags)
1990}
1991
1992#[must_use]
1996pub fn matches_pathspec_for_object(
1997 spec: &str,
1998 path: &str,
1999 mode: u32,
2000 attr_rules: &[AttrRule],
2001) -> bool {
2002 matches_pathspec_for_object_with_attrs(spec, path, mode, AttrLookup::rules_only(attr_rules))
2003}
2004
2005fn matches_pathspec_for_object_with_attrs(
2006 spec: &str,
2007 path: &str,
2008 mode: u32,
2009 attrs: AttrLookup<'_>,
2010) -> bool {
2011 let (elem_magic, raw_pattern) = parse_element_magic(spec);
2012 let mut magic = combine_magic(elem_magic);
2013 magic.exclude = false;
2014
2015 if magic.literal && magic.glob {
2016 return false;
2017 }
2018
2019 let ctx = context_from_mode_bits(mode);
2020 let is_dir_for_attr = path.ends_with('/') || ctx.is_directory || ctx.is_git_submodule;
2021
2022 if !magic.attr_requirements.is_empty()
2023 && !attr_requirements_match(&magic.attr_requirements, attrs, path, is_dir_for_attr, mode)
2024 {
2025 return false;
2026 }
2027
2028 let pattern = strip_top_magic(raw_pattern);
2029 let path_for_match = if let Some(prefix) = magic.prefix.as_deref() {
2030 match path_for_match_under_magic_prefix(path, prefix) {
2031 Some(rest) => rest,
2032 None => return false,
2033 }
2034 } else {
2035 path
2036 };
2037 if magic.literal || magic.glob || magic.icase {
2038 pathspec_matches_tail(pattern, path_for_match, magic)
2039 } else {
2040 matches_pathspec_with_context(pattern, path_for_match, ctx)
2041 }
2042}
2043
2044#[derive(Debug, Clone)]
2046pub struct PathOutsideRepository {
2047 pub elt: String,
2049 pub path: String,
2051 pub work_tree: PathBuf,
2053}
2054
2055impl std::fmt::Display for PathOutsideRepository {
2056 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2057 write!(
2058 f,
2059 "{}: '{}' is outside repository at '{}'",
2060 self.elt,
2061 self.path,
2062 self.work_tree.display()
2063 )
2064 }
2065}
2066
2067impl From<PathOutsideRepository> for PathspecResolveError {
2068 fn from(outside: PathOutsideRepository) -> Self {
2069 Self::OutsideRepository {
2070 elt: outside.elt,
2071 path: outside.path,
2072 work_tree: outside.work_tree.display().to_string(),
2073 }
2074 }
2075}
2076
2077pub fn resolve_magic_pathspec(spec: &str, cwd_prefix: &str) -> Option<String> {
2083 if !spec.starts_with(":(") {
2084 return None;
2085 }
2086 let close_idx = spec.find(')')?;
2087 let magic_prefix = &spec[..=close_idx];
2088 let tail = &spec[close_idx + 1..];
2089 Some(resolve_magic_pathspec_parts(magic_prefix, tail, cwd_prefix))
2090}
2091
2092fn resolve_magic_pathspec_parts(magic_prefix: &str, tail: &str, cwd_prefix: &str) -> String {
2093 if has_magic_prefix_token(magic_prefix) {
2094 return format!("{magic_prefix}{tail}");
2095 }
2096
2097 if let Some(rooted_tail) = tail.strip_prefix('/') {
2098 return format!("{magic_prefix}{}", normalize_relative_path_str(rooted_tail));
2099 }
2100
2101 let combined = if cwd_prefix.is_empty() {
2102 normalize_relative_path_str(tail)
2103 } else {
2104 normalize_relative_path_str(&format!("{cwd_prefix}{tail}"))
2105 };
2106
2107 let cwd_base = normalize_relative_path_str(cwd_prefix.trim_end_matches('/'));
2108 if !cwd_base.is_empty()
2109 && (combined == cwd_base || combined.starts_with(&format!("{cwd_base}/")))
2110 {
2111 let after_base = combined
2112 .strip_prefix(&cwd_base)
2113 .unwrap_or(combined.as_str());
2114 let remainder = after_base.strip_prefix('/').unwrap_or(after_base);
2115 let magic_with_prefix = inject_magic_prefix_token(magic_prefix, &format!("{cwd_base}/"));
2116 return format!("{magic_with_prefix}{remainder}");
2117 }
2118
2119 format!("{magic_prefix}{combined}")
2120}
2121
2122fn has_magic_prefix_token(magic_prefix: &str) -> bool {
2123 let Some(inner) = magic_prefix
2124 .strip_prefix(":(")
2125 .and_then(|s| s.strip_suffix(')'))
2126 else {
2127 return false;
2128 };
2129 inner
2130 .split(',')
2131 .map(str::trim)
2132 .any(|token| token.starts_with("prefix:"))
2133}
2134
2135fn inject_magic_prefix_token(magic_prefix: &str, prefix: &str) -> String {
2136 let Some(inner) = magic_prefix
2137 .strip_prefix(":(")
2138 .and_then(|s| s.strip_suffix(')'))
2139 else {
2140 return magic_prefix.to_string();
2141 };
2142 if inner.trim().is_empty() {
2143 format!(":(prefix:{prefix})")
2144 } else {
2145 format!(":({inner},prefix:{prefix})")
2146 }
2147}
2148
2149fn normalize_repo_root_relative_pathspec(pathspec: &str) -> String {
2154 let mut spec = pathspec;
2155 let mut stripped = false;
2156 while let Some(rest) = spec.strip_prefix("./") {
2157 stripped = true;
2158 spec = rest.trim_start_matches('/');
2159 }
2160 if !stripped {
2161 return pathspec.to_owned();
2162 }
2163 if spec.is_empty() {
2164 return ".".to_owned();
2165 }
2166 if spec.starts_with(':') && !literal_pathspecs_enabled() {
2167 return format!(":(literal){spec}");
2168 }
2169 spec.to_owned()
2170}
2171
2172fn normalize_pathspec_separators(pathspec: &str) -> std::borrow::Cow<'_, str> {
2174 #[cfg(windows)]
2175 {
2176 if !pathspec.starts_with(':') && pathspec.contains('\\') {
2177 return std::borrow::Cow::Owned(pathspec.replace('\\', "/"));
2178 }
2179 }
2180 std::borrow::Cow::Borrowed(pathspec)
2181}
2182
2183fn normalize_relative_path_str(path: &str) -> String {
2184 let mut parts: Vec<String> = Vec::new();
2185 for component in std::path::Path::new(path).components() {
2186 match component {
2187 std::path::Component::CurDir => {}
2188 std::path::Component::ParentDir => {
2189 parts.pop();
2190 }
2191 std::path::Component::Normal(seg) => {
2192 parts.push(seg.to_string_lossy().to_string());
2193 }
2194 std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
2195 }
2196 }
2197 parts.join("/")
2198}
2199
2200#[must_use]
2202pub fn pathdiff(cwd: &Path, work_tree: &Path) -> Option<String> {
2203 use crate::git_path::{path_for_disk_compare, path_to_git_slash};
2204
2205 let cwd_cmp = path_for_disk_compare(cwd);
2206 let wt_cmp = path_for_disk_compare(work_tree);
2207
2208 if cwd_cmp == wt_cmp {
2209 return None;
2210 }
2211
2212 let rel = cwd_cmp.strip_prefix(&wt_cmp).ok()?;
2213 let git = path_to_git_slash(rel);
2214 if git.is_empty() {
2215 None
2216 } else {
2217 Some(git)
2218 }
2219}
2220
2221fn prepend_cwd_to_short_exclude_pathspec(spec: &str, cwd: &str) -> Option<String> {
2225 let cwd = cwd.trim_end_matches('/');
2226 if cwd.is_empty() {
2227 return None;
2228 }
2229 let (elem_magic, pattern) = parse_element_magic(spec);
2230 let magic = combine_magic(elem_magic);
2231 if !magic.exclude || magic.top {
2232 return None;
2233 }
2234 if pattern.is_empty() || pattern.starts_with('/') {
2235 return None;
2236 }
2237 if magic.glob || magic.literal || magic.icase || !magic.attr_requirements.is_empty() {
2238 return None;
2239 }
2240 Some(format!(":(exclude,prefix:{cwd}/){pattern}"))
2241}
2242
2243#[must_use]
2245pub fn pathspec_match_context_with_precompose(precompose_paths: bool) -> PathspecMatchContext {
2246 PathspecMatchContext {
2247 precompose_paths,
2248 ..PathspecMatchContext::default()
2249 }
2250}
2251
2252#[must_use]
2254pub fn matches_pathspec_list_precompose(
2255 path: &str,
2256 specs: &[String],
2257 precompose_paths: bool,
2258) -> bool {
2259 matches_pathspec_list_with_context(
2260 path,
2261 specs,
2262 pathspec_match_context_with_precompose(precompose_paths),
2263 )
2264}
2265
2266#[must_use]
2268pub fn argv_pathspec_preserves_spelling(pathspec: &str) -> bool {
2269 pathspec.starts_with(":(")
2270 || pathspec.starts_with(":/")
2271 || pathspec.starts_with(":!")
2272 || pathspec.starts_with(":^")
2273}
2274
2275#[must_use]
2277pub fn precompose_argv_pathspec(pathspec: &str) -> Cow<'_, str> {
2278 if argv_pathspec_preserves_spelling(pathspec) {
2279 Cow::Borrowed(pathspec)
2280 } else {
2281 precompose_utf8_path(pathspec)
2282 }
2283}
2284
2285#[must_use]
2290pub fn resolve_pathspec(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2291 resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, false)
2292}
2293
2294#[must_use]
2296pub fn resolve_pathspec_with_argv_precompose(
2297 pathspec: &str,
2298 work_tree: &Path,
2299 prefix: Option<&str>,
2300 argv_precompose: bool,
2301) -> String {
2302 let pathspec = if argv_precompose {
2303 precompose_argv_pathspec(pathspec)
2304 } else {
2305 Cow::Borrowed(pathspec)
2306 };
2307 resolve_pathspec_impl(pathspec.as_ref(), work_tree, prefix)
2308}
2309
2310fn resolve_pathspec_impl(pathspec: &str, work_tree: &Path, prefix: Option<&str>) -> String {
2311 let pathspec = normalize_pathspec_separators(pathspec);
2312 let pathspec = pathspec.as_ref();
2313 if pathspec == "." {
2316 return match prefix {
2317 Some(p) if !p.is_empty() => p.to_owned(),
2318 _ => ".".to_owned(),
2319 };
2320 }
2321 if pathspec.contains("../") || pathspec.starts_with("../") {
2322 let cwd = match prefix.filter(|p| !p.is_empty()) {
2323 Some(p) => work_tree.join(p),
2324 None => work_tree.to_path_buf(),
2325 };
2326 let abs = cwd.join(pathspec);
2327 let mut parts: Vec<std::ffi::OsString> = Vec::new();
2328 for component in abs.components() {
2329 use std::path::Component;
2330 match component {
2331 Component::ParentDir => {
2332 parts.pop();
2333 }
2334 Component::CurDir => {}
2335 other => parts.push(other.as_os_str().to_os_string()),
2336 }
2337 }
2338 let abs_norm: PathBuf = parts.iter().collect();
2339 if let Some(rel) = crate::git_path::strip_worktree_prefix(&abs_norm, work_tree) {
2340 return rel;
2341 }
2342 }
2343 if Path::new(pathspec).is_absolute() {
2344 let abs = Path::new(pathspec);
2345 if let Some(rel) = crate::git_path::strip_worktree_prefix(abs, work_tree) {
2346 return rel;
2347 }
2348 return pathspec.to_owned();
2349 }
2350
2351 if pathspec.starts_with(':') {
2352 if let Some(p) = prefix {
2353 if !p.is_empty() && !literal_pathspecs_enabled() {
2354 let cwd_ps = format!("{}/", p.trim_end_matches('/'));
2355 if pathspec.starts_with(":(") {
2356 if let Some(resolved) = resolve_magic_pathspec(pathspec, &cwd_ps) {
2357 return resolved;
2358 }
2359 return pathspec.to_owned();
2360 }
2361 if pathspec_is_exclude(pathspec) {
2362 if let Some(fixed) = prepend_cwd_to_short_exclude_pathspec(pathspec, p) {
2363 return fixed;
2364 }
2365 }
2366 }
2367 }
2368 if let Some(rest) = pathspec.strip_prefix(":/") {
2369 if rest.starts_with('!') || rest.starts_with('^') {
2371 return pathspec.to_owned();
2372 }
2373 return rest.to_owned();
2374 }
2375 if pathspec.starts_with(":(") {
2378 return pathspec.to_owned();
2379 }
2380 return pathspec.to_owned();
2381 }
2382
2383 match prefix {
2384 Some(p) if !p.is_empty() => {
2385 normalize_relative_path_str(&PathBuf::from(p).join(pathspec).to_string_lossy())
2386 }
2387 _ => normalize_repo_root_relative_pathspec(pathspec),
2388 }
2389}
2390
2391pub fn resolve_pathspec_in_worktree(
2396 elt: &str,
2397 pathspec: &str,
2398 work_tree: &Path,
2399 prefix: Option<&str>,
2400) -> Result<String, PathOutsideRepository> {
2401 resolve_pathspec_in_worktree_with_argv_precompose(elt, pathspec, work_tree, prefix, false)
2402}
2403
2404pub(crate) fn resolve_pathspec_in_worktree_with_argv_precompose(
2409 elt: &str,
2410 pathspec: &str,
2411 work_tree: &Path,
2412 prefix: Option<&str>,
2413 argv_precompose: bool,
2414) -> Result<String, PathOutsideRepository> {
2415 let resolved =
2416 resolve_pathspec_with_argv_precompose(pathspec, work_tree, prefix, argv_precompose);
2417 if Path::new(&resolved).is_absolute() {
2418 let wt = work_tree
2419 .canonicalize_simplified()
2420 .unwrap_or_else(|_| work_tree.to_path_buf());
2421 return Err(PathOutsideRepository {
2422 elt: elt.to_string(),
2423 path: resolved,
2424 work_tree: wt,
2425 });
2426 }
2427 Ok(resolved)
2428}
2429
2430#[must_use]
2434pub fn normalize_worktree_file_path(
2435 file_path: &str,
2436 work_tree: &Path,
2437 prefix: Option<&str>,
2438) -> String {
2439 normalize_worktree_file_path_with_git_dir(file_path, work_tree, prefix, None)
2440}
2441
2442#[must_use]
2444pub fn normalize_worktree_file_path_with_git_dir(
2445 file_path: &str,
2446 work_tree: &Path,
2447 prefix: Option<&str>,
2448 git_dir: Option<&Path>,
2449) -> String {
2450 let argv_precompose = argv_precompose_enabled(git_dir);
2451 let resolved =
2452 resolve_pathspec_with_argv_precompose(file_path, work_tree, prefix, argv_precompose);
2453 if Path::new(&resolved).is_absolute() {
2454 file_path.to_string()
2455 } else {
2456 resolved
2457 }
2458}
2459
2460#[cfg(test)]
2461mod tree_entry_pathspec_tests {
2462 use super::*;
2463
2464 #[test]
2465 fn t6130_bracket_filename_matches_pathspec() {
2466 assert!(matches_pathspec("f[o][o]", "f[o][o]"));
2467 assert!(matches_pathspec(":(glob)f[o][o]", "f[o][o]"));
2468 }
2469
2470 #[test]
2471 fn literal_prefix_and_exact() {
2472 assert!(matches_pathspec("path1", "path1/file1"));
2473 assert!(matches_pathspec_with_context(
2474 "path1/",
2475 "path1/file1",
2476 PathspecMatchContext::default()
2477 ));
2478 assert!(matches_pathspec("file0", "file0"));
2479 assert!(!matches_pathspec("path", "path1/file1"));
2480 }
2481
2482 #[test]
2483 fn dir_prefix_needs_slash_boundary() {
2484 assert!(matches_pathspec("a/b", "a/b/c"));
2485 assert!(!matches_pathspec("a/b", "a/bc"));
2486 assert!(!matches_pathspec("a/b", "a"));
2487 assert!(matches_pathspec(":(literal)dir", "dir/x"));
2488 assert!(!matches_pathspec(":(literal)dir", "dirx"));
2489 assert!(matches_pathspec(":(icase)DIR", "dir/x"));
2490 assert!(!matches_pathspec(":(icase)DIR", "dirx"));
2491 assert!(matches_pathspec("dir/", "dir/x"));
2492 assert!(!matches_pathspec("dir/", "dir"));
2493 }
2494
2495 #[test]
2496 fn sorted_lookup_agrees_with_linear_scan() {
2497 let mut paths: Vec<&str> = vec![
2498 "a",
2499 "a-b",
2500 "a.txt",
2501 "a/b",
2502 "a/b/c.txt",
2503 "a/bc",
2504 "a0",
2505 "b/x[1].txt",
2506 "dir/sub/file",
2507 "dir-sub",
2508 "f[o][o]",
2509 "z",
2510 "caf\u{e9}/menu",
2511 "cafe\u{301}/old",
2512 "\u{212a}.txt",
2513 ];
2514 paths.sort_unstable();
2515 let specs = [
2516 "caf\u{e9}",
2517 "cafe\u{301}/",
2518 "cafe\u{301}/old",
2519 "K.txt",
2520 "\u{212a}.txt",
2521 "a",
2522 "a/",
2523 "a/b",
2524 "a/b/",
2525 "a/bc",
2526 "a-",
2527 "a-b",
2528 "a.txt",
2529 "b",
2530 "b/",
2531 "dir",
2532 "dir/sub",
2533 "dir/sub/",
2534 "dir/su",
2535 "dir-sub",
2536 "f[o][o]",
2537 "*.txt",
2538 "a/*",
2539 ":(glob)**/*.txt",
2540 ":(literal)f[o][o]",
2541 ":(icase)A/B",
2542 ":!a",
2543 ".",
2544 "./a/b",
2545 "",
2546 "z",
2547 "zz",
2548 "/",
2549 "a//",
2550 ];
2551 for ctx in [
2552 PathspecMatchContext::default(),
2553 PathspecMatchContext {
2554 precompose_paths: true,
2555 ..PathspecMatchContext::default()
2556 },
2557 PathspecMatchContext {
2558 is_directory: true,
2559 ..PathspecMatchContext::default()
2560 },
2561 ] {
2562 for spec in specs {
2563 let list = [spec.to_owned()];
2564 let linear = paths
2565 .iter()
2566 .any(|p| matches_pathspec_list_with_context(p, &list, ctx));
2567 assert_eq!(
2568 sorted_paths_match_pathspec(spec, &paths, ctx),
2569 linear,
2570 "spec {spec:?} ctx {ctx:?}"
2571 );
2572 }
2573 }
2574 let empty: [&str; 0] = [];
2575 assert!(!sorted_paths_match_pathspec(
2576 "a",
2577 &empty,
2578 PathspecMatchContext::default()
2579 ));
2580 }
2581
2582 #[test]
2583 fn list_matcher_agrees_with_linear_matching() {
2584 let paths = [
2585 "a",
2586 "a-b",
2587 "a.txt",
2588 "a/",
2589 "a/b",
2590 "a/b/c.txt",
2591 "a/bc",
2592 "a//x",
2593 "a0",
2594 "b/x[1].txt",
2595 "dir/sub/file",
2596 "dir-sub",
2597 "f[o][o]",
2598 "z",
2599 "zz/a",
2600 "é/x",
2601 "e\u{301}/y",
2602 "\u{212a}.txt",
2603 "K.txt",
2604 "",
2605 ];
2606 let lists: &[&[&str]] = &[
2607 &[],
2608 &["a"],
2609 &["a/"],
2610 &["a//"],
2611 &["a/b", "dir/sub/", "z"],
2612 &["a/b/", "a/bc", "dir", "zz"],
2613 &["dir/su", "dir-sub", "f[o][o]"],
2614 &["é", "a-"],
2615 &["e\u{301}", "z"],
2616 &["e\u{301}/y", "K.txt"],
2617 &["\u{212a}.txt"],
2618 &["a", "*.txt"],
2619 &["dir", ":!dir/sub"],
2620 &[":!a"],
2621 &["./a", "z"],
2622 &[".", "a"],
2623 &["", "a"],
2624 &[":(icase)A/B", "z"],
2625 ];
2626 for ctx in [
2627 PathspecMatchContext::default(),
2628 PathspecMatchContext {
2629 precompose_paths: true,
2630 ..PathspecMatchContext::default()
2631 },
2632 PathspecMatchContext {
2633 is_directory: true,
2634 ..PathspecMatchContext::default()
2635 },
2636 ] {
2637 for list in lists {
2638 let specs: Vec<String> = list.iter().map(|s| (*s).to_owned()).collect();
2639 let matcher = PathspecListMatcher::new(&specs, ctx);
2640 for path in paths {
2641 assert_eq!(
2642 matcher.matches(path),
2643 matches_pathspec_list_with_context(path, &specs, ctx),
2644 "path {path:?} specs {specs:?} ctx {ctx:?}"
2645 );
2646 }
2647 }
2648 }
2649 }
2650
2651 #[test]
2652 fn list_matcher_uses_literal_lookup_only_for_plain_lists() {
2653 let ctx = PathspecMatchContext::default();
2654 let plain = vec!["a/b".to_owned(), "dir/".to_owned()];
2655 assert!(PathspecListMatcher::new(&plain, ctx).literals.is_some());
2656 let glob = vec!["a/b".to_owned(), "*.txt".to_owned()];
2657 assert!(PathspecListMatcher::new(&glob, ctx).literals.is_none());
2658 let exclude = vec!["a/b".to_owned(), ":!a/b/c".to_owned()];
2659 assert!(PathspecListMatcher::new(&exclude, ctx).literals.is_none());
2660 assert!(PathspecListMatcher::new(&[], ctx).literals.is_none());
2661 }
2662
2663 #[test]
2664 fn precomposed_literal_specs_keep_fast_lookups() {
2665 let ctx = PathspecMatchContext {
2666 precompose_paths: true,
2667 ..PathspecMatchContext::default()
2668 };
2669 let specs: Vec<String> = (0..100).map(|i| format!("d{i}/file.txt")).collect();
2670 let matcher = PathspecListMatcher::new(&specs, ctx);
2671 assert!(
2672 matcher.literals.is_some(),
2673 "core.precomposeunicode must not force a per-spec scan of every path"
2674 );
2675 assert!(matcher.matches("d42/file.txt"));
2676 assert!(!matcher.matches("d42/other.txt"));
2677 let nfd = vec!["cafe\u{301}".to_owned()];
2678 let matcher = PathspecListMatcher::new(&nfd, ctx);
2679 assert!(matcher.literals.is_some());
2680 assert!(matcher.matches("caf\u{e9}/menu"));
2681 assert!(matcher.matches("cafe\u{301}/menu"));
2682 assert!(exact_literal_pathspec_set(&specs, ctx).is_none());
2683 }
2684
2685 #[test]
2686 fn ls_tree_bracket_in_name_is_literal_prefix() {
2687 assert!(matches_ls_tree_pathspec(
2688 "a[a]",
2689 "a[a]/three",
2690 0o100644,
2691 &[]
2692 ));
2693 assert!(!matches_pathspec_with_context(
2694 "a[a]",
2695 "a[a]/three",
2696 PathspecMatchContext::default()
2697 ));
2698 }
2699
2700 #[test]
2701 fn wildcards_cross_slash_by_default() {
2702 assert!(matches_pathspec("f*", "file0"));
2703 assert!(matches_pathspec("*file1", "path1/file1"));
2704 assert!(matches_pathspec_with_context(
2705 "path1/f*",
2706 "path1",
2707 PathspecMatchContext {
2708 is_directory: true,
2709 ..Default::default()
2710 }
2711 ));
2712 assert!(matches_pathspec("path1/*file1", "path1/file1"));
2713 }
2714
2715 #[test]
2716 fn glob_double_star_txt_at_repo_root() {
2717 assert!(pathspec_matches(":(glob)**/*.txt", "untracked.txt"));
2718 assert!(pathspec_matches(":(glob)**/*.txt", "d/untracked.txt"));
2719 }
2720
2721 #[test]
2722 fn trailing_slash_directory_only() {
2723 assert!(!matches_pathspec_with_context(
2724 "file0/",
2725 "file0",
2726 PathspecMatchContext::default()
2727 ));
2728 assert!(matches_pathspec_with_context(
2729 "file0/",
2730 "file0",
2731 PathspecMatchContext {
2732 is_directory: true,
2733 ..Default::default()
2734 }
2735 ));
2736 assert!(matches_pathspec_with_context(
2737 "submod/",
2738 "submod",
2739 PathspecMatchContext {
2740 is_git_submodule: true,
2741 ..Default::default()
2742 }
2743 ));
2744 }
2745
2746 #[test]
2747 fn exclude_top_short_magic_subtracts_from_positive() {
2748 let specs = vec!["*".to_string(), ":/!sub2".to_string()];
2749 assert!(matches_pathspec_list("sub/file", &specs));
2750 assert!(!matches_pathspec_list("sub2/file", &specs));
2751 assert!(pathspec_exclude_matches(":/!sub2", "sub2/file"));
2752 }
2753}
2754
2755#[cfg(test)]
2756mod exact_literal_pathspec_set_tests {
2757 use super::*;
2758
2759 #[test]
2760 fn exact_literal_pathspec_set_accepts_file_paths() {
2761 let ctx = PathspecMatchContext::default();
2762 let set = exact_literal_pathspec_set(&["large.txt".to_string()], ctx).expect("set");
2763 assert_eq!(set.len(), 1);
2764 assert!(set.contains("large.txt"));
2765 }
2766
2767 #[test]
2768 fn exact_literal_pathspec_set_rejects_directory_trailing_slash() {
2769 let ctx = PathspecMatchContext::default();
2770 assert!(exact_literal_pathspec_set(&["src/".to_string()], ctx).is_none());
2771 }
2772
2773 #[test]
2774 fn exact_literal_pathspec_set_rejects_glob_magic() {
2775 let ctx = PathspecMatchContext::default();
2776 assert!(exact_literal_pathspec_set(&[":(glob)*.rs".to_string()], ctx).is_none());
2777 }
2778}
2779
2780#[cfg(test)]
2781mod pathspec_list_tests {
2782 use super::*;
2783 use crate::crlf::parse_gitattributes_content;
2784
2785 #[test]
2786 fn exclude_removes_paths_matching_icase_positive() {
2787 let specs = vec![
2788 ":(icase)*.txt".to_string(),
2789 ":(exclude)submodule/subsub/*".to_string(),
2790 ];
2791 assert!(path_allowed_by_pathspec_list(&specs, "submodule/g.txt"));
2792 assert!(!path_allowed_by_pathspec_list(
2793 &specs,
2794 "submodule/subsub/e.txt"
2795 ));
2796 }
2797
2798 #[test]
2799 fn prefixed_attr_exclude_removes_matching_child_path() {
2800 let specs = vec![
2801 "sub".to_string(),
2802 ":(exclude,attr:labelB,prefix:sub/)".to_string(),
2803 ];
2804 let exclude_only = vec![":(exclude,attr:labelB,prefix:sub/)".to_string()];
2805 let attrs = parse_gitattributes_content("fileB labelB\n");
2806 assert!(!matches_pathspec_list_for_object(
2807 "sub/fileB",
2808 0o100644,
2809 &attrs,
2810 &specs,
2811 ));
2812 assert!(!matches_pathspec_list_for_object(
2813 "sub/fileB",
2814 0o100644,
2815 &attrs,
2816 &exclude_only,
2817 ));
2818 }
2819}
2820
2821#[cfg(test)]
2822mod resolve_pathspec_tests {
2823 use super::*;
2824
2825 fn wt() -> PathBuf {
2826 PathBuf::from("/tmp/grit-pathspec-worktree")
2827 }
2828
2829 #[test]
2830 fn strips_leading_dot_slash_at_repo_root() {
2831 let wt = wt();
2832 assert_eq!(resolve_pathspec("./-", &wt, None), "-");
2833 assert_eq!(resolve_pathspec("./a/b", &wt, None), "a/b");
2834 assert_eq!(resolve_pathspec("././a", &wt, None), "a");
2835 assert_eq!(resolve_pathspec(".//a", &wt, None), "a");
2836 assert_eq!(resolve_pathspec("./", &wt, None), ".");
2837 assert_eq!(resolve_pathspec(".", &wt, None), ".");
2838 }
2839
2840 #[test]
2841 fn prefixed_cwd_resolution_unchanged() {
2842 let wt = wt();
2843 assert_eq!(
2844 resolve_pathspec("file", &wt, Some("sub/dir")),
2845 "sub/dir/file"
2846 );
2847 assert_eq!(resolve_pathspec(":(glob)*.rs", &wt, None), ":(glob)*.rs");
2848 }
2849
2850 #[test]
2851 fn dot_slash_colon_filename_stays_literal_not_exclude_magic() {
2852 let wt = wt();
2853 let resolved = resolve_pathspec("./:!foo", &wt, None);
2854 assert_eq!(resolved, ":(literal):!foo");
2855 assert!(!pathspec_is_exclude(&resolved));
2856 assert!(pathspec_matches(&resolved, ":!foo"));
2857 assert!(!pathspec_matches(&resolved, "other"));
2858 }
2859
2860 #[test]
2861 fn resolve_absolute_path_under_worktree() {
2862 let tmp = tempfile::tempdir().expect("tempdir");
2863 let wt = tmp.path().join("repo");
2864 std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2865 let file = wt.join("d/b.txt");
2866 std::fs::write(&file, b"x").expect("write");
2867 let wt = wt.canonicalize_simplified().expect("canonicalize");
2868 let abs = file.canonicalize_simplified().expect("canonicalize file");
2869 let spec = abs.to_string_lossy();
2870 assert_eq!(
2871 resolve_pathspec(&spec, &wt, None),
2872 "d/b.txt",
2873 "absolute forward-slash pathspec"
2874 );
2875 }
2876
2877 #[cfg(windows)]
2878 mod windows {
2879 use super::*;
2880
2881 #[test]
2882 fn resolve_backslash_relative_and_absolute_pathspecs() {
2883 let tmp = tempfile::tempdir().expect("tempdir");
2884 let wt = tmp.path().join("repo");
2885 std::fs::create_dir_all(wt.join("d")).expect("mkdir");
2886 let file_a = wt.join("d/a.txt");
2887 let file_b = wt.join("d/b.txt");
2888 std::fs::write(&file_a, b"a").expect("write");
2889 std::fs::write(&file_b, b"b").expect("write");
2890 let wt = wt.canonicalize_simplified().expect("canonicalize worktree");
2891
2892 assert_eq!(
2893 resolve_pathspec(r"d\a.txt", &wt, None),
2894 "d/a.txt",
2895 "backslash relative pathspec (issue #915 A)"
2896 );
2897
2898 let abs_back = file_b.canonicalize_simplified().expect("canonicalize");
2899 let abs_back_spec = abs_back.display().to_string();
2900 assert_eq!(
2901 resolve_pathspec(&abs_back_spec, &wt, None),
2902 "d/b.txt",
2903 "absolute backslash pathspec (issue #915 B)"
2904 );
2905
2906 let abs_forward = abs_back_spec.replace('\\', "/");
2907 assert_eq!(
2908 resolve_pathspec(&abs_forward, &wt, None),
2909 "d/b.txt",
2910 "absolute forward-slash pathspec (issue #915 C)"
2911 );
2912 }
2913 }
2914
2915 #[test]
2916 fn nfd_pathspec_matches_nfc_index_path_when_precompose_enabled() {
2917 let nfc_path = "caf\u{00e9}.txt";
2918 let nfd_spec = format!("cafe\u{0301}.txt");
2919 assert!(!matches_pathspec_list(&nfc_path, &[nfd_spec.clone()]));
2920 assert!(matches_pathspec_list_precompose(
2921 nfc_path,
2922 &[nfd_spec.clone()],
2923 true
2924 ));
2925 }
2926
2927 #[test]
2928 fn argv_precompose_normalizes_nfd_literal_pathspec() {
2929 let nfd = format!("cafe\u{0301}.txt");
2930 let nfc = precompose_argv_pathspec(&nfd);
2931 assert_eq!(nfc.as_ref(), "caf\u{00e9}.txt");
2932 assert!(argv_pathspec_preserves_spelling(":(glob)*.rs"));
2933 assert_eq!(
2934 precompose_argv_pathspec(":(glob)*.rs").as_ref(),
2935 ":(glob)*.rs"
2936 );
2937 }
2938}
2939
2940#[cfg(test)]
2941mod resolved_pathspecs_tests {
2942 use super::*;
2943 use crate::repo::{InitOptions, Repository};
2944
2945 fn repo_with_tree() -> (tempfile::TempDir, Repository) {
2946 let dir = tempfile::tempdir().expect("tempdir");
2947 let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
2948 std::fs::write(dir.path().join("top.txt"), b"a").expect("write");
2949 std::fs::create_dir_all(dir.path().join("sub")).expect("mkdir");
2950 std::fs::write(dir.path().join("sub/inner.txt"), b"b").expect("write");
2951 (dir, repo)
2952 }
2953
2954 #[test]
2955 fn resolved_pathspecs_subdir_prefix() {
2956 let (dir, repo) = repo_with_tree();
2957 let sub = dir.path().join("sub");
2958 let resolved =
2959 ResolvedPathspecs::resolve(&repo, &sub, &["inner.txt".to_string()], None).expect("ok");
2960 assert_eq!(resolved.specs, ["sub/inner.txt"]);
2961 assert!(resolved.scoped);
2962 }
2963
2964 #[test]
2965 fn resolved_pathspecs_top_level_magic() {
2966 let (dir, repo) = repo_with_tree();
2967 let resolved =
2968 ResolvedPathspecs::resolve(&repo, dir.path(), &[":/top.txt".to_string()], None)
2969 .expect("ok");
2970 assert_eq!(resolved.specs, ["top.txt"]);
2971 }
2972
2973 #[test]
2974 fn resolved_pathspecs_parent_outside_repo() {
2975 let (dir, repo) = repo_with_tree();
2976 let outside = dir.path().parent().expect("parent").join("outside.txt");
2977 std::fs::write(&outside, b"x").expect("write outside");
2978 let spec = outside.to_string_lossy().into_owned();
2979 let err =
2980 ResolvedPathspecs::resolve(&repo, dir.path(), &[spec], None).expect_err("outside");
2981 assert!(matches!(
2982 err,
2983 PathspecResolveError::OutsideRepository { .. }
2984 ));
2985 }
2986
2987 #[test]
2988 fn resolved_pathspecs_empty_argv() {
2989 let (dir, repo) = repo_with_tree();
2990 let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[String::new()], None)
2991 .expect_err("empty");
2992 assert_eq!(err, PathspecResolveError::EmptyPathspec);
2993 }
2994
2995 #[test]
2996 fn resolved_pathspecs_from_file_lf_and_quoted() {
2997 let (dir, repo) = repo_with_tree();
2998 let input = PathspecInput::new(b"top.txt\n\"sub/inner.txt\"\n".to_vec(), false);
2999 let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3000 assert_eq!(resolved.specs, ["top.txt", "sub/inner.txt"]);
3001 }
3002
3003 #[test]
3004 fn resolved_pathspecs_from_file_nul() {
3005 let (dir, repo) = repo_with_tree();
3006 let input = PathspecInput::new(b"top.txt\0sub/\0".to_vec(), true);
3007 let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3008 assert_eq!(resolved.specs, ["top.txt", "sub/"]);
3009 }
3010
3011 #[test]
3012 fn resolved_pathspecs_from_file_nul_preserves_literal_bytes() {
3013 let (dir, repo) = repo_with_tree();
3014 std::fs::write(dir.path().join(" spaced "), b"x").expect("write");
3015 let quoted_dir = dir.path().join("\"double\"");
3016 std::fs::create_dir_all("ed_dir).expect("mkdir");
3017 std::fs::write(quoted_dir.join("f"), b"y").expect("write");
3018 let input = PathspecInput::new(b" spaced \0\"double\"\0".to_vec(), true);
3019 let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect("ok");
3020 assert_eq!(resolved.sources, [" spaced ", "\"double\""]);
3021 }
3022
3023 #[test]
3024 fn resolved_pathspecs_from_file_blank_line_errors() {
3025 let (dir, repo) = repo_with_tree();
3026 let input = PathspecInput::new(b"\n".to_vec(), false);
3027 let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3028 assert_eq!(err, PathspecResolveError::EmptyPathspec);
3029 }
3030
3031 #[test]
3032 fn resolved_pathspecs_from_file_nul_empty_record_errors() {
3033 let (dir, repo) = repo_with_tree();
3034 let input = PathspecInput::new(b"a\0\0b".to_vec(), true);
3035 let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3036 assert_eq!(err, PathspecResolveError::EmptyPathspec);
3037 }
3038
3039 #[test]
3040 fn resolved_pathspecs_from_file_invalid_quote() {
3041 let (dir, repo) = repo_with_tree();
3042 let input = PathspecInput::new(b"\"bad\\z\"\n".to_vec(), false);
3043 let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3044 assert!(matches!(
3045 err,
3046 PathspecResolveError::FromFile(
3047 PathspecFromFileParseError::InvalidEscapeSequence { .. }
3048 )
3049 ));
3050 let input = PathspecInput::new(b"\"unterminated\n".to_vec(), false);
3051 let err = ResolvedPathspecs::resolve(&repo, dir.path(), &[], Some(input)).expect_err("err");
3052 assert!(matches!(
3053 err,
3054 PathspecResolveError::FromFile(PathspecFromFileParseError::InvalidCStyleQuoting { .. })
3055 ));
3056 }
3057
3058 #[test]
3059 fn resolved_pathspecs_entire_tree_when_unscoped() {
3060 let (dir, repo) = repo_with_tree();
3061 let resolved = ResolvedPathspecs::resolve(&repo, dir.path(), &[], None).expect("ok");
3062 assert!(resolved.is_entire_tree());
3063 assert!(resolved.specs.is_empty());
3064 }
3065}
3066
3067#[cfg(test)]
3068mod rev_walk_pathspec_resolution_tests {
3069 use super::*;
3070 use crate::config::environment::{Environment, RepositoryOptions};
3071 use crate::repo::{InitOptions, Repository};
3072
3073 fn repo_from_sub(worktree: &std::path::Path, sub: &std::path::Path) -> Repository {
3074 let mut env = Environment::empty();
3075 env.cwd = sub.to_path_buf();
3076 let mut opts = RepositoryOptions::empty();
3077 opts.environment = env;
3078 Repository::discover(Some(worktree), &opts).expect("discover")
3079 }
3080
3081 #[test]
3082 fn glob_magic_from_subdirectory_gets_prefix_and_matches() {
3083 let dir = tempfile::tempdir().expect("tempdir");
3084 let wt = dir.path();
3085 std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3086 std::fs::write(wt.join("sub/f.txt"), b"x").expect("write");
3087 Repository::init(wt, &InitOptions::default()).expect("init");
3088 let repo = repo_from_sub(wt, &wt.join("sub"));
3089 let specs = repo
3090 .resolve_rev_walk_pathspecs(&[":(glob)**/f.txt".to_owned()])
3091 .expect("resolve");
3092 assert_eq!(specs, [":(glob,prefix:sub/)**/f.txt"]);
3093 assert!(pathspec_matches(&specs[0], "sub/f.txt"));
3094 assert!(!pathspec_matches(&specs[0], "other/f.txt"));
3095 }
3096
3097 #[test]
3098 fn short_exclude_from_subdirectory_uses_prefix_magic() {
3099 let dir = tempfile::tempdir().expect("tempdir");
3100 let wt = dir.path();
3101 std::fs::create_dir_all(wt.join("sub")).expect("mkdir");
3102 Repository::init(wt, &InitOptions::default()).expect("init");
3103 let repo = repo_from_sub(wt, &wt.join("sub"));
3104 let specs = repo
3105 .resolve_rev_walk_pathspecs(&[":!f.txt".to_owned()])
3106 .expect("resolve");
3107 assert_eq!(specs, [".", ":(exclude,prefix:sub/)f.txt"]);
3108 assert!(matches_pathspec_list("other/g.txt", &specs));
3109 assert!(!matches_pathspec_list("sub/f.txt", &specs));
3110 }
3111
3112 #[test]
3113 fn glob_with_prefix_descends_into_cwd_directory() {
3114 let spec = ":(glob,prefix:sub/)**/f.txt";
3115 assert!(pathspec_wants_descent_into_tree(spec, "sub"));
3116 assert!(pathspec_entry_is_relevant(
3117 "sub/f.txt",
3118 false,
3119 &[spec.to_owned()]
3120 ));
3121 }
3122}