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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
//! Conflicts mode: the one place that finishes or cancels an in-progress merge, rebase,
//! cherry-pick, revert or `git am`.
//!
//! State is re-read from git on every redraw (git keeps its own state on disk, so a crash or a
//! restart needs nothing else). Per conflicted file: keep one side (labels follow the operation,
//! because "ours"/"theirs" swap during a rebase), keep or delete a file in a delete/modify
//! conflict, edit in `$VISUAL`/`$EDITOR`, mark resolved, view the diff, or run the merge tool.
//! Globally: continue, skip (rebase/cherry-pick/revert/am) and abort (with a backup ref first).

use crate::{
    git::{self, Opts},
    input,
    model::Config,
    policy,
    repo_state::{self, Entry, Head, InProgress, RepoState},
    safety, screen, ui,
};
use anyhow::{bail, Result};
use std::collections::BTreeSet;
use std::path::Path;

/// How to end the operation in progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Finish {
    Continue,
    Skip,
    Abort,
}

/// One side of a conflict as git names it (index stage 2 = ours, 3 = theirs).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Ours,
    Theirs,
}

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

/// Plain-English kind of a conflicted entry from its porcelain `XY` letters. "Here" is the
/// checked-out side (HEAD), "incoming" the side being merged, picked or replayed.
pub fn conflict_kind(x: char, y: char) -> &'static str {
    match (x, y) {
        ('U', 'U') => "both sides changed it",
        ('A', 'A') => "both sides added it",
        ('D', 'U') => "deleted here, changed by the incoming side",
        ('U', 'D') => "changed here, deleted by the incoming side",
        ('A', 'U') => "added here only",
        ('U', 'A') => "added by the incoming side only",
        ('D', 'D') => "deleted on both sides",
        _ => "conflicted",
    }
}

/// True for the conflicts that are about a file existing at all (keep it or delete it).
pub fn is_delete_kind(x: char, y: char) -> bool {
    !matches!((x, y), ('U', 'U') | ('A', 'A'))
}

/// True when a line starts with a git conflict marker: `<<<<<<< `, a lone `=======`, or
/// `>>>>>>> ` (also `|||||||` of diff3 style). CRLF-safe; markers inside a line do not count.
pub fn has_conflict_markers(bytes: &[u8]) -> bool {
    fn marker(line: &[u8], mark: &[u8]) -> bool {
        line.strip_prefix(mark)
            .is_some_and(|rest| rest.is_empty() || rest[0] == b' ')
    }
    bytes.split(|b| *b == b'\n').any(|line| {
        let line = line.strip_suffix(b"\r").unwrap_or(line);
        line == b"======="
            || marker(line, b"<<<<<<<")
            || marker(line, b">>>>>>>")
            || marker(line, b"|||||||")
    })
}

/// The git arguments that continue, skip or abort `op`. None when the action does not apply
/// (a merge has no skip; bisect is not finished here).
pub fn continue_args(op: InProgress, action: Finish) -> Option<Vec<&'static str>> {
    let flag = match action {
        Finish::Continue => "--continue",
        Finish::Skip => "--skip",
        Finish::Abort => "--abort",
    };
    let command = match op {
        InProgress::Merge => {
            return match action {
                Finish::Continue => Some(vec!["commit", "--no-edit"]),
                Finish::Abort => Some(vec!["merge", "--abort"]),
                Finish::Skip => None,
            }
        }
        InProgress::Bisect => return None,
        InProgress::Rebase => "rebase",
        InProgress::CherryPick => "cherry-pick",
        InProgress::Revert => "revert",
        InProgress::Am => "am",
    };
    Some(vec![command, flag])
}

fn read_trimmed(git_dir: &Path, rel: &str) -> Option<String> {
    std::fs::read_to_string(git_dir.join(rel))
        .ok()
        .map(|text| text.trim().to_string())
        .filter(|text| !text.is_empty())
}

fn short(oid: &str) -> String {
    oid.chars().take(7).collect()
}

/// The branch named in a merge message ("Merge branch 'x' into y" -> "x").
pub fn merge_branch(message: &str) -> Option<String> {
    let first = message.lines().next()?;
    let start = first.find('\'')? + 1;
    let len = first[start..].find('\'')?;
    Some(first[start..start + len].to_string()).filter(|name| !name.is_empty())
}

/// The rebase state directory in use ("rebase-merge" or "rebase-apply").
fn rebase_dir(git_dir: &Path) -> &'static str {
    if git_dir.join("rebase-merge").is_dir() {
        "rebase-merge"
    } else {
        "rebase-apply"
    }
}

/// ", step N of M" from two counter files, or "" when they are missing.
fn step(git_dir: &Path, dir: &str, num: &str, end: &str, noun: &str) -> String {
    let number = |file: &str| {
        read_trimmed(git_dir, &format!("{dir}/{file}")).and_then(|t| t.parse::<u32>().ok())
    };
    match (number(num), number(end)) {
        (Some(n), Some(m)) => format!(", {noun} {n} of {m}"),
        _ => String::new(),
    }
}

/// One-line description of the operation, from git's state files (best effort).
pub fn describe_op(op: InProgress, git_dir: &Path) -> String {
    match op {
        InProgress::Rebase => {
            let dir = rebase_dir(git_dir);
            let branch = read_trimmed(git_dir, &format!("{dir}/head-name"))
                .filter(|head| head != "detached HEAD")
                .map(|head| {
                    head.strip_prefix("refs/heads/")
                        .unwrap_or(&head)
                        .to_string()
                })
                .unwrap_or_else(|| "a detached HEAD".into());
            let onto = read_trimmed(git_dir, &format!("{dir}/onto"))
                .map(|oid| short(&oid))
                .unwrap_or_else(|| "its new base".into());
            let (num, end) = if dir == "rebase-merge" {
                ("msgnum", "end")
            } else {
                ("next", "last")
            };
            format!(
                "Rebasing {branch} onto {onto}{}",
                step(git_dir, dir, num, end, "step")
            )
        }
        InProgress::Merge => {
            match read_trimmed(git_dir, "MERGE_MSG").and_then(|m| merge_branch(&m)) {
                Some(branch) => format!("Merging {branch}"),
                None => "Merging (a merge is in progress)".into(),
            }
        }
        InProgress::CherryPick => match read_trimmed(git_dir, "CHERRY_PICK_HEAD") {
            Some(oid) => format!("Cherry-picking {}", short(&oid)),
            None => "Cherry-picking a commit".into(),
        },
        InProgress::Revert => match read_trimmed(git_dir, "REVERT_HEAD") {
            Some(oid) => format!("Reverting {}", short(&oid)),
            None => "Reverting a commit".into(),
        },
        InProgress::Am => format!(
            "Applying patches (git am){}",
            step(git_dir, "rebase-apply", "next", "last", "patch")
        ),
        InProgress::Bisect => "A bisect is running".into(),
    }
}

/// The incoming side's name: the merged branch, or the short hash being replayed/picked.
fn incoming_name(op: InProgress, git_dir: &Path) -> String {
    let oid = |file: &str| read_trimmed(git_dir, file).map(|oid| short(&oid));
    match op {
        InProgress::Merge => read_trimmed(git_dir, "MERGE_MSG").and_then(|m| merge_branch(&m)),
        InProgress::Rebase => oid("REBASE_HEAD").or_else(|| oid("rebase-merge/stopped-sha")),
        InProgress::CherryPick => oid("CHERRY_PICK_HEAD"),
        InProgress::Revert => oid("REVERT_HEAD"),
        InProgress::Am | InProgress::Bisect => None,
    }
    .unwrap_or_default()
}

/// Short footer labels for the `o` and `t` keys.
pub fn side_keys(op: Option<InProgress>) -> [&'static str; 2] {
    match op {
        Some(InProgress::Rebase) => ["keep upstream", "keep my change"],
        Some(InProgress::Merge) => ["keep mine", "keep theirs"],
        Some(InProgress::CherryPick) => ["keep current", "keep picked"],
        Some(InProgress::Revert) => ["keep current", "keep revert"],
        Some(InProgress::Am) => ["keep current", "keep patch"],
        None | Some(InProgress::Bisect) => ["keep current", "keep stashed"],
    }
}

/// Menu titles for keeping git's "ours" and "theirs" side. During a rebase "ours" is the branch
/// being replayed onto (`current` = its name) and "theirs" is your commit (`incoming`).
pub fn side_titles(op: Option<InProgress>, current: &str, incoming: &str) -> [String; 2] {
    let named = |text: &str, name: &str| {
        if name.is_empty() {
            text.to_string()
        } else {
            format!("{text} ({name})")
        }
    };
    match op {
        Some(InProgress::Rebase) => [
            named("Keep upstream", current),
            named("Keep my change", incoming),
        ],
        Some(InProgress::Merge) => [
            "Keep mine (current branch)".into(),
            named("Keep theirs", incoming),
        ],
        Some(InProgress::CherryPick) => [
            named("Keep current branch", current),
            named("Keep the picked commit", incoming),
        ],
        Some(InProgress::Revert) => [
            named("Keep current branch", current),
            named("Keep the revert", incoming),
        ],
        Some(InProgress::Am) => [
            named("Keep current branch", current),
            "Keep the patch".into(),
        ],
        None | Some(InProgress::Bisect) => [
            "Keep the current version".into(),
            "Keep the stashed version".into(),
        ],
    }
}

fn op_noun(op: InProgress) -> &'static str {
    match op {
        InProgress::Merge => "merge",
        InProgress::Rebase => "rebase",
        InProgress::CherryPick => "cherry-pick",
        InProgress::Revert => "revert",
        InProgress::Am => "patch series (git am)",
        InProgress::Bisect => "bisect",
    }
}

/// Why continuing is not allowed yet; empty when it is.
pub fn continue_blockers(conflicted: &[String], with_markers: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    if !conflicted.is_empty() {
        out.push(format!(
            "{} file(s) still conflicted: {}",
            conflicted.len(),
            conflicted.join(", ")
        ));
    }
    if !with_markers.is_empty() {
        out.push(format!(
            "Conflict markers are still in: {} (mark them resolved again to confirm)",
            with_markers.join(", ")
        ));
    }
    out
}

// ---------------------------------------------------------------------------------------------
// Executors (no UI; tested with TempRepo)
// ---------------------------------------------------------------------------------------------

/// A pathspec for a repo-root-relative path that ignores the current directory and glob magic.
fn spec(path: &str) -> String {
    format!(":(top,literal){path}")
}

fn run_ok(args: &[&str]) -> Result<String> {
    git::git_ok(args, &Opts::default())
}

/// Keeps one side's version of `path` and stages it. When that side deleted the file, the file
/// is removed instead. Returns the commands that ran.
pub fn take_side(path: &str, side: Side) -> Result<Vec<String>> {
    let flag = match side {
        Side::Ours => "--ours",
        Side::Theirs => "--theirs",
    };
    let p = spec(path);
    let out = git::git_raw(&["checkout", flag, "--", &p], &Opts::default())?;
    if out.ok() {
        run_ok(&["add", "-A", "--", &p])?;
        return Ok(vec![
            format!("git checkout {flag} -- {path}"),
            format!("git add -- {path}"),
        ]);
    }
    if out.stderr.contains("does not have") {
        return delete_file(path);
    }
    bail!("{}", out.stderr.trim())
}

/// Stages `path` as it is in the working tree (mark resolved / keep the file).
pub fn keep_file(path: &str) -> Result<Vec<String>> {
    run_ok(&["add", "-A", "--", &spec(path)])?;
    Ok(vec![format!("git add -- {path}")])
}

/// Resolves by deleting `path`.
pub fn delete_file(path: &str) -> Result<Vec<String>> {
    run_ok(&["rm", "-q", "--ignore-unmatch", "--", &spec(path)])?;
    Ok(vec![format!("git rm -- {path}")])
}

/// True when the user has already changed `path` by hand, so taking a side would throw those
/// edits away. `current` is the working file; `stages` are the index blobs of the sides.
/// A text conflict that still has markers is untouched. Otherwise (markers resolved by hand, a
/// binary conflict, a delete/modify conflict: no markers ever) the file counts as edited when it
/// matches none of the index stages (base, ours, theirs).
pub fn has_manual_edits(current: Option<&[u8]>, delete_kind: bool, stages: &[Vec<u8>]) -> bool {
    let Some(current) = current else {
        return false;
    };
    if !delete_kind && has_conflict_markers(current) {
        return false;
    }
    let norm = |bytes: &[u8]| {
        bytes
            .iter()
            .copied()
            .filter(|b| *b != b'\r')
            .collect::<Vec<u8>>()
    };
    let current = norm(current);
    !stages.iter().any(|stage| norm(stage) == current)
}

/// Reads `path` and its side blobs, then asks `has_manual_edits`.
pub fn edited_by_user(workdir: &Path, path: &str, delete_kind: bool) -> bool {
    let current = std::fs::read(workdir.join(path)).ok();
    let mut stages = Vec::new();
    let markers = current.as_deref().is_some_and(has_conflict_markers);
    if delete_kind || !markers {
        for stage in [1, 2, 3] {
            if let Ok(out) = git::git_raw(&["show", &format!(":{stage}:{path}")], &Opts::default())
            {
                if out.ok() {
                    stages.push(out.stdout);
                }
            }
        }
    }
    has_manual_edits(current.as_deref(), delete_kind, &stages)
}

/// Paths named by `git diff --cached --check` as holding leftover conflict markers.
pub fn parse_marker_check(output: &str) -> Vec<String> {
    let mut paths: Vec<String> = Vec::new();
    for line in output.lines() {
        let Some((head, _)) = line.split_once(": leftover conflict marker") else {
            continue;
        };
        let path = head.rsplit_once(':').map_or(head, |(path, _line)| path);
        if !paths.iter().any(|known| known == path) {
            paths.push(path.to_string());
        }
    }
    paths
}

/// Files whose staged content still has conflict markers, including ones staged before this
/// mode opened.
pub fn staged_marker_files() -> Result<Vec<String>> {
    let out = git::git_raw(&["diff", "--cached", "--check"], &Opts::default())?;
    Ok(parse_marker_check(&String::from_utf8_lossy(&out.stdout)))
}

/// Backs up HEAD, then skips the current commit. Returns git's result and the backup ref.
pub fn skip_op(op: InProgress) -> Result<(git::Out, String)> {
    let backup = safety::backup("skip", "HEAD")?;
    let out = finish(op, Finish::Skip)?;
    Ok((out, backup))
}

/// Runs `git mergetool` for `path` on the real terminal (no timeout, inherited stdio), so
/// terminal tools get a terminal, GUI tools may run as long as they like and git's own
/// `git add` of the result happens.
fn run_mergetool(workdir: &Path, path: &str) -> Result<std::process::ExitStatus> {
    Ok(std::process::Command::new("git")
        .args(["mergetool", "--no-prompt", "--", path])
        .current_dir(workdir)
        .env("GIT_LITERAL_PATHSPECS", "1")
        .env_remove("GIT_TERMINAL_PROMPT")
        .status()?)
}

/// Runs continue/skip/abort for `op`; the result carries git's exit code (a rebase that stops
/// again at the next commit exits non-zero).
pub fn finish(op: InProgress, action: Finish) -> Result<git::Out> {
    let Some(args) = continue_args(op, action) else {
        bail!("A {} cannot be finished that way here", op_noun(op));
    };
    git::git_raw(&args, &Opts::default())
}

/// Files (from `watched`, not `confirmed`) that still contain conflict markers on disk.
fn files_with_markers(
    workdir: &Path,
    watched: &BTreeSet<String>,
    confirmed: &BTreeSet<String>,
) -> Vec<String> {
    watched
        .iter()
        .filter(|path| !confirmed.contains(*path))
        .filter(|path| {
            std::fs::read(workdir.join(path)).is_ok_and(|bytes| has_conflict_markers(&bytes))
        })
        .cloned()
        .collect()
}

/// Continues the operation in progress unless files are still conflicted or `watched` files
/// still hold markers the user has not confirmed.
pub fn continue_op(watched: &BTreeSet<String>, confirmed: &BTreeSet<String>) -> Result<git::Out> {
    let state = repo_state::load()?;
    let Some(op) = state.op else {
        bail!("Nothing is in progress, so there is nothing to continue.");
    };
    let conflicted: Vec<String> = state
        .entries
        .iter()
        .filter(|e| e.conflicted())
        .map(|e| e.path.clone())
        .collect();
    let markers = files_with_markers(&state.workdir, watched, confirmed);
    let blockers = continue_blockers(&conflicted, &markers);
    if !blockers.is_empty() {
        bail!("{}", blockers.join("\n"));
    }
    finish(op, Finish::Continue)
}

/// Backs up HEAD, then aborts `op`. Returns the backup ref name.
pub fn abort_op(op: InProgress) -> Result<String> {
    let backup = safety::backup("abort", "HEAD")?;
    let out = finish(op, Finish::Abort)?;
    if !out.ok() {
        bail!("{}\n(backup kept at {backup})", out.stderr.trim());
    }
    Ok(backup)
}

/// Branch name pointing at the rebase's `onto` commit, when there is one.
fn onto_name(git_dir: &Path) -> Option<String> {
    let oid = read_trimmed(git_dir, &format!("{}/onto", rebase_dir(git_dir)))?;
    let refs = run_ok(&[
        "for-each-ref",
        "--points-at",
        &oid,
        "--format=%(refname:short)",
        "refs/heads",
        "refs/remotes",
    ])
    .ok()?;
    refs.lines()
        .find(|name| !name.ends_with("/HEAD"))
        .map(str::to_string)
}

fn merge_tool_set() -> bool {
    run_ok(&["config", "merge.tool"]).is_ok_and(|tool| !tool.trim().is_empty())
}

fn edit_file(path: &Path) -> Result<()> {
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| {
            if cfg!(windows) {
                "notepad".into()
            } else {
                "vi".into()
            }
        });
    let mut parts = input::split_command(&editor).into_iter();
    let Some(program) = parts.next() else {
        bail!("The editor command ($VISUAL / $EDITOR) is empty");
    };
    let args: Vec<String> = parts.collect();
    let status = ui::suspended(|| Ok(input::run_editor(&program, &args, path)?))?;
    if !status.success() {
        bail!("The editor exited with {status}");
    }
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// UI glue
// ---------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Act {
    Side(Side),
    Keep,
    Delete,
    Edit,
    Mark,
    Diff,
    Tool,
    Finish(Finish),
    Refresh,
}

/// What the screen shows about the operation, rebuilt on each redraw.
struct View {
    op: Option<InProgress>,
    title: String,
    sides: [String; 2],
    keys: [&'static str; 2],
    tool: bool,
}

impl View {
    fn new(state: &RepoState) -> View {
        let branch = match &state.branch.head {
            Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
            Head::Detached { oid } => short(oid),
        };
        let op = state.op;
        let (title, current, incoming) = match op {
            Some(op) => {
                let mut title = describe_op(op, &state.git_dir);
                let mut current = branch;
                if op == InProgress::Rebase {
                    let onto = read_trimmed(
                        &state.git_dir,
                        &format!("{}/onto", rebase_dir(&state.git_dir)),
                    );
                    current = onto.as_deref().map(short).unwrap_or_default();
                    if let Some(name) = onto_name(&state.git_dir) {
                        if !current.is_empty() {
                            title = title.replacen(&current, &name, 1);
                        }
                        current = name;
                    }
                }
                (title, current, incoming_name(op, &state.git_dir))
            }
            None => (
                "Conflicts with nothing in progress".to_string(),
                branch,
                String::new(),
            ),
        };
        View {
            op,
            title,
            sides: side_titles(op, &current, &incoming),
            keys: side_keys(op),
            tool: merge_tool_set(),
        }
    }

    fn can_skip(&self) -> bool {
        matches!(
            self.op,
            Some(InProgress::Rebase | InProgress::CherryPick | InProgress::Revert | InProgress::Am)
        )
    }
}

#[derive(Default)]
struct Session {
    /// Every path seen conflicted this session (scanned for markers before continuing).
    watched: BTreeSet<String>,
    /// Paths the user marked resolved although markers remained.
    confirmed: BTreeSet<String>,
    status: Option<String>,
    index: usize,
}

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let mut session = Session::default();
    loop {
        let state = repo_state::load()?;
        let conflicted: Vec<&Entry> = state.entries.iter().filter(|e| e.conflicted()).collect();
        session
            .watched
            .extend(conflicted.iter().map(|e| e.path.clone()));
        match state.op {
            Some(InProgress::Bisect) => {
                return ui::notice(
                    "Conflicts",
                    &[
                        "A bisect is running. That is not a conflict, so it is not finished here."
                            .into(),
                        screen::muted(
                            "Finish it with `git bisect reset` (or the mode that started it).",
                        ),
                    ],
                )
            }
            None if conflicted.is_empty() => return nothing_to_resolve(config),
            _ => {}
        }
        let view = View::new(&state);
        let header = header(config, &view, conflicted.len(), session.status.take());
        let mut rows: Vec<String> = conflicted
            .iter()
            .map(|e| {
                format!(
                    "{}  {}",
                    e.path,
                    screen::muted(format!("({})", conflict_kind(e.x, e.y)))
                )
            })
            .collect();
        if let Some(op) = view.op {
            rows.push(screen::accent(format!(
                "> Finish: continue, skip or abort the {}",
                op_noun(op)
            )));
        }
        let keys = keys(&view, &conflicted);
        let choice = ui::action_list("Conflicts", &header, &rows, &keys, &mut session.index)?;
        let (act, entry) = match choice {
            ui::Choice::Back => return Ok(()),
            ui::Choice::Open(i) => match menu(&view, conflicted.get(i).copied())? {
                Some(act) => (act, conflicted.get(i).copied()),
                None => continue,
            },
            ui::Choice::Action(key, i) => match key_act(key) {
                Some(act) => (act, conflicted.get(i).copied()),
                None => continue,
            },
        };
        if act_on(config, &mut session, &state, &view, entry, act)? {
            return Ok(());
        }
    }
}

fn header(cfg: &Config, view: &View, left: usize, status: Option<String>) -> Vec<String> {
    let mut lines = vec![screen::accent(&view.title)];
    if view.op.is_none() {
        lines.push(screen::warning(
            "Probably from `git stash pop` / `stash apply`. Stash conflicts have no abort:",
        ));
        lines.push(screen::muted(
            "fix each file, mark it resolved, then run `git reset` to unstage; drop the stash in Stash mode.",
        ));
    }
    lines.push(if left > 0 {
        screen::warning(format!("! {left} file(s) still conflicted"))
    } else {
        screen::success("All conflicts resolved: press C to continue")
    });
    lines.extend(ui::explain(
        cfg,
        &[
            "Each file below has parts from both sides. Keep one side, or edit the file and mark it resolved.",
            "When no file is left, continue to finish; abort puts everything back as it was before.",
        ],
    ));
    if let Some(status) = status {
        lines.push(status);
    }
    lines
}

fn keys(view: &View, conflicted: &[&Entry]) -> Vec<ui::Key> {
    let key = |key: char, label: &'static str| ui::Key { key, label };
    let mut keys = Vec::new();
    if !conflicted.is_empty() {
        keys.extend([key('o', view.keys[0]), key('t', view.keys[1])]);
        if conflicted.iter().any(|e| is_delete_kind(e.x, e.y)) {
            keys.extend([key('k', "keep file"), key('x', "delete file")]);
        }
        keys.extend([
            key('e', "edit"),
            key('m', "mark resolved"),
            key('d', "diff"),
        ]);
        if view.tool {
            keys.push(key('g', "merge tool"));
        }
    }
    if view.op.is_some() {
        keys.push(key('C', "continue"));
        if view.can_skip() {
            keys.push(key('n', "skip commit"));
        }
        keys.push(key('A', "abort"));
    }
    keys.push(key('r', "refresh"));
    keys
}

fn key_act(key: char) -> Option<Act> {
    Some(match key {
        'o' => Act::Side(Side::Ours),
        't' => Act::Side(Side::Theirs),
        'k' => Act::Keep,
        'x' => Act::Delete,
        'e' => Act::Edit,
        'm' => Act::Mark,
        'd' => Act::Diff,
        'g' => Act::Tool,
        'C' => Act::Finish(Finish::Continue),
        'n' => Act::Finish(Finish::Skip),
        'A' => Act::Finish(Finish::Abort),
        'r' => Act::Refresh,
        _ => return None,
    })
}

/// The Enter menu: file actions for a file row, then the global actions.
fn menu(view: &View, entry: Option<&Entry>) -> Result<Option<Act>> {
    let mut options: Vec<(String, Act)> = Vec::new();
    let mut context = Vec::new();
    if let Some(e) = entry {
        context.push(format!(
            "{}  {}",
            screen::accent(&e.path),
            screen::muted(conflict_kind(e.x, e.y))
        ));
        if is_delete_kind(e.x, e.y) {
            options.push(("Keep the file (git add)".into(), Act::Keep));
            options.push(("Delete the file (git rm)".into(), Act::Delete));
        } else {
            options.push((view.sides[0].clone(), Act::Side(Side::Ours)));
            options.push((view.sides[1].clone(), Act::Side(Side::Theirs)));
        }
        options.push(("Edit in your editor".into(), Act::Edit));
        options.push(("Mark resolved".into(), Act::Mark));
        options.push(("Show the diff".into(), Act::Diff));
        if view.tool {
            options.push(("Open the merge tool".into(), Act::Tool));
        }
    }
    if let Some(op) = view.op {
        let noun = op_noun(op);
        options.push((
            format!("Continue the {noun}"),
            Act::Finish(Finish::Continue),
        ));
        if view.can_skip() {
            options.push(("Skip this commit".into(), Act::Finish(Finish::Skip)));
        }
        options.push((format!("Abort the {noun}"), Act::Finish(Finish::Abort)));
    }
    options.push(("Refresh".into(), Act::Refresh));
    let labels: Vec<&str> = options.iter().map(|(label, _)| label.as_str()).collect();
    Ok(ui::choose("Conflicts", &context, &labels)?
        .and_then(|i| options.get(i).map(|(_, act)| *act)))
}

fn done(commands: &[String], what: String) -> String {
    format!(
        "{} {}",
        screen::success(format!("ok: {what}")),
        screen::muted(format!("($ {})", commands.join("; ")))
    )
}

/// Runs one action; true when the mode should close.
fn act_on(
    cfg: &mut Config,
    s: &mut Session,
    state: &RepoState,
    view: &View,
    entry: Option<&Entry>,
    act: Act,
) -> Result<bool> {
    if let Act::Finish(action) = act {
        return finish_flow(cfg, s, view, action);
    }
    if act == Act::Refresh {
        return Ok(false);
    }
    let Some(e) = entry else {
        s.status = Some(screen::warning("Pick a file first."));
        return Ok(false);
    };
    let path = e.path.as_str();
    let full = state.workdir.join(path);
    match act {
        Act::Side(side) => {
            let (title, flag) = match side {
                Side::Ours => (&view.sides[0], "--ours"),
                Side::Theirs => (&view.sides[1], "--theirs"),
            };
            let command = format!("git checkout {flag} -- {path} && git add -- {path}");
            let edited = edited_by_user(&state.workdir, path, is_delete_kind(e.x, e.y));
            let go = if edited {
                let what =
                    format!("{title} for {path}? Your manual edits in this file will be replaced.");
                let verdict = policy::check(cfg, &policy::Op::DiscardUnstaged);
                ui::gate(cfg, &verdict, &what, &command)?
            } else {
                ui::confirm_action(
                    cfg,
                    &format!("{title} for {path}? Edits in this file are replaced."),
                    &command,
                )?
            };
            if go {
                s.status = Some(match take_side(path, side) {
                    Ok(cmds) => done(&cmds, format!("{title}: {path}")),
                    Err(error) => screen::danger(format!("x {error}")),
                });
            }
        }
        Act::Keep | Act::Delete if !is_delete_kind(e.x, e.y) => {
            s.status = Some(screen::warning(
                "Both sides have this file: keep one side (o/t) or edit it, then mark it resolved.",
            ));
        }
        Act::Keep => s.status = Some(result(keep_file(path), format!("kept {path}"))),
        Act::Delete => {
            if ui::confirm_action(
                cfg,
                &format!("Delete {path} to resolve the conflict?"),
                &format!("git rm -- {path}"),
            )? {
                s.status = Some(result(delete_file(path), format!("deleted {path}")));
            }
        }
        Act::Edit => {
            if let Err(error) = edit_file(&full) {
                s.status = Some(screen::danger(format!("x {error}")));
                return Ok(false);
            }
            let markers = std::fs::read(&full).is_ok_and(|b| has_conflict_markers(&b));
            if markers {
                s.status = Some(screen::warning(format!(
                    "! {path} still has conflict markers"
                )));
            } else if ui::confirm_action(
                cfg,
                &format!("No conflict markers left in {path}. Mark it resolved?"),
                &format!("git add -- {path}"),
            )? {
                s.status = Some(result(keep_file(path), format!("resolved {path}")));
            }
        }
        Act::Mark => {
            let markers = std::fs::read(&full).is_ok_and(|b| has_conflict_markers(&b));
            if markers
                && !ui::confirm_action(
                    cfg,
                    &format!("Warning: {path} still contains conflict markers (<<<<<<< / ======= / >>>>>>>). Mark it resolved anyway?"),
                    &format!("git add -- {path}"),
                )?
            {
                return Ok(false);
            }
            if markers {
                s.confirmed.insert(path.to_string());
            }
            s.status = Some(result(keep_file(path), format!("resolved {path}")));
        }
        Act::Diff => {
            let out = git::git_raw(&["diff", "--", &spec(path)], &Opts::default())?;
            let lines: Vec<String> = out.text().lines().map(str::to_string).collect();
            if lines.is_empty() {
                s.status = Some(screen::muted("No diff to show for this file."));
            } else {
                ui::diff_view(&format!("Diff: {path}"), &lines, &[])?;
            }
        }
        Act::Tool => {
            let status = ui::suspended(|| run_mergetool(&state.workdir, path))?;
            s.status = Some(if status.success() {
                screen::success(format!(
                    "ok: merge tool finished for {path} ($ git mergetool --no-prompt -- {path})"
                ))
            } else {
                screen::danger(format!("x merge tool for {path} ended with {status}"))
            });
        }
        Act::Finish(_) | Act::Refresh => {}
    }
    Ok(false)
}

fn result(outcome: Result<Vec<String>>, what: String) -> String {
    match outcome {
        Ok(cmds) => done(&cmds, what),
        Err(error) => screen::danger(format!("x {error}")),
    }
}

fn finish_flow(cfg: &mut Config, s: &mut Session, view: &View, action: Finish) -> Result<bool> {
    let Some(op) = view.op else {
        s.status = Some(screen::warning(
            "Nothing is in progress (stash conflict): fix the files, then `git reset`; drop the stash in Stash mode.",
        ));
        return Ok(false);
    };
    let noun = op_noun(op);
    let Some(args) = continue_args(op, action) else {
        s.status = Some(screen::warning(format!("A {noun} has no skip.")));
        return Ok(false);
    };
    let command = format!("git {}", args.join(" "));
    match action {
        Finish::Abort => {
            let verdict = policy::check(cfg, &policy::Op::Abort);
            let what = format!("Abort the {noun}? Everything goes back to how it was before it started; resolutions so far are lost.");
            if !ui::gate(cfg, &verdict, &what, &command)? {
                return Ok(false);
            }
            let backup = ui::git_job("Aborting...", || abort_op(op));
            let mut lines = match backup {
                Ok(backup) => vec![
                    screen::success(format!("The {noun} was aborted.")),
                    format!("{} {}", screen::muted("Command:"), screen::accent(&command)),
                    format!("{} {backup}", screen::muted("Backup of where you were:")),
                ],
                Err(error) => vec![screen::danger(format!("Could not abort: {error}"))],
            };
            lines.extend(ui::explain(
                cfg,
                &["`git reset --hard <backup ref>` brings the abandoned state back."],
            ));
            ui::notice("Abort", &lines)?;
            Ok(true)
        }
        Finish::Continue | Finish::Skip => {
            if action == Finish::Continue {
                let verdict = policy::check(cfg, &policy::Op::CreatesCommit);
                if !ui::gate(cfg, &verdict, &format!("Continue the {noun}?"), &command)? {
                    return Ok(false);
                }
                let staged: Vec<String> = staged_marker_files()
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|path| !s.confirmed.contains(path))
                    .collect();
                if !staged.is_empty() {
                    let context = vec![
                        screen::danger("Staged files still contain conflict markers:"),
                        staged.join(", "),
                    ];
                    if !input::confirm(&context, "Continue anyway and commit the markers?", false)?
                    {
                        return Ok(false);
                    }
                }
            } else {
                let verdict = policy::check(cfg, &policy::Op::Abort);
                let what = "Skip this commit? Its changes and your resolutions for it are thrown away (a backup of HEAD is kept first).";
                if !ui::gate(cfg, &verdict, what, &command)? {
                    return Ok(false);
                }
            }
            let (watched, confirmed) = (&s.watched, &s.confirmed);
            let outcome = ui::git_job("Working...", || match action {
                Finish::Continue => continue_op(watched, confirmed).map(|out| (out, None)),
                _ => skip_op(op).map(|(out, backup)| (out, Some(backup))),
            });
            let (out, backup) = match outcome {
                Ok(done) => done,
                Err(error) => {
                    let lines: Vec<String> =
                        error.to_string().lines().map(screen::warning).collect();
                    ui::notice("Cannot continue yet", &lines)?;
                    return Ok(false);
                }
            };
            if let Some(backup) = &backup {
                let lines = [
                    screen::success("The commit was skipped."),
                    format!("{} {}", screen::muted("Command:"), screen::accent(&command)),
                    format!("{} {backup}", screen::muted("Backup of where you were:")),
                ];
                ui::notice("Skipped", &lines)?;
            }
            let after = repo_state::load()?;
            match after.op {
                None => finished(cfg, s, op, &command),
                Some(next) => {
                    let conflicts = after.entries.iter().any(|e| e.conflicted());
                    if out.ok() || conflicts {
                        let now = describe_op(next, &after.git_dir);
                        s.status = Some(if conflicts {
                            screen::warning(format!("! Stopped again with conflicts: {now}"))
                        } else {
                            screen::success(format!("ok: {command}. Now: {now}"))
                        });
                    } else {
                        let mut lines = vec![screen::danger(format!("$ {command} failed:"))];
                        lines.extend(out.stderr.lines().map(str::to_string));
                        ui::notice("Not finished", &lines)?;
                    }
                    Ok(false)
                }
            }
        }
    }
}

/// True when nothing is left for this mode: no operation in progress and no conflicted file.
fn settled(state: &RepoState) -> bool {
    state.op.is_none() && !state.entries.iter().any(|e| e.conflicted())
}

/// Reports the finished operation and offers Sync. True when the mode should close; false when
/// something opened from here (a pull in Sync) left new conflicts, so they show here next.
fn finished(cfg: &mut Config, s: &mut Session, op: InProgress, command: &str) -> Result<bool> {
    let noun = op_noun(op);
    let mut lines = vec![
        screen::success(format!("The {noun} is finished.")),
        format!("{} {}", screen::muted("Command:"), screen::accent(command)),
        String::new(),
    ];
    lines.push(if op == InProgress::Rebase {
        "Next step: push with Sync. The branch was rewritten, so if it was already pushed Sync uses --force-with-lease (it refuses if someone else pushed meanwhile).".into()
    } else {
        "Next step: push the new commit(s) with Sync.".into()
    });
    if ui::choose("Done", &lines, &["Open Sync", "Back"])? == Some(0) {
        crate::modes::open("sync", cfg)?;
    }
    let after = repo_state::load()?;
    if settled(&after) {
        return Ok(true);
    }
    s.status = Some(screen::warning(match after.op {
        Some(next) => format!(
            "! New conflicts to resolve: {}",
            describe_op(next, &after.git_dir)
        ),
        None => "! New conflicts to resolve".to_string(),
    }));
    Ok(false)
}

fn nothing_to_resolve(cfg: &Config) -> Result<()> {
    let mut lines = vec![
        screen::success("Nothing to resolve."),
        "No merge, rebase, cherry-pick, revert or patch series is in progress, and no file is conflicted.".into(),
        String::new(),
        screen::muted("Next step: when a merge or rebase (Sync, Branch) stops with conflicts, come back here."),
    ];
    lines.extend(ui::explain(
        cfg,
        &["A conflict happens when two changes touch the same lines; git then asks you to pick."],
    ));
    ui::notice("Conflicts", &lines)
}

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

    #[test]
    fn conflict_kind_table() {
        let table = [
            ('U', 'U', "both sides changed it"),
            ('A', 'A', "both sides added it"),
            ('D', 'U', "deleted here, changed by the incoming side"),
            ('U', 'D', "changed here, deleted by the incoming side"),
            ('A', 'U', "added here only"),
            ('U', 'A', "added by the incoming side only"),
            ('D', 'D', "deleted on both sides"),
            ('M', '.', "conflicted"),
        ];
        for (x, y, want) in table {
            assert_eq!(conflict_kind(x, y), want, "{x}{y}");
            assert!(!want.contains("ours") && !want.contains("theirs"));
        }
        assert!(!is_delete_kind('U', 'U') && !is_delete_kind('A', 'A'));
        assert!(is_delete_kind('D', 'U') && is_delete_kind('U', 'D') && is_delete_kind('D', 'D'));
    }

    #[test]
    fn markers_detection() {
        assert!(has_conflict_markers(
            b"a\n<<<<<<< HEAD\nx\n=======\ny\n>>>>>>> feature\n"
        ));
        assert!(has_conflict_markers(b"a\r\n<<<<<<< HEAD\r\nx\r\n"));
        assert!(has_conflict_markers(b"x\r\n=======\r\ny"));
        assert!(has_conflict_markers(b">>>>>>> theirs"));
        assert!(!has_conflict_markers(b""));
        assert!(!has_conflict_markers(
            b"text <<<<<<< HEAD in the middle\nand ======= too\n"
        ));
        assert!(!has_conflict_markers(b"<<<<<<<<< nine\n========\n"));
        assert!(!has_conflict_markers(
            " ünïcode\r\n  <<<<<<< indented\r\n".as_bytes()
        ));
    }

    #[test]
    fn continue_args_table() {
        use Finish::*;
        use InProgress::*;
        let table: [(InProgress, Finish, Option<Vec<&str>>); 12] = [
            (Merge, Continue, Some(vec!["commit", "--no-edit"])),
            (Merge, Skip, None),
            (Merge, Abort, Some(vec!["merge", "--abort"])),
            (Rebase, Continue, Some(vec!["rebase", "--continue"])),
            (Rebase, Skip, Some(vec!["rebase", "--skip"])),
            (Rebase, Abort, Some(vec!["rebase", "--abort"])),
            (CherryPick, Skip, Some(vec!["cherry-pick", "--skip"])),
            (Revert, Abort, Some(vec!["revert", "--abort"])),
            (Revert, Continue, Some(vec!["revert", "--continue"])),
            (Am, Continue, Some(vec!["am", "--continue"])),
            (Am, Skip, Some(vec!["am", "--skip"])),
            (Bisect, Abort, None),
        ];
        for (op, action, want) in table {
            assert_eq!(continue_args(op, action), want, "{op:?} {action:?}");
        }
    }

    #[test]
    fn describe_op_from_files() {
        let tmp = TempRepo::outside();
        let dir = tmp.path();
        let write = |rel: &str, text: &str| {
            let path = dir.join(rel);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        };
        assert_eq!(
            describe_op(InProgress::Rebase, dir),
            "Rebasing a detached HEAD onto its new base"
        );
        write("rebase-apply/head-name", "refs/heads/topic\n");
        write("rebase-apply/next", "2\n");
        write("rebase-apply/last", "5\n");
        assert_eq!(
            describe_op(InProgress::Rebase, dir),
            "Rebasing topic onto its new base, step 2 of 5"
        );
        assert_eq!(
            describe_op(InProgress::Am, dir),
            "Applying patches (git am), patch 2 of 5"
        );
        write("rebase-merge/head-name", "refs/heads/feature\r\n");
        write(
            "rebase-merge/onto",
            "0123456789abcdef0123456789abcdef01234567\n",
        );
        write("rebase-merge/msgnum", "3\n");
        write("rebase-merge/end", "7\n");
        assert_eq!(
            describe_op(InProgress::Rebase, dir),
            "Rebasing feature onto 0123456, step 3 of 7"
        );
        assert_eq!(
            describe_op(InProgress::Merge, dir),
            "Merging (a merge is in progress)"
        );
        write(
            "MERGE_MSG",
            "Merge branch 'feature/x' into main\n\n# Conflicts:\n",
        );
        assert_eq!(describe_op(InProgress::Merge, dir), "Merging feature/x");
        write("CHERRY_PICK_HEAD", "abcdef1234567890\n");
        assert_eq!(
            describe_op(InProgress::CherryPick, dir),
            "Cherry-picking abcdef1"
        );
        write("REVERT_HEAD", "fedcba9876543210\n");
        assert_eq!(describe_op(InProgress::Revert, dir), "Reverting fedcba9");
        assert_eq!(
            merge_branch("Merge remote-tracking branch 'origin/dev'"),
            Some("origin/dev".into())
        );
        assert_eq!(merge_branch("no quotes"), None);
        assert_eq!(merge_branch(""), None);
    }

    #[test]
    fn side_labels_follow_the_operation() {
        let [ours, theirs] = side_titles(Some(InProgress::Rebase), "main", "abc1234");
        assert_eq!(ours, "Keep upstream (main)");
        assert_eq!(theirs, "Keep my change (abc1234)");
        let [ours, theirs] = side_titles(Some(InProgress::Merge), "main", "feature");
        assert_eq!(ours, "Keep mine (current branch)");
        assert_eq!(theirs, "Keep theirs (feature)");
        assert_eq!(
            side_keys(Some(InProgress::Rebase)),
            ["keep upstream", "keep my change"]
        );
        assert_eq!(side_titles(None, "main", "")[1], "Keep the stashed version");
        assert_eq!(continue_blockers(&[], &[]), Vec::<String>::new());
        assert_eq!(continue_blockers(&["a".into()], &["b".into()]).len(), 2);
    }

    #[test]
    fn split_command_keeps_quoted_windows_paths() {
        use crate::input::split_command;
        assert_eq!(
            split_command(r#""C:\Program Files\Microsoft VS Code\code.exe" --wait"#),
            vec![r"C:\Program Files\Microsoft VS Code\code.exe", "--wait"]
        );
        assert_eq!(split_command("  vim  -n "), vec!["vim", "-n"]);
        assert!(split_command("   ").is_empty());
        assert_eq!(
            split_command(r"C:\Users\O'Brien\vim.exe -f"),
            vec![r"C:\Users\O'Brien\vim.exe", "-f"]
        );
    }

    #[test]
    fn parse_marker_check_lists_unique_paths() {
        let out = "a.txt:1: leftover conflict marker\na.txt:5: leftover conflict marker\nb.txt:2: trailing whitespace.\n+x \nsub/c d.txt:9: leftover conflict marker\n";
        assert_eq!(parse_marker_check(out), vec!["a.txt", "sub/c d.txt"]);
        assert!(parse_marker_check("").is_empty());
    }

    #[test]
    fn manual_edit_decision_table() {
        let marked = b"<<<<<<< ours\nx\n=======\ny\n>>>>>>> theirs\n";
        assert!(!has_manual_edits(None, false, &[]));
        assert!(!has_manual_edits(Some(marked), false, &[]));
        assert!(has_manual_edits(Some(b"resolved\n"), false, &[]));
        let stage = b"main\n".to_vec();
        assert!(!has_manual_edits(
            Some(b"main\r\n"),
            true,
            std::slice::from_ref(&stage)
        ));
        assert!(has_manual_edits(Some(b"mine\n"), true, &[stage]));
    }

    /// main and feature both change a.txt after a common base commit.
    fn conflict_repo() -> TempRepo {
        let repo = TempRepo::new(1);
        repo.write("a.txt", "base\n");
        repo.git(&["add", "a.txt"]);
        repo.git(&["commit", "-q", "-m", "base"]);
        repo.git(&["checkout", "-q", "-b", "feature"]);
        repo.write("a.txt", "feature\n");
        repo.git(&["commit", "-q", "-am", "feature change"]);
        repo.git(&["checkout", "-q", "main"]);
        repo.write("a.txt", "main\n");
        repo.git(&["commit", "-q", "-am", "main change"]);
        repo
    }

    fn start(args: &[&str]) {
        let out = git::git_raw(args, &Opts::default()).unwrap();
        assert!(!out.ok(), "expected a conflict from {args:?}");
    }

    fn read(repo: &TempRepo, rel: &str) -> String {
        std::fs::read_to_string(repo.path().join(rel))
            .unwrap()
            .replace('\r', "")
    }

    #[test]
    fn merge_keep_theirs_then_continue() {
        let repo = conflict_repo();
        repo.run(|| {
            start(&["merge", "feature"]);
            let state = repo_state::load().unwrap();
            assert_eq!(state.op, Some(InProgress::Merge));
            assert_eq!(
                describe_op(InProgress::Merge, &state.git_dir),
                "Merging feature"
            );
            let watched: BTreeSet<String> = ["a.txt".to_string()].into();
            let err = continue_op(&watched, &BTreeSet::new())
                .unwrap_err()
                .to_string();
            assert!(err.contains("still conflicted"), "{err}");
            take_side("a.txt", Side::Theirs).unwrap();
            keep_file("a.txt").unwrap();
            let out = continue_op(&watched, &BTreeSet::new()).unwrap();
            assert!(out.ok(), "{}", out.stderr);
            assert_eq!(repo_state::load().unwrap().op, None);
        });
        assert_eq!(read(&repo, "a.txt"), "feature\n");
        assert_eq!(
            repo.git(&["rev-list", "--parents", "-n1", "HEAD"])
                .split(' ')
                .count(),
            3
        );
    }

    #[test]
    fn continue_refused_while_markers_remain() {
        let repo = conflict_repo();
        repo.run(|| {
            start(&["merge", "feature"]);
            keep_file("a.txt").unwrap(); // staged with markers still inside
            let watched: BTreeSet<String> = ["a.txt".to_string()].into();
            let err = continue_op(&watched, &BTreeSet::new())
                .unwrap_err()
                .to_string();
            assert!(err.contains("markers"), "{err}");
            let confirmed = watched.clone();
            assert!(continue_op(&watched, &confirmed).unwrap().ok());
        });
    }

    #[test]
    fn rebase_uses_swapped_labels_and_finishes() {
        let repo = conflict_repo();
        repo.git(&["checkout", "-q", "feature"]);
        repo.run(|| {
            start(&["rebase", "main"]);
            let state = repo_state::load().unwrap();
            assert_eq!(state.op, Some(InProgress::Rebase));
            let view = View::new(&state);
            assert!(
                view.title.starts_with("Rebasing feature onto main"),
                "{}",
                view.title
            );
            assert!(
                view.sides[0].starts_with("Keep upstream (main)"),
                "{}",
                view.sides[0]
            );
            assert!(
                view.sides[1].starts_with("Keep my change"),
                "{}",
                view.sides[1]
            );
            take_side("a.txt", Side::Theirs).unwrap();
            let out = continue_op(&["a.txt".to_string()].into(), &BTreeSet::new()).unwrap();
            assert!(out.ok(), "{}", out.stderr);
            assert_eq!(repo_state::load().unwrap().op, None);
        });
        assert_eq!(read(&repo, "a.txt"), "feature\n");
        assert_eq!(
            repo.git(&["rev-parse", "HEAD~1"]),
            repo.git(&["rev-parse", "main"])
        );
    }

    #[test]
    fn abort_restores_head_and_keeps_a_backup() {
        let repo = conflict_repo();
        let before = repo.git(&["rev-parse", "HEAD"]);
        let backup = repo.run(|| {
            start(&["merge", "feature"]);
            abort_op(InProgress::Merge).unwrap()
        });
        assert!(backup.starts_with("refs/gct/backup/"), "{backup}");
        assert_eq!(repo.git(&["rev-parse", "HEAD"]), before);
        assert!(!repo.git(&["for-each-ref", "refs/gct/backup/"]).is_empty());
        assert_eq!(read(&repo, "a.txt"), "main\n");
    }

    /// feature deletes a.txt while main changes it: a "changed here, deleted incoming" conflict.
    fn delete_modify_repo() -> TempRepo {
        let repo = TempRepo::new(1);
        repo.write("a.txt", "base\n");
        repo.git(&["add", "a.txt"]);
        repo.git(&["commit", "-q", "-m", "base"]);
        repo.git(&["checkout", "-q", "-b", "feature"]);
        repo.git(&["rm", "-q", "a.txt"]);
        repo.git(&["commit", "-q", "-m", "delete a"]);
        repo.git(&["checkout", "-q", "main"]);
        repo.write("a.txt", "main\n");
        repo.git(&["commit", "-q", "-am", "main change"]);
        repo
    }

    #[test]
    fn delete_modify_resolves_both_ways() {
        for keep in [true, false] {
            let repo = delete_modify_repo();
            repo.run(|| {
                start(&["merge", "feature"]);
                let state = repo_state::load().unwrap();
                let entry = state.entries.iter().find(|e| e.conflicted()).unwrap();
                assert_eq!((entry.x, entry.y), ('U', 'D'));
                assert!(is_delete_kind(entry.x, entry.y));
                if keep {
                    keep_file("a.txt").unwrap();
                } else {
                    // Taking the side that deleted it removes the file.
                    assert_eq!(
                        take_side("a.txt", Side::Theirs).unwrap(),
                        vec!["git rm -- a.txt"]
                    );
                }
                assert!(continue_op(&BTreeSet::new(), &BTreeSet::new())
                    .unwrap()
                    .ok());
            });
            assert_eq!(repo.path().join("a.txt").exists(), keep);
            let tracked = repo.git(&["ls-files", "a.txt"]);
            assert_eq!(tracked.is_empty(), !keep);
        }
    }

    #[test]
    fn staged_markers_are_found_even_when_not_watched() {
        let repo = conflict_repo();
        repo.run(|| {
            start(&["merge", "feature"]);
            assert!(staged_marker_files().unwrap().is_empty());
            keep_file("a.txt").unwrap();
            assert_eq!(staged_marker_files().unwrap(), vec!["a.txt"]);
        });
    }

    #[test]
    fn edited_by_user_detects_manual_resolution() {
        let repo = conflict_repo();
        repo.run(|| {
            start(&["merge", "feature"]);
            let workdir = repo_state::load().unwrap().workdir;
            assert!(!edited_by_user(&workdir, "a.txt", false));
            std::fs::write(workdir.join("a.txt"), "mine\n").unwrap();
            assert!(edited_by_user(&workdir, "a.txt", false));
        });
        let repo = delete_modify_repo();
        repo.run(|| {
            start(&["merge", "feature"]);
            let workdir = repo_state::load().unwrap().workdir;
            assert!(!edited_by_user(&workdir, "a.txt", true));
            std::fs::write(workdir.join("a.txt"), "mine\n").unwrap();
            assert!(edited_by_user(&workdir, "a.txt", true));
        });
    }

    #[test]
    fn binary_conflict_counts_as_edited_only_when_it_matches_no_side() {
        let repo = TempRepo::new(1);
        let bytes = |tag: u8| vec![0u8, 1, 2, tag, 0, 255];
        let write = |data: &[u8]| std::fs::write(repo.path().join("b.bin"), data).unwrap();
        write(&bytes(0));
        repo.git(&["add", "b.bin"]);
        repo.git(&["commit", "-q", "-m", "base"]);
        repo.git(&["checkout", "-q", "-b", "feature"]);
        write(&bytes(1));
        repo.git(&["commit", "-q", "-am", "feature"]);
        repo.git(&["checkout", "-q", "main"]);
        write(&bytes(2));
        repo.git(&["commit", "-q", "-am", "main"]);
        repo.run(|| {
            start(&["merge", "feature"]);
            let workdir = repo_state::load().unwrap().workdir;
            assert!(
                !edited_by_user(&workdir, "b.bin", false),
                "untouched (ours) is not an edit"
            );
            for (tag, edited) in [(0, false), (1, false), (2, false), (9, true)] {
                std::fs::write(workdir.join("b.bin"), bytes(tag)).unwrap();
                assert_eq!(
                    edited_by_user(&workdir, "b.bin", false),
                    edited,
                    "content {tag}"
                );
            }
        });
        assert!(has_manual_edits(Some(b"x"), false, &[b"y".to_vec()]));
        assert!(!has_manual_edits(Some(b"y"), false, &[b"y".to_vec()]));
    }

    #[test]
    fn settled_only_when_nothing_is_left() {
        let repo = conflict_repo();
        repo.run(|| {
            assert!(settled(&repo_state::load().unwrap()));
            start(&["merge", "feature"]);
            assert!(!settled(&repo_state::load().unwrap()));
            take_side("a.txt", Side::Ours).unwrap();
            assert!(!settled(&repo_state::load().unwrap()), "still merging");
            assert!(continue_op(&BTreeSet::new(), &BTreeSet::new())
                .unwrap()
                .ok());
            assert!(settled(&repo_state::load().unwrap()));
        });
        // A new conflict right after finishing (like a pull from Sync) is not settled.
        repo.git(&["checkout", "-q", "-b", "other"]);
        repo.write("a.txt", "other\n");
        repo.git(&["commit", "-q", "-am", "other change"]);
        repo.git(&["checkout", "-q", "main"]);
        repo.write("a.txt", "main again\n");
        repo.git(&["commit", "-q", "-am", "main again"]);
        repo.run(|| {
            start(&["merge", "other"]);
            assert!(!settled(&repo_state::load().unwrap()));
        });
    }

    #[test]
    fn skip_keeps_a_backup_and_drops_the_commit() {
        let repo = conflict_repo();
        repo.git(&["checkout", "-q", "feature"]);
        let backup = repo.run(|| {
            start(&["rebase", "main"]);
            let (out, backup) = skip_op(InProgress::Rebase).unwrap();
            assert!(out.ok(), "{}", out.stderr);
            assert_eq!(repo_state::load().unwrap().op, None);
            backup
        });
        assert!(backup.starts_with("refs/gct/backup/"), "{backup}");
        assert!(backup.ends_with("-skip"), "{backup}");
        assert_eq!(
            repo.git(&["rev-parse", "HEAD"]),
            repo.git(&["rev-parse", "main"])
        );
        assert!(!repo.git(&["for-each-ref", "refs/gct/backup/"]).is_empty());
    }

    #[test]
    fn delete_file_removes_and_stages() {
        let repo = TempRepo::new(2);
        repo.run(|| {
            assert_eq!(delete_file("f1.txt").unwrap(), vec!["git rm -- f1.txt"]);
            delete_file("never-existed.txt").unwrap();
        });
        assert!(!repo.path().join("f1.txt").exists());
        assert!(repo.git(&["status", "--porcelain"]).contains("D  f1.txt"));
    }
}