wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
use crate::fleet::config::GitModules;
use crate::fleet::error::{Result, SuperGitError};
use crate::prelude::*;
use std::collections::HashSet;

/// Hard ceiling on submodule nesting. Real fleets are 2-3 deep; anything beyond
/// this is a configuration mistake or a cycle we failed to detect by path.
pub const MAX_SUBMODULE_DEPTH: usize = 32;

/// A submodule discovered anywhere in the nesting tree, not just at the top level.
#[derive(Debug, Clone)]
pub struct SubmoduleNode {
    /// Name as declared in the immediate parent's `.gitmodules`. Not unique across the tree.
    pub name: String,
    /// Path relative to the immediate parent repository.
    pub rel_path: PathBuf,
    /// Slash-separated path from the fleet root. Unique across the tree; use this
    /// for display, selection, and include/exclude matching.
    pub display_path: String,
    /// Absolute path of the submodule working tree.
    pub abs_path: PathBuf,
    /// Absolute path of the repository that declares this submodule.
    pub parent_path: PathBuf,
    /// URL exactly as declared in `.gitmodules`, which may be relative
    /// (`./x`, `../x`). Call [`SubmoduleNode::resolved_url`] to get a clonable URL.
    pub url: String,
    pub branch: Option<String>,
    /// 0 for a direct submodule of the fleet root.
    pub depth: usize,
    /// Whether the working tree has been checked out (its `.git` exists).
    pub initialized: bool,
}

impl SubmoduleNode {
    /// Label for output: the full path from the fleet root, which disambiguates
    /// same-named submodules at different depths.
    pub fn label(&self) -> &str {
        &self.display_path
    }

    /// The URL to clone this submodule from, resolving a `./`- or `../`-relative
    /// declaration against the remote of the repository that declares it.
    ///
    /// Resolved here rather than during discovery because a URL only has to be
    /// resolvable when something actually clones: an already checked-out tree is
    /// perfectly usable even if a parent has no remote configured, and failing
    /// the whole walk over an unused URL would make such trees unreadable.
    pub fn resolved_url(&self) -> Result<String> {
        if !is_relative_submodule_url(&self.url) {
            return Ok(self.url.clone());
        }

        let base = parent_remote_url(&self.parent_path)?.ok_or_else(|| {
            SuperGitError::Other(format!(
                "Submodule '{}' uses the relative URL '{}', but its parent repository at '{}' \
                 has no 'origin' remote to resolve it against",
                self.display_path,
                self.url,
                self.parent_path.display()
            ))
        })?;

        Ok(resolve_relative_url(&base, &self.url))
    }
}

/// Every submodule reachable from a fleet root, at any depth.
#[derive(Debug, Clone)]
pub struct SubmoduleTree {
    pub root: PathBuf,
    /// Pre-order: a parent always precedes its children.
    nodes: Vec<SubmoduleNode>,
    /// Paths from the root that were skipped because the worktree ignores them.
    ignored: Vec<String>,
    /// Configured patterns that matched no submodule in this tree.
    unmatched_ignore_patterns: Vec<String>,
}

impl SubmoduleTree {
    /// Walk the whole nesting tree from `root`, skipping submodules the
    /// worktree ignores.
    ///
    /// Uninitialized submodules are included as leaves — we cannot see their
    /// `.gitmodules` until they are checked out, so their children appear only
    /// after a later discovery pass.
    pub fn discover<P: AsRef<Path>>(root: P) -> Result<Self> {
        let root = root.as_ref().to_path_buf();
        let patterns = ignore_patterns(&root)?;
        Self::discover_with_ignores(root, &patterns)
    }

    /// Walk the tree using an explicit ignore list instead of the worktree's.
    pub fn discover_with_ignores<P: AsRef<Path>>(root: P, patterns: &[String]) -> Result<Self> {
        let tree = Self::build(root, patterns)?;
        if tree.nodes.is_empty() {
            // "none declared" and "all of them ignored" are different problems and
            // must not share an error, or a stray pattern looks like a missing
            // .gitmodules.
            if !tree.ignored.is_empty() {
                return Err(SuperGitError::Other(format!(
                    "All {} submodule(s) are excluded by 'ignored_submodules' in the worktree \
                     at '{}'; relax the pattern(s) to operate on them",
                    tree.ignored.len(),
                    tree.root.display()
                )));
            }
            return Err(SuperGitError::NoSubmodules);
        }
        Ok(tree)
    }

    /// Walk the tree, returning it even when every submodule was ignored or none
    /// exist. Keeping the walk's findings — including what was ignored — is why
    /// the empty case is built here rather than synthesised by the caller.
    fn build<P: AsRef<Path>>(root: P, patterns: &[String]) -> Result<Self> {
        let root = root.as_ref().to_path_buf();
        let mut nodes = Vec::new();
        let mut ignored = Vec::new();
        let mut matched = vec![false; patterns.len()];
        let mut visited = HashSet::new();
        visited.insert(canonical_key(&root)?);

        walk(
            &root,
            None,
            0,
            patterns,
            &mut matched,
            &mut ignored,
            &mut visited,
            &mut nodes,
        )?;

        let unmatched_ignore_patterns = patterns
            .iter()
            .zip(&matched)
            .filter(|(_, hit)| !**hit)
            .map(|(pattern, _)| pattern.clone())
            .collect();

        Ok(SubmoduleTree {
            root,
            nodes,
            ignored,
            unmatched_ignore_patterns,
        })
    }

    /// Like `discover`, but yields an empty tree instead of erroring when the
    /// root declares no submodules or every one of them is ignored.
    pub fn discover_allow_empty<P: AsRef<Path>>(root: P) -> Result<Self> {
        let patterns = ignore_patterns(root.as_ref())?;
        Self::build(root, &patterns)
    }

    /// Submodules skipped because the worktree ignores them, as paths from the root.
    pub fn ignored(&self) -> &[String] {
        &self.ignored
    }

    /// Configured ignore patterns that matched nothing — usually a typo, so
    /// callers should surface them rather than let them silently do nothing.
    pub fn unmatched_ignore_patterns(&self) -> &[String] {
        &self.unmatched_ignore_patterns
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Parents before children. Use for operations that push state outward from
    /// the superproject: init, checkout, pull, fetch, sync.
    pub fn top_down(&self) -> &[SubmoduleNode] {
        &self.nodes
    }

    /// Children before parents. Use for operations where a parent's result
    /// depends on its children having been recorded first: stage, commit, push.
    pub fn bottom_up(&self) -> Vec<&SubmoduleNode> {
        let mut ordered: Vec<&SubmoduleNode> = self.nodes.iter().collect();
        // Stable sort by descending depth keeps siblings in discovery order while
        // guaranteeing every child precedes its parent.
        ordered.sort_by_key(|node| std::cmp::Reverse(node.depth));
        ordered
    }

    /// Direct submodules of the fleet root.
    pub fn top_level(&self) -> impl Iterator<Item = &SubmoduleNode> {
        self.nodes.iter().filter(|node| node.depth == 0)
    }

    /// The repositories that declare submodules, deepest first, each paired with
    /// the children it must record. Use when updating gitlinks after committing.
    pub fn parents_bottom_up(&self) -> Vec<(PathBuf, Vec<&SubmoduleNode>)> {
        let mut groups: Vec<(PathBuf, Vec<&SubmoduleNode>)> = Vec::new();
        for node in self.bottom_up() {
            match groups
                .iter_mut()
                .find(|(parent, _)| parent == &node.parent_path)
            {
                Some((_, children)) => children.push(node),
                None => groups.push((node.parent_path.clone(), vec![node])),
            }
        }
        groups
    }

    pub fn find(&self, display_path: &str) -> Option<&SubmoduleNode> {
        self.nodes
            .iter()
            .find(|node| node.display_path == display_path)
    }
}

#[allow(clippy::too_many_arguments)]
fn walk(
    current: &Path,
    prefix: Option<&str>,
    depth: usize,
    patterns: &[String],
    matched: &mut [bool],
    ignored: &mut Vec<String>,
    visited: &mut HashSet<PathBuf>,
    out: &mut Vec<SubmoduleNode>,
) -> Result<()> {
    if depth >= MAX_SUBMODULE_DEPTH {
        return Err(SuperGitError::Other(format!(
            "Submodule nesting exceeds the maximum depth of {MAX_SUBMODULE_DEPTH} at '{}' — \
             this usually means .gitmodules entries form a cycle",
            current.display()
        )));
    }

    let gitmodules = match GitModules::parse(current) {
        Ok(parsed) => parsed,
        // A repository with no submodules is a leaf, not an error.
        Err(SuperGitError::NoSubmodules) => return Ok(()),
        Err(err) => return Err(err),
    };

    for submodule in &gitmodules.submodules {
        validate_submodule_path(&submodule.path, current)?;

        let abs_path = current.join(&submodule.path);
        let display_path = match prefix {
            Some(prefix) => format!("{prefix}/{}", to_slash(&submodule.path)),
            None => to_slash(&submodule.path),
        };

        // An ignored submodule is skipped along with everything nested inside it:
        // we neither record it nor descend into its own .gitmodules.
        let mut is_ignored = false;
        for (index, pattern) in patterns.iter().enumerate() {
            if path_matches_pattern(pattern, &display_path) {
                matched[index] = true;
                is_ignored = true;
            }
        }
        if is_ignored {
            ignored.push(display_path);
            continue;
        }

        let initialized = is_initialized(&abs_path);

        out.push(SubmoduleNode {
            name: submodule.name.clone(),
            rel_path: submodule.path.clone(),
            display_path: display_path.clone(),
            abs_path: abs_path.clone(),
            parent_path: current.to_path_buf(),
            url: submodule.url.clone(),
            branch: submodule.branch.clone(),
            depth,
            initialized,
        });

        if !initialized {
            continue;
        }

        // Guard against symlinked or self-referential checkouts that would
        // otherwise make the walk run until the depth cap.
        if !visited.insert(canonical_key(&abs_path)?) {
            return Err(SuperGitError::Other(format!(
                "Submodule cycle detected: '{display_path}' resolves to a repository already \
                 visited in this tree",
            )));
        }

        walk(
            &abs_path,
            Some(&display_path),
            depth + 1,
            patterns,
            matched,
            ignored,
            visited,
            out,
        )?;
    }

    Ok(())
}

/// Reject submodule paths that would let a `.gitmodules` file write outside the
/// repository that declares it.
fn validate_submodule_path(path: &Path, parent: &Path) -> Result<()> {
    if path.as_os_str().is_empty() {
        return Err(SuperGitError::GitModulesParse(format!(
            "empty submodule path declared in '{}'",
            parent.display()
        )));
    }
    if path.is_absolute() {
        return Err(SuperGitError::GitModulesParse(format!(
            "submodule path '{}' in '{}' is absolute; submodule paths must be relative to the \
             repository that declares them",
            path.display(),
            parent.display()
        )));
    }

    for component in path.components() {
        match component {
            std::path::Component::ParentDir => {
                return Err(SuperGitError::GitModulesParse(format!(
                    "submodule path '{}' in '{}' escapes the repository via '..'",
                    path.display(),
                    parent.display()
                )));
            }
            std::path::Component::Prefix(_) | std::path::Component::RootDir => {
                return Err(SuperGitError::GitModulesParse(format!(
                    "submodule path '{}' in '{}' is not a plain relative path",
                    path.display(),
                    parent.display()
                )));
            }
            std::path::Component::Normal(part) => {
                if part.eq_ignore_ascii_case(".git") {
                    return Err(SuperGitError::GitModulesParse(format!(
                        "submodule path '{}' in '{}' targets a .git directory",
                        path.display(),
                        parent.display()
                    )));
                }
            }
            std::path::Component::CurDir => {}
        }
    }

    Ok(())
}

/// A checked-out submodule has a `.git` entry — a directory when cloned standalone,
/// a file containing a `gitdir:` pointer when registered by git itself.
fn is_initialized(path: &Path) -> bool {
    path.join(".git").exists()
}

/// Identity of a checked-out repository on disk, with symlinks resolved so that a
/// symlinked submodule cannot masquerade as a distinct repository.
///
/// Only ever called on paths we have already established exist; a failure here
/// means the tree changed underneath us and we must not guess.
fn canonical_key(path: &Path) -> Result<PathBuf> {
    crate::platform::canonicalize(path).map_err(|err| {
        SuperGitError::Other(format!(
            "Failed to resolve '{}' while walking the submodule tree: {}",
            path.display(),
            err
        ))
    })
}

fn to_slash(path: &Path) -> String {
    path.components()
        .filter_map(|component| match component {
            std::path::Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/")
}

/// The `origin` URL of the repository that declares a submodule, needed to resolve
/// relative submodule URLs. `None` means the remote genuinely is not configured,
/// which is a distinct case from failing to read the repository at all.
fn parent_remote_url(repo_root: &Path) -> Result<Option<String>> {
    let repo = crate::git_backend::open_repo(repo_root).map_err(|err| {
        SuperGitError::Other(format!(
            "Failed to open '{}' to resolve relative submodule URLs: {}",
            repo_root.display(),
            err
        ))
    })?;
    Ok(crate::git_backend::remote_url(&repo, "origin").ok())
}

/// The submodules the project checked out at `root` ignores, read from its
/// `.wsb/project.json`.
///
/// A checkout that commits no project settings ignores nothing. Settings that
/// exist but cannot be read are a real failure and are propagated.
fn ignore_patterns(root: &Path) -> Result<Vec<String>> {
    let state = wsb_prj::settings::ProjectSettings::load(root).map_err(|err| {
        SuperGitError::Other(format!(
            "Failed to read ignored submodules from the project settings at '{}': {err:#}",
            root.display(),
        ))
    })?;

    for pattern in &state.ignored_submodules {
        if pattern.trim().is_empty() {
            return Err(SuperGitError::Other(format!(
                "'ignored_submodules' in the project settings at '{}' contains an empty pattern, which \
                 would match nothing; remove it or give it a submodule path",
                root.display()
            )));
        }
    }

    Ok(state.ignored_submodules)
}

/// Match a submodule's path from the fleet root against an ignore pattern.
///
/// `*` matches any run of characters within one path segment and `**` matches
/// any number of segments, so `ext/*` covers `ext/gtest` while `ext/**` also
/// covers anything deeper.
pub fn path_matches_pattern(pattern: &str, path: &str) -> bool {
    let pattern_segments: Vec<&str> = pattern
        .trim_matches('/')
        .split('/')
        .filter(|segment| !segment.is_empty())
        .collect();
    let path_segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    segments_match(&pattern_segments, &path_segments)
}

fn segments_match(pattern: &[&str], path: &[&str]) -> bool {
    match pattern.split_first() {
        None => path.is_empty(),
        Some((&"**", rest)) => {
            // `**` consumes any number of segments, including none.
            (0..=path.len()).any(|skip| segments_match(rest, &path[skip..]))
        }
        Some((head, rest)) => match path.split_first() {
            Some((candidate, path_rest)) if segment_matches(head, candidate) => {
                segments_match(rest, path_rest)
            }
            _ => false,
        },
    }
}

/// Wildcard match within a single path segment, supporting `*` and `?`.
fn segment_matches(pattern: &str, value: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let value: Vec<char> = value.chars().collect();

    // Classic two-cursor wildcard match with backtracking on the last `*`.
    let (mut p, mut v) = (0usize, 0usize);
    let (mut star, mut backtrack) = (None, 0usize);

    while v < value.len() {
        if p < pattern.len() && (pattern[p] == '?' || pattern[p] == value[v]) {
            p += 1;
            v += 1;
        } else if p < pattern.len() && pattern[p] == '*' {
            star = Some(p);
            backtrack = v;
            p += 1;
        } else if let Some(star_index) = star {
            p = star_index + 1;
            backtrack += 1;
            v = backtrack;
        } else {
            return false;
        }
    }

    pattern[p..].iter().all(|&ch| ch == '*')
}

/// Per gitmodules(5), a URL beginning with `./` or `../` is relative to the
/// superproject's own remote.
pub fn is_relative_submodule_url(url: &str) -> bool {
    url.starts_with("./") || url.starts_with("../")
}

/// Resolve a `./`- or `../`-prefixed submodule URL against the parent's remote URL,
/// applying each `..` to the last path segment of the base.
///
/// Handles the three forms a remote can take: URL-style (`https://host/org/repo`),
/// scp-style (`git@host:org/repo`), and a plain local path (`/srv/git/repo`).
pub fn resolve_relative_url(base: &str, relative: &str) -> String {
    let base = base.trim_end_matches('/');

    // A Windows path spells its folders with `\`, and `..` steps over those
    // as it steps over `/`. Split only on `/`, the whole of `C:\work\mid.git`
    // was one segment, and `../leaf.git` resolved to a bare `leaf.git`.
    if base.contains('\\') && split_base(base).0.is_none() {
        return resolve_against_windows_path(base.trim_end_matches('\\'), relative);
    }

    // Split off the prefix that must survive verbatim from the path `..` may pop.
    let (prefix, path) = split_base(base);
    let mut segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();

    for segment in relative.split('/') {
        match segment {
            "." | "" => {}
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }

    let joined = segments.join("/");
    match prefix {
        // An authority already supplies its own separator semantics.
        Some(prefix) if prefix.ends_with(':') => format!("{prefix}{joined}"),
        Some(prefix) => format!("{prefix}/{joined}"),
        // A bare local path keeps whatever rootedness it started with; dropping a
        // leading '/' would silently turn an absolute remote into a relative one.
        None if base.starts_with('/') => format!("/{joined}"),
        None => joined,
    }
}

/// [`resolve_relative_url`] for a local Windows path: `..` takes off the
/// last folder, whichever separator spells it, and never the drive.
fn resolve_against_windows_path(base: &str, relative: &str) -> String {
    let drive = match base.find(['\\', '/']) {
        Some(index) if base[..index].ends_with(':') => index,
        _ => 0,
    };
    let mut kept = base.to_string();
    let mut added: Vec<&str> = Vec::new();
    for segment in relative.split('/') {
        match segment {
            "." | "" => {}
            ".." => {
                if added.pop().is_none() {
                    match kept.rfind(['\\', '/']) {
                        Some(index) if index > drive => kept.truncate(index),
                        _ => kept.truncate(drive),
                    }
                }
            }
            other => added.push(other),
        }
    }
    if added.is_empty() {
        kept
    } else {
        format!("{kept}/{}", added.join("/"))
    }
}

/// Returns the part of the base URL that must be preserved verbatim, and the
/// path portion that `..` segments may pop from.
fn split_base(base: &str) -> (Option<&str>, &str) {
    if let Some(scheme_end) = base.find("://") {
        let after_scheme = scheme_end + 3;
        return match base[after_scheme..].find('/') {
            Some(offset) => {
                let split = after_scheme + offset;
                (Some(&base[..split]), &base[split + 1..])
            }
            None => (Some(base), ""),
        };
    }

    // scp-style `user@host:path`. A colon only introduces one when it comes before
    // any '/', and a single leading character is a Windows drive letter, not a host.
    if let Some(colon) = base.find(':') {
        if colon > 1 && !base[..colon].contains('/') {
            return (Some(&base[..=colon]), &base[colon + 1..]);
        }
    }

    (None, base)
}

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

    /// TEST20045: a relative submodule URL resolves against a Windows path.
    ///
    /// A local remote on Windows is spelled with backslashes, and a resolver
    /// that split only on `/` treated the whole path as one folder: `..` took
    /// all of it, and the submodule's URL became a bare name.
    #[test]
    fn test20045_relative_urls_resolve_against_a_windows_path() {
        assert_eq!(
            resolve_relative_url(r"C:\work\repos\mid.git", "../leaf.git"),
            r"C:\work\repos/leaf.git"
        );
        assert_eq!(
            resolve_relative_url(r"C:\work\repos\mid.git", "./nested"),
            r"C:\work\repos\mid.git/nested"
        );
        assert_eq!(
            resolve_relative_url(r"C:\work\mid.git", "../../../leaf.git"),
            r"C:/leaf.git",
            "`..` stops at the drive"
        );
        assert_eq!(
            resolve_relative_url(r"C:\work\a\mid.git", "../x/../leaf.git"),
            r"C:\work\a/leaf.git"
        );
    }

    #[test]
    fn resolves_relative_urls_against_https_base() {
        assert_eq!(
            resolve_relative_url("https://github.com/acme/super", "../core"),
            "https://github.com/acme/core"
        );
        assert_eq!(
            resolve_relative_url("https://github.com/acme/super", "./nested"),
            "https://github.com/acme/super/nested"
        );
        assert_eq!(
            resolve_relative_url("https://github.com/acme/group/super", "../../other/lib"),
            "https://github.com/acme/other/lib"
        );
    }

    #[test]
    fn resolves_relative_urls_against_scp_style_base() {
        assert_eq!(
            resolve_relative_url("git@github.com:acme/super.git", "../core.git"),
            "git@github.com:acme/core.git"
        );
        assert_eq!(
            resolve_relative_url("git@github.com:acme/super.git", "./deep.git"),
            "git@github.com:acme/super.git/deep.git"
        );
    }

    #[test]
    fn resolves_relative_urls_against_a_local_path_base() {
        // Local bare remotes are ordinary absolute paths; losing the leading
        // separator would turn them into paths relative to the process CWD.
        assert_eq!(
            resolve_relative_url("/srv/git/super.git", "../core.git"),
            "/srv/git/core.git"
        );
        assert_eq!(
            resolve_relative_url("/srv/git/super.git", "./nested.git"),
            "/srv/git/super.git/nested.git"
        );
        assert_eq!(
            resolve_relative_url("relative/base", "../sibling"),
            "relative/sibling"
        );
    }

    #[test]
    fn a_windows_drive_letter_is_not_mistaken_for_an_scp_host() {
        assert_eq!(
            resolve_relative_url("C:/repos/super.git", "../core.git"),
            "C:/repos/core.git"
        );
    }

    #[test]
    fn relative_url_detection_only_matches_dot_prefixes() {
        assert!(is_relative_submodule_url("../core.git"));
        assert!(is_relative_submodule_url("./core.git"));
        assert!(!is_relative_submodule_url("https://example.com/core.git"));
        assert!(!is_relative_submodule_url("git@example.com:acme/core.git"));
    }

    #[test]
    fn ignore_patterns_match_a_whole_directory_of_submodules() {
        // The motivating case: skip every vendored dependency under ext/.
        assert!(path_matches_pattern("ext/*", "ext/gtest"));
        assert!(path_matches_pattern("ext/*", "ext/gulrak-filesystem"));
        assert!(!path_matches_pattern("ext/*", "libs/core"));

        // A single `*` stays within one segment; `**` crosses them.
        assert!(!path_matches_pattern("ext/*", "ext/a/b"));
        assert!(path_matches_pattern("ext/**", "ext/a/b"));
        assert!(path_matches_pattern("**", "anything/at/all"));
    }

    #[test]
    fn ignore_patterns_match_exact_paths_and_partial_names() {
        assert!(path_matches_pattern("ext/gtest", "ext/gtest"));
        assert!(!path_matches_pattern("ext/gtest", "ext/gtest-extra"));
        assert!(!path_matches_pattern("gtest", "ext/gtest"));

        assert!(path_matches_pattern("ext/g*", "ext/gtest"));
        assert!(path_matches_pattern("ext/*test", "ext/gtest"));
        assert!(path_matches_pattern("ext/g?est", "ext/gtest"));
        assert!(!path_matches_pattern("ext/g?est", "ext/gaaest"));
    }

    #[test]
    fn a_bare_pattern_does_not_accidentally_match_a_subtree() {
        // `ext` names a submodule at ext, not everything beneath it. Matching the
        // subtree requires saying so, otherwise one entry silently hides many.
        assert!(path_matches_pattern("ext", "ext"));
        assert!(!path_matches_pattern("ext", "ext/gtest"));
    }

    #[test]
    fn rejects_submodule_paths_that_escape_the_parent() {
        let parent = Path::new("/tmp/super");
        assert!(validate_submodule_path(Path::new("../outside"), parent).is_err());
        assert!(validate_submodule_path(Path::new("libs/../../outside"), parent).is_err());
        assert!(validate_submodule_path(Path::new("/etc/passwd"), parent).is_err());
        assert!(validate_submodule_path(Path::new(".git/hooks"), parent).is_err());
        assert!(validate_submodule_path(Path::new("libs/core"), parent).is_ok());
    }
}