1use std::borrow::Cow;
5use std::ffi::OsString;
6use std::fs;
7use std::path::{Component, Path, PathBuf};
8
9use crate::path_icase::worktree_path_for_index_entry;
10use crate::pathspec::has_glob_chars;
11use crate::unicode_normalization::resolve_worktree_path_for_staging;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum GitPathError {
17 EscapesRoot,
19 InvalidRelativeUrl,
21}
22
23#[inline]
24fn is_dir_sep(c: u8) -> bool {
25 c == b'/'
26}
27
28pub fn normalize_path_copy(src: &str) -> Result<String, GitPathError> {
32 let is_abs = src.starts_with('/');
33 let raw_ends_dir = {
34 let stripped = src.trim_end_matches('/');
35 stripped.ends_with("/.")
36 || stripped.ends_with("/..")
37 || src.ends_with('/')
38 || src == "."
39 || src == ".."
40 };
41 let trailing_slash = raw_ends_dir && !src.is_empty();
42 let mut stack: Vec<String> = Vec::new();
43 let bytes = src.as_bytes();
44 let mut i = 0usize;
45 if is_abs {
46 i = 1;
47 }
48 while i < bytes.len() {
49 while i < bytes.len() && bytes[i] == b'/' {
50 i += 1;
51 }
52 if i >= bytes.len() {
53 break;
54 }
55 let start = i;
56 while i < bytes.len() && bytes[i] != b'/' {
57 i += 1;
58 }
59 let part = &src[start..i];
60 if part == "." {
61 continue;
62 }
63 if part == ".." {
64 if stack.pop().is_none() {
65 return Err(GitPathError::EscapesRoot);
66 }
67 } else {
68 stack.push(part.to_string());
69 }
70 }
71
72 let mut out = if is_abs {
73 if stack.is_empty() {
74 "/".to_string()
75 } else {
76 "/".to_string() + &stack.join("/")
77 }
78 } else if stack.is_empty() {
79 String::new()
80 } else {
81 stack.join("/")
82 };
83 if trailing_slash && !out.is_empty() && !out.ends_with('/') {
84 out.push('/');
85 }
86 Ok(out)
87}
88
89pub fn longest_ancestor_length(path: &str, prefixes_colon_sep: &str) -> Result<i32, GitPathError> {
91 let path = normalize_path_copy(path)?;
92 if path == "/" {
93 return Ok(-1);
94 }
95 let mut max_len: i64 = -1;
96 for ceil_raw in prefixes_colon_sep.split(':') {
97 if ceil_raw.is_empty() {
98 continue;
99 }
100 let ceil = normalize_path_copy(ceil_raw)?;
101 let mut len = ceil.len();
102 if len > 0 && ceil.as_bytes()[len - 1] == b'/' {
103 len -= 1;
104 }
105 let p = path.as_bytes();
106 let c = ceil.as_bytes();
107 if len > p.len() || len > c.len() || p[..len] != c[..len] {
108 continue;
109 }
110 if len == p.len() || p[len] != b'/' || p.get(len + 1).is_none() {
112 continue;
113 }
114 if len as i64 > max_len {
115 max_len = len as i64;
116 }
117 }
118 Ok(max_len as i32)
119}
120
121fn have_same_root(path1: &str, path2: &str) -> bool {
122 let abs1 = path1.starts_with('/');
123 let abs2 = path2.starts_with('/');
124 (abs1 && abs2) || (!abs1 && !abs2)
125}
126
127pub fn relative_path<'a>(in_path: &'a str, prefix: &'a str, sb: &'a mut String) -> Option<&'a str> {
129 let in_len = in_path.len();
130 let prefix_len = prefix.len();
131 let mut in_off = 0usize;
132 let mut prefix_off = 0usize;
133 let mut i = 0usize;
134 let mut j = 0usize;
135
136 if in_len == 0 {
137 return Some("./");
138 }
139 if prefix_len == 0 {
140 return Some(in_path);
141 }
142
143 if !have_same_root(in_path, prefix) {
144 return Some(in_path);
145 }
146
147 let in_b = in_path.as_bytes();
148 let pre_b = prefix.as_bytes();
149
150 while i < prefix_len && j < in_len && pre_b[i] == in_b[j] {
151 if is_dir_sep(pre_b[i]) {
152 while i < prefix_len && is_dir_sep(pre_b[i]) {
153 i += 1;
154 }
155 while j < in_len && is_dir_sep(in_b[j]) {
156 j += 1;
157 }
158 prefix_off = i;
159 in_off = j;
160 } else {
161 i += 1;
162 j += 1;
163 }
164 }
165
166 if i >= prefix_len && prefix_off < prefix_len {
167 if j >= in_len {
168 in_off = in_len;
169 } else if is_dir_sep(in_b[j]) {
170 while j < in_len && is_dir_sep(in_b[j]) {
171 j += 1;
172 }
173 in_off = j;
174 } else {
175 i = prefix_off;
176 }
177 } else if j >= in_len && in_off < in_len && is_dir_sep(pre_b[i]) {
178 while i < prefix_len && is_dir_sep(pre_b[i]) {
179 i += 1;
180 }
181 in_off = in_len;
182 }
183
184 let in_suffix = &in_path[in_off..];
185 let in_suffix_len = in_suffix.len();
186
187 if i >= prefix_len {
188 if in_suffix_len == 0 {
189 return Some("./");
190 }
191 return Some(in_suffix);
192 }
193
194 sb.clear();
195 sb.reserve(in_suffix_len.saturating_add(prefix_len * 3));
196
197 while i < prefix_len {
198 if is_dir_sep(pre_b[i]) {
199 sb.push_str("../");
200 while i < prefix_len && is_dir_sep(pre_b[i]) {
201 i += 1;
202 }
203 continue;
204 }
205 i += 1;
206 }
207 if prefix_len > 0 && !is_dir_sep(pre_b[prefix_len - 1]) {
208 sb.push_str("../");
209 }
210 sb.push_str(in_suffix);
211
212 Some(sb.as_str())
213}
214
215#[must_use]
220pub fn cleanup_path(path: &str) -> &str {
221 if let Some(rest) = path.strip_prefix("./") {
222 rest.trim_start_matches('/')
223 } else {
224 path
225 }
226}
227
228#[must_use]
234pub fn git_path_relative_component(path: &str) -> &str {
235 let trimmed = path.strip_prefix('/').unwrap_or(path);
238 cleanup_path(trimmed)
239}
240
241struct CommonDir {
243 is_dir: bool,
244 is_common: bool,
245 path: &'static str,
246}
247
248const COMMON_LIST: &[CommonDir] = &[
253 CommonDir {
254 is_dir: true,
255 is_common: true,
256 path: "branches",
257 },
258 CommonDir {
259 is_dir: true,
260 is_common: true,
261 path: "common",
262 },
263 CommonDir {
264 is_dir: true,
265 is_common: true,
266 path: "hooks",
267 },
268 CommonDir {
269 is_dir: true,
270 is_common: true,
271 path: "info",
272 },
273 CommonDir {
274 is_dir: false,
275 is_common: false,
276 path: "info/sparse-checkout",
277 },
278 CommonDir {
279 is_dir: true,
280 is_common: true,
281 path: "logs",
282 },
283 CommonDir {
284 is_dir: false,
285 is_common: false,
286 path: "logs/HEAD",
287 },
288 CommonDir {
289 is_dir: true,
290 is_common: false,
291 path: crate::refs::store::paths::LOGS_REFS_BISECT,
292 },
293 CommonDir {
294 is_dir: true,
295 is_common: false,
296 path: crate::refs::store::paths::LOGS_REFS_REWRITTEN,
297 },
298 CommonDir {
299 is_dir: true,
300 is_common: false,
301 path: crate::refs::store::paths::LOGS_REFS_WORKTREE,
302 },
303 CommonDir {
304 is_dir: true,
305 is_common: true,
306 path: "lost-found",
307 },
308 CommonDir {
309 is_dir: true,
310 is_common: true,
311 path: "objects",
312 },
313 CommonDir {
314 is_dir: true,
315 is_common: true,
316 path: "refs",
317 },
318 CommonDir {
319 is_dir: true,
320 is_common: false,
321 path: "refs/bisect",
322 },
323 CommonDir {
324 is_dir: true,
325 is_common: false,
326 path: "refs/rewritten",
327 },
328 CommonDir {
329 is_dir: true,
330 is_common: false,
331 path: "refs/worktree",
332 },
333 CommonDir {
334 is_dir: true,
335 is_common: true,
336 path: "remotes",
337 },
338 CommonDir {
339 is_dir: true,
340 is_common: true,
341 path: "worktrees",
342 },
343 CommonDir {
344 is_dir: true,
345 is_common: true,
346 path: "rr-cache",
347 },
348 CommonDir {
349 is_dir: true,
350 is_common: true,
351 path: "svn",
352 },
353 CommonDir {
354 is_dir: false,
355 is_common: true,
356 path: "config",
357 },
358 CommonDir {
359 is_dir: false,
360 is_common: true,
361 path: "gc.pid",
362 },
363 CommonDir {
364 is_dir: false,
365 is_common: true,
366 path: crate::refs::store::paths::packed_refs_rel(),
367 },
368 CommonDir {
369 is_dir: false,
370 is_common: true,
371 path: "shallow",
372 },
373];
374
375fn check_common(entry: &CommonDir, unmatched: &[u8]) -> Option<bool> {
378 let first = unmatched.first().copied();
379 if entry.is_dir && (first.is_none() || first == Some(b'/')) {
380 return Some(entry.is_common);
381 }
382 if !entry.is_dir && first.is_none() {
383 return Some(entry.is_common);
384 }
385 None
386}
387
388fn trie_find_common(key: &[u8]) -> Option<bool> {
397 let norm = normalize_double_slashes(key);
404 let mut matches: Vec<&CommonDir> = COMMON_LIST
406 .iter()
407 .filter(|e| key_has_prefix_node(&norm, e.path.as_bytes()))
408 .collect();
409 matches.sort_by_key(|a| std::cmp::Reverse(a.path.len()));
410 for entry in matches {
411 let plen = entry.path.len();
412 let unmatched = &norm[plen..];
413 if let Some(verdict) = check_common(entry, unmatched) {
414 return Some(verdict);
415 }
416 }
419 None
420}
421
422fn normalize_double_slashes(key: &[u8]) -> Vec<u8> {
426 let mut out = Vec::with_capacity(key.len());
427 let mut prev_slash = false;
428 for &b in key {
429 if b == b'/' {
430 if !prev_slash {
431 out.push(b);
432 }
433 prev_slash = true;
434 } else {
435 out.push(b);
436 prev_slash = false;
437 }
438 }
439 out
440}
441
442fn key_has_prefix_node(key: &[u8], node: &[u8]) -> bool {
444 if key.len() < node.len() || &key[..node.len()] != node {
445 return false;
446 }
447 matches!(key.get(node.len()), None | Some(b'/'))
448}
449
450#[must_use]
457pub fn is_common_git_path(rel: &str) -> bool {
458 let stripped = rel.strip_suffix(".lock").unwrap_or(rel);
459 matches!(trie_find_common(stripped.as_bytes()), Some(true))
460}
461
462pub fn abspath_part_inside_repo(path: &str, work_tree: &Path) -> Option<String> {
467 let normalized = normalize_path_copy(path).ok()?;
468 if !normalized.starts_with('/') {
469 return None;
470 }
471 let wt_display = work_tree.to_string_lossy();
472 let wt_trim: &str = if wt_display == "/" {
473 "/"
474 } else {
475 wt_display.trim_end_matches('/')
476 };
477 let wt_len = wt_trim.len();
478 let p = normalized.as_str();
479 let len = p.len();
480
481 if wt_len <= len && p.starts_with(wt_trim) {
482 if len > wt_len && p.as_bytes()[wt_len] == b'/' {
483 return Some(p[wt_len + 1..].to_string());
484 }
485 if len == wt_len {
486 return Some(String::new());
487 }
488 if wt_len > 0 && wt_trim.as_bytes()[wt_len - 1] == b'/' {
489 return Some(p[wt_len..].trim_start_matches('/').to_string());
490 }
491 }
492
493 let wt_canon = path_for_disk_compare(work_tree);
494 let mut cum = String::new();
495 for seg in p.split('/').filter(|s| !s.is_empty()) {
496 cum.push('/');
497 cum.push_str(seg);
498 let rp = path_for_disk_compare(Path::new(&cum));
499 if rp == wt_canon {
500 if p.len() == cum.len() {
501 return Some(String::new());
502 }
503 if p.as_bytes().get(cum.len()) == Some(&b'/') {
504 return Some(p[cum.len() + 1..].to_string());
505 }
506 }
507 }
508 let full = path_for_disk_compare(Path::new(p));
509 if full == wt_canon {
510 return Some(String::new());
511 }
512 None
513}
514
515pub(crate) const SUBPROCESS_GIT_PATH_VARS: [&str; 5] = [
517 "GIT_DIR",
518 "GIT_COMMON_DIR",
519 "GIT_WORK_TREE",
520 "GIT_INDEX_FILE",
521 "GIT_OBJECT_DIRECTORY",
522];
523
524pub(crate) fn strip_verbatim_prefix_from_subprocess_path_vars(set: &mut [(OsString, OsString)]) {
526 for (key, value) in set.iter_mut() {
527 if !SUBPROCESS_GIT_PATH_VARS.iter().any(|var| key == *var) {
528 continue;
529 }
530 let Some(s) = value.to_str() else {
531 continue;
532 };
533 let stripped = strip_verbatim_path_prefix_str(s);
534 if stripped.len() != s.len() {
535 *value = OsString::from(stripped.into_owned());
536 }
537 }
538}
539
540#[must_use]
542pub(crate) fn strip_verbatim_path_prefix_str(path: &str) -> Cow<'_, str> {
543 if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
544 Cow::Owned(format!(r"\\{rest}"))
545 } else if let Some(rest) = path.strip_prefix(r"\\?\") {
546 Cow::Borrowed(rest)
547 } else {
548 Cow::Borrowed(path)
549 }
550}
551
552#[must_use]
557pub(crate) fn path_without_verbatim_prefix(path: &Path) -> Cow<'_, Path> {
558 #[cfg(windows)]
559 if let Some(s) = path.to_str() {
560 let stripped = strip_verbatim_path_prefix_str(s);
561 if stripped.len() != s.len() {
562 return Cow::Owned(PathBuf::from(stripped.into_owned()));
563 }
564 }
565 Cow::Borrowed(path)
566}
567
568#[cfg(any(windows, test))]
571const WIN32_MAX_PATH_UNITS: usize = 259;
572
573#[cfg(any(windows, test))]
581fn simplify_verbatim_str(path: &str) -> Option<String> {
582 let (simple, components) = if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
583 let mut parts = rest.splitn(3, '\\');
584 let (server, share) = (parts.next()?, parts.next()?);
585 if server.is_empty() || share.is_empty() {
586 return None;
587 }
588 (format!(r"\\{rest}"), rest)
589 } else {
590 let rest = path.strip_prefix(r"\\?\")?;
591 let drive = rest.as_bytes();
592 if drive.len() < 3 || !drive[0].is_ascii_alphabetic() || drive[1..3] != *b":\\" {
593 return None;
594 }
595 (rest.to_owned(), &rest[3..])
596 };
597 let round_trips =
598 components.is_empty() || components.split('\\').all(win32_component_round_trips);
599 (round_trips && simple.encode_utf16().count() <= WIN32_MAX_PATH_UNITS).then_some(simple)
600}
601
602#[cfg(any(windows, test))]
604pub(crate) fn win32_component_round_trips(component: &str) -> bool {
605 const RESERVED: [&str; 6] = ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"];
606 if component.is_empty()
607 || component.ends_with(['.', ' '])
608 || component.contains(['/', ':', '<', '>', '"', '|', '?', '*'])
609 || component.chars().any(char::is_control)
610 {
611 return false;
612 }
613 let stem = component
614 .split('.')
615 .next()
616 .unwrap_or(component)
617 .trim_end_matches(' ');
618 if RESERVED.iter().any(|name| stem.eq_ignore_ascii_case(name)) {
619 return false;
620 }
621 let numbered_device = ["COM", "LPT"].iter().any(|device| {
622 stem.get(..3)
623 .is_some_and(|head| head.eq_ignore_ascii_case(device))
624 && matches!(
625 &stem[3..],
626 "1" | "2"
627 | "3"
628 | "4"
629 | "5"
630 | "6"
631 | "7"
632 | "8"
633 | "9"
634 | "\u{b9}"
635 | "\u{b2}"
636 | "\u{b3}"
637 )
638 });
639 !numbered_device
640}
641
642#[cfg(any(windows, test))]
644pub(crate) fn win32_storage_path_components_round_trip(path: &str) -> bool {
645 path.split('/').all(win32_component_round_trips)
646}
647
648#[must_use]
656pub(crate) fn simplify_verbatim_path(path: PathBuf) -> PathBuf {
657 #[cfg(windows)]
658 if let Some(simple) = path.to_str().and_then(simplify_verbatim_str) {
659 return PathBuf::from(simple);
660 }
661 path
662}
663
664pub(crate) trait CanonicalizeExt {
669 fn canonicalize_simplified(&self) -> std::io::Result<PathBuf>;
676}
677
678impl CanonicalizeExt for Path {
679 #[allow(clippy::disallowed_methods)]
680 fn canonicalize_simplified(&self) -> std::io::Result<PathBuf> {
681 fs::canonicalize(self).map(simplify_verbatim_path)
682 }
683}
684
685#[must_use]
687pub fn user_display_path(path: &Path) -> String {
688 strip_verbatim_path_prefix_str(&path.display().to_string()).replace('\\', "/")
689}
690
691#[must_use]
693pub fn path_for_error_message(path: &Path) -> String {
694 user_display_path(path)
695}
696
697#[must_use]
702pub fn absolute_path_for_gitfile_stored_path(path: &Path) -> String {
703 let canon = path
704 .canonicalize_simplified()
705 .unwrap_or_else(|_| path.to_path_buf());
706 user_display_path(&canon)
707}
708
709#[must_use]
714pub fn path_lexical_for_disk_compare(path: &Path) -> PathBuf {
715 let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
716 let normalized = lexical_normalize_path_buf(abs);
717 #[cfg(windows)]
718 let normalized = PathBuf::from(
719 strip_verbatim_path_prefix_str(&normalized.display().to_string()).into_owned(),
720 );
721 normalized
722}
723
724fn lexical_normalize_path_buf(path: PathBuf) -> PathBuf {
725 let mut out = PathBuf::new();
726 for c in path.components() {
727 match c {
728 Component::Prefix(prefix) => out.push(prefix.as_os_str()),
729 Component::RootDir => out.push(c),
730 Component::CurDir => {}
731 Component::ParentDir => {
732 out.pop();
733 }
734 Component::Normal(_) => out.push(c),
735 }
736 }
737 out
738}
739
740#[must_use]
742pub(crate) fn strip_worktree_prefix(path: &Path, work_tree: &Path) -> Option<String> {
743 let path_key = apply_macos_private_alias_for_compare(path_lexical_for_disk_compare(path));
744 let wt_key = path_for_disk_compare(work_tree);
745 let rel = path_key.strip_prefix(&wt_key).ok()?;
746 Some(path_to_git_slash(rel))
747}
748
749#[must_use]
751pub(crate) fn path_to_git_slash(path: &Path) -> String {
752 path.components()
753 .filter_map(|c| match c {
754 Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
755 _ => None,
756 })
757 .collect::<Vec<_>>()
758 .join("/")
759}
760
761#[must_use]
766pub fn relative_path_for_display(from: &Path, to: &Path) -> Option<String> {
767 let from_cmp = path_for_disk_compare(from);
768 let to_cmp = apply_macos_private_alias_for_compare(path_lexical_for_disk_compare(to));
769 if from_cmp == to_cmp {
770 return Some(".".to_owned());
771 }
772
773 let from_parts: Vec<_> = from_cmp.components().collect();
774 let to_parts: Vec<_> = to_cmp.components().collect();
775 let common = from_parts
776 .iter()
777 .zip(to_parts.iter())
778 .take_while(|(a, b)| a == b)
779 .count();
780
781 let mut segments: Vec<String> = Vec::new();
782 for part in &from_parts[common..] {
783 if matches!(part, Component::Normal(_)) {
784 segments.push("..".to_owned());
785 }
786 }
787 for part in &to_parts[common..] {
788 match part {
789 Component::Normal(name) => segments.push(name.to_string_lossy().into_owned()),
790 Component::ParentDir => {
791 segments.pop();
792 }
793 Component::CurDir | Component::RootDir | Component::Prefix(_) => {}
794 }
795 }
796
797 if segments.is_empty() {
798 Some(".".to_owned())
799 } else {
800 Some(segments.join("/"))
801 }
802}
803
804#[must_use]
810fn apply_macos_private_alias_for_compare(path: PathBuf) -> PathBuf {
811 #[cfg(target_os = "macos")]
812 {
813 if let Ok(stripped) = path.strip_prefix("/private") {
814 let without_private = PathBuf::from("/").join(stripped);
815 if without_private.exists() {
816 return without_private;
817 }
818 let mut probe = without_private.as_path();
819 while let Some(parent) = probe.parent() {
820 if parent == Path::new("") {
821 break;
822 }
823 if parent.exists() {
824 return without_private;
825 }
826 probe = parent;
827 }
828 }
829 }
830 path
831}
832
833#[must_use]
841pub fn path_for_disk_compare(path: &Path) -> PathBuf {
842 let canon = path
843 .canonicalize_simplified()
844 .unwrap_or_else(|_| path.to_path_buf());
845 #[cfg(windows)]
846 let canon =
847 PathBuf::from(strip_verbatim_path_prefix_str(&canon.display().to_string()).into_owned());
848 apply_macos_private_alias_for_compare(canon)
849}
850
851#[must_use]
856pub(crate) fn pathspec_traverses_symlink_dir(
857 work_tree: &Path,
858 rel_path: &str,
859 precompose_unicode: bool,
860 ignorecase: bool,
861) -> bool {
862 if rel_path.is_empty()
863 || has_glob_chars(rel_path)
864 || rel_path.starts_with(":(")
865 || rel_path.starts_with(':')
866 {
867 return false;
868 }
869 let directory_pathspec = rel_path.ends_with('/');
870 let components: Vec<&str> = rel_path.split('/').filter(|c| !c.is_empty()).collect();
871 if components.is_empty() {
872 return false;
873 }
874 let check_through = if directory_pathspec {
875 components.len()
876 } else if components.len() <= 1 {
877 return false;
878 } else {
879 components.len() - 1
880 };
881 let mut prefix = String::new();
882 for component in &components[..check_through] {
883 if !prefix.is_empty() {
884 prefix.push('/');
885 }
886 prefix.push_str(component);
887 let abs = if precompose_unicode {
888 resolve_worktree_path_for_staging(work_tree, &prefix, true).abs
889 } else {
890 worktree_path_for_index_entry(work_tree, &prefix, ignorecase)
891 };
892 let Ok(meta) = fs::symlink_metadata(&abs) else {
893 continue;
894 };
895 if meta.file_type().is_symlink() {
896 return true;
897 }
898 }
899 false
900}
901
902pub fn prefix_path_gently(prefix: &str, path: &str, work_tree: &Path) -> Option<String> {
904 if path.starts_with('/') {
905 let n = normalize_path_copy(path).ok()?;
906 abspath_part_inside_repo(&n, work_tree)
907 } else {
908 let concat = format!("{prefix}{path}");
909 normalize_path_copy(&concat).ok()
910 }
911}
912
913#[cfg(test)]
914mod git_path_component_tests {
915 use super::*;
916
917 #[test]
918 #[cfg(unix)]
919 fn pathspec_traverses_symlink_dir_detects_intermediate_symlink() {
920 use std::os::unix::fs::symlink;
921
922 let tmp = tempfile::TempDir::new().expect("tempdir");
923 let root = tmp.path();
924 std::fs::create_dir_all(root.join("real")).expect("mkdir");
925 std::fs::write(root.join("real/f"), b"x").expect("write");
926 symlink("real", root.join("dl")).expect("symlink");
927 assert!(pathspec_traverses_symlink_dir(root, "dl/f", false, false));
928 assert!(!pathspec_traverses_symlink_dir(root, "dl", false, false));
929 assert!(!pathspec_traverses_symlink_dir(
930 root, "real/f", false, false
931 ));
932 assert!(pathspec_traverses_symlink_dir(root, "dl/", false, false));
933 assert!(pathspec_traverses_symlink_dir(root, "dl/f/", false, false));
934 }
935
936 #[test]
937 fn cleanup_path_strips_leading_dot_slash() {
938 assert_eq!(cleanup_path("./foo"), "foo");
939 assert_eq!(cleanup_path(".//foo"), "foo");
940 assert_eq!(cleanup_path("foo"), "foo");
941 }
942
943 #[test]
944 fn cleanup_path_keeps_internal_double_slashes() {
945 assert_eq!(
947 cleanup_path("info//sparse-checkout"),
948 "info//sparse-checkout"
949 );
950 assert_eq!(cleanup_path("./info//grafts"), "info//grafts");
951 }
952
953 #[test]
954 fn git_path_component_drops_one_leading_slash_keeps_interior() {
955 assert_eq!(
956 git_path_relative_component("info//sparse-checkout"),
957 "info//sparse-checkout"
958 );
959 assert_eq!(git_path_relative_component("/info//grafts"), "info//grafts");
960 assert_eq!(git_path_relative_component("HEAD"), "HEAD");
961 }
962
963 #[test]
964 fn is_common_git_path_matches_git_common_list() {
965 use crate::refs::store::paths;
966 let common_cases = [
967 paths::logs_refs_rel().to_owned(),
968 format!("{}/", paths::logs_refs_rel()),
969 paths::logs_refs_child("bisec/foo"),
970 paths::logs_refs_child("bisec"),
971 paths::logs_refs_child("bisectfoo"),
972 "objects".to_owned(),
973 "objects/bar".to_owned(),
974 "info/exclude".to_owned(),
975 "info/grafts".to_owned(),
976 "remotes/bar".to_owned(),
977 "branches/bar".to_owned(),
978 paths::LOGS_REFS_HEADS_MAIN.to_owned(),
979 "refs/heads/main".to_owned(),
980 "hooks/me".to_owned(),
981 "config".to_owned(),
982 paths::packed_refs_rel().to_owned(),
983 "shallow".to_owned(),
984 "common".to_owned(),
985 "common/file".to_owned(),
986 ];
987 for p in &common_cases {
989 assert!(is_common_git_path(p), "{p} should be common");
990 }
991 let worktree_cases = [
992 "index".to_owned(),
993 "index.lock".to_owned(),
994 "HEAD".to_owned(),
995 "logs/HEAD".to_owned(),
996 "logs/HEAD.lock".to_owned(),
997 paths::logs_refs_child("bisect/foo"),
998 "info/sparse-checkout".to_owned(),
999 "refs/bisect/foo".to_owned(),
1000 ];
1001 for p in &worktree_cases {
1003 assert!(!is_common_git_path(p), "{p} should be worktree-local");
1004 }
1005 }
1006
1007 #[test]
1008 fn strip_verbatim_extended_path_prefix() {
1009 assert_eq!(strip_verbatim_path_prefix_str(r"\\?\C:\tmp\p"), r"C:\tmp\p");
1010 assert_eq!(
1011 strip_verbatim_path_prefix_str(r"\\?\UNC\server\share\dir"),
1012 r"\\server\share\dir"
1013 );
1014 assert_eq!(strip_verbatim_path_prefix_str(r"C:\tmp\p"), r"C:\tmp\p");
1015 }
1016
1017 #[test]
1018 fn simplify_verbatim_str_rewrites_only_round_tripping_paths() {
1019 let long_tail = "d".repeat(WIN32_MAX_PATH_UNITS - r"C:\".len());
1020 let too_long_tail = format!("{long_tail}x");
1021 let long_drive = format!(r"\\?\C:\{long_tail}");
1022 let too_long_drive = format!(r"\\?\C:\{too_long_tail}");
1023 let cases: &[(&str, Option<&str>)] = &[
1024 (r"\\?\C:\Users\me\proj", Some(r"C:\Users\me\proj")),
1025 (r"\\?\c:\proj\.git", Some(r"c:\proj\.git")),
1026 (r"\\?\C:\", Some(r"C:\")),
1027 (r"\\?\C:\a b\file.txt", Some(r"C:\a b\file.txt")),
1028 ("\\\\?\\C:\\caf\u{e9}\\x", Some("C:\\caf\u{e9}\\x")),
1029 (r"\\?\C:\console\nulled", Some(r"C:\console\nulled")),
1030 (r"\\?\C:\COM10\LPT0", Some(r"C:\COM10\LPT0")),
1031 (r"\\?\UNC\server\share\dir", Some(r"\\server\share\dir")),
1032 (r"\\?\UNC\server\share", Some(r"\\server\share")),
1033 (long_drive.as_str(), Some(&long_drive[4..])),
1034 (too_long_drive.as_str(), None),
1035 (r"\\?\C:\proj\dir.", None),
1036 (r"\\?\C:\proj\dir ", None),
1037 (r"\\?\C:\proj\.\x", None),
1038 (r"\\?\C:\proj\..\x", None),
1039 (r"\\?\C:\proj\\x", None),
1040 (r"\\?\C:\proj\a/b", None),
1041 (r"\\?\C:\proj\a:b", None),
1042 (r"\\?\C:\proj\a*b", None),
1043 (r"\\?\C:\proj\NUL", None),
1044 (r"\\?\C:\proj\nul.txt", None),
1045 (r"\\?\C:\proj\Com1", None),
1046 (r"\\?\C:\proj\lpt9.log", None),
1047 ("\\\\?\\C:\\proj\\COM\u{b9}", None),
1048 (r"\\?\C:\proj\CONOUT$", None),
1049 (r"\\?\C:", None),
1050 (r"\\?\C:proj", None),
1051 (r"\\?\1:\proj", None),
1052 (r"\\?\UNC\server", None),
1053 (r"\\?\UNC\\share", None),
1054 (r"\\?\UNC\server\share\x.", None),
1055 (
1056 r"\\?\Volume{0a1b2c3d-0000-0000-0000-100000000000}\dir",
1057 None,
1058 ),
1059 (r"\\.\C:\proj", None),
1060 (r"\\.\PhysicalDrive0", None),
1061 (r"\??\C:\proj", None),
1062 (r"C:\proj", None),
1063 (r"\\server\share", None),
1064 ("/home/me/proj", None),
1065 ];
1066 for (input, expected) in cases {
1067 assert_eq!(
1068 simplify_verbatim_str(input).as_deref(),
1069 *expected,
1070 "simplify {input:?}"
1071 );
1072 }
1073 }
1074
1075 #[test]
1076 fn simplify_verbatim_path_keeps_non_windows_paths() {
1077 let unix = PathBuf::from("/home/me/proj");
1078 assert_eq!(simplify_verbatim_path(unix.clone()), unix);
1079 let verbatim = PathBuf::from(r"\\?\C:\proj");
1080 let expected = if cfg!(windows) {
1081 PathBuf::from(r"C:\proj")
1082 } else {
1083 verbatim.clone()
1084 };
1085 assert_eq!(simplify_verbatim_path(verbatim), expected);
1086 }
1087
1088 #[test]
1089 fn canonicalize_simplified_matches_canonicalize_without_prefix() {
1090 let tmp = tempfile::tempdir().expect("tempdir");
1091 let dir = tmp.path().join("a").join("..").join("b");
1092 std::fs::create_dir_all(tmp.path().join("a")).expect("mkdir a");
1093 std::fs::create_dir_all(tmp.path().join("b")).expect("mkdir b");
1094 let simplified = dir.canonicalize_simplified().expect("canonicalize");
1095 let raw = std::fs::canonicalize(&dir).expect("canonicalize");
1096 assert_eq!(simplified, simplify_verbatim_path(raw));
1097 assert!(!simplified.to_string_lossy().starts_with(r"\\?\"));
1098 assert!(simplified.is_dir());
1099 assert!(Path::new("does-not-exist-here")
1100 .canonicalize_simplified()
1101 .is_err());
1102 }
1103
1104 #[test]
1105 fn repository_paths_are_simplified_canonical_paths() {
1106 use crate::config::environment::RepositoryOptions;
1107 use crate::ref_storage::RefStorageFormat;
1108 use crate::repo::{init_repository, Repository};
1109
1110 let tmp = tempfile::tempdir().expect("tempdir");
1111 let work = tmp.path().join("hw");
1112 init_repository(&work, false, "main", None, RefStorageFormat::Files).expect("init");
1113 std::fs::create_dir_all(work.join("sub")).expect("mkdir sub");
1114 let expected = work.canonicalize_simplified().expect("canonicalize");
1115
1116 for start in [work.clone(), work.join("sub"), work.join("sub").join("..")] {
1117 let repo = Repository::discover(Some(start.as_path()), &RepositoryOptions::empty())
1118 .expect("discover");
1119 let wt = repo.work_tree().expect("work tree");
1120 assert!(!wt.to_string_lossy().starts_with(r"\\?\"), "{wt:?}");
1121 assert_eq!(wt, expected.as_path());
1122 assert_eq!(repo.git_dir(), expected.join(".git"));
1123 assert_eq!(repo.common_git_dir(), repo.git_dir());
1124 assert!(repo.git_dir().join("config").is_file());
1125 repo.config()
1126 .snapshot()
1127 .expect("config through stored git dir");
1128 }
1129
1130 let opened = Repository::open(
1131 &work.join(".git"),
1132 &RepositoryOptions::empty().with_work_tree(&work),
1133 )
1134 .expect("open");
1135 assert_eq!(opened.work_tree(), Some(expected.as_path()));
1136 assert_eq!(opened.git_dir(), expected.join(".git"));
1137 }
1138
1139 #[test]
1140 fn separate_git_dir_gitfile_is_plain_absolute_path() {
1141 let tmp = tempfile::tempdir().expect("tempdir");
1142 let work = tmp.path().join("wt");
1143 let git_dir = tmp.path().join("store.git");
1144 let repo = crate::repo::Repository::init(
1145 &work,
1146 &crate::repo::InitOptions::new()
1147 .with_initial_branch("main")
1148 .with_separate_git_dir(Some(git_dir.to_path_buf())),
1149 )
1150 .map(|(repo, _)| repo)
1151 .expect("init separate git dir");
1152 let gitfile = std::fs::read_to_string(work.join(".git")).expect("read gitfile");
1153 let stored = gitfile
1154 .strip_prefix("gitdir: ")
1155 .and_then(|rest| rest.strip_suffix('\n'))
1156 .expect("gitdir line");
1157 assert!(!stored.contains("?"), "{stored}");
1158 assert_eq!(stored, absolute_path_for_gitfile_stored_path(&git_dir));
1159 assert_eq!(
1160 repo.git_dir(),
1161 git_dir.canonicalize_simplified().expect("canonicalize")
1162 );
1163
1164 let out = std::process::Command::new("git")
1165 .args(["rev-parse", "--absolute-git-dir"])
1166 .current_dir(&work)
1167 .env("GIT_CEILING_DIRECTORIES", tmp.path())
1168 .output();
1169 let Ok(out) = out else {
1170 return;
1171 };
1172 assert!(out.status.success(), "git rev-parse failed: {out:?}");
1173 let git_view = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1174 assert_eq!(
1175 git_view
1176 .canonicalize_simplified()
1177 .expect("canonicalize git view"),
1178 repo.git_dir()
1179 );
1180 }
1181
1182 #[test]
1183 fn user_display_path_uses_forward_slashes() {
1184 assert_eq!(
1185 user_display_path(Path::new(r"\\?\C:\tmp\p\.git")),
1186 "C:/tmp/p/.git"
1187 );
1188 }
1189
1190 #[test]
1191 fn path_for_error_message_strips_verbatim_prefix() {
1192 let msg = path_for_error_message(Path::new(r"\\?\C:\Users\tmp\r"));
1193 assert!(!msg.contains(r"\\?\"));
1194 assert_eq!(msg, "C:/Users/tmp/r");
1195 }
1196
1197 #[test]
1198 fn library_error_messages_use_user_display_paths() {
1199 use crate::remote::RemoteError;
1200 use std::path::PathBuf;
1201
1202 let verbatim = PathBuf::from(r"\\?\C:\Users\x\pack.tmp");
1203 let temp_missing = RemoteError::ReceivedPackTempMissing {
1204 path: verbatim.clone(),
1205 };
1206 assert!(
1207 temp_missing.to_string().contains("C:/Users/x/pack.tmp"),
1208 "{}",
1209 temp_missing
1210 );
1211 assert!(!temp_missing.to_string().contains(r"\\?\"));
1212 }
1213
1214 #[test]
1215 fn absolute_path_for_gitfile_stored_path_strips_verbatim() {
1216 let tmp = tempfile::tempdir().expect("tempdir");
1217 let dir = tmp.path().join("linked");
1218 std::fs::create_dir_all(&dir).expect("mkdir");
1219 let stored = absolute_path_for_gitfile_stored_path(&dir);
1220 assert!(!stored.contains(r"\\?\"));
1221 assert!(!stored.contains("//?/"));
1222 #[cfg(windows)]
1223 {
1224 assert!(stored.contains('/'));
1225 assert_eq!(
1226 absolute_path_for_gitfile_stored_path(Path::new(r"\\?\C:\tmp\t\src\.git")),
1227 "C:/tmp/t/src/.git"
1228 );
1229 }
1230 }
1231
1232 #[test]
1233 fn relative_path_for_display_above_and_below_cwd() {
1234 let tmp = tempfile::tempdir().expect("tempdir");
1235 let repo = tmp.path().join("repo");
1236 let deep = repo.join("d");
1237 std::fs::create_dir_all(&deep).expect("mkdir");
1238 std::fs::write(repo.join("a.txt"), b"root").expect("write");
1239 std::fs::write(deep.join("a.txt"), b"nested").expect("write");
1240
1241 let cwd = deep.canonicalize_simplified().expect("canonicalize cwd");
1242 let above = repo
1243 .join("a.txt")
1244 .canonicalize_simplified()
1245 .expect("canonicalize above");
1246 let below = deep
1247 .join("a.txt")
1248 .canonicalize_simplified()
1249 .expect("canonicalize below");
1250
1251 assert_eq!(
1252 relative_path_for_display(&cwd, &above).as_deref(),
1253 Some("../a.txt")
1254 );
1255 assert_eq!(
1256 relative_path_for_display(&cwd, &below).as_deref(),
1257 Some("a.txt")
1258 );
1259 }
1260
1261 #[cfg(unix)]
1262 #[test]
1263 fn strip_worktree_prefix_preserves_symlink_spelling() {
1264 use std::os::unix::fs::symlink;
1265
1266 let tmp = tempfile::tempdir().expect("tempdir");
1267 let repo = tmp.path().join("repo");
1268 std::fs::create_dir_all(repo.join("d")).expect("mkdir");
1269 let outside = tmp.path().join("outside");
1270 std::fs::create_dir_all(&outside).expect("mkdir outside");
1271 symlink(&outside, repo.join("d/link")).expect("symlink");
1272 assert_eq!(
1273 strip_worktree_prefix(&repo.join("d/link"), &repo).as_deref(),
1274 Some("d/link")
1275 );
1276 }
1277
1278 #[test]
1279 fn strip_worktree_prefix_for_nested_file() {
1280 let tmp = tempfile::tempdir().expect("tempdir");
1281 let repo = tmp.path().join("repo");
1282 std::fs::create_dir_all(repo.join("d")).expect("mkdir");
1283 let file = repo.join("d/a.txt");
1284 std::fs::write(&file, b"x").expect("write");
1285 assert_eq!(
1286 strip_worktree_prefix(&file, &repo).as_deref(),
1287 Some("d/a.txt")
1288 );
1289 }
1290
1291 #[cfg(target_os = "macos")]
1292 #[test]
1293 fn strip_worktree_prefix_macos_private_tmp_alias() {
1294 let tmp = tempfile::tempdir().expect("tempdir");
1295 let canon = tmp
1296 .path()
1297 .canonicalize_simplified()
1298 .expect("canonicalize tempdir");
1299 let public = if let Ok(stripped) = canon.strip_prefix("/private") {
1300 std::path::PathBuf::from("/").join(stripped)
1301 } else {
1302 canon.clone()
1303 };
1304 if public == canon {
1305 return;
1306 }
1307 std::fs::create_dir_all(public.join("nested")).expect("mkdir");
1308 let file_public = public.join("nested/file.txt");
1309 std::fs::write(&file_public, b"x").expect("write");
1310 assert_eq!(
1311 strip_worktree_prefix(&file_public, &canon).as_deref(),
1312 Some("nested/file.txt")
1313 );
1314
1315 let missing_private = canon.join("nested/not-yet.txt");
1316 assert_eq!(
1317 strip_worktree_prefix(&missing_private, &canon).as_deref(),
1318 Some("nested/not-yet.txt")
1319 );
1320 }
1321
1322 #[cfg(target_os = "macos")]
1323 #[test]
1324 fn relative_path_for_display_macos_private_tmp_alias() {
1325 let tmp = tempfile::tempdir().expect("tempdir");
1326 let repo_canon = tmp
1327 .path()
1328 .canonicalize_simplified()
1329 .expect("canonicalize tempdir");
1330 let repo_public = if let Ok(stripped) = repo_canon.strip_prefix("/private") {
1331 std::path::PathBuf::from("/").join(stripped)
1332 } else {
1333 repo_canon.clone()
1334 };
1335 if repo_public == repo_canon {
1336 return;
1337 }
1338 let sub = repo_public.join("sub");
1339 std::fs::create_dir_all(&sub).expect("mkdir sub");
1340 let file = sub.join("f.txt");
1341 std::fs::write(&file, b"x").expect("write");
1342
1343 let cwd = sub.clone();
1345 let target = repo_canon.join("sub/f.txt");
1346 assert_eq!(
1347 relative_path_for_display(&cwd, &target).as_deref(),
1348 Some("f.txt")
1349 );
1350
1351 let cwd_private = sub.canonicalize_simplified().expect("canonicalize sub");
1353 assert_eq!(
1354 relative_path_for_display(&cwd_private, &target).as_deref(),
1355 Some("f.txt")
1356 );
1357 }
1358
1359 #[test]
1360 fn relative_path_preserves_interior_double_slash_suffix() {
1361 let mut sb = String::new();
1364 let rel = relative_path("/repo/.git/info//sparse-checkout", "/repo", &mut sb);
1365 assert_eq!(rel, Some(".git/info//sparse-checkout"));
1366 }
1367
1368 #[test]
1369 fn win32_storage_path_components_round_trip_ref_names() {
1370 let ok = win32_storage_path_components_round_trip;
1371 assert!(!ok("refs/heads/aux"));
1372 assert!(!ok("refs/heads/AUX"));
1373 assert!(!ok("refs/heads/com1"));
1374 assert!(!ok("refs/heads/COM1.txt"));
1375 assert!(!ok("refs/heads/foo/aux/bar"));
1376 assert!(!ok("refs/heads/foo./bar"));
1377 assert!(!ok("refs/heads/conin$"));
1378 assert!(ok("refs/heads/auxiliary"));
1379 assert!(ok("refs/heads/commit"));
1380 assert!(ok("HEAD"));
1381 }
1382}