grit-lib 0.5.29

Core library for the grit Git implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Safety checks and path resolution for local transport URLs (matches Git `connect.c` / `path.c`).

use crate::git_path::CanonicalizeExt;
use std::path::{Path, PathBuf};

use thiserror::Error;

use crate::error::Error;

/// Repository root used to resolve relative `remote.<name>.url` values — the linked or main
/// worktree directory when known, otherwise inferred from `git_dir` (including linked
/// worktree admin dirs via `gitdir` / `commondir`).
#[must_use]
pub(crate) fn configured_remote_base(git_dir: &Path, work_tree: Option<&Path>) -> PathBuf {
    if let Some(wt) = work_tree {
        return wt.to_path_buf();
    }
    if git_dir.join("commondir").is_file() {
        if let Ok(wt) = crate::worktree::read_worktree_path(git_dir) {
            return wt;
        }
    }
    if git_dir.file_name().is_some_and(|name| name == ".git") {
        git_dir
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| git_dir.to_path_buf())
    } else {
        git_dir.to_path_buf()
    }
}

/// True when a clone source should be stored as an absolute filesystem path (scheme-less
/// local paths only — not `file://`, HTTP, SSH, etc.).
#[must_use]
pub(crate) fn should_store_absolute_local_clone_url(url: &str) -> bool {
    let url = url.trim();
    !url.starts_with("file://") && is_local_path_remote_url(url)
}

/// Git `url_is_local_not_ssh` (`connect.c`): local unless scp-style `host:path` with no directory
/// separator before the first `:` (Windows drive letters and `\` separators included).
#[must_use]
pub(crate) fn url_is_local_not_ssh(url: &str) -> bool {
    let url = url.trim();
    let colon = url.find(':');
    match colon {
        None => true,
        Some(ci) => {
            let sep = url[..ci].find(['/', '\\']);
            if sep.is_some() {
                return true;
            }
            let b = url.as_bytes();
            ci == 1 && b.first().is_some_and(u8::is_ascii_alphabetic)
        }
    }
}

/// Strip the Windows verbatim `\\?\` prefix when present.
#[must_use]
pub(crate) fn strip_verbatim_path_prefix(path: &str) -> &str {
    path.strip_prefix(r"\\?\").unwrap_or(path)
}

/// Returns the display form of a remote URL: `url` with any embedded username and password
/// removed, safe for logs, errors and command output.
///
/// Remote URLs may carry credentials in configuration or on the command line; user-facing output
/// (human, JSON and Markdown alike) must never echo them. Use this for every copy of a remote
/// address that is shown, and keep the original for transport and configuration.
///
/// Only the userinfo is removed: everything else is returned byte for byte (surrounding
/// whitespace aside), so host case, ports, paths and percent-encoding are never rewritten. Local
/// paths (see [`url_is_local_not_ssh`]) and addresses without an `@` are returned unchanged. For
/// `scheme://` URLs the userinfo ends at the last `@` before the path, so an unescaped `@` in a
/// password is removed too; SCP-style `user@host:path` drops everything up to that `@`.
#[must_use]
pub fn redact_url_for_display(url: &str) -> String {
    let trimmed = url.trim();
    if !trimmed.contains('@') || url_is_local_not_ssh(trimmed) {
        return trimmed.to_owned();
    }
    if let Some((scheme, rest)) = trimmed.split_once("://") {
        let host_start = userinfo_host_start(rest);
        return format!("{scheme}://{}", &rest[host_start..]);
    }
    let host_start = scp_host_start(trimmed);
    trimmed[host_start..].to_owned()
}

/// Index where `host:path` begins in an SCP-style address: just past the last `@` that is
/// followed by a `host:` (a `:` with no `/` before it). An `@` inside the path is not userinfo.
fn scp_host_start(url: &str) -> usize {
    url.match_indices('@')
        .rev()
        .map(|(at, _)| at + 1)
        .find(|&start| {
            let rest = &url[start..];
            rest.find(':')
                .is_some_and(|colon| !rest[..colon].contains('/'))
        })
        .unwrap_or(0)
}

/// Index in `authority_or_url` where the host begins after optional `user:pass@` userinfo.
fn userinfo_host_start(authority_or_url: &str) -> usize {
    let bytes = authority_or_url.as_bytes();
    let mut host_start = 0usize;
    let mut idx = 0usize;
    while idx < bytes.len() {
        let b = bytes[idx];
        if b == b'/' || b == b'?' || b == b'#' {
            break;
        }
        if b == b'@' {
            host_start = idx + 1;
        }
        idx += 1;
    }
    host_start
}

/// Normalize a local path for storage in `remote.*.url` (Git-style forward slashes, no `\\?\`).
#[must_use]
pub(crate) fn normalize_local_path_for_config(path: &Path) -> String {
    let lossy = path.to_string_lossy();
    let stripped = strip_verbatim_path_prefix(&lossy);
    #[cfg(windows)]
    {
        stripped.replace('\\', "/")
    }
    #[cfg(not(windows))]
    {
        stripped.to_string()
    }
}

/// Absolute form of a local clone source path, matching Git's `absolute_pathdup`: prepend the
/// current directory when relative, but leave `.`/`..`/`./` components untouched (no
/// normalization). The parent of `source_path` is canonicalized when possible (Git resolves
/// the cwd via `getcwd`).
#[must_use]
pub(crate) fn absolute_local_clone_source_url(source_path: &Path) -> String {
    absolute_local_clone_source_url_from(source_path, &crate::environment::Environment::empty().cwd)
}

/// [`absolute_local_clone_source_url`] with a relative `source_path` taken from `cwd`.
fn absolute_local_clone_source_url_from(source_path: &Path, cwd: &Path) -> String {
    let absolute = if source_path.is_absolute() {
        source_path.to_path_buf()
    } else {
        let cwd = cwd
            .canonicalize_simplified()
            .unwrap_or_else(|_| cwd.to_path_buf());
        cwd.join(source_path)
    };
    normalize_local_path_for_config(&absolute)
}

/// Decode a `file://` remote URL into a local filesystem path (percent-decoding and `/C:/` → `C:/`).
///
/// # Errors
///
/// Returns [`Error::Message`] when a `%` escape is truncated or invalid.
pub(crate) fn file_url_to_local_path(url: &str) -> Result<String, Error> {
    let trimmed = url.trim();
    let mut path_part = trimmed
        .strip_prefix("file://")
        .ok_or_else(|| Error::Message("not a file:// URL".to_owned()))?;
    if path_part.starts_with("localhost") {
        path_part = &path_part["localhost".len()..];
    }
    let decoded = percent_decode_path(path_part)?;
    let decoded = String::from_utf8(decoded).map_err(|_| {
        Error::Message("file URL path is not valid UTF-8 after decoding".to_owned())
    })?;
    Ok(dos_file_url_path_to_local(&decoded))
}

fn dos_file_url_path_to_local(path: &str) -> String {
    let path = strip_verbatim_path_prefix(path);
    if path.len() >= 3 {
        let b = path.as_bytes();
        if b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\') {
            return path.to_string();
        }
    }
    if path.starts_with('/') && path.len() >= 4 {
        let b = path.as_bytes();
        if b[1].is_ascii_alphabetic() && b[2] == b':' && (b[3] == b'/' || b[3] == b'\\') {
            return path[1..].to_string();
        }
    }
    path.to_string()
}

fn percent_decode_path(path: &str) -> Result<Vec<u8>, Error> {
    let bytes = path.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            let h1 = bytes
                .get(i + 1)
                .ok_or_else(|| Error::Message("bad % escape in file URL".to_owned()))?;
            let h2 = bytes
                .get(i + 2)
                .ok_or_else(|| Error::Message("bad % escape in file URL".to_owned()))?;
            let byte = u8::from_str_radix(
                std::str::from_utf8(&[*h1, *h2])
                    .map_err(|_| Error::Message("bad % escape in file URL".to_owned()))?,
                16,
            )
            .map_err(|_| Error::Message("bad % escape in file URL".to_owned()))?;
            out.push(byte);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    Ok(out)
}

fn local_path_from_remote_url(url: &str) -> Result<PathBuf, Error> {
    let trimmed = url.trim();
    let path_str = if trimmed.starts_with("file://") {
        file_url_to_local_path(trimmed)?
    } else {
        dos_file_url_path_to_local(strip_verbatim_path_prefix(trimmed))
    };
    Ok(PathBuf::from(path_str))
}

/// Filesystem path for a local clone or fetch source, with relative paths resolved from
/// `discovery_cwd` (the caller's working directory before a clone destination exists).
///
/// # Errors
///
/// Returns [`Error::Message`] when a `file://` URL is malformed.
pub(crate) fn resolve_local_clone_source_path(
    url: &str,
    discovery_cwd: &Path,
) -> Result<PathBuf, Error> {
    let mut remote_path = local_path_from_remote_url(url.trim())?;
    if remote_path.is_relative() {
        let base = discovery_cwd
            .canonicalize_simplified()
            .unwrap_or_else(|_| discovery_cwd.to_path_buf());
        remote_path = base.join(remote_path);
    }
    Ok(remote_path)
}

/// True when `url` names a local filesystem remote (not `http(s)://`, `git://`, `ssh`, or `ext::`).
#[must_use]
pub(crate) fn is_local_path_remote_url(url: &str) -> bool {
    let url = url.trim();
    !(url.starts_with("git://")
        || url.starts_with("http://")
        || url.starts_with("https://")
        || url.starts_with("ext::")
        || crate::transport::is_ssh_url(url))
}

/// Resolve a local remote URL to the remote repository's git directory.
///
/// Relative paths are interpreted from [`configured_remote_base`], not from the process
/// current working directory. This matches Git's handling of configured `remote.<name>.url`
/// during fetch and push.
#[must_use]
pub fn resolve_local_remote_git_dir(
    url: &str,
    git_dir: &Path,
    work_tree: Option<&Path>,
) -> PathBuf {
    let mut remote_path = local_path_from_remote_url(url)
        .unwrap_or_else(|_| PathBuf::from(strip_verbatim_path_prefix(url.trim())));
    if remote_path.is_relative() {
        let base = configured_remote_base(git_dir, work_tree);
        remote_path = base.join(&remote_path);
    }
    local_git_dir_from_filesystem_path(&remote_path)
}

fn local_git_dir_from_filesystem_path(path: &Path) -> PathBuf {
    if path.ends_with(".git") || path.join("HEAD").is_file() {
        return path.to_path_buf();
    }
    let dot_git = path.join(".git");
    if dot_git.is_dir() {
        dot_git
    } else if dot_git.is_file() {
        // A linked worktree or `--separate-git-dir` checkout points at its git dir.
        crate::repo::resolve_dot_git(&dot_git).unwrap_or_else(|_| path.to_path_buf())
    } else {
        path.to_path_buf()
    }
}

/// Error returned by [`git_url_basename`] when no directory name can be derived from a URL.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[error("No directory name could be guessed.\nPlease specify a directory on the command line")]
pub struct NoDirectoryName;

/// Directory separator test for [`git_url_basename`], matching Git's `is_dir_sep`.
///
/// Both `/` and `\` are treated as separators so Windows-style local clone sources
/// (`..\..\origin.git`, `C:\scratch\a\origin.git`) derive the same default directory
/// name as `git clone`.
#[inline]
fn is_dir_sep(b: u8) -> bool {
    b == b'/' || b == b'\\'
}

#[inline]
fn bytes_have_dir_sep(bytes: &[u8]) -> bool {
    bytes.iter().any(|&b| is_dir_sep(b))
}

/// Derive the "humanish" directory name Git would use for `git clone <repo>` when no explicit
/// target directory is given. It matches the behavior of Git's `git_url_basename`:
/// it operates on the **raw URL string** (not a pre-parsed path), so it can
/// fall back to the hostname when the URL has no path component (e.g. `ssh://host/` → `host`).
///
/// # Parameters
/// - `repo`: the raw repository URL or path exactly as passed on the command line.
/// - `is_bundle`: strip a trailing `.bundle` suffix instead of `.git`.
/// - `is_bare`: append `.git` to the guessed name (for `--bare` clones).
///
/// # Errors
/// Returns [`NoDirectoryName`] when the URL collapses to an empty (or single-slash) name, which
/// is the condition under which Git dies asking for an explicit directory.
///
/// Note: callers handle the `--mirror` exception (bare clone without a `.git` directory suffix)
/// by passing `is_bare = false`, matching Git's `option_bare && !option_mirror` logic.
pub(crate) fn git_url_basename(
    repo: &str,
    is_bundle: bool,
    is_bare: bool,
) -> Result<String, NoDirectoryName> {
    let bytes = repo.as_bytes();
    let mut end = bytes.len();

    // Skip scheme (everything up to and including "://").
    let mut start = match repo.find("://") {
        Some(idx) => idx + 3,
        None => 0,
    };

    // Skip authentication data, greedily up to the last '@' before the first dir separator.
    let mut ptr = start;
    while ptr < end && !is_dir_sep(bytes[ptr]) {
        if bytes[ptr] == b'@' {
            start = ptr + 1;
        }
        ptr += 1;
    }

    // Strip trailing spaces, slashes and a trailing "/.git".
    while start < end && (is_dir_sep(bytes[end - 1]) || bytes[end - 1].is_ascii_whitespace()) {
        end -= 1;
    }
    if end > start + 5 && is_dir_sep(bytes[end - 5]) && &bytes[end - 4..end] == b".git" {
        end -= 5;
        while start < end && is_dir_sep(bytes[end - 1]) {
            end -= 1;
        }
    }

    if end < start {
        return Err(NoDirectoryName);
    }

    // Strip a trailing port number when we have only a hostname (no dir separator but a colon).
    // This must NOT strip URIs like '/foo/bar:2222.git', which should guess dir '2222' for
    // backwards compatibility.
    let slice = &bytes[start..end];
    if !bytes_have_dir_sep(slice) && slice.contains(&b':') {
        let mut p = end;
        while start < p && bytes[p - 1].is_ascii_digit() && bytes[p - 1] != b':' {
            p -= 1;
        }
        if start < p && bytes[p - 1] == b':' {
            end = p - 1;
        }
    }

    // Find last component; colons also act as separators for backwards compatibility
    // (`foo:bar.git` → `bar`).
    let mut p = end;
    while start < p && !is_dir_sep(bytes[p - 1]) && bytes[p - 1] != b':' {
        p -= 1;
    }
    start = p;

    // Strip a trailing .{bundle,git}.
    let suffix: &[u8] = if is_bundle { b".bundle" } else { b".git" };
    let mut len = end - start;
    if len >= suffix.len() && &bytes[start + len - suffix.len()..start + len] == suffix {
        len -= suffix.len();
    }

    if len == 0 || (len == 1 && bytes[start] == b'/') {
        return Err(NoDirectoryName);
    }

    let core = &repo[start..start + len];
    let mut dir = if is_bare {
        format!("{core}.git")
    } else {
        core.to_string()
    };

    dir = collapse_control_and_whitespace(&dir);
    Ok(dir)
}

/// Replace runs of control characters and whitespace in a guessed directory name with a single
/// ASCII space, then strip leading and trailing spaces — mirroring the final pass of Git's
/// `git_url_basename`.
fn collapse_control_and_whitespace(dir: &str) -> String {
    let mut out = String::with_capacity(dir.len());
    let mut prev_space = true; // strip leading whitespace
    for &b in dir.as_bytes() {
        let ch = if b < 0x20 { b' ' } else { b };
        if ch.is_ascii_whitespace() {
            if prev_space {
                continue;
            }
            prev_space = true;
        } else {
            prev_space = false;
        }
        out.push(ch as char);
    }
    if prev_space {
        while out.ends_with(' ') {
            out.pop();
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn basename(url: &str) -> String {
        git_url_basename(url, false, false).expect("dir name")
    }

    #[test]
    fn scp_style_basic() {
        assert_eq!(basename("host:foo"), "foo");
        assert_eq!(basename("host:foo.git"), "foo");
        assert_eq!(basename("host:foo/.git"), "foo");
    }

    #[test]
    fn ssh_url_basic() {
        assert_eq!(basename("ssh://host/foo"), "foo");
        assert_eq!(basename("ssh://host/foo.git"), "foo");
        assert_eq!(basename("ssh://host/foo/.git"), "foo");
    }

    #[test]
    fn trailing_slashes_and_git() {
        assert_eq!(basename("ssh://host/foo/"), "foo");
        assert_eq!(basename("ssh://host/foo///"), "foo");
        assert_eq!(basename("ssh://host/foo/.git/"), "foo");
        assert_eq!(basename("ssh://host/foo.git/"), "foo");
        assert_eq!(basename("ssh://host/foo.git///"), "foo");
        assert_eq!(basename("ssh://host/foo///.git/"), "foo");
        assert_eq!(basename("ssh://host/foo/.git///"), "foo");

        assert_eq!(basename("host:foo/"), "foo");
        assert_eq!(basename("host:foo///"), "foo");
        assert_eq!(basename("host:foo.git/"), "foo");
        assert_eq!(basename("host:foo/.git/"), "foo");
        assert_eq!(basename("host:foo.git///"), "foo");
        assert_eq!(basename("host:foo///.git/"), "foo");
        assert_eq!(basename("host:foo/.git///"), "foo");
    }

    #[test]
    fn empty_path_defaults_to_hostname() {
        assert_eq!(basename("ssh://host/"), "host");
        assert_eq!(basename("ssh://host:1234/"), "host");
        assert_eq!(basename("ssh://user@host/"), "host");
        assert_eq!(basename("host:/"), "host");
    }

    #[test]
    fn auth_material_is_redacted() {
        assert_eq!(basename("ssh://user:password@host/"), "host");
        assert_eq!(basename("ssh://user:password@host:1234/"), "host");
        assert_eq!(basename("ssh://user:passw@rd@host:1234/"), "host");
        assert_eq!(basename("user@host:/"), "host");
        assert_eq!(basename("user:password@host:/"), "host");
        assert_eq!(basename("user:passw@rd@host:/"), "host");
    }

    #[test]
    fn auth_like_material_kept_in_path() {
        assert_eq!(basename("ssh://host/foo@bar"), "foo@bar");
        assert_eq!(basename("ssh://host/foo@bar.git"), "foo@bar");
        assert_eq!(basename("ssh://user:password@host/foo@bar"), "foo@bar");
        assert_eq!(basename("ssh://user:passw@rd@host/foo@bar.git"), "foo@bar");
        assert_eq!(basename("host:/foo@bar"), "foo@bar");
        assert_eq!(basename("host:/foo@bar.git"), "foo@bar");
        assert_eq!(basename("user:password@host:/foo@bar"), "foo@bar");
        assert_eq!(basename("user:passw@rd@host:/foo@bar.git"), "foo@bar");
    }

    #[test]
    fn trailing_port_like_numbers_in_path_kept() {
        assert_eq!(basename("ssh://user:password@host/test:1234"), "1234");
        assert_eq!(basename("ssh://user:password@host/test:1234.git"), "1234");
    }

    #[test]
    fn bare_appends_git() {
        assert_eq!(
            git_url_basename("host:foo", false, true).unwrap(),
            "foo.git"
        );
        assert_eq!(
            git_url_basename("host:foo.git", false, true).unwrap(),
            "foo.git"
        );
    }

    #[test]
    fn empty_name_is_error() {
        assert_eq!(git_url_basename("/", false, false), Err(NoDirectoryName));
        assert_eq!(git_url_basename("", false, false), Err(NoDirectoryName));
    }

    #[test]
    fn windows_style_local_path_components() {
        assert_eq!(basename(r"..\..\origin.git"), "origin");
        assert_eq!(basename(r"..\..\\origin.git"), "origin");
        assert_eq!(basename(r"C:\scratch\a\origin.git"), "origin");
        assert_eq!(basename(r"C:/scratch/a/origin.git"), "origin");
        assert_eq!(basename(r"foo\bar\repo"), "repo");
    }

    #[test]
    fn configured_remote_base_worktree_and_bare() {
        assert_eq!(
            configured_remote_base(Path::new("/tmp/wt/.git"), None),
            PathBuf::from("/tmp/wt")
        );
        assert_eq!(
            configured_remote_base(Path::new("/tmp/remote.git"), None),
            PathBuf::from("/tmp/remote.git")
        );
        assert_eq!(
            configured_remote_base(
                Path::new("/tmp/main/.git/worktrees/feature"),
                Some(Path::new("/tmp/linked"))
            ),
            PathBuf::from("/tmp/linked")
        );
    }

    #[test]
    fn resolve_local_remote_git_dir_from_relative_url() {
        let base = PathBuf::from("/tmp/parent/clone");
        let git_dir = base.join(".git");
        let resolved = resolve_local_remote_git_dir("origin.git", &git_dir, Some(&base));
        assert_eq!(resolved, base.join("origin.git"));
    }

    #[test]
    fn should_store_absolute_local_clone_url_classification() {
        assert!(super::should_store_absolute_local_clone_url("origin.git"));
        assert!(!super::should_store_absolute_local_clone_url(
            "file:///tmp/x.git"
        ));
        assert!(!super::should_store_absolute_local_clone_url(
            "https://h/r.git"
        ));
    }

    #[test]
    fn is_local_path_remote_url_classification() {
        assert!(is_local_path_remote_url("./foo.git"));
        assert!(is_local_path_remote_url("/abs/foo.git"));
        assert!(is_local_path_remote_url("file:///tmp/x"));
        assert!(!is_local_path_remote_url("https://example.com/x.git"));
        assert!(!is_local_path_remote_url("git://host/x.git"));
        assert!(!is_local_path_remote_url("host:repo.git"));
        assert!(is_local_path_remote_url("C:/tmp/x"));
        assert!(is_local_path_remote_url(r"C:\tmp\x"));
    }

    #[test]
    fn url_is_local_not_ssh_windows_drive_and_scp() {
        assert!(url_is_local_not_ssh("C:/tmp/src"));
        assert!(url_is_local_not_ssh(r"C:\tmp\src"));
        assert!(url_is_local_not_ssh(r"\\?\C:\tmp\src"));
        assert!(url_is_local_not_ssh("../t/src"));
        assert!(url_is_local_not_ssh("src"));
        assert!(!url_is_local_not_ssh("host:repo.git"));
    }

    #[test]
    fn file_url_to_local_path_decodes_drive() {
        assert_eq!(
            file_url_to_local_path("file:///C:/tmp/t/src").unwrap(),
            "C:/tmp/t/src"
        );
        assert_eq!(file_url_to_local_path("file:///tmp/x").unwrap(), "/tmp/x");
        assert_eq!(
            file_url_to_local_path("file://localhost/tmp/x").unwrap(),
            "/tmp/x"
        );
    }

    #[test]
    fn file_url_preserves_percent_encoded_question_mark() {
        let base = std::env::temp_dir().join(format!("grit-file-qmark-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).expect("temp base");
        let repo_dir = base.join("origin?repo.git");
        std::fs::create_dir_all(&repo_dir).expect("repo dir");
        std::fs::write(repo_dir.join("HEAD"), "ref: refs/heads/main\n").expect("HEAD");

        let url = format!(
            "file://{}/origin%3Frepo.git",
            base.to_str().expect("utf8 base")
        );
        let decoded = file_url_to_local_path(&url).expect("decode");
        assert!(
            decoded.ends_with("origin?repo.git"),
            "decoded path must keep literal ?, got {decoded}"
        );
        let resolved =
            resolve_local_remote_git_dir(&url, &base.join("clone/.git"), Some(&base.join("clone")));
        assert_eq!(resolved, repo_dir);

        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn absolute_local_clone_source_url_keeps_dot_components() {
        let base = std::env::temp_dir().join(format!("grit-abs-clone-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).expect("temp base");
        // Not `set_current_dir`: that would move every test running in this process.
        let stored = absolute_local_clone_source_url_from(Path::new("./nested/../peer"), &base);
        let _ = std::fs::remove_dir_all(&base);
        assert!(
            stored.contains("nested/../peer") || stored.ends_with("peer"),
            "expected dot components preserved, got {stored}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn absolute_local_clone_source_url_preserves_symlink() {
        use std::os::unix::fs::symlink;

        let base = std::env::temp_dir().join(format!("grit-abs-symlink-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).expect("temp base");
        let real = base.join("real-src");
        std::fs::create_dir_all(&real).expect("real dir");
        let link = base.join("link-src");
        symlink(&real, &link).expect("symlink");

        let stored = absolute_local_clone_source_url(&link);
        let _ = std::fs::remove_dir_all(&base);

        assert_eq!(stored, normalize_local_path_for_config(&link));
        assert_ne!(stored, normalize_local_path_for_config(&real));
    }

    #[test]
    fn normalize_local_path_for_config_strips_verbatim() {
        let path = Path::new(r"\\?\C:\tmp\t\src");
        #[cfg(windows)]
        assert_eq!(normalize_local_path_for_config(path), "C:/tmp/t/src");
        #[cfg(not(windows))]
        assert_eq!(normalize_local_path_for_config(path), r"C:\tmp\t\src");
    }

    #[test]
    fn redact_url_for_display_strips_http_userinfo() {
        assert_eq!(
            redact_url_for_display(
                "http://bob:wrongpass@127.0.0.1:18082/priv.git/info/refs?service=git-upload-pack"
            ),
            "http://127.0.0.1:18082/priv.git/info/refs?service=git-upload-pack"
        );
        assert_eq!(
            redact_url_for_display("https://user:secret@example.com/repo.git"),
            "https://example.com/repo.git"
        );
    }

    #[test]
    fn redact_url_for_display_percent_encoded_userinfo() {
        assert_eq!(
            redact_url_for_display("http://alice:pa%24%24w%30rd@host.example/repo.git"),
            "http://host.example/repo.git"
        );
        assert_eq!(
            redact_url_for_display("http://user:pass%40word@host.example/r.git"),
            "http://host.example/r.git"
        );
    }

    #[test]
    fn redact_url_for_display_scp_and_at_in_password() {
        assert_eq!(
            redact_url_for_display("user:password@host.example:repo.git"),
            "host.example:repo.git"
        );
        assert_eq!(
            redact_url_for_display("http://user:passw@rd@host.example/repo.git"),
            "http://host.example/repo.git"
        );
    }

    #[test]
    fn redact_url_for_display_leaves_path_at_signs() {
        assert_eq!(
            redact_url_for_display("https://host.example/foo@bar.git"),
            "https://host.example/foo@bar.git"
        );
        assert_eq!(
            redact_url_for_display("file:///srv/me@work/repo.git"),
            "file:///srv/me@work/repo.git"
        );
        assert_eq!(
            redact_url_for_display("git@host.example:org/repo@v1.git"),
            "host.example:org/repo@v1.git"
        );
        assert_eq!(
            redact_url_for_display("host.example:org/repo@v1.git"),
            "host.example:org/repo@v1.git"
        );
    }

    #[test]
    fn redact_url_for_display_never_rewrites_credential_free_urls() {
        for url in [
            "http://127.0.0.1:9419/auth.git",
            "HTTP://Host.Example:80/a%20b/Repo.git",
            "https://host.example:443/r.git?x=1#frag",
            "ssh://host.example:2222/~/repo.git",
            "git://[::1]/repo",
            "host.example:repo.git",
            "origin",
            "",
        ] {
            assert_eq!(redact_url_for_display(url), url);
        }
        assert_eq!(
            redact_url_for_display("HTTP://u:p@Host.Example:80/a%20b/Repo.git"),
            "HTTP://Host.Example:80/a%20b/Repo.git"
        );
    }

    #[test]
    fn redact_url_for_display_leaves_local_paths_alone() {
        for path in [
            "/tmp/alice@laptop/repo.git",
            "../me@there/repo",
            "me@there",
            "./a:b@c",
        ] {
            assert_eq!(redact_url_for_display(path), path);
        }
    }
}