cargo-port 0.1.0

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
use std::collections::HashMap;
use std::path::Path;
use std::time::SystemTime;

use serde::Serialize;

use super::checkout;
use super::command;
use super::constants::GIT_ABBREV_REF_ARG;
use super::constants::GIT_CONFIG_COMMAND;
use super::constants::GIT_CONFIG_REMOTE_PREFIX;
use super::constants::GIT_CONFIG_REMOTE_PUSHURL_PATTERN;
use super::constants::GIT_CONFIG_REMOTE_PUSHURL_SUFFIX;
use super::constants::GIT_FORMAT_ISO8601_ARG;
use super::constants::GIT_GET_REGEXP_ARG;
use super::constants::GIT_GET_URL_ARG;
use super::constants::GIT_HEAD;
use super::constants::GIT_HEAD_REVSPEC_PREFIX;
use super::constants::GIT_LOCAL_BRANCH_REF_PREFIX;
use super::constants::GIT_LOG_COMMAND;
use super::constants::GIT_MAX_PARENTS_ZERO_ARG;
use super::constants::GIT_ORIGIN_HEAD_REF;
use super::constants::GIT_QUIET_ARG;
use super::constants::GIT_REMOTE_COMMAND;
use super::constants::GIT_REMOTE_HEAD_REF_SUFFIX;
use super::constants::GIT_REMOTE_ORIGIN;
use super::constants::GIT_REMOTE_ORIGIN_PREFIX;
use super::constants::GIT_REMOTE_REF_PREFIX;
use super::constants::GIT_REMOTE_UPSTREAM;
use super::constants::GIT_REV_PARSE_COMMAND;
use super::constants::GIT_REVERSE_ARG;
use super::constants::GIT_SHORT_ARG;
use super::constants::GIT_SHOW_REF_COMMAND;
use super::constants::GIT_SYMBOLIC_FULL_NAME_ARG;
use super::constants::GIT_SYMBOLIC_REF_COMMAND;
use super::constants::GIT_UPSTREAM_REF;
use super::constants::GIT_VERIFY_ARG;
use super::discovery;
use crate::config;
use crate::config::CargoPortConfig;
use crate::constants::GIT_REMOTE_SUFFIX;

/// 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,
}

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

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

/// How a single git remote relates to the repo: a plain clone or the fork
/// origin when an `upstream` remote also exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum RemoteKind {
    Clone,
    Fork,
}

/// A well-known push-disable sentinel that users put in `remote.<name>.pushurl`
/// to lock out accidental pushes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum KnownSentinel {
    Disabled,
    NoPush,
    DoNotPush,
}

impl KnownSentinel {
    pub const fn label(self) -> &'static str {
        match self {
            Self::Disabled => "DISABLED",
            Self::NoPush => "no-push",
            Self::DoNotPush => "do_not_push",
        }
    }

    fn from_pushurl(value: &str) -> Option<Self> {
        match value.to_ascii_lowercase().as_str() {
            "disabled" => Some(Self::Disabled),
            "no-push" => Some(Self::NoPush),
            "do_not_push" => Some(Self::DoNotPush),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub(crate) enum PushDisabledReason {
    KnownSentinel(KnownSentinel),
    NoPushUrl,
}

/// Whether `git push` against this remote is enabled, and the URL it
/// would push to. Derived from `git config remote.<name>.pushurl` —
/// when unset, push resolves to the fetch URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case", tag = "state")]
pub(crate) enum PushState {
    Enabled { push_url: String },
    Disabled { reason: PushDisabledReason },
}

/// Per-remote metadata. A repo may have any number of these (`origin`,
/// `upstream`, and others).
#[derive(Debug, Clone, Serialize)]
pub(crate) struct RemoteInfo {
    pub name:         String,
    pub url:          Option<String>,
    pub owner:        Option<String>,
    pub repo:         Option<String>,
    pub tracked_ref:  Option<String>,
    pub ahead_behind: Option<(usize, usize)>,
    pub kind:         RemoteKind,
    pub push:         PushState,
}

/// Repo-level metadata: state that is the same across every checkout of
/// the same git repo. Lives on `GitRepo::repo_info` so siblings cannot
/// drift.
#[derive(Debug, Clone, Default, Serialize)]
pub(crate) struct RepoInfo {
    /// All remotes declared for this repo.
    pub remotes:           Vec<RemoteInfo>,
    /// Whether `.github/workflows/` contains any `.yml` or `.yaml` files.
    pub workflows:         WorkflowPresence,
    /// ISO 8601 date of the first commit (inception).
    pub first_commit:      Option<String>,
    /// ISO 8601 timestamp of the last `git fetch` against any remote,
    /// derived from the mtime of `FETCH_HEAD` in the common git dir.
    pub last_fetched:      Option<String>,
    /// The repo's default branch name resolved from `origin/HEAD`.
    pub default_branch:    Option<String>,
    /// The local branch name used for `M` comparisons.
    pub local_main_branch: Option<String>,
}

impl RepoInfo {
    /// Repo-level origin classification derived from `remotes`.
    pub fn origin_kind(&self) -> GitOrigin {
        if self.remotes.is_empty() {
            GitOrigin::Local
        } else if self.remotes.iter().any(|r| r.name == GIT_REMOTE_UPSTREAM) {
            GitOrigin::Fork
        } else {
            GitOrigin::Clone
        }
    }

    /// Probe per-repo git metadata. Run once per repo (typically on the
    /// primary checkout's path) and shared across every linked
    /// worktree. Excludes `first_commit`, which is handled by
    /// `schedule_git_first_commit_refreshes` batched by repo root.
    pub fn get(probe_path: &Path) -> Option<Self> {
        let repo_root = discovery::git_repo_root(probe_path)?;
        let active_config = config::active_config();

        // Branch / upstream / default-branch context is probed here
        // because `build_remote_info` uses it to resolve each remote's
        // `tracked_ref` and compute `ahead_behind`. Siblings reuse this
        // work; the canonical source is the primary checkout's view.
        let branch = get_current_branch(&repo_root);
        let current_upstream = get_upstream_branch(&repo_root);
        let default_branch = get_default_branch(&repo_root);
        let local_main_branch = resolve_local_main_branch(&repo_root);

        let remote_names = list_remote_names(&repo_root);
        let has_upstream = remote_names.iter().any(|n| n == GIT_REMOTE_UPSTREAM);
        let pushurls = list_remote_pushurls(&repo_root);
        let remote_context = RemoteResolveContext {
            repo_root: &repo_root,
            has_upstream,
            current_upstream: current_upstream.as_deref(),
            default_branch: default_branch.as_deref(),
            current_branch: branch.as_deref(),
            config: &active_config,
        };
        let remotes: Vec<RemoteInfo> = remote_names
            .iter()
            .map(|name| {
                build_remote_info(
                    &remote_context,
                    name,
                    pushurls.get(name.as_str()).map(String::as_str),
                )
            })
            .collect();

        Some(Self {
            remotes,
            workflows: get_workflow_presence(&repo_root),
            first_commit: None,
            last_fetched: get_last_fetched(&repo_root),
            default_branch,
            local_main_branch,
        })
    }
}

pub(super) fn get_current_branch(repo_root: &Path) -> Option<String> {
    command::git_output_logged(
        repo_root,
        "rev_parse_head",
        [GIT_REV_PARSE_COMMAND, GIT_ABBREV_REF_ARG, GIT_HEAD],
    )
    .ok()
    .and_then(|o| {
        let b = String::from_utf8_lossy(&o.stdout).trim().to_string();
        if b.is_empty() { None } else { Some(b) }
    })
}

pub(super) fn get_upstream_branch(project_dir: &Path) -> Option<String> {
    command::git_output_logged(
        project_dir,
        "rev_parse_upstream_name",
        [
            GIT_REV_PARSE_COMMAND,
            GIT_ABBREV_REF_ARG,
            GIT_SYMBOLIC_FULL_NAME_ARG,
            GIT_UPSTREAM_REF,
        ],
    )
    .ok()
    .and_then(|o| {
        let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
        if s.is_empty() { None } else { Some(s) }
    })
}

/// Resolve the repo's default branch from `origin/HEAD` (e.g. `main`).
fn get_default_branch(repo_root: &Path) -> Option<String> {
    command::git_output_logged(
        repo_root,
        "symbolic_ref_origin_head",
        [GIT_SYMBOLIC_REF_COMMAND, GIT_ORIGIN_HEAD_REF, GIT_SHORT_ARG],
    )
    .ok()
    .and_then(|o| {
        let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
        s.strip_prefix(GIT_REMOTE_ORIGIN_PREFIX)
            .filter(|b| !b.is_empty())
            .map(str::to_string)
    })
}

fn list_remote_names(repo_root: &Path) -> Vec<String> {
    command::git_output_logged(repo_root, "remote", [GIT_REMOTE_COMMAND])
        .ok()
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(str::trim)
                .filter(|line| !line.is_empty())
                .map(String::from)
                .collect()
        })
        .unwrap_or_default()
}

struct RemoteResolveContext<'a> {
    repo_root:        &'a Path,
    has_upstream:     bool,
    current_upstream: Option<&'a str>,
    default_branch:   Option<&'a str>,
    current_branch:   Option<&'a str>,
    config:           &'a CargoPortConfig,
}

fn build_remote_info(
    context: &RemoteResolveContext<'_>,
    name: &str,
    pushurl: Option<&str>,
) -> RemoteInfo {
    let (owner, url, repo) = remote_url_info(context.repo_root, name);
    let tracked_ref = resolve_tracked_ref(
        context.repo_root,
        name,
        context.current_upstream,
        context.default_branch,
        context.current_branch,
        context.config,
    );
    let ahead_behind = tracked_ref.as_deref().and_then(|r| {
        checkout::parse_ahead_behind(
            context.repo_root,
            &format!("{GIT_HEAD_REVSPEC_PREFIX}{r}"),
            &format!("tracked_{name}"),
        )
    });
    let kind = if name == GIT_REMOTE_ORIGIN && context.has_upstream {
        RemoteKind::Fork
    } else {
        RemoteKind::Clone
    };
    let push = resolve_push_state(url.as_deref(), pushurl);
    RemoteInfo {
        name: name.to_string(),
        url,
        owner,
        repo,
        tracked_ref,
        ahead_behind,
        kind,
        push,
    }
}

/// Map `pushurl` (or its absence) and the remote's fetch URL into a
/// `PushState`. Rules:
///
/// - No `pushurl` entry → `Enabled` with the fetch URL.
/// - Empty `pushurl` → `Disabled { NoPushUrl }`.
/// - `pushurl` matches a known sentinel (case-insensitive) → `Disabled { KnownSentinel(_) }`.
/// - Any other `pushurl` → `Enabled` with that URL. Anything that looks intentionally non-routable
///   is not heuristically demoted to disabled in this stage — explicit sentinels only.
fn resolve_push_state(fetch_url: Option<&str>, pushurl: Option<&str>) -> PushState {
    let push_url_for_fetch = || PushState::Enabled {
        push_url: fetch_url.unwrap_or_default().to_string(),
    };
    let Some(value) = pushurl else {
        return push_url_for_fetch();
    };
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return PushState::Disabled {
            reason: PushDisabledReason::NoPushUrl,
        };
    }
    if let Some(sentinel) = KnownSentinel::from_pushurl(trimmed) {
        return PushState::Disabled {
            reason: PushDisabledReason::KnownSentinel(sentinel),
        };
    }
    PushState::Enabled {
        push_url: trimmed.to_string(),
    }
}

/// Batch-read every `remote.<name>.pushurl` value with a single
/// `git config --get-regexp` shell-out. Returns a map keyed by remote
/// name (with `remote.` and `.pushurl` stripped).
fn list_remote_pushurls(repo_root: &Path) -> HashMap<String, String> {
    let mut map = HashMap::new();
    let Ok(output) = command::git_output_logged(
        repo_root,
        "config_get_regexp_pushurl",
        [
            GIT_CONFIG_COMMAND,
            GIT_GET_REGEXP_ARG,
            GIT_CONFIG_REMOTE_PUSHURL_PATTERN,
        ],
    ) else {
        return map;
    };
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        let Some((key, value)) = line.split_once(' ') else {
            continue;
        };
        let Some(rest) = key.strip_prefix(GIT_CONFIG_REMOTE_PREFIX) else {
            continue;
        };
        let Some(name) = rest.strip_suffix(GIT_CONFIG_REMOTE_PUSHURL_SUFFIX) else {
            continue;
        };
        map.insert(name.to_string(), value.to_string());
    }
    map
}

fn remote_url_info(
    repo_root: &Path,
    name: &str,
) -> (Option<String>, Option<String>, Option<String>) {
    command::git_output_logged(
        repo_root,
        &format!("remote_get_url_{name}"),
        [GIT_REMOTE_COMMAND, GIT_GET_URL_ARG, name],
    )
    .ok()
    .map_or((None, None, None), |out| {
        let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
        parse_remote_url(&raw)
    })
}

/// Resolve the tracked ref for a remote with a fallback chain.
///
/// Tries, in order:
/// 1. The current branch's `@{upstream}` if it belongs to this remote.
/// 2. `symbolic-ref refs/remotes/<remote>/HEAD`.
/// 3. `<remote>/<default_branch>` (from `origin/HEAD`) if the ref exists.
/// 4. `<remote>/<current_branch>` if the ref exists.
/// 5. `<remote>/<cfg.tui.main_branch>` and each `other_primary_branches` entry if the ref exists.
fn resolve_tracked_ref(
    repo_root: &Path,
    remote_name: &str,
    current_upstream: Option<&str>,
    default_branch: Option<&str>,
    current_branch: Option<&str>,
    cfg: &CargoPortConfig,
) -> Option<String> {
    let prefix = format!("{remote_name}/");
    if let Some(us) = current_upstream
        && us.starts_with(&prefix)
    {
        return Some(us.to_string());
    }
    if let Ok(out) = command::git_output_logged(
        repo_root,
        &format!("symbolic_ref_{remote_name}_head"),
        [
            GIT_SYMBOLIC_REF_COMMAND,
            &format!("{GIT_REMOTE_REF_PREFIX}{remote_name}{GIT_REMOTE_HEAD_REF_SUFFIX}"),
            GIT_SHORT_ARG,
        ],
    ) {
        let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if s.starts_with(&prefix) {
            return Some(s);
        }
    }
    if let Some(db) = default_branch
        && remote_ref_exists(repo_root, remote_name, db)
    {
        return Some(format!("{remote_name}/{db}"));
    }
    if let Some(cb) = current_branch
        && remote_ref_exists(repo_root, remote_name, cb)
    {
        return Some(format!("{remote_name}/{cb}"));
    }
    std::iter::once(cfg.tui.main_branch.as_str())
        .chain(cfg.tui.other_primary_branches.iter().map(String::as_str))
        .find(|b| remote_ref_exists(repo_root, remote_name, b))
        .map(|b| format!("{remote_name}/{b}"))
}

fn remote_ref_exists(repo_root: &Path, remote_name: &str, branch: &str) -> bool {
    command::git_output_logged(
        repo_root,
        &format!("show_ref_{remote_name}"),
        [
            GIT_SHOW_REF_COMMAND,
            GIT_VERIFY_ARG,
            GIT_QUIET_ARG,
            &format!("{GIT_REMOTE_REF_PREFIX}{remote_name}/{branch}"),
        ],
    )
    .is_ok()
}

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 {
    command::git_output_logged(
        project_dir,
        "show_ref_local_main",
        [
            GIT_SHOW_REF_COMMAND,
            GIT_VERIFY_ARG,
            GIT_QUIET_ARG,
            &format!("{GIT_LOCAL_BRANCH_REF_PREFIX}{branch}"),
        ],
    )
    .is_ok()
}

fn get_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 get_first_commit(project_dir: &Path) -> Option<String> {
    let repo_root = discovery::git_repo_root(project_dir)?;
    command::git_output_logged(
        &repo_root,
        "log_first_commit",
        [
            GIT_LOG_COMMAND,
            GIT_MAX_PARENTS_ZERO_ARG,
            GIT_REVERSE_ARG,
            GIT_FORMAT_ISO8601_ARG,
            GIT_HEAD,
        ],
    )
    .ok()
    .and_then(|o| {
        String::from_utf8_lossy(&o.stdout)
            .lines()
            .next()
            .filter(|s| !s.is_empty())
            .map(std::string::ToString::to_string)
    })
}

/// Read `FETCH_HEAD` mtime from the common git dir and render it as UTC ISO
/// 8601. `FETCH_HEAD` is rewritten on every `git fetch` regardless of whether
/// refs changed, so its mtime is the most reliable "last fetched" signal.
fn get_last_fetched(repo_root: &Path) -> Option<String> {
    let common_dir = discovery::resolve_common_git_dir(repo_root)?;
    let fetch_head = common_dir.join("FETCH_HEAD");
    let modified = std::fs::metadata(&fetch_head).ok()?.modified().ok()?;
    system_time_to_iso8601_utc(modified)
}

fn system_time_to_iso8601_utc(t: SystemTime) -> Option<String> {
    let secs = i64::try_from(
        t.duration_since(std::time::SystemTime::UNIX_EPOCH)
            .ok()?
            .as_secs(),
    )
    .ok()?;
    let days = secs.div_euclid(86_400);
    let time_of_day = secs.rem_euclid(86_400);
    let hour = time_of_day / 3_600;
    let min = (time_of_day % 3_600) / 60;
    let sec = time_of_day % 60;
    let (year, month, day) = civil_from_days(days);
    Some(format!(
        "{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z"
    ))
}

/// Inverse of `days_from_civil`: days since Unix epoch → (year, month, day).
/// Howard Hinnant's algorithm.
#[allow(
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::cast_possible_truncation,
    reason = "Hinnant's algorithm bounces between signed/unsigned; month/day always 1..=12 / 1..=31"
)]
const fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };
    (year, m as u32, d as u32)
}

/// Extract `(owner, url, repo)` from a git remote URL.
///
/// Handles:
/// - `https://github.com/owner/repo.git`
/// - `git@github.com:owner/repo.git`
///
/// SSH forms are canonicalized to HTTPS so downstream prefix-matching against
/// `default_remote_host_url` works uniformly.
fn parse_remote_url(raw: &str) -> (Option<String>, Option<String>, Option<String>) {
    if let Some(after_at) = raw.strip_prefix("git@")
        && let Some((host, path)) = after_at.split_once(':')
    {
        let path = path.strip_suffix(GIT_REMOTE_SUFFIX).unwrap_or(path);
        let mut parts = path.splitn(2, '/');
        let owner = parts.next().map(String::from);
        let repo = parts.next().map(String::from);
        let url = format!("https://{host}/{path}");
        return (owner, Some(url), repo);
    }

    if raw.starts_with("https://") || raw.starts_with("http://") {
        let clean = raw.strip_suffix(GIT_REMOTE_SUFFIX).unwrap_or(raw);
        let mut segments = clean.split('/').skip(3);
        let owner = segments.next().map(String::from);
        let repo = segments.next().map(String::from);
        return (owner, Some(clean.to_string()), repo);
    }

    (None, None, None)
}

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

    use super::*;

    #[test]
    fn push_state_unset_uses_fetch_url() {
        let push = resolve_push_state(Some("https://github.com/a/b.git"), None);
        assert_eq!(
            push,
            PushState::Enabled {
                push_url: "https://github.com/a/b.git".to_string(),
            }
        );
    }

    #[test]
    fn push_state_empty_is_no_push_url() {
        let push = resolve_push_state(Some("https://github.com/a/b.git"), Some(""));
        assert_eq!(
            push,
            PushState::Disabled {
                reason: PushDisabledReason::NoPushUrl,
            }
        );
    }

    #[test]
    fn push_state_disabled_sentinel_case_insensitive() {
        for value in ["DISABLED", "disabled", "Disabled"] {
            let push = resolve_push_state(Some("ignored"), Some(value));
            assert_eq!(
                push,
                PushState::Disabled {
                    reason: PushDisabledReason::KnownSentinel(KnownSentinel::Disabled),
                }
            );
        }
    }

    #[test]
    fn push_state_unknown_pushurl_stays_enabled() {
        let push = resolve_push_state(Some("https://github.com/a/b.git"), Some("ssh://other/repo"));
        assert_eq!(
            push,
            PushState::Enabled {
                push_url: "ssh://other/repo".to_string(),
            }
        );
    }

    #[test]
    fn push_state_serde_round_trip() {
        for state in [
            PushState::Enabled {
                push_url: "https://example.com".to_string(),
            },
            PushState::Disabled {
                reason: PushDisabledReason::NoPushUrl,
            },
            PushState::Disabled {
                reason: PushDisabledReason::KnownSentinel(KnownSentinel::Disabled),
            },
        ] {
            let json = serde_json::to_string(&state).expect("serialize");
            let _: Value = serde_json::from_str(&json).expect("valid JSON");
        }
    }
}