cargo-port 0.0.3

A TUI for inspecting and managing Rust projects
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
use std::io;
use std::path::Path;
use std::process::Command;

use serde::Deserialize;
use serde::Serialize;

use super::paths::AbsolutePath;
use crate::config;
use crate::constants::GIT_CLONE;
use crate::constants::GIT_FORK;
use crate::constants::GIT_LOCAL;
use crate::constants::GIT_STATUS_CLEAN;
use crate::constants::GIT_STATUS_MODIFIED;
use crate::constants::GIT_STATUS_UNTRACKED;

/// Whether a project is a plain clone or a fork (has an "upstream" remote).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum GitOrigin {
    /// A local-only repo (no origin remote).
    Local,
    /// A plain git clone (has "origin" remote).
    Clone,
    /// A fork (has an "upstream" remote).
    Fork,
}

impl GitOrigin {
    pub(crate) const fn icon(self) -> &'static str {
        match self {
            Self::Local => GIT_LOCAL,
            Self::Clone => GIT_CLONE,
            Self::Fork => GIT_FORK,
        }
    }

    pub(crate) const fn label(self) -> &'static str {
        match self {
            Self::Local => "local",
            Self::Clone => "clone",
            Self::Fork => "fork",
        }
    }
}

/// Whether `.github/workflows/` contains any `.yml` or `.yaml` files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub(crate) enum WorkflowPresence {
    /// At least one workflow YAML file exists.
    Present,
    /// No workflow files found (or no `.github/workflows/` directory).
    Missing,
}

impl WorkflowPresence {
    pub(crate) const fn is_present(self) -> bool { matches!(self, Self::Present) }
}

/// Git metadata for a project: origin type, owner, repo URL, and current branch.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct GitInfo {
    /// Git path state (clean, modified, untracked, etc.) for this project path.
    pub path_state:          GitPathState,
    /// Whether this is a clone or a fork.
    pub origin:              GitOrigin,
    /// The current branch name.
    pub branch:              Option<String>,
    /// The GitHub/GitLab owner (e.g. "natepiano").
    pub owner:               Option<String>,
    /// The HTTPS URL to the repository.
    pub url:                 Option<String>,
    /// ISO 8601 date of the first commit (inception).
    pub first_commit:        Option<String>,
    /// ISO 8601 date of the most recent commit.
    pub last_commit:         Option<String>,
    /// Commits ahead and behind the upstream tracking branch (ahead, behind).
    pub ahead_behind:        Option<(usize, usize)>,
    /// The upstream tracking ref for the current branch (e.g. `origin/main`).
    pub upstream_branch:     Option<String>,
    /// The repo's default branch name resolved from `origin/HEAD`.
    pub default_branch:      Option<String>,
    /// Commits ahead and behind `origin/{default_branch}`.
    pub ahead_behind_origin: Option<(usize, usize)>,
    /// The local branch name used for `M` comparisons.
    pub local_main_branch:   Option<String>,
    /// Commits ahead and behind the local `{local_main_branch}`.
    pub ahead_behind_local:  Option<(usize, usize)>,
    /// Whether `.github/workflows/` contains any `.yml` or `.yaml` files.
    pub workflows:           WorkflowPresence,
}

impl GitInfo {
    /// Detect git info for a project directory (excludes `first_commit`, which
    /// is handled by `schedule_git_first_commit_refreshes` batched by repo root).
    pub(crate) fn detect_fast(project_dir: &Path) -> Option<Self> {
        let repo_root = git_repo_root(project_dir)?;

        let remote_output = git_output_logged(&repo_root, "remote", ["remote"]).ok()?;
        let remotes = String::from_utf8_lossy(&remote_output.stdout);
        let has_origin = remotes.lines().any(|line| line.trim() == "origin");
        let has_upstream = remotes.lines().any(|line| line.trim() == "upstream");
        let origin = if !has_origin {
            GitOrigin::Local
        } else if has_upstream {
            GitOrigin::Fork
        } else {
            GitOrigin::Clone
        };

        let (owner, url) = git_output_logged(
            &repo_root,
            "remote_get_url_origin",
            ["remote", "get-url", "origin"],
        )
        .ok()
        .map_or((None, None), |url_output| {
            let raw_url = String::from_utf8_lossy(&url_output.stdout)
                .trim()
                .to_string();
            parse_remote_url(&raw_url)
        });

        let branch = git_output_logged(
            &repo_root,
            "rev_parse_head",
            ["rev-parse", "--abbrev-ref", "HEAD"],
        )
        .ok()
        .and_then(|o| {
            let b = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if b.is_empty() { None } else { Some(b) }
        });

        let ahead_behind = parse_ahead_behind(&repo_root, "HEAD...@{upstream}", "upstream");
        let upstream_branch = detect_upstream_branch(&repo_root);

        // Resolve the repo's default branch from origin/HEAD (e.g. "origin/main").
        let default_branch = git_output_logged(
            &repo_root,
            "symbolic_ref_origin_head",
            ["symbolic-ref", "refs/remotes/origin/HEAD", "--short"],
        )
        .ok()
        .and_then(|o| {
            let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
            // Comes back as "origin/main" — strip the "origin/" prefix.
            s.strip_prefix("origin/")
                .filter(|b| !b.is_empty())
                .map(str::to_string)
        });

        // Compare HEAD against the remote default branch when it differs from the current branch.
        let not_on_default = default_branch
            .as_deref()
            .filter(|db| branch.as_deref() != Some(*db));
        let ahead_behind_origin = not_on_default.and_then(|db| {
            parse_ahead_behind(&repo_root, &format!("HEAD...origin/{db}"), "default_origin")
        });
        let local_main_branch = resolve_local_main_branch(&repo_root);
        let ahead_behind_local = local_main_branch
            .as_deref()
            .filter(|branch_name| branch.as_deref() != Some(*branch_name))
            .and_then(|branch_name| {
                parse_ahead_behind(
                    &repo_root,
                    &format!("HEAD...{branch_name}"),
                    "configured_local_main",
                )
            });

        let last_commit =
            git_output_logged(&repo_root, "log_last_commit", ["log", "-1", "--format=%aI"])
                .ok()
                .and_then(|o| {
                    let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
                    if s.is_empty() { None } else { Some(s) }
                });

        let path_state = detect_git_path_state_with_root(project_dir, &repo_root);

        Some(Self {
            path_state,
            origin,
            branch,
            owner,
            url,
            first_commit: None,
            last_commit,
            ahead_behind,
            upstream_branch,
            default_branch,
            ahead_behind_origin,
            local_main_branch,
            ahead_behind_local,
            workflows: detect_workflow_presence(&repo_root),
        })
    }
}

fn detect_upstream_branch(project_dir: &Path) -> Option<String> {
    git_output_logged(
        project_dir,
        "rev_parse_upstream_name",
        [
            "rev-parse",
            "--abbrev-ref",
            "--symbolic-full-name",
            "@{upstream}",
        ],
    )
    .ok()
    .and_then(|o| {
        let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
        if s.is_empty() { None } else { Some(s) }
    })
}

fn resolve_local_main_branch(project_dir: &Path) -> Option<String> {
    let cfg = config::active_config();
    std::iter::once(cfg.tui.main_branch.as_str())
        .chain(cfg.tui.other_primary_branches.iter().map(String::as_str))
        .find(|branch| local_branch_exists(project_dir, branch))
        .map(str::to_string)
}

fn local_branch_exists(project_dir: &Path, branch: &str) -> bool {
    git_output_logged(
        project_dir,
        "show_ref_local_main",
        [
            "show-ref",
            "--verify",
            "--quiet",
            &format!("refs/heads/{branch}"),
        ],
    )
    .is_ok()
}

fn detect_workflow_presence(repo_root: &Path) -> WorkflowPresence {
    let workflows_dir = repo_root.join(".github").join("workflows");
    let has_yaml = std::fs::read_dir(workflows_dir).is_ok_and(|entries| {
        entries.filter_map(Result::ok).any(|entry| {
            let name = entry.file_name();
            let name = name.to_string_lossy();
            name.ends_with(".yml") || name.ends_with(".yaml")
        })
    });
    if has_yaml {
        WorkflowPresence::Present
    } else {
        WorkflowPresence::Missing
    }
}

pub(crate) fn detect_first_commit(project_dir: &Path) -> Option<String> {
    let repo_root = git_repo_root(project_dir)?;
    git_output_logged(
        &repo_root,
        "log_first_commit",
        [
            "log",
            "--max-parents=0",
            "--reverse",
            "--format=%aI",
            "HEAD",
        ],
    )
    .ok()
    .and_then(|o| {
        String::from_utf8_lossy(&o.stdout)
            .lines()
            .next()
            .filter(|s| !s.is_empty())
            .map(std::string::ToString::to_string)
    })
}

fn git_output_logged<const N: usize>(
    repo_root: &Path,
    op: &str,
    args: [&str; N],
) -> io::Result<std::process::Output> {
    let started = std::time::Instant::now();
    let output = Command::new("git")
        .args(args)
        .current_dir(repo_root)
        .output();
    let status = output
        .as_ref()
        .ok()
        .and_then(|out| out.status.code())
        .map_or_else(|| "signal".to_string(), |code| code.to_string());
    tracing::info!(
        elapsed_ms = crate::perf_log::ms(started.elapsed().as_millis()),
        repo_root = %repo_root.display(),
        op,
        status,
        "git_info_detect_call"
    );
    output
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum GitPathState {
    #[default]
    OutsideRepo,
    Clean,
    Modified,
    Untracked,
    Ignored,
}

impl GitPathState {
    pub(crate) const fn label(self) -> &'static str {
        match self {
            Self::OutsideRepo => "outside repo",
            Self::Clean => "clean",
            Self::Modified => "modified",
            Self::Untracked => "untracked",
            Self::Ignored => "ignored",
        }
    }

    pub(crate) const fn icon(self) -> &'static str {
        match self {
            Self::Clean => GIT_STATUS_CLEAN,
            Self::Modified => GIT_STATUS_MODIFIED,
            Self::Untracked => GIT_STATUS_UNTRACKED,
            Self::OutsideRepo | Self::Ignored => "",
        }
    }

    pub(crate) fn label_with_icon(self) -> String {
        let icon = self.icon();
        if icon.is_empty() {
            self.label().to_string()
        } else {
            format!("{icon} {}", self.label())
        }
    }
}

/// Wrapper for `GitInfo` that distinguishes "not yet detected" from
/// "detected with full metadata."
#[derive(Clone, Debug, Default)]
pub(crate) enum LocalGitState {
    /// Not yet detected (during startup/scan).
    #[default]
    Pending,
    /// Full git metadata detected for this project.
    Detected(Box<GitInfo>),
}

impl LocalGitState {
    pub(crate) fn info(&self) -> Option<&GitInfo> {
        match self {
            Self::Detected(info) => Some(info),
            Self::Pending => None,
        }
    }

    pub(crate) fn info_mut(&mut self) -> Option<&mut GitInfo> {
        match self {
            Self::Detected(info) => Some(info),
            Self::Pending => None,
        }
    }
}

/// Detect git path state when the repo root is already known, avoiding a
/// redundant `git_repo_root()` call.
fn detect_git_path_state_with_root(project_dir: &Path, repo_root: &Path) -> GitPathState {
    let started = std::time::Instant::now();
    let relative_path = relative_git_path(repo_root, project_dir);
    if relative_path != "." {
        let ignored = Command::new("git")
            .args(["check-ignore", "-q", "--", &relative_path])
            .current_dir(repo_root)
            .status()
            .ok()
            .is_some_and(|status| status.success());
        if ignored {
            let state = GitPathState::Ignored;
            tracing::info!(
                elapsed_ms = crate::perf_log::ms(started.elapsed().as_millis()),
                repo_root = %repo_root.display(),
                project_dir = %project_dir.display(),
                state = %state.label(),
                "git_path_state_single"
            );
            return state;
        }
    }
    let status_output = Command::new("git")
        .args([
            "status",
            "--porcelain=v1",
            "--ignored=matching",
            "--untracked-files=all",
            "--",
            &relative_path,
        ])
        .current_dir(repo_root)
        .output();
    let Ok(status_output) = status_output else {
        return GitPathState::Clean;
    };
    let stdout = String::from_utf8_lossy(&status_output.stdout);
    let mut has_modified = false;
    let mut has_untracked = false;

    for line in stdout.lines().filter(|line| line.len() >= 3) {
        let status_code = &line[..2];
        match status_code {
            "!!" => {},
            "??" => has_untracked = true,
            _ => has_modified = true,
        }
    }

    let state = if has_modified {
        GitPathState::Modified
    } else if has_untracked {
        GitPathState::Untracked
    } else {
        GitPathState::Clean
    };
    tracing::info!(
        elapsed_ms = crate::perf_log::ms(started.elapsed().as_millis()),
        repo_root = %repo_root.display(),
        project_dir = %project_dir.display(),
        state = %state.label(),
        "git_path_state_single"
    );
    state
}

pub(crate) fn git_repo_root(project_dir: &Path) -> Option<AbsolutePath> {
    project_dir
        .ancestors()
        .find(|dir| {
            let git_path = dir.join(".git");
            git_path.is_dir() || git_path.is_file()
        })
        .map(AbsolutePath::from)
}

/// Resolve the on-disk git directory for a repo root.
///
/// For normal repos, returns `repo_root/.git`.
/// For worktrees, `.git` is a file containing `gitdir: <path>` — this
/// function reads that file and returns the resolved path.
pub(crate) fn resolve_git_dir(repo_root: &Path) -> Option<AbsolutePath> {
    let git_path = repo_root.join(".git");
    if git_path.is_dir() {
        return Some(git_path.into());
    }
    if git_path.is_file() {
        let contents = std::fs::read_to_string(&git_path).ok()?;
        let target = contents.strip_prefix("gitdir: ")?.trim();
        return Some(AbsolutePath::resolve(target, repo_root));
    }
    None
}

/// Resolve the common git directory for a repo root.
///
/// For normal repos this is the same path as [`resolve_git_dir`]. For linked
/// worktrees, the resolved git dir may contain a `commondir` file pointing back
/// to the shared `<primary>/.git` directory where branch refs are updated.
pub(crate) fn resolve_common_git_dir(repo_root: &Path) -> Option<AbsolutePath> {
    let git_dir = resolve_git_dir(repo_root)?;
    let commondir_path = git_dir.join("commondir");
    if !commondir_path.is_file() {
        return Some(git_dir);
    }

    let contents = std::fs::read_to_string(&commondir_path).ok()?;
    let target = contents.trim();
    Some(AbsolutePath::resolve(target, &git_dir))
}

fn relative_git_path(repo_root: &Path, project_dir: &Path) -> String {
    project_dir.strip_prefix(repo_root).ok().map_or_else(
        || ".".to_string(),
        |path| {
            let normalized = path
                .components()
                .filter_map(|component| match component {
                    std::path::Component::Normal(segment) => {
                        Some(segment.to_string_lossy().to_string())
                    },
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("/");
            if normalized.is_empty() {
                ".".to_string()
            } else {
                normalized
            }
        },
    )
}

/// Parse `git rev-list --left-right --count` output into `(ahead, behind)`.
fn parse_ahead_behind(
    project_dir: &Path,
    revspec: &str,
    op_suffix: &str,
) -> Option<(usize, usize)> {
    git_output_logged(
        project_dir,
        &format!("rev_list_{op_suffix}"),
        ["rev-list", "--left-right", "--count", revspec],
    )
    .ok()
    .and_then(|o| {
        let s = String::from_utf8_lossy(&o.stdout);
        let mut parts = s.trim().split('\t');
        let ahead = parts.next()?.parse::<usize>().ok()?;
        let behind = parts.next()?.parse::<usize>().ok()?;
        Some((ahead, behind))
    })
}

/// Extract the owner and HTTPS URL from a git remote URL.
///
/// Handles:
/// - `https://github.com/owner/repo.git`
/// - `git@github.com:owner/repo.git`
fn parse_remote_url(raw: &str) -> (Option<String>, Option<String>) {
    // SSH: git@github.com:owner/repo.git
    if let Some(after_at) = raw.strip_prefix("git@")
        && let Some((host, path)) = after_at.split_once(':')
    {
        let path = path.strip_suffix(".git").unwrap_or(path);
        let owner = path.split('/').next().map(|s| (*s).to_string());
        let url = format!("https://{host}/{path}");
        return (owner, Some(url));
    }

    // HTTPS: https://github.com/owner/repo.git
    if raw.starts_with("https://") || raw.starts_with("http://") {
        let clean = raw.strip_suffix(".git").unwrap_or(raw);
        // Extract owner from path: https://host/owner/repo
        let owner = clean.split('/').nth(3).map(|s| (*s).to_string());
        return (owner, Some((*clean).to_string()));
    }

    (None, None)
}

/// Whether a project path lives inside a git repository.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GitRepoPresence {
    InRepo,
    OutsideRepo,
}

impl GitRepoPresence {
    pub(crate) const fn is_in_repo(self) -> bool { matches!(self, Self::InRepo) }
}

/// Check if a project directory is a broken worktree — `.git` is a file whose
/// gitdir target does not exist on disk.
pub(crate) fn detect_worktree_health(project_dir: &Path) -> WorktreeHealth {
    let git_path = project_dir.join(".git");
    if !git_path.is_file() {
        return WorktreeHealth::Normal;
    }
    let Ok(contents) = std::fs::read_to_string(&git_path) else {
        return WorktreeHealth::Broken;
    };
    let Some(gitdir_str) = contents.strip_prefix("gitdir: ") else {
        return WorktreeHealth::Broken;
    };
    let gitdir = AbsolutePath::resolve_no_canonicalize(gitdir_str.trim(), project_dir);
    if gitdir.exists() {
        WorktreeHealth::Normal
    } else {
        WorktreeHealth::Broken
    }
}

pub(super) fn detect_worktree_name(project_dir: &Path) -> Option<String> {
    let mut dir = project_dir;
    loop {
        let git_path = dir.join(".git");
        if git_path.is_file() {
            return dir.file_name().map(|n| n.to_string_lossy().to_string());
        }
        if git_path.is_dir() {
            // Found a real .git directory — not a worktree
            return None;
        }
        dir = dir.parent()?;
    }
}

/// Resolve the primary git repo root for a project directory.
///
/// For worktrees (`.git` is a file containing `gitdir: ...`), parse the gitdir
/// path and strip the `.git/worktrees/<name>` suffix to find the primary root.
/// For primary repos (`.git` is a directory), return the canonicalized directory.
pub(super) fn detect_worktree_primary(project_dir: &Path) -> Option<String> {
    let mut dir = project_dir;
    loop {
        let git_path = dir.join(".git");
        if git_path.is_file() {
            let contents = std::fs::read_to_string(&git_path).ok()?;
            let gitdir_str = contents.strip_prefix("gitdir: ")?.trim();
            let gitdir = AbsolutePath::resolve(gitdir_str, dir);
            // gitdir is `<primary>/.git/worktrees/<name>` — go up 3 levels
            let canonical = gitdir;
            let primary_root = canonical.parent()?.parent()?.parent()?;
            return Some(primary_root.to_string_lossy().to_string());
        }
        if git_path.is_dir() {
            // This IS the primary — canonicalize for consistent comparison
            return dir
                .canonicalize()
                .ok()
                .map(|p| p.to_string_lossy().to_string());
        }
        dir = dir.parent()?;
    }
}

use super::info::WorktreeHealth;

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests should panic on unexpected values"
)]
mod tests {
    use super::*;

    #[test]
    fn git_repo_root_finds_ancestor_git_directory() {
        let tmp = tempfile::tempdir().unwrap_or_else(|_| std::process::abort());
        let repo_root = tmp.path().join("repo");
        let nested = repo_root.join("crates").join("demo");
        std::fs::create_dir_all(repo_root.join(".git")).unwrap_or_else(|_| std::process::abort());
        std::fs::create_dir_all(&nested).unwrap_or_else(|_| std::process::abort());

        assert_eq!(git_repo_root(&nested).as_deref(), Some(repo_root.as_path()));
    }

    #[test]
    fn git_repo_root_finds_worktree_git_file() {
        let tmp = tempfile::tempdir().unwrap_or_else(|_| std::process::abort());
        let repo_root = tmp.path().join("repo");
        let nested = repo_root.join("crates").join("demo");
        std::fs::create_dir_all(&nested).unwrap_or_else(|_| std::process::abort());
        std::fs::write(repo_root.join(".git"), "gitdir: /tmp/fake\n")
            .unwrap_or_else(|_| std::process::abort());

        assert_eq!(git_repo_root(&nested).as_deref(), Some(repo_root.as_path()));
    }

    #[test]
    fn resolve_git_dir_returns_dot_git_for_normal_repo() {
        let tmp = tempfile::tempdir().unwrap_or_else(|_| std::process::abort());
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(repo.join(".git")).unwrap_or_else(|_| std::process::abort());

        assert_eq!(
            resolve_git_dir(&repo).as_deref(),
            Some(repo.join(".git").as_path())
        );
    }

    #[test]
    fn resolve_git_dir_follows_worktree_gitdir_file() {
        let tmp = tempfile::tempdir().unwrap_or_else(|_| std::process::abort());
        let main_git = tmp
            .path()
            .join("main")
            .join(".git")
            .join("worktrees")
            .join("wt");
        std::fs::create_dir_all(&main_git).unwrap_or_else(|_| std::process::abort());

        let wt = tmp.path().join("wt");
        std::fs::create_dir_all(&wt).unwrap_or_else(|_| std::process::abort());
        std::fs::write(wt.join(".git"), format!("gitdir: {}\n", main_git.display()))
            .unwrap_or_else(|_| std::process::abort());

        let resolved = resolve_git_dir(&wt).expect("should resolve");
        assert_eq!(resolved.canonicalize().ok(), main_git.canonicalize().ok());
    }

    #[test]
    fn resolve_git_dir_returns_none_without_git() {
        let tmp = tempfile::tempdir().unwrap_or_else(|_| std::process::abort());
        assert_eq!(resolve_git_dir(tmp.path()), None);
    }
}