git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
//! Sync mode: fetch, pull, push and the list of remotes.
//!
//! Decisions (remote choice, command arguments, error classification) are pure functions; the
//! executors (`run_fetch`, `run_pull`, `lease_for`) take plain arguments so tests drive them
//! with a TempRepo; the screens are thin glue around them.

use crate::git::{self, Opts};
use crate::input;
use crate::model::{Config, Level};
use crate::policy::{self, Op};
use crate::repo_state::{self, Head, RepoState};
use crate::screen;
use crate::ui::{self, Choice, Key};
use anyhow::{anyhow, Result};
use std::sync::atomic::AtomicBool;
use std::time::Duration;

const FETCH_SECS: u64 = 180;
const PULL_SECS: u64 = 180;

// ---------------------------------------------------------------------------------------------
// Pure logic
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullChoice {
    FastForward,
    Rebase,
    Merge,
}

impl PullChoice {
    const ALL: [PullChoice; 3] = [
        PullChoice::FastForward,
        PullChoice::Rebase,
        PullChoice::Merge,
    ];

    fn label(self) -> &'static str {
        match self {
            PullChoice::FastForward => "Fast-forward only (safe)",
            PullChoice::Rebase => "Rebase my commits on top",
            PullChoice::Merge => "Merge (creates a merge commit)",
        }
    }
}

/// The local integration step of a pull, run on `FETCH_HEAD` after
/// `git fetch <remote> refs/heads/<branch>` (no remote-tracking ref is needed). A rebase with a
/// known `fork_point` (the old upstream tip, from the tracking ref's reflog) replays only the
/// commits after it, so an upstream force-push does not replay commits it already rewrote.
fn integrate_args(choice: PullChoice, fork_point: Option<&str>) -> Vec<String> {
    let args: Vec<&str> = match (choice, fork_point) {
        (PullChoice::FastForward, _) => vec!["merge", "--ff-only", "FETCH_HEAD"],
        (PullChoice::Rebase, Some(fork)) => vec!["rebase", "--onto", "FETCH_HEAD", fork],
        (PullChoice::Rebase, None) => vec!["rebase", "FETCH_HEAD"],
        (PullChoice::Merge, _) => vec!["merge", "--no-edit", "FETCH_HEAD"],
    };
    args.into_iter().map(String::from).collect()
}

/// The fetch step of a pull: only the one branch, into FETCH_HEAD (and its tracking ref when the
/// remote's fetch refspec covers it).
fn fetch_args(remote: &str, branch: &str) -> Vec<String> {
    vec![
        "fetch".into(),
        remote.into(),
        format!("refs/heads/{branch}"),
    ]
}

/// The two commands a pull runs, for display.
fn pull_command(
    choice: PullChoice,
    remote: &str,
    branch: &str,
    fork_point: Option<&str>,
) -> String {
    format!(
        "{} && git {}",
        fetch_args(remote, branch).join(" "),
        integrate_args(choice, fork_point).join(" ")
    )
}

/// Why a branch name cannot be pushed or pulled, or None when it is fine.
fn branch_problem(name: &str) -> Option<String> {
    if name.is_empty() || name.starts_with('-') {
        return Some(format!("'{name}' is not a usable branch name."));
    }
    let ok = git::git_raw(&["check-ref-format", "--branch", name], &Opts::default())
        .is_ok_and(|out| out.ok());
    (!ok).then(|| format!("'{name}' is not a valid branch name."))
}

/// Checks both names before they reach a push or pull command.
fn names_problem(remote: &str, branch: &str) -> Option<String> {
    remote_name_problem(remote)
        .map(String::from)
        .or_else(|| branch_problem(branch))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PullError {
    Diverged,
    NoUpstream,
    Auth,
    Conflict,
    Other,
}

fn looks_like_auth(text: &str) -> bool {
    [
        "authentication failed",
        "could not read username",
        "could not read password",
        "permission denied",
        "terminal prompts disabled",
        "invalid credentials",
        "the requested url returned error: 403",
        "the requested url returned error: 401",
    ]
    .iter()
    .any(|needle| text.contains(needle))
}

fn classify_pull_error(stderr: &str) -> PullError {
    let text = stderr.to_ascii_lowercase();
    if looks_like_auth(&text) {
        PullError::Auth
    } else if text.contains("conflict")
        || text.contains("automatic merge failed")
        || text.contains("could not apply")
    {
        PullError::Conflict
    } else if text.contains("not possible to fast-forward")
        || text.contains("divergent branches")
        || text.contains("need to specify how to reconcile")
    {
        PullError::Diverged
    } else if text.contains("no tracking information") || text.contains("no upstream") {
        PullError::NoUpstream
    } else {
        PullError::Other
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PushError {
    Rejected,
    NoUpstream,
    Auth,
    Other,
}

fn classify_push_error(stderr: &str) -> PushError {
    let text = stderr.to_ascii_lowercase();
    if looks_like_auth(&text) {
        PushError::Auth
    } else if text.contains("no upstream branch") {
        PushError::NoUpstream
    } else if text.contains("[remote rejected]") {
        PushError::Other
    } else if text.contains("[rejected]")
        || text.contains("non-fast-forward")
        || text.contains("fetch first")
        || text.contains("stale info")
    {
        PushError::Rejected
    } else {
        PushError::Other
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum RemoteChoice {
    Use(String),
    Pick(Vec<String>),
    None,
}

/// The remote named by an upstream like "origin/main" (longest match, remote names may hold '/').
fn upstream_remote<'a>(upstream: &str, remotes: &'a [String]) -> Option<&'a str> {
    remotes
        .iter()
        .filter(|remote| {
            upstream
                .strip_prefix(remote.as_str())
                .is_some_and(|rest| rest.starts_with('/'))
        })
        .max_by_key(|remote| remote.len())
        .map(String::as_str)
}

/// default_remote when it exists, else the upstream's remote, else the only remote, else ask.
fn choose_remote(default: &str, remotes: &[String], upstream: Option<&str>) -> RemoteChoice {
    if remotes.is_empty() {
        return RemoteChoice::None;
    }
    if remotes.iter().any(|remote| remote == default) {
        return RemoteChoice::Use(default.to_string());
    }
    if let Some(remote) = upstream.and_then(|up| upstream_remote(up, remotes)) {
        return RemoteChoice::Use(remote.to_string());
    }
    if let [only] = remotes {
        return RemoteChoice::Use(only.clone());
    }
    RemoteChoice::Pick(remotes.to_vec())
}

/// The branch to pull: the upstream's branch when it lives on `remote`, else the local name.
fn pull_branch(upstream: Option<&str>, remote: &str, local: &str) -> String {
    upstream
        .and_then(|up| up.strip_prefix(remote))
        .and_then(|rest| rest.strip_prefix('/'))
        .filter(|name| !name.is_empty())
        .unwrap_or(local)
        .to_string()
}

/// Parses `git remote -v` into (name, fetch url), one entry per remote.
fn parse_remotes(text: &str) -> Vec<(String, String)> {
    let mut found: Vec<(String, String)> = Vec::new();
    for line in text.lines() {
        let Some((name, rest)) = line.trim_end().split_once('\t') else {
            continue;
        };
        let url = rest
            .strip_suffix(" (fetch)")
            .or_else(|| rest.strip_suffix(" (push)"));
        let Some(url) = url else { continue };
        if !found.iter().any(|(known, _)| known == name) {
            found.push((name.to_string(), url.to_string()));
        }
    }
    found
}

/// Why a remote name cannot be used, or None when it is fine.
fn remote_name_problem(name: &str) -> Option<&'static str> {
    if name.is_empty() {
        Some("The name cannot be empty.")
    } else if name.starts_with('-') {
        Some("The name cannot start with '-'.")
    } else if name.contains("..")
        || name
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || "~^:?*[\\".contains(c))
    {
        Some("The name has characters git does not allow (spaces, ~ ^ : ? * [ \\ or ..).")
    } else {
        None
    }
}

fn remote_url_problem(url: &str) -> Option<&'static str> {
    if url.trim().is_empty() {
        Some("The URL cannot be empty.")
    } else if url.starts_with('-') {
        Some("The URL cannot start with '-'.")
    } else {
        None
    }
}

/// The active gct account's GitHub login (same lookup as the commit flow).
fn login_of(cfg: &Config) -> Option<String> {
    let label = cfg.active_account.as_deref()?;
    let account = cfg.accounts.iter().find(|account| account.label == label)?;
    Some(account.github_username.clone()).filter(|login| !login.is_empty())
}

/// The local branch name, or why a push/pull cannot work from this HEAD.
fn branch_name(head: &Head) -> Result<&str, &'static str> {
    match head {
        Head::Branch { name, .. } => Ok(name),
        Head::Unborn { .. } => Err("This branch has no commits yet. Make a commit first."),
        Head::Detached { .. } => {
            Err("HEAD is detached (not on a branch). Check out a branch first, for example in Branch mode.")
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Item {
    Fetch,
    Pull,
    Push,
    PushSetUpstream,
    ForcePush,
    Remotes,
}

impl Item {
    fn row(self) -> &'static str {
        match self {
            Item::Fetch => "Fetch          download news, change nothing",
            Item::Pull => "Pull           bring remote commits into this branch",
            Item::Push => "Push           send this branch to the remote",
            Item::PushSetUpstream => "Push and set upstream   first push of a new branch",
            Item::ForcePush => "Force push with lease   overwrite the remote branch (careful)",
            Item::Remotes => "Remotes        list, add, rename, remove",
        }
    }

    fn key(self) -> Key {
        let (key, label) = match self {
            Item::Fetch => ('f', "fetch"),
            Item::Pull => ('l', "pull"),
            Item::Push => ('p', "push"),
            Item::PushSetUpstream => ('u', "push+upstream"),
            Item::ForcePush => ('x', "force push"),
            Item::Remotes => ('m', "remotes"),
        };
        Key { key, label }
    }
}

fn menu_items(level: Level, has_upstream: bool) -> Vec<Item> {
    let mut items = vec![Item::Fetch, Item::Pull, Item::Push];
    if !has_upstream {
        items.push(Item::PushSetUpstream);
    }
    if level != Level::Beginner {
        items.push(Item::ForcePush);
    }
    items.push(Item::Remotes);
    items
}

// ---------------------------------------------------------------------------------------------
// Executors
// ---------------------------------------------------------------------------------------------

#[derive(Debug)]
enum Net {
    Done(String),
    Failed(String),
    Cancelled,
}

/// Runs a network git command with a timeout; git's report is stderr plus stdout.
fn run_net(args: &[&str], secs: u64, cancel: &AtomicBool) -> Result<Net> {
    let opts = Opts {
        timeout: Some(Duration::from_secs(secs)),
        cancel: Some(cancel),
        ..Opts::default()
    };
    let out = git::git_raw(args, &opts)?;
    if out.cancelled {
        return Ok(Net::Cancelled);
    }
    let mut text = out.stderr.trim().to_string();
    let stdout = out.text();
    if !stdout.is_empty() {
        if !text.is_empty() {
            text.push('\n');
        }
        text.push_str(&stdout);
    }
    if out.ok() {
        Ok(Net::Done(text))
    } else if text.is_empty() {
        Ok(Net::Failed(format!(
            "git did not finish (timed out after {secs}s or was stopped)"
        )))
    } else {
        Ok(Net::Failed(text))
    }
}

/// `git fetch --prune <remote>`, or `--all` when `remote` is None.
fn run_fetch(remote: Option<&str>, cancel: &AtomicBool) -> Result<Net> {
    match remote {
        Some(remote) => run_net(&["fetch", "--prune", remote], FETCH_SECS, cancel),
        None => run_net(&["fetch", "--prune", "--all"], FETCH_SECS, cancel),
    }
}

/// Runs a local git command (no timeout, never cancelled: killing it mid merge/rebase is unsafe).
fn run_local(args: &[&str]) -> Result<Net> {
    let out = git::git_raw(args, &Opts::default())?;
    let mut text = out.stderr.trim().to_string();
    let stdout = out.text();
    if !stdout.is_empty() {
        if !text.is_empty() {
            text.push('\n');
        }
        text.push_str(&stdout);
    }
    Ok(if out.ok() {
        Net::Done(text)
    } else {
        Net::Failed(text)
    })
}

/// Where the local branch forked from `refs/remotes/<remote>/<branch>` (its reflog included),
/// or None when that tracking ref does not exist or has no common history with HEAD.
fn fork_point(remote: &str, branch: &str) -> Option<String> {
    let tracking = format!("refs/remotes/{remote}/{branch}");
    git::git_ok(
        &["rev-parse", "--verify", "--quiet", &tracking],
        &Opts::default(),
    )
    .ok()?;
    git::git_ok(
        &["merge-base", "--fork-point", &tracking, "HEAD"],
        &Opts::default(),
    )
    .ok()
    .map(|oid| oid.trim().to_string())
    .filter(|oid| !oid.is_empty())
}

/// What a pull did: git's outcome, the backup ref taken before a rebase or merge, and the
/// commands that ran (for display).
type Pulled = (Net, Option<String>, String);

/// Pull = cancellable fetch of the branch, then a non-cancellable local integration of
/// FETCH_HEAD.
fn run_pull(choice: PullChoice, remote: &str, branch: &str, cancel: &AtomicBool) -> Result<Pulled> {
    // Read before the fetch moves the tracking ref.
    let fork = if choice == PullChoice::Rebase {
        fork_point(remote, branch)
    } else {
        None
    };
    let command = pull_command(choice, remote, branch, fork.as_deref());
    let fetch = fetch_args(remote, branch);
    let fetch: Vec<&str> = fetch.iter().map(String::as_str).collect();
    match run_net(&fetch, PULL_SECS, cancel)? {
        Net::Done(_) => {}
        other => return Ok((other, None, command)),
    }
    let has_head = git::git_ok(
        &["rev-parse", "--verify", "--quiet", "HEAD"],
        &Opts::default(),
    )
    .is_ok();
    let backup = if choice != PullChoice::FastForward && has_head {
        Some(crate::safety::backup("pull", "HEAD")?)
    } else {
        None
    };
    let owned = integrate_args(choice, fork.as_deref());
    let args: Vec<&str> = owned.iter().map(String::as_str).collect();
    Ok((run_local(&args)?, backup, command))
}

/// The lease value for a force push: "refs/heads/<branch>:<oid we last saw on the remote>".
fn lease_for(remote: &str, branch: &str) -> Result<String> {
    let tracking = format!("refs/remotes/{remote}/{branch}");
    let oid = git::git_ok(
        &["rev-parse", "--verify", "--quiet", &tracking],
        &Opts::default(),
    )
    .map_err(|_| anyhow!("{remote}/{branch} is not known locally yet; fetch first"))?;
    Ok(format!("refs/heads/{branch}:{oid}"))
}

fn list_remotes() -> Result<Vec<(String, String)>> {
    Ok(parse_remotes(&git::git_ok(
        &["remote", "-v"],
        &Opts::default(),
    )?))
}

fn remote_names() -> Result<Vec<String>> {
    Ok(list_remotes()?.into_iter().map(|(name, _)| name).collect())
}

// ---------------------------------------------------------------------------------------------
// Screens
// ---------------------------------------------------------------------------------------------

fn error_lines(plain: &str, stderr: &str) -> Vec<String> {
    let mut lines = vec![screen::danger(plain), String::new()];
    lines.extend(crate::cmdlog::mask(stderr).lines().map(String::from));
    lines
}

fn result_lines(command: &str, report: &str, cfg: &Config, why: &[&str]) -> Vec<String> {
    let mut lines = vec![
        screen::success("Done."),
        screen::muted(format!("$ git {command}")),
        String::new(),
    ];
    lines.extend(crate::cmdlog::mask(report).lines().map(String::from));
    lines.extend(ui::explain(cfg, why));
    lines
}

fn header_lines(state: &RepoState, remotes: &[String]) -> Vec<String> {
    let info = &state.branch;
    let branch = match &info.head {
        Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
        Head::Detached { oid } => format!("(detached at {})", oid.get(..7).unwrap_or(oid)),
    };
    let upstream = match (&info.upstream, info.upstream_gone) {
        (Some(up), true) => format!("{up} (gone from the remote)"),
        (Some(up), false) => format!("{up}  ahead {} / behind {}", info.ahead, info.behind),
        (None, _) => "none (not published yet)".to_string(),
    };
    let names = if remotes.is_empty() {
        "none".to_string()
    } else {
        remotes.join(", ")
    };
    vec![
        format!("{} {}", screen::muted("Branch  "), screen::accent(branch)),
        format!("{} {}", screen::muted("Upstream"), upstream),
        format!("{} {}", screen::muted("Remotes "), names),
        String::new(),
    ]
}

/// The remote to use, asking when needed; no remotes leads into the add-remote flow.
fn resolve_remote(cfg: &mut Config, upstream: Option<&str>) -> Result<Option<String>> {
    let mut remotes = remote_names()?;
    if remotes.is_empty() {
        let mut lines =
            vec!["This repository has no remote, so there is nowhere to sync with.".to_string()];
        lines.extend(ui::explain(
            cfg,
            &["A remote is a copy of the project on a server, like GitHub."],
        ));
        lines.push("Next you can add one.".into());
        ui::notice("No remote", &lines)?;
        add_remote(cfg)?;
        remotes = remote_names()?;
    }
    match choose_remote(&cfg.default_remote, &remotes, upstream) {
        RemoteChoice::Use(name) => Ok(Some(name)),
        RemoteChoice::None => Ok(None),
        RemoteChoice::Pick(names) => {
            let options: Vec<&str> = names.iter().map(String::as_str).collect();
            let context = vec!["Which remote?".to_string()];
            Ok(ui::choose("Choose a remote", &context, &options)?.map(|i| names[i].clone()))
        }
    }
}

fn conflicts_pending() -> bool {
    repo_state::load()
        .is_ok_and(|state| state.op.is_some() || state.entries.iter().any(|e| e.conflicted()))
}

fn fetch_flow(cfg: &mut Config) -> Result<()> {
    let state = repo_state::load()?;
    let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
        return Ok(());
    };
    let mut all = false;
    if remote_names()?.len() > 1 {
        let options = [format!("Only {remote}"), "All remotes".to_string()];
        let options: Vec<&str> = options.iter().map(String::as_str).collect();
        match ui::choose("Fetch from", &[], &options)? {
            Some(1) => all = true,
            Some(_) => {}
            None => return Ok(()),
        }
    }
    let target = if all { None } else { Some(remote.as_str()) };
    let command = if all {
        "fetch --prune --all".to_string()
    } else {
        format!("fetch --prune {remote}")
    };
    let net = ui::git_job_cancellable(
        &format!("Fetching {}...", target.unwrap_or("all remotes")),
        |cancel| run_fetch(target, cancel),
    )?;
    match net {
        Net::Done(report) => {
            let report = if report.is_empty() {
                "Already up to date.".to_string()
            } else {
                report
            };
            let why = ["Fetch only downloads. Your files and branches stay untouched."];
            ui::notice("Fetch", &result_lines(&command, &report, cfg, &why))
        }
        Net::Failed(text) => {
            let plain = if looks_like_auth(&text.to_ascii_lowercase()) {
                "Git could not sign in. Run `gct --account` to pick or add a GitHub account."
            } else {
                "The fetch failed."
            };
            ui::notice("Fetch failed", &error_lines(plain, &text))
        }
        Net::Cancelled => ui::notice("Fetch", &["Cancelled.".to_string()]),
    }
}

fn pull_flow(cfg: &mut Config) -> Result<()> {
    let state = repo_state::load()?;
    if state.op.is_some() || state.entries.iter().any(|e| e.conflicted()) {
        ui::notice(
            "Pull",
            &["Finish the operation in progress first. Opening the conflicts screen.".to_string()],
        )?;
        return crate::modes::open("conflicts", cfg);
    }
    let local = match branch_name(&state.branch.head) {
        Ok(name) => name.to_string(),
        Err(why) => return ui::notice("Pull", &[why.to_string()]),
    };
    let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
        return Ok(());
    };
    let branch = pull_branch(state.branch.upstream.as_deref(), &remote, &local);
    let labels: Vec<&str> = PullChoice::ALL.iter().map(|c| c.label()).collect();
    let mut context = vec![format!("Pull {remote}/{branch} into {local}")];
    context.extend(ui::explain(
        cfg,
        &["Fast-forward only refuses to pull when both sides have new commits."],
    ));
    if let Some(problem) = names_problem(&remote, &branch) {
        return ui::notice("Pull", &[problem]);
    }
    let Some(first) = ui::choose("Pull how?", &context, &labels)? else {
        return Ok(());
    };
    let mut choice = PullChoice::ALL[first];
    loop {
        let (net, backup, command) =
            ui::git_job_cancellable(&format!("Pulling {remote}/{branch}..."), |cancel| {
                run_pull(choice, &remote, &branch, cancel)
            })?;
        let backup_line = backup
            .as_ref()
            .map(|name| format!("Backup of your branch before the pull: {name}"));
        let text = match net {
            Net::Done(report) => {
                let why = ["Pull = fetch + bring the new commits into your branch."];
                let mut lines = result_lines(&command, &report, cfg, &why);
                lines.extend(backup_line);
                return ui::notice("Pull", &lines);
            }
            Net::Cancelled => return ui::notice("Pull", &["Cancelled.".to_string()]),
            Net::Failed(text) => text,
        };
        let kind = classify_pull_error(&text);
        if kind == PullError::Conflict || conflicts_pending() {
            let mut lines = error_lines(
                "Some files changed on both sides. Resolve them next.",
                &text,
            );
            lines.extend(backup_line);
            ui::notice("Pull stopped on conflicts", &lines)?;
            return crate::modes::open("conflicts", cfg);
        }
        match kind {
            PullError::Diverged => {
                let context = vec![
                    "Your branch and the remote both have new commits, so they have diverged."
                        .to_string(),
                    "A fast-forward is not possible. Pick another way to combine them:".to_string(),
                ];
                let others: Vec<PullChoice> = PullChoice::ALL
                    .into_iter()
                    .filter(|c| *c != choice)
                    .collect();
                let mut labels: Vec<&str> = others.iter().map(|c| c.label()).collect();
                labels.push("Cancel");
                match ui::choose("Branches diverged", &context, &labels)? {
                    Some(i) if i < others.len() => choice = others[i],
                    _ => return Ok(()),
                }
            }
            PullError::NoUpstream => {
                return ui::notice(
                    "Pull",
                    &error_lines("This branch is not tracking a remote branch yet. Push it with 'Push and set upstream' first.", &text),
                );
            }
            PullError::Auth => return ui::notice("Pull", &error_lines(AUTH_HELP, &text)),
            PullError::Conflict | PullError::Other => {
                return ui::notice("Pull failed", &error_lines("The pull failed.", &text));
            }
        }
    }
}

const AUTH_HELP: &str =
    "Git could not sign in. Run `gct --account` to pick or add a GitHub account.";

fn push_flow(cfg: &mut Config, force: bool, set_upstream: bool) -> Result<()> {
    let state = repo_state::load()?;
    let branch = match branch_name(&state.branch.head) {
        Ok(name) => name.to_string(),
        Err(why) => return ui::notice("Push", &[why.to_string()]),
    };
    let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
        return Ok(());
    };
    if let Some(problem) = names_problem(&remote, &branch) {
        return ui::notice("Push", &[problem]);
    }
    let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
    let mut lease = None;
    let mut command = format!(
        "push {}{remote} {refspec}",
        if set_upstream { "-u " } else { "" }
    );
    if force {
        let verdict = policy::check(
            cfg,
            &Op::ForcePush {
                remote: &remote,
                branch: &branch,
            },
        );
        let what = format!("Overwrite {remote}/{branch} with your local {branch}. Commits only on the remote are lost.");
        // The lease needs the remote's last known commit; build the command text first.
        let value = match lease_for(&remote, &branch) {
            Ok(value) => value,
            Err(error) => {
                if matches!(verdict, policy::Verdict::Deny(_)) {
                    ui::gate(cfg, &verdict, &what, "")?;
                    return Ok(());
                }
                return ui::notice("Force push", &[error.to_string()]);
            }
        };
        command = format!("push --force-with-lease={value} --force-if-includes {remote} {refspec}");
        if !ui::gate(cfg, &verdict, &what, &format!("git {command}"))? {
            return Ok(());
        }
        lease = Some(value);
    }
    let login = login_of(cfg);
    let net = ui::git_job_cancellable(&format!("Pushing {branch} to {remote}..."), |cancel| {
        git::push_to_cancellable(
            &remote,
            &branch,
            lease.as_deref(),
            set_upstream,
            login.as_deref(),
            Some(cancel),
        )
    });
    match net {
        Ok(report) => {
            let why = ["Push uploads your commits so others (and GitHub) can see them."];
            let report = if report.is_empty() {
                "Everything is already up to date.".to_string()
            } else {
                report
            };
            ui::notice("Push", &result_lines(&command, &report, cfg, &why))
        }
        Err(error) if input::is_cancel(&error) || error.is::<ui::JobPanic>() => Err(error),
        Err(error) => push_failed(cfg, set_upstream, force, &format!("{error:#}")),
    }
}

fn push_failed(cfg: &mut Config, set_upstream: bool, force: bool, text: &str) -> Result<()> {
    match classify_push_error(text) {
        PushError::Rejected => {
            let mut lines = error_lines(
                if force {
                    "The remote branch changed since you last fetched, so the lease refused the overwrite. Fetch and look first."
                } else {
                    "The remote has commits you do not have yet, so git refused the push."
                },
                text,
            );
            lines.extend(ui::explain(
                cfg,
                &["Pull first to combine both histories, then push again."],
            ));
            ui::notice("Push rejected", &lines)?;
            if !force && ui::choose("Next step", &[], &["Pull now", "Back"])? == Some(0) {
                return pull_flow(cfg);
            }
            Ok(())
        }
        PushError::NoUpstream if !set_upstream => {
            let context = error_lines(
                "This branch has no upstream yet (it was never pushed).",
                text,
            );
            if ui::choose(
                "Set the upstream?",
                &context,
                &["Push and set upstream", "Back"],
            )? == Some(0)
            {
                return push_flow(cfg, false, true);
            }
            Ok(())
        }
        PushError::Auth => ui::notice("Push failed", &error_lines(AUTH_HELP, text)),
        PushError::NoUpstream | PushError::Other => {
            ui::notice("Push failed", &error_lines("The push failed.", text))
        }
    }
}

/// Pushes the current branch, optionally setting its upstream (cross-mode entry point).
pub fn push_current(cfg: &mut Config, set_upstream: bool) -> Result<()> {
    push_flow(cfg, false, set_upstream)
}

/// Asks for a name and URL and adds a remote (cross-mode entry point).
pub fn add_remote(cfg: &mut Config) -> Result<()> {
    let existing = remote_names()?;
    let initial = if existing.contains(&cfg.default_remote) {
        ""
    } else {
        cfg.default_remote.as_str()
    };
    let Some(name) = ui::ask("Remote name (usually origin)", initial)? else {
        return Ok(());
    };
    let name = name.trim().to_string();
    if let Some(problem) = remote_name_problem(&name) {
        return ui::notice("Add remote", &[problem.to_string()]);
    }
    if existing.contains(&name) {
        return ui::notice(
            "Add remote",
            &[format!("A remote named '{name}' already exists.")],
        );
    }
    let Some(url) = ui::ask("Remote URL (https://github.com/you/repo.git)", "")? else {
        return Ok(());
    };
    let url = url.trim().to_string();
    if let Some(problem) = remote_url_problem(&url) {
        return ui::notice("Add remote", &[problem.to_string()]);
    }
    ui::run_git(cfg, "Adding the remote...", &["remote", "add", &name, &url])?;
    let mut lines = result_lines(
        &format!("remote add {name} {}", crate::cmdlog::mask(&url)),
        "",
        cfg,
        &[],
    );
    lines.extend(ui::explain(
        cfg,
        &["Next: Fetch to download it, then Push and set upstream."],
    ));
    ui::notice("Remote added", &lines)
}

fn remotes_screen(cfg: &mut Config) -> Result<()> {
    let mut index = 0usize;
    loop {
        let remotes = list_remotes()?;
        let rows: Vec<String> = remotes
            .iter()
            .map(|(name, url)| format!("{name:<12} {}", crate::cmdlog::mask(url)))
            .collect();
        let header = if rows.is_empty() {
            vec![
                "No remotes yet. Press A to add one.".to_string(),
                String::new(),
            ]
        } else {
            vec![String::new()]
        };
        let keys = [
            Key {
                key: 'a',
                label: "add",
            },
            Key {
                key: 'n',
                label: "rename",
            },
            Key {
                key: 'u',
                label: "set URL",
            },
            Key {
                key: 'd',
                label: "remove",
            },
        ];
        let (action, at) = match ui::action_list("Remotes", &header, &rows, &keys, &mut index)? {
            Choice::Back => return Ok(()),
            Choice::Action(key, at) => (key, at),
            Choice::Open(at) => {
                let picked = ui::choose(
                    "Remote",
                    &[rows.get(at).cloned().unwrap_or_default()],
                    &["Rename", "Change URL", "Remove", "Back"],
                )?;
                match picked {
                    Some(0) => ('n', at),
                    Some(1) => ('u', at),
                    Some(2) => ('d', at),
                    _ => continue,
                }
            }
        };
        if action == 'a' {
            add_remote(cfg)?;
            continue;
        }
        let Some((name, url)) = remotes.get(at) else {
            continue;
        };
        match action {
            'n' => {
                let Some(new) = ui::ask(&format!("New name for {name}"), name)? else {
                    continue;
                };
                let new = new.trim().to_string();
                if let Some(problem) = remote_name_problem(&new) {
                    ui::notice("Rename remote", &[problem.to_string()])?;
                } else if &new != name {
                    ui::run_git(cfg, "Renaming...", &["remote", "rename", name, &new])?;
                }
            }
            'u' => {
                let Some(new) = ui::ask(&format!("New URL for {name}"), url)? else {
                    continue;
                };
                let new = new.trim().to_string();
                if let Some(problem) = remote_url_problem(&new) {
                    ui::notice("Change URL", &[problem.to_string()])?;
                } else {
                    ui::run_git(
                        cfg,
                        "Changing the URL...",
                        &["remote", "set-url", name, &new],
                    )?;
                }
            }
            'd' => {
                let what = format!("Remove the remote '{name}'. Its remote-tracking branches are forgotten locally; the server is not touched.");
                if ui::confirm_danger(cfg, &what, &format!("git remote remove {name}"))? {
                    ui::run_git(cfg, "Removing...", &["remote", "remove", name])?;
                }
            }
            _ => {}
        }
    }
}

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    loop {
        let state = repo_state::load()?;
        let remotes = remote_names()?;
        let items = menu_items(config.level(), state.branch.upstream.is_some());
        let rows: Vec<String> = items.iter().map(|item| item.row().to_string()).collect();
        let keys: Vec<Key> = items.iter().map(|item| item.key()).collect();
        let header = header_lines(&state, &remotes);
        let item = match ui::action_list("Sync", &header, &rows, &keys, &mut index)? {
            Choice::Back => return Ok(()),
            Choice::Open(at) => items.get(at).copied(),
            Choice::Action(key, _) => items.iter().find(|item| item.key().key == key).copied(),
        };
        match item {
            Some(Item::Fetch) => fetch_flow(config)?,
            Some(Item::Pull) => pull_flow(config)?,
            Some(Item::Push) => push_flow(config, false, false)?,
            Some(Item::PushSetUpstream) => push_flow(config, false, true)?,
            Some(Item::ForcePush) => push_flow(config, true, false)?,
            Some(Item::Remotes) => remotes_screen(config)?,
            None => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::Verdict;
    use crate::testutil::TempRepo;

    fn names(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn classify_push_table() {
        let cases = [
            ("! [rejected]        main -> main (non-fast-forward)\nerror: failed to push some refs", PushError::Rejected),
            (" ! [rejected]        main -> main (fetch first)", PushError::Rejected),
            (" ! [rejected]        main -> main (stale info)", PushError::Rejected),
            ("fatal: The current branch feat has no upstream branch.\nTo push the current branch and set the remote as upstream, use", PushError::NoUpstream),
            ("remote: Invalid username or password.\nfatal: Authentication failed for 'https://github.com/a/b.git/'", PushError::Auth),
            ("fatal: could not read Username for 'https://github.com': terminal prompts disabled", PushError::Auth),
            (" ! [remote rejected] main -> main (protected branch hook declined)", PushError::Other),
            ("fatal: unable to access: Could not resolve host", PushError::Other),
            ("", PushError::Other),
        ];
        for (text, want) in cases {
            assert_eq!(classify_push_error(text), want, "{text}");
        }
    }

    #[test]
    fn classify_pull_table() {
        let cases = [
            ("fatal: Not possible to fast-forward, aborting.", PullError::Diverged),
            ("hint: You have divergent branches\nfatal: Need to specify how to reconcile divergent branches.", PullError::Diverged),
            ("CONFLICT (content): Merge conflict in a.txt\nAutomatic merge failed; fix conflicts", PullError::Conflict),
            ("error: could not apply 1234567... msg", PullError::Conflict),
            ("There is no tracking information for the current branch.", PullError::NoUpstream),
            ("fatal: Authentication failed for 'https://x/y.git/'", PullError::Auth),
            ("fatal: couldn't find remote ref nope", PullError::Other),
        ];
        for (text, want) in cases {
            assert_eq!(classify_pull_error(text), want, "{text}");
        }
    }

    #[test]
    fn integrate_args_table() {
        assert_eq!(
            integrate_args(PullChoice::FastForward, Some("x")),
            ["merge", "--ff-only", "FETCH_HEAD"]
        );
        assert_eq!(
            integrate_args(PullChoice::Rebase, None),
            ["rebase", "FETCH_HEAD"]
        );
        assert_eq!(
            integrate_args(PullChoice::Rebase, Some("abc")),
            ["rebase", "--onto", "FETCH_HEAD", "abc"]
        );
        assert_eq!(
            integrate_args(PullChoice::Merge, None),
            ["merge", "--no-edit", "FETCH_HEAD"]
        );
        assert_eq!(
            pull_command(PullChoice::Rebase, "o", "b", None),
            "fetch o refs/heads/b && git rebase FETCH_HEAD"
        );
    }

    #[test]
    fn branch_names_are_validated() {
        let repo = TempRepo::new(1);
        repo.run(|| {
            assert!(names_problem("origin", "feat/x").is_none());
            assert!(names_problem("origin", "-x").is_some());
            assert!(names_problem("origin", "a..b").is_some());
            assert!(names_problem("", "main").is_some());
            assert!(names_problem("--upload-pack=x", "main").is_some());
        });
    }

    #[test]
    fn rebase_and_merge_pull_take_a_backup() {
        for choice in [PullChoice::Rebase, PullChoice::Merge] {
            let repo = TempRepo::new(2).with_remote();
            let dir = other_clone(&repo);
            commit_in(&repo, &dir, "theirs.txt", None);
            repo.write("mine.txt", "m\n");
            repo.git(&["add", "."]);
            repo.git(&["commit", "-q", "-m", "mine"]);
            let before = repo.git(&["rev-parse", "HEAD"]);
            let cancel = AtomicBool::new(false);
            repo.run(|| {
                let (net, backup, _) = run_pull(choice, "origin", "main", &cancel).unwrap();
                assert!(matches!(net, Net::Done(_)), "{net:?}");
                let name = backup.expect("backup taken");
                assert_eq!(
                    git::git_ok(&["rev-parse", &name], &Opts::default()).unwrap(),
                    before
                );
            });
            assert!(repo.path().join("theirs.txt").exists());
        }
    }

    #[test]
    fn ff_pull_takes_no_backup() {
        let repo = TempRepo::new(2).with_remote();
        let cancel = AtomicBool::new(false);
        repo.run(|| {
            let (net, backup, _) =
                run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap();
            assert!(matches!(net, Net::Done(_)));
            assert!(backup.is_none());
        });
    }

    #[test]
    fn choose_remote_table() {
        let two = names(&["origin", "second"]);
        assert_eq!(choose_remote("origin", &[], None), RemoteChoice::None);
        assert_eq!(
            choose_remote("second", &two, Some("origin/main")),
            RemoteChoice::Use("second".into())
        );
        assert_eq!(
            choose_remote("zzz", &two, Some("second/main")),
            RemoteChoice::Use("second".into())
        );
        assert_eq!(
            choose_remote("zzz", &two, None),
            RemoteChoice::Pick(two.clone())
        );
        assert_eq!(
            choose_remote("zzz", &names(&["only"]), None),
            RemoteChoice::Use("only".into())
        );
        let nested = names(&["a", "a/b"]);
        assert_eq!(
            choose_remote("zzz", &nested, Some("a/b/main")),
            RemoteChoice::Use("a/b".into())
        );
        assert_eq!(pull_branch(Some("origin/feat/x"), "origin", "x"), "feat/x");
        assert_eq!(pull_branch(Some("other/main"), "origin", "dev"), "dev");
        assert_eq!(pull_branch(None, "origin", "dev"), "dev");
    }

    #[test]
    fn remotes_and_validation() {
        let text = "origin\thttps://h/a.git (fetch)\r\norigin\thttps://h/a.git (push)\nüp\tC:\\Users\\x y\\r (fetch)\nüp\tC:\\Users\\x y\\r (push)\n";
        assert_eq!(
            parse_remotes(text),
            [
                ("origin".to_string(), "https://h/a.git".to_string()),
                ("üp".to_string(), "C:\\Users\\x y\\r".to_string())
            ]
        );
        assert!(parse_remotes("").is_empty());
        assert!(remote_name_problem("").is_some());
        assert!(remote_name_problem("-x").is_some());
        assert!(remote_name_problem("a b").is_some());
        assert!(remote_name_problem("up-stream").is_none());
        assert!(remote_url_problem("  ").is_some());
        assert!(remote_url_problem("--upload-pack=x").is_some());
        assert!(remote_url_problem("https://h/r.git").is_none());
    }

    #[test]
    fn menu_depends_on_level_and_upstream() {
        let beginner = menu_items(Level::Beginner, true);
        assert!(!beginner.contains(&Item::ForcePush));
        assert!(!beginner.contains(&Item::PushSetUpstream));
        let pro = menu_items(Level::Pro, false);
        assert!(pro.contains(&Item::ForcePush) && pro.contains(&Item::PushSetUpstream));
        assert!(branch_name(&Head::Detached { oid: "a".into() }).is_err());
    }

    #[test]
    fn login_uses_active_account() {
        let mut cfg = Config::default();
        assert_eq!(login_of(&cfg), None);
        cfg.accounts.push(crate::accounts::Account {
            label: "w".into(),
            name: String::new(),
            email: String::new(),
            github_username: "octo".into(),
        });
        cfg.active_account = Some("w".into());
        assert_eq!(login_of(&cfg).as_deref(), Some("octo"));
    }

    #[test]
    fn push_to_second_default_remote() {
        let repo = TempRepo::new(2).with_remote();
        let second = repo.path().parent().unwrap().join("second.git");
        repo.git(&[
            "init",
            "-q",
            "--bare",
            "-b",
            "main",
            &second.to_string_lossy(),
        ]);
        repo.git(&["remote", "add", "second", &second.to_string_lossy()]);
        let cfg = Config {
            default_remote: "second".into(),
            ..Config::default()
        };
        let want = repo.git(&["rev-parse", "HEAD"]);
        repo.run(|| {
            let remotes = remote_names().unwrap();
            let RemoteChoice::Use(remote) =
                choose_remote(&cfg.default_remote, &remotes, Some("origin/main"))
            else {
                panic!("expected a remote");
            };
            assert_eq!(remote, "second");
            git::push_to(&remote, "main", None, true, None).unwrap();
        });
        assert_eq!(
            repo.git(&["--git-dir", &second.to_string_lossy(), "rev-parse", "main"]),
            want
        );
        assert_eq!(
            repo.git(&["rev-parse", "--abbrev-ref", "@{u}"]),
            "second/main"
        );
    }

    #[test]
    fn force_push_to_main_is_denied() {
        let cfg = Config::default();
        let verdict = policy::check(
            &cfg,
            &Op::ForcePush {
                remote: "origin",
                branch: "main",
            },
        );
        assert!(matches!(verdict, Verdict::Deny(_)));
        let other = policy::check(
            &cfg,
            &Op::ForcePush {
                remote: "origin",
                branch: "feat",
            },
        );
        assert_eq!(other, Verdict::Danger);
    }

    fn other_clone(repo: &TempRepo) -> String {
        let dir = repo.path().parent().unwrap().join("other");
        let dir = dir.to_string_lossy().into_owned();
        repo.git(&["clone", "-q", &repo.remote_path().to_string_lossy(), &dir]);
        dir
    }

    fn commit_in(repo: &TempRepo, dir: &str, file: &str, branch: Option<&str>) {
        if let Some(branch) = branch {
            repo.git(&["-C", dir, "checkout", "-q", branch]);
        }
        std::fs::write(std::path::Path::new(dir).join(file), "x\n").unwrap();
        repo.git(&["-C", dir, "add", "."]);
        repo.git(&[
            "-C",
            dir,
            "-c",
            "user.name=O",
            "-c",
            "user.email=o@e.com",
            "commit",
            "-q",
            "-m",
            file,
        ]);
        repo.git(&["-C", dir, "push", "-q"]);
    }

    #[test]
    fn fetch_then_ff_pull_round_trip() {
        let repo = TempRepo::new(2).with_remote();
        let dir = other_clone(&repo);
        commit_in(&repo, &dir, "new.txt", None);
        let cancel = AtomicBool::new(false);
        repo.run(|| {
            assert!(matches!(
                run_fetch(Some("origin"), &cancel).unwrap(),
                Net::Done(_)
            ));
            assert!(matches!(run_fetch(None, &cancel).unwrap(), Net::Done(_)));
            let state = repo_state::load().unwrap();
            assert_eq!(state.branch.behind, 1);
            let (net, _, _) = run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap();
            assert!(matches!(net, Net::Done(_)), "{net:?}");
            assert_eq!(repo_state::load().unwrap().branch.behind, 0);
        });
        assert!(repo.path().join("new.txt").exists());
    }

    #[test]
    fn diverged_ff_pull_is_classified() {
        let repo = TempRepo::new(2).with_remote();
        let dir = other_clone(&repo);
        commit_in(&repo, &dir, "theirs.txt", None);
        repo.write("mine.txt", "m\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "mine"]);
        let cancel = AtomicBool::new(false);
        repo.run(|| {
            let (Net::Failed(text), _, _) =
                run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap()
            else {
                panic!("ff pull should fail");
            };
            assert_eq!(classify_pull_error(&text), PullError::Diverged, "{text}");
            let Net::Failed(text) = git::push_to("origin", "main", None, false, None)
                .map(Net::Done)
                .unwrap_or_else(|e| Net::Failed(format!("{e:#}")))
            else {
                panic!("push should be rejected");
            };
            assert_eq!(classify_push_error(&text), PushError::Rejected, "{text}");
            assert!(matches!(
                run_pull(PullChoice::Merge, "origin", "main", &cancel)
                    .unwrap()
                    .0,
                Net::Done(_)
            ));
        });
    }

    /// Commits `file` = `text` in the other clone `dir` (no push).
    fn commit_text(repo: &TempRepo, dir: &str, file: &str, text: &str, extra: &[&str]) {
        std::fs::write(std::path::Path::new(dir).join(file), text).unwrap();
        repo.git(&["-C", dir, "add", "."]);
        let mut args = vec![
            "-C",
            dir,
            "-c",
            "user.name=O",
            "-c",
            "user.email=o@e.com",
            "commit",
            "-q",
            "-m",
            file,
        ];
        args.extend_from_slice(extra);
        repo.git(&args);
    }

    #[test]
    fn pull_works_without_a_tracking_ref() {
        for choice in [
            PullChoice::FastForward,
            PullChoice::Rebase,
            PullChoice::Merge,
        ] {
            let repo = TempRepo::new(2).with_remote();
            let dir = other_clone(&repo);
            repo.git(&["-C", &dir, "checkout", "-q", "-b", "feat"]);
            commit_text(&repo, &dir, "theirs.txt", "t\n", &[]);
            repo.git(&["-C", &dir, "push", "-q", "origin", "feat"]);
            // A fetch refspec that does not cover feat (like a single-branch clone).
            repo.git(&[
                "config",
                "remote.origin.fetch",
                "+refs/heads/main:refs/remotes/origin/main",
            ]);
            repo.git(&["checkout", "-q", "-b", "feat"]);
            if choice != PullChoice::FastForward {
                repo.write("mine.txt", "m\n");
                repo.git(&["add", "."]);
                repo.git(&["commit", "-q", "-m", "mine"]);
            }
            let cancel = AtomicBool::new(false);
            repo.run(|| {
                let (net, _, command) = run_pull(choice, "origin", "feat", &cancel).unwrap();
                assert!(matches!(net, Net::Done(_)), "{choice:?}: {net:?}");
                assert!(
                    command.starts_with("fetch origin refs/heads/feat && git "),
                    "{command}"
                );
            });
            assert!(repo.path().join("theirs.txt").exists(), "{choice:?}");
            assert_eq!(
                repo.git(&["for-each-ref", "refs/remotes/origin/feat"]),
                "",
                "no tracking ref was made"
            );
            assert_eq!(repo.git(&["status", "--porcelain"]), "");
        }
    }

    #[test]
    fn rebase_after_upstream_force_push_replays_only_my_commits() {
        let repo = TempRepo::new(2).with_remote();
        let dir = other_clone(&repo);
        commit_text(&repo, &dir, "shared.txt", "b1\n", &[]);
        repo.git(&["-C", &dir, "push", "-q"]);
        repo.git(&["pull", "-q", "--ff-only"]);
        repo.write("mine.txt", "m\n");
        repo.git(&["add", "."]);
        repo.git(&["commit", "-q", "-m", "mine"]);
        // Upstream rewrites the commit we already built on.
        commit_text(&repo, &dir, "shared.txt", "b2\n", &["--amend"]);
        repo.git(&["-C", &dir, "push", "-q", "--force"]);
        let cancel = AtomicBool::new(false);
        repo.run(|| {
            let (net, backup, command) =
                run_pull(PullChoice::Rebase, "origin", "main", &cancel).unwrap();
            assert!(matches!(net, Net::Done(_)), "{net:?}");
            assert!(backup.is_some());
            assert!(command.contains("rebase --onto FETCH_HEAD "), "{command}");
            assert_eq!(repo_state::load().unwrap().op, None);
        });
        let upstream = repo.git(&[
            "--git-dir",
            &repo.remote_path().to_string_lossy(),
            "rev-parse",
            "main",
        ]);
        assert_eq!(repo.git(&["rev-parse", "HEAD~1"]), upstream);
        assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "mine");
        let shared = std::fs::read_to_string(repo.path().join("shared.txt")).unwrap();
        assert_eq!(shared.replace('\r', ""), "b2\n");
    }

    #[test]
    fn failed_fetch_leaves_the_repo_untouched() {
        let repo = TempRepo::new(2).with_remote();
        let before = repo.git(&["rev-parse", "HEAD"]);
        let cancel = AtomicBool::new(false);
        for choice in PullChoice::ALL {
            repo.run(|| {
                let (net, backup, _) =
                    run_pull(choice, "origin", "no-such-branch", &cancel).unwrap();
                assert!(matches!(net, Net::Failed(_)), "{net:?}");
                assert!(backup.is_none());
            });
        }
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), before);
        assert_eq!(repo.git(&["for-each-ref", "refs/gct/"]), "");
        assert_eq!(repo.git(&["status", "--porcelain"]), "");
    }

    #[test]
    fn force_with_lease_overwrites_and_detects_stale() {
        let repo = TempRepo::new(2).with_remote();
        repo.git(&["checkout", "-q", "-b", "feat"]);
        repo.git(&["push", "-q", "-u", "origin", "feat"]);
        repo.git(&["commit", "-q", "--amend", "-m", "rewritten"]);
        let local = repo.git(&["rev-parse", "HEAD"]);
        repo.run(|| {
            let lease = lease_for("origin", "feat").unwrap();
            assert!(lease.starts_with("refs/heads/feat:"));
            git::push_to("origin", "feat", Some(&lease), false, None).unwrap();
        });
        assert_eq!(
            repo.git(&[
                "--git-dir",
                &repo.remote_path().to_string_lossy(),
                "rev-parse",
                "feat"
            ]),
            local
        );
        // Someone else pushes; our lease is now stale and the push must be refused.
        let dir = other_clone(&repo);
        commit_in(&repo, &dir, "o.txt", Some("feat"));
        repo.git(&["commit", "-q", "--amend", "-m", "again"]);
        repo.run(|| {
            let lease = lease_for("origin", "feat").unwrap();
            let error = git::push_to("origin", "feat", Some(&lease), false, None).unwrap_err();
            assert_eq!(
                classify_push_error(&format!("{error:#}")),
                PushError::Rejected,
                "{error:#}"
            );
            assert!(lease_for("origin", "nope").is_err());
        });
    }
}