git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use std::io::Write as _;
use std::path::Path;
use std::process::Command;
use std::time::Instant;

use anyhow::{Context, Result, bail};
use git2::{BranchType, Repository, Sort};

use crate::core::msg;
use crate::core::repo;
use crate::git;
use crate::trace as loom_trace;

/// Remote type detected for the push operation.
#[derive(Debug, PartialEq, Eq)]
enum RemoteType {
    Plain,
    GitHub,
    AzureDevOps,
    Gerrit { target_branch: String },
}

/// Push a feature branch to remote.
///
/// Detects the remote type (plain, GitHub, Gerrit) and dispatches to the
/// appropriate push strategy. Accepts an optional branch argument (name or
/// shortID); if omitted, shows an interactive picker.
///
/// When `no_pr` is true, skips PR/review creation for all remote types.
/// For Gerrit, branches without a `wip/` prefix get a confirmation prompt.
pub fn run(branch: Option<String>, no_pr: bool) -> Result<()> {
    let repo = repo::open_repo()?;
    let workdir = repo::require_workdir(&repo, "push")?.to_path_buf();
    let info = repo::gather_repo_info(&repo, false, 1)?;

    if info.branches.is_empty() {
        bail!("No woven branches to push\nCreate a branch with `git loom branch` first");
    }

    let branch_name = match branch {
        Some(b) => resolve_branch(&repo, &info, &b)?,
        None => pick_branch(&info)?,
    };

    let remote_type = detect_remote_type(&repo, &workdir, &info.upstream.label)?;
    let remote_name = resolve_push_remote(&repo, &workdir, &info.upstream.label, &remote_type);

    let target_branch = extract_target_branch(&info.upstream.label);

    if no_pr {
        return match remote_type {
            RemoteType::Gerrit { .. } => push_gerrit_no_pr(&workdir, &remote_name, &branch_name),
            _ => push_plain(&workdir, &remote_name, &branch_name),
        };
    }

    let base_oid = info.upstream.merge_base_oid;

    match remote_type {
        RemoteType::Plain => push_plain(&workdir, &remote_name, &branch_name),
        RemoteType::GitHub => push_github(
            &repo,
            &workdir,
            &remote_name,
            &branch_name,
            &target_branch,
            base_oid,
            &info.upstream.label,
        ),
        RemoteType::AzureDevOps => push_azure(
            &repo,
            &workdir,
            &remote_name,
            &branch_name,
            &target_branch,
            base_oid,
        ),
        RemoteType::Gerrit { target_branch } => {
            push_gerrit(&workdir, &remote_name, &branch_name, &target_branch)
        }
    }
}

fn resolve_branch(repo: &Repository, info: &repo::RepoInfo, branch_arg: &str) -> Result<String> {
    let name = repo::resolve_arg(repo, branch_arg, &[repo::TargetKind::Branch])?.expect_branch()?;
    if info.branches.iter().any(|b| b.name == name) {
        Ok(name)
    } else {
        bail!("Branch '{}' is not woven into the integration branch", name)
    }
}

fn pick_branch(info: &repo::RepoInfo) -> Result<String> {
    let items: Vec<String> = info.branches.iter().map(|b| b.name.clone()).collect();
    msg::select("Select branch to push", items)
}

/// Detect the remote type from config, URL heuristics, or hook inspection.
///
/// Priority: git config `loom.remote-type` → URL contains `github.com` →
/// `.git/hooks/commit-msg` contains "gerrit" → Plain fallback.
fn detect_remote_type(
    repo: &Repository,
    workdir: &Path,
    upstream_label: &str,
) -> Result<RemoteType> {
    if let Ok(config_value) = git::run_git_stdout(workdir, &["config", "--get", "loom.remote-type"])
    {
        let value = config_value.trim().to_lowercase();
        if value == "github" {
            return Ok(RemoteType::GitHub);
        }
        if value == "azure" {
            return Ok(RemoteType::AzureDevOps);
        }
        if value == "gerrit" {
            let target_branch = extract_target_branch(upstream_label);
            return Ok(RemoteType::Gerrit { target_branch });
        }
        msg::warn(&format!(
            "Unknown loom.remote-type '{}' — falling back to auto-detection.\n\
             Valid values: github, azure, gerrit",
            config_value.trim()
        ));
    }

    let remote_name = extract_remote_name(upstream_label);
    if let Ok(remote) = repo.find_remote(&remote_name)
        && let Some(url) = remote.url()
    {
        if url.contains("github.com") {
            return Ok(RemoteType::GitHub);
        }
        if url.contains("dev.azure.com") {
            return Ok(RemoteType::AzureDevOps);
        }
    }

    // Use repo.commondir() so this works in worktrees (where hooks are shared)
    let hook_path = repo.commondir().join("hooks").join("commit-msg");
    if let Ok(content) = std::fs::read_to_string(&hook_path)
        && content.to_lowercase().contains("gerrit")
    {
        let target_branch = extract_target_branch(upstream_label);
        return Ok(RemoteType::Gerrit { target_branch });
    }

    Ok(RemoteType::Plain)
}

/// Extract the remote name from an upstream label like "origin/main" → "origin".
fn extract_remote_name(upstream_label: &str) -> String {
    upstream_label
        .split('/')
        .next()
        .unwrap_or("origin")
        .to_string()
}

/// Extract `owner/repo` from a git remote URL for use with `gh --repo`.
///
/// Handles SCP-style SSH URLs (with or without `git@` prefix) and HTTPS URLs:
/// - `git@github.com:owner/repo.git`
/// - `git@github-alias:owner/repo.git`
/// - `github-work:owner/repo` (bare alias, no `git@`)
/// - `https://github.com/owner/repo.git`
///
/// Returns `None` if the remote doesn't exist or the URL can't be parsed.
fn extract_gh_repo(repo: &Repository, remote: &str) -> Option<String> {
    let remote = repo.find_remote(remote).ok()?;
    let url = remote.url()?;

    // SCP-style SSH URLs: [git@]<hostname>:owner/repo[.git]
    // Covers git@github.com:owner/repo.git, git@github-alias:owner/repo.git,
    // and bare aliases like github-work:owner/repo (no git@ prefix).
    // Distinguish from URLs by requiring no '://' and no '/' before the ':'.
    let scp_url = url.strip_prefix("git@").unwrap_or(url);
    if !scp_url.contains("://")
        && let Some(colon_idx) = scp_url.find(':')
    {
        let host = &scp_url[..colon_idx];
        if !host.contains('/') {
            let path = &scp_url[colon_idx + 1..];
            return Some(path.trim_end_matches(".git").to_string());
        }
    }

    // HTTPS: https://github.com/owner/repo.git
    if let Some(path) = url
        .strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("http://github.com/"))
    {
        return Some(path.trim_end_matches(".git").to_string());
    }

    None
}

/// Extract the target branch from an upstream label like "origin/main" → "main".
fn extract_target_branch(upstream_label: &str) -> String {
    let branch = repo::upstream_local_branch(upstream_label);
    if branch.is_empty() {
        "main".to_string()
    } else {
        branch
    }
}

/// Determine the push remote for the given upstream label and remote type.
///
/// Priority:
/// 1. `git config loom.push-remote` — explicit override
/// 2. GitHub fork convention — if integration remote is `upstream` and `origin` exists, use `origin`
/// 3. Integration branch's remote — fallback
///
/// For non-standard fork setups (e.g., integration tracks `origin`, fork is `personal`),
/// set `git config loom.push-remote personal`.
fn resolve_push_remote(
    repo: &Repository,
    workdir: &Path,
    upstream_label: &str,
    remote_type: &RemoteType,
) -> String {
    if let Ok(push_remote) = git::run_git_stdout(workdir, &["config", "--get", "loom.push-remote"])
    {
        let remote = push_remote.trim();
        if !remote.is_empty() && repo.find_remote(remote).is_ok() {
            return remote.to_string();
        }
    }

    let remote_name = extract_remote_name(upstream_label);
    if *remote_type == RemoteType::GitHub
        && remote_name == "upstream"
        && repo.find_remote("origin").is_ok()
    {
        "origin".to_string()
    } else {
        remote_name
    }
}

fn git_push(workdir: &Path, remote: &str, branch: &str) -> Result<()> {
    git::run_git(
        workdir,
        &[
            "push",
            "--force-with-lease",
            "--force-if-includes",
            "-u",
            remote,
            branch,
        ],
    )?;
    msg::success(&format!("Pushed `{}` to `{}`", branch, remote));
    Ok(())
}

/// Collect commits for a branch from oldest to newest, skipping merge commits.
///
/// Returns `(subject, body)` pairs where `body` is everything after the first
/// line of the commit message (may be empty).
fn gather_branch_commits(
    repo: &Repository,
    branch_name: &str,
    base_oid: git2::Oid,
) -> Result<Vec<(String, String)>> {
    let branch = repo.find_branch(branch_name, BranchType::Local)?;
    let tip_oid = branch
        .get()
        .target()
        .context("Branch does not point to a commit")?;

    let mut revwalk = repo.revwalk()?;
    revwalk.push(tip_oid)?;
    revwalk.hide(base_oid)?;
    revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::REVERSE)?;

    let mut commits = Vec::new();
    for oid_result in revwalk {
        let oid = oid_result?;
        let commit = repo.find_commit(oid)?;
        if commit.parent_count() > 1 {
            continue; // skip merge commits
        }
        let subject = repo::commit_subject(&commit);
        let body = commit.body().unwrap_or("").to_string();
        commits.push((subject, body));
    }

    Ok(commits)
}

/// Build a PR title and description from the commits in a branch.
///
/// - **Single commit**: title = commit subject, description = commit body.
/// - **Multiple commits**: prompts the user for a title, then concatenates all
///   commit messages (oldest → newest) as the description.
fn pr_title_and_description(
    repo: &Repository,
    branch_name: &str,
    base_oid: git2::Oid,
) -> Result<(String, String)> {
    let commits = gather_branch_commits(repo, branch_name, base_oid)?;

    if commits.is_empty() {
        return Ok((branch_name.to_string(), String::new()));
    }

    if commits.len() == 1 {
        let (subject, body) = &commits[0];
        return Ok((subject.clone(), body.clone()));
    }

    let title = msg::input("PR title", |s| {
        if s.is_empty() {
            Err("Title cannot be empty")
        } else {
            Ok(())
        }
    })?;

    let description = commits
        .iter()
        .map(|(subject, body)| {
            if body.is_empty() {
                subject.clone()
            } else {
                format!("{}\n\n{}", subject, body)
            }
        })
        .collect::<Vec<_>>()
        .join("\n\n---\n\n");

    Ok((title, description))
}

fn push_plain(workdir: &Path, remote: &str, branch: &str) -> Result<()> {
    git_push(workdir, remote, branch)
}

/// Push to GitHub: push the branch, then open `gh pr create --web`.
///
/// Supports fork workflow where the integration branch tracks the upstream
/// repository and the branch is pushed to a fork remote. The PR is created
/// against the integration branch's remote (usually the upstream/main repo)
/// with the head pointing to the push remote.
///
/// If the branch being pushed is the upstream target branch itself (e.g.
/// pushing `main` when tracking `origin/main`), skip PR creation and fall
/// back to a plain force-with-lease push.
///
/// If a PR already exists for the branch, prints the PR URL instead of
/// opening the browser.
fn push_github(
    repo: &Repository,
    workdir: &Path,
    remote: &str,
    branch: &str,
    target_branch: &str,
    base_oid: git2::Oid,
    upstream_label: &str,
) -> Result<()> {
    git_push(workdir, remote, branch)?;

    // Skip PR creation when pushing the upstream target branch itself
    if branch == target_branch {
        return Ok(());
    }

    let start = Instant::now();
    let gh_check = Command::new("gh").arg("--version").output();
    let gh_available = gh_check.as_ref().is_ok_and(|o| o.status.success());
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("gh", "--version", duration_ms, gh_available, "");

    if !gh_available {
        msg::warn("Install 'gh' CLI to create pull requests: https://cli.github.com");
        return Ok(());
    }

    // Determine PR target repo and head:
    // - For fork workflow: upstream branch's remote is the target (base of PR),
    //   push remote is the head (where the branch is pushed).
    // - For non-fork: both are the same.
    let integration_remote = extract_remote_name(upstream_label);
    let (pr_target_remote, pr_target_repo) = extract_gh_repo(repo, &integration_remote)
        .map(|r| (integration_remote.as_str(), r))
        .or_else(|| {
            // Fallback: try to extract from push remote if integration remote doesn't exist
            extract_gh_repo(repo, remote).map(|r| (remote, r))
        })
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Could not determine target repository for PR creation\n\
                 Run `gh repo set-default` to select a default remote repository"
            )
        })?;

    let is_fork = remote != pr_target_remote;

    // In fork workflow, --head needs "fork-owner:branch" prefix
    let head_arg = if is_fork {
        extract_gh_repo(repo, remote)
            .and_then(|r| r.split('/').next().map(|s| format!("{}:{}", s, branch)))
            .unwrap_or_else(|| branch.to_string())
    } else {
        branch.to_string()
    };

    if let Some(pr_url) = find_existing_github_pr(workdir, &pr_target_repo, branch) {
        msg::success(&format!("PR updated: {}", pr_url));
        return Ok(());
    }

    let (title, body) = pr_title_and_description(repo, branch, base_oid)?;

    // Open PR creation in browser (inherits stdio so browser opens)
    let args = vec![
        "pr",
        "create",
        "--web",
        "--head",
        &head_arg,
        "--base",
        target_branch,
        "--repo",
        &pr_target_repo,
        "--title",
        &title,
        "--body",
        &body,
    ];

    let start = Instant::now();
    let status = Command::new("gh")
        .current_dir(workdir)
        .args(&args)
        .status()?;

    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("gh", &args.join(" "), duration_ms, status.success(), "");

    if !status.success() {
        msg::warn("PR creation may have failed — check your browser");
    }

    Ok(())
}

/// Check if a GitHub PR already exists for the given branch.
///
/// Returns the PR URL if found, or `None` if no PR exists or the check fails.
fn find_existing_github_pr(workdir: &Path, gh_repo: &str, head_arg: &str) -> Option<String> {
    let output = Command::new("gh")
        .current_dir(workdir)
        .args([
            "pr", "list", "--head", head_arg, "--repo", gh_repo, "--json", "url", "--limit", "1",
        ])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();

    if trimmed == "[]" {
        return None;
    }

    let prs: serde_json::Value = serde_json::from_str(trimmed).ok()?;
    prs.get(0)?.get("url")?.as_str().map(str::to_string)
}

/// Extract the Azure DevOps organization URL from a remote URL.
///
/// Supports:
/// - HTTPS:  `https://dev.azure.com/<org>/...`       → `https://dev.azure.com/<org>`
/// - SSH:    `git@ssh.dev.azure.com:v3/<org>/...`    → `https://dev.azure.com/<org>`
/// - Legacy: `https://<org>.visualstudio.com/...`    → `https://<org>.visualstudio.com`
///
/// Returns `None` if the URL is unrecognised.
fn extract_azure_org_url(repo: &Repository, remote: &str) -> Option<String> {
    let remote = repo.find_remote(remote).ok()?;
    let url = remote.url()?;

    if let Some(rest) = url.strip_prefix("https://dev.azure.com/") {
        let org = rest.split('/').next()?;
        return Some(format!("https://dev.azure.com/{}", org));
    }

    if let Some(rest) = url.strip_prefix("git@ssh.dev.azure.com:v3/") {
        let org = rest.split('/').next()?;
        return Some(format!("https://dev.azure.com/{}", org));
    }

    if let Some(rest) = url.strip_prefix("https://")
        && let Some(host) = rest.split('/').next()
        && host.ends_with(".visualstudio.com")
    {
        return Some(format!("https://{}", host));
    }

    None
}

/// Build a `Command` for the Azure CLI.
///
/// On Windows `az` is a `.cmd` batch script which `CreateProcess` cannot
/// resolve directly, so we run it through `cmd /C`.
fn az_command() -> Command {
    if cfg!(windows) {
        let mut cmd = Command::new("cmd");
        cmd.args(["/C", "az"]);
        cmd
    } else {
        Command::new("az")
    }
}

/// Push to Azure DevOps: push the branch, then open `az repos pr create --open`.
///
/// If a PR already exists for the branch, prints the PR URL instead of
/// opening the browser.
fn push_azure(
    repo: &Repository,
    workdir: &Path,
    remote: &str,
    branch: &str,
    target_branch: &str,
    base_oid: git2::Oid,
) -> Result<()> {
    git_push(workdir, remote, branch)?;

    let start = Instant::now();
    let az_check = az_command().arg("--version").output();
    let az_available = az_check.as_ref().is_ok_and(|o| o.status.success());
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command("az", "--version", duration_ms, az_available, "");

    if !az_available {
        msg::warn(
            "Install 'az' CLI to create pull requests: \
             https://learn.microsoft.com/cli/azure/install-azure-cli",
        );
        return Ok(());
    }

    // Extract the org URL so we can pass --org explicitly rather than relying
    // on --detect, which produces a misleading "need to login" error when it
    // fails to infer the organisation from the remote URL.
    let org_url = extract_azure_org_url(repo, remote);

    // If a PR already exists, show its URL instead of opening the browser
    if let Some(pr_url) = find_existing_azure_pr(workdir, branch, org_url.as_deref()) {
        msg::success(&format!("PR updated: {}", pr_url));
        return Ok(());
    }

    let (title, description) = pr_title_and_description(repo, branch, base_oid)?;

    // Write description to a temp file and pass `--description @<path>` to az.
    // This avoids any argument-parsing issues with lines that start with `-`
    // (e.g., `---` separators) when the command is invoked through `cmd /C az`
    // on Windows.
    let mut desc_file = tempfile::Builder::new()
        .suffix(".txt")
        .tempfile()
        .context("Failed to create temp file for PR description")?;
    write!(desc_file, "{}", description).context("Failed to write PR description")?;
    let desc_path = desc_file.path().to_string_lossy().into_owned();
    let desc_arg = format!("@{}", desc_path);

    let mut args: Vec<&str> = vec![
        "repos",
        "pr",
        "create",
        "--open",
        "--source-branch",
        branch,
        "--target-branch",
        target_branch,
        "--title",
        &title,
    ];

    if let Some(ref org) = org_url {
        args.push("--org");
        args.push(org);
    } else {
        args.push("--detect");
    }

    if !description.is_empty() {
        args.push("--description");
        args.push(&desc_arg);
    }

    let start = Instant::now();
    let output = az_command().current_dir(workdir).args(&args).output()?;
    let duration_ms = start.elapsed().as_millis();
    loom_trace::log_command(
        "az",
        &args.join(" "),
        duration_ms,
        output.status.success(),
        "",
    );

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("{}", stderr.trim());
    }

    Ok(())
}

/// Check if an Azure DevOps PR already exists for the given source branch.
///
/// Returns the PR web URL if found, or `None` if no PR exists or the check fails.
fn find_existing_azure_pr(workdir: &Path, branch: &str, org_url: Option<&str>) -> Option<String> {
    let mut cmd = az_command();
    cmd.current_dir(workdir);
    cmd.args([
        "repos",
        "pr",
        "list",
        "--source-branch",
        branch,
        "--output",
        "json",
    ]);
    if let Some(org) = org_url {
        cmd.args(["--org", org]);
    } else {
        cmd.arg("--detect");
    }
    let output = cmd.output().ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let trimmed = stdout.trim();

    let prs: serde_json::Value = serde_json::from_str(trimmed).ok()?;
    let pr = prs.get(0)?;

    // Construct the web URL from the structured fields, since the API URL
    // uses GUIDs and does not contain the browser-accessible "/pullrequest/" path.
    let repo_url = pr["repository"]["url"].as_str()?;
    let org = repo_url
        .strip_prefix("https://dev.azure.com/")?
        .split('/')
        .next()?;
    let project = pr["repository"]["project"]["name"].as_str()?;
    let repo = pr["repository"]["name"].as_str()?;
    let pr_id = pr["pullRequestId"].as_u64()?;

    Some(format!(
        "https://dev.azure.com/{org}/{project}/_git/{repo}/pullrequest/{pr_id}"
    ))
}

/// Push to Gerrit without creating a review (plain force push).
///
/// If the branch is already prefixed with `wip/`, pushes directly.
/// Otherwise, warns the user that a Gerrit admin will be needed to delete
/// the remote branch later, and asks them to choose:
///   - Push as-is
///   - Push as `wip/<branch>` instead (no admin needed to delete)
///   - Cancel
fn push_gerrit_no_pr(workdir: &Path, remote: &str, branch: &str) -> Result<()> {
    if branch.starts_with("wip/") {
        return push_plain(workdir, remote, branch);
    }

    let opt_as_is = format!("Push as `{}` (admin required to delete it later)", branch);
    let opt_wip = format!("Push as `wip/{}` instead", branch);

    let choice = msg::select(
        &format!(
            "Branch `{}` is not prefixed with `wip/` — a Gerrit admin will be needed to delete the remote branch later",
            branch
        ),
        vec![opt_as_is.clone(), opt_wip.clone(), "Cancel".to_string()],
    )?;

    if choice == opt_as_is {
        push_plain(workdir, remote, branch)
    } else if choice == opt_wip {
        let wip_name = format!("wip/{}", branch);
        let refspec = format!("{}:{}", branch, wip_name);
        git::run_git(
            workdir,
            &[
                "push",
                "--force-with-lease",
                "--force-if-includes",
                remote,
                &refspec,
            ],
        )?;
        msg::success(&format!(
            "Pushed `{}` to `{}` as `{}`",
            branch, remote, wip_name
        ));
        Ok(())
    } else {
        bail!("Cancelled")
    }
}

/// Push to Gerrit with topic and refs/for/ refspec.
///
/// Captures stderr from the push command and extracts Gerrit review URLs
/// (lines starting with `remote:` that contain `http://` or `https://`).
fn push_gerrit(workdir: &Path, remote: &str, branch: &str, target_branch: &str) -> Result<()> {
    let refspec = format!("{}:refs/for/{}", branch, target_branch);
    let topic_opt = format!("topic={}", branch);

    let args = ["push", "-o", &topic_opt, remote, &refspec];
    let start = Instant::now();
    let output = Command::new("git")
        .current_dir(workdir)
        .args(args)
        .output()?;

    let duration_ms = start.elapsed().as_millis();
    let stderr = String::from_utf8_lossy(&output.stderr);
    let cmd = args.join(" ");
    loom_trace::log_command("git", &cmd, duration_ms, output.status.success(), &stderr);

    if !output.status.success() {
        bail!("git push failed");
    }

    let mut message = format!(
        "Pushed `{}` to `{}` (Gerrit: `refs/for/{}`)",
        branch, remote, target_branch
    );
    for line in stderr.lines() {
        if let Some(rest) = line.strip_prefix("remote:") {
            let trimmed = rest.trim();
            if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
                message.push('\n');
                if trimmed.ends_with(']') {
                    if let Some(pos) = trimmed.rfind('[') {
                        let (before, tag) = trimmed.split_at(pos);
                        message.push_str(&format!("{}`{}`", before, tag));
                    } else {
                        message.push_str(trimmed);
                    }
                } else {
                    message.push_str(trimmed);
                }
            }
        }
    }
    msg::success(&message);

    Ok(())
}

#[cfg(test)]
#[path = "push_test.rs"]
mod tests;