grit-lib 0.5.24

Core library for the grit Git implementation
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
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
//! `git merge` index/head algorithm core.
//!
//! The full merge command in the `grit` binary is a large stateful sequencer:
//! it parses args, launches the merge-message editor, runs hooks, prints
//! progress (`"Trying merge strategy ..."`, `"Already up to date."`), and
//! writes the working tree. Those responsibilities — argv parsing, terminal
//! output, editor/hook subprocess dispatch, and exit-code mapping — stay in the
//! CLI.
//!
//! What lives here is the self-contained, presentation-free part of that
//! sequencer: the pure data transforms over trees, indexes, and the commit
//! graph that the CLI calls but that compute results from repository data
//! alone.
//!
//! # What this module owns
//!
//! - [`reduce_octopus_merge_heads`] — Git's "reduce parents": drop any merge
//!   head that is an ancestor of another listed head, preserving input order.
//! - [`compose_fast_forward_index`] — build the post-fast-forward index from the
//!   target tree, carrying forward staged additions that the fast-forward does
//!   not touch.
//! - [`compose_octopus_final_index`] — fold staged paths from before an octopus
//!   merge back into the merge result.
//! - [`tree_to_index_entries`] / [`tree_to_map`] — flatten a tree object into a
//!   recursive list (or path-keyed map) of [`IndexEntry`] values; the shared
//!   building block the three transforms above (and most of the CLI merge code)
//!   are written against.
//! - [`resolve_merge_source`] — turn a merge argument (branch, tag, object id or any
//!   revision expression) into the commit to merge.

use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::path::Path;

use crate::change_id::{change_id, ChangeId, ChangeIdPolicy};
use crate::config::ConfigSet;
use crate::diagnostics::Warning;
use crate::diff::diff_trees;
use crate::error::{Error, OverwriteReason, Result};
use crate::hooks::{run_post_merge, PostOperationHooks};
use crate::ident::{parse_signature_times, Signature};
use crate::ident_resolve::{resolve_loose_committer_identity_with, IdentRole};
use crate::index::{Index, IndexEntry};
use crate::merge_base::{
    is_ancestor, merge_bases_first_vs_rest, walk_commits_reachable_excluding_ancestors_of,
    ReachableWalkLimit,
};
use crate::merge_file::{ConflictStyle, MergeFavor};
use crate::merge_trees::{
    apply_tree_merge_output_to_index, materialized_merge_result_tree, merge_trees_three_way,
    DirectoryRenameMode, TreeMergeConflictPresentation, TreeMergeOutput, WhitespaceMergeOptions,
};
use crate::objects::{parse_commit, parse_tree, CommitData, ObjectId, ObjectKind};
use crate::operation::{conflicts_from_tree_merge, tree_merge_has_conflicts, Conflict};
use crate::path_population::validate_tree_walk_entry;
use crate::path_validate::ProtectOptions;
use crate::porcelain::checkout;
use crate::porcelain::commit::{
    normalize_commit_message, stamp_change_id_on_new_commit, write_commit_object,
};
use crate::porcelain::index_from_tree::{
    index_from_tree_with_worktree_stats, refresh_stage0_index_stats_from_worktree,
};
use crate::porcelain::restore::conflict_style_from_config;
use crate::porcelain::switch::{
    checkout_prepared_tree_transition_for_merge, prepare_tree_transition_allow_local,
    verify_tree_transition_allow_local, TreeTransitionPrepareError, TreeTransitionVerifyError,
};
use crate::porcelain::tree_merge_checkout::{
    finalize_clean_tree_merge_index, write_index_after_merge_checkout,
};
use crate::porcelain::worktree_guard::prepare_tree_checkout;
use crate::progress::{poll_cancel, Cancel, ProgressSink};
use crate::refs;
use crate::refs::store::{Expected, RawRef, RefUpdate, RefUpdateFlags};
use crate::repo::Repository;
use crate::rev_parse_error::RevParseError;
use crate::state::{
    clear_merge_state, read_merge_heads, read_merge_msg, read_orig_head_for_repository,
    write_orig_head,
};
use crate::stripspace::{process as stripspace_process, Mode as StripspaceMode};
use thiserror::Error;

use crate::hooks::{run_commit_hook, CommitHookEnv, HookName};
use crate::porcelain::add::stage_for_commit_on_index;
use crate::porcelain::commit::{
    create_commit_with_loaded_index, default_commit_scope_from_config, run_commit_message_hooks,
    CommitRequest, CommitScope, HookPolicy, MessageSource,
};
use crate::worktree_rules::WorktreeRules;
use crate::write_tree::write_tree_from_index;

/// Flatten a tree object into a recursive list of [`IndexEntry`] values.
///
/// Sub-trees are walked depth-first and their paths are prefixed with `prefix`
/// joined by `/`. The returned entries carry stage 0, zeroed stat fields, and
/// the tree's mode/oid — exactly what a freshly read-tree index holds.
///
/// # Errors
///
/// Returns an error if `oid` cannot be read or does not name a tree object.
pub fn tree_to_index_entries(
    repo: &Repository,
    oid: &ObjectId,
    prefix: &str,
) -> Result<Vec<IndexEntry>> {
    let protect = ProtectOptions::from_config(&*repo.config()?);
    let prefix_bytes = crate::repo_relpath::storage_bytes(prefix);
    tree_to_index_entries_with_protect(repo, oid, &prefix_bytes, protect)
}

fn tree_to_index_entries_with_protect(
    repo: &Repository,
    oid: &ObjectId,
    prefix: &[u8],
    protect: ProtectOptions,
) -> Result<Vec<IndexEntry>> {
    let obj = repo.odb().read(oid)?;
    if obj.kind != ObjectKind::Tree {
        return Err(Error::Message(format!("expected tree, got {}", obj.kind)));
    }
    let entries = parse_tree(&obj.data)?;
    let mut result = Vec::new();

    for te in entries {
        let path_bytes = crate::repo_relpath::join_rel(prefix, &te.name);
        validate_tree_walk_entry(prefix, &te.name, te.mode, protect)?;

        if te.mode == 0o040000 {
            let sub = tree_to_index_entries_with_protect(repo, &te.oid, &path_bytes, protect)?;
            result.extend(sub);
        } else {
            result.push(IndexEntry {
                ctime_sec: 0,
                ctime_nsec: 0,
                mtime_sec: 0,
                mtime_nsec: 0,
                dev: 0,
                ino: 0,
                mode: te.mode,
                uid: 0,
                gid: 0,
                size: 0,
                oid: te.oid,
                flags: path_bytes.len().min(0xFFF) as u16,
                flags_extended: None,
                path: path_bytes,
                base_index_pos: 0,
            });
        }
    }
    Ok(result)
}

/// Index a flat entry list by path, keeping the last entry for any duplicate.
#[must_use]
pub fn tree_to_map(entries: Vec<IndexEntry>) -> HashMap<Vec<u8>, IndexEntry> {
    let mut out = HashMap::new();
    for e in entries {
        out.insert(e.path.clone(), e);
    }
    out
}

/// Build the index that results from fast-forwarding `current_index` to
/// `target_tree`.
///
/// Starts from `target_tree`'s flattened entries and carries forward any
/// stage-0 path that is staged in `current_index`, is absent from
/// `target_tree`, and is also absent from `head_tree` — i.e. a staged addition
/// that the fast-forward should not discard.
///
/// # Errors
///
/// Returns an error if `target_tree` or `head_tree` cannot be read as trees.
pub fn compose_fast_forward_index(
    repo: &Repository,
    target_tree: ObjectId,
    head_tree: ObjectId,
    current_index: &Index,
) -> Result<Index> {
    let mut new_entries = tree_to_index_entries(repo, &target_tree, "")?;
    let target_paths: BTreeSet<Vec<u8>> = new_entries.iter().map(|e| e.path.clone()).collect();
    let head_entries = tree_to_map(tree_to_index_entries(repo, &head_tree, "")?);
    for e in &current_index.entries {
        if e.stage() != 0 {
            continue;
        }
        if target_paths.contains(&e.path) {
            continue;
        }
        // Staged addition: not in HEAD — keep alongside the fast-forwarded tree.
        if !head_entries.contains_key(&e.path) {
            new_entries.push(e.clone());
        }
    }
    let mut index = Index::new();
    index.entries = new_entries;
    index.sort();
    // A duplicate-entry tree (t4058) flattens to several identical-path entries; Git's index keeps
    // only one per path. Restore that invariant so status/diff against HEAD is consistent.
    index.dedup_paths_keep_last();
    Ok(index)
}

/// Preserve staged paths from before an octopus merge that the merge result does not touch
/// (e.g. unrelated `git add`), matching Git's index composition.
pub fn compose_octopus_final_index(pre_merge_index: &Index, final_index: &mut Index) {
    let final_paths: BTreeSet<Vec<u8>> = final_index
        .entries
        .iter()
        .filter(|e| e.stage() == 0)
        .map(|e| e.path.clone())
        .collect();
    for e in &pre_merge_index.entries {
        if e.stage() != 0 {
            continue;
        }
        if final_paths.contains(&e.path) {
            continue;
        }
        final_index.push_entry_unsorted(e.clone());
    }
    final_index.sort();
}

/// Drop merge heads that are ancestors of another listed head (Git's "reduce parents").
///
/// Order of the remaining heads matches the first occurrence in the input (t7603).
///
/// # Errors
///
/// Returns an error if a commit-graph walk required for an ancestry test fails.
pub fn reduce_octopus_merge_heads(
    repo: &Repository,
    merge_oids: &[ObjectId],
    merge_names: &[String],
) -> Result<(Vec<ObjectId>, Vec<String>)> {
    debug_assert_eq!(merge_oids.len(), merge_names.len());
    let mut out_oids = Vec::with_capacity(merge_oids.len());
    let mut out_names = Vec::with_capacity(merge_names.len());
    for i in 0..merge_oids.len() {
        let oid = merge_oids[i];
        let redundant = merge_oids
            .iter()
            .enumerate()
            .any(|(j, &other)| j != i && is_ancestor(repo, oid, other).unwrap_or(false));
        if !redundant {
            out_oids.push(oid);
            out_names.push(merge_names[i].clone());
        }
    }
    Ok((out_oids, out_names))
}

/// Fast-forward policy for branch integration.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum FastForwardPolicy {
    /// Fast-forward when `other_oid` is a descendant of `into_oid`.
    #[default]
    Allow,
    /// Refuse when a fast-forward is not possible; nothing changes.
    Only,
    /// Always record a merge commit when a real merge is required, even when a fast-forward is possible.
    Never,
}

/// Whether integration stops before creating a commit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MergeCommitMode {
    /// Create a merge commit (or fast-forward) on success without conflicts.
    #[default]
    Commit,
    /// Apply the merge to the index and worktree but leave `MERGE_HEAD` for a follow-up commit.
    NoCommit,
    /// Apply the merged tree and write `SQUASH_MSG` without updating the branch ref.
    Squash,
}

/// Options for [`integrate_branch_with`].
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct MergeOptions {
    /// When to fast-forward versus creating a merge commit.
    pub fast_forward: FastForwardPolicy,
    /// Whether to stop before committing.
    pub commit: MergeCommitMode,
    /// Overrides the default merge commit / `MERGE_MSG` text when set.
    pub message: Option<String>,
    /// Prefer ours or theirs when both sides changed the same region (`-X ours|theirs`).
    pub favor: MergeFavor,
    /// Conflict marker style; when unset, [`resolve_merge_conflict_style`] reads config.
    pub conflict_style: Option<ConflictStyle>,
    /// When histories share no commits, use the empty tree as merge base (Git `--allow-unrelated-histories`).
    pub allow_unrelated: bool,
    /// Whether to run `post-merge` after a fast-forward, merge commit or squash.
    pub hooks: PostOperationHooks,
    /// Whether `pre-merge-commit` and `commit-msg` run before a merge commit is recorded
    /// ([`HookPolicy::SkipVerify`] is `--no-verify`). `prepare-commit-msg` runs either way, and
    /// `post-merge` follows [`Self::hooks`].
    pub verify: HookPolicy,
    /// Whether files the merged branch added inside a directory the current branch renamed
    /// (or the reverse) follow the rename; when unset, `merge.directoryRenames` decides
    /// ([`DirectoryRenameMode::from_repo`]).
    pub directory_renames: Option<DirectoryRenameMode>,
}

/// Resolve conflict marker style: explicit option, then `merge.conflictStyle`, then `merge`.
#[must_use]
pub fn resolve_merge_conflict_style(
    repo: &Repository,
    override_style: Option<ConflictStyle>,
) -> ConflictStyle {
    override_style.unwrap_or_else(|| conflict_style_from_config(repo))
}

/// Directory rename handling: explicit option, then `merge.directoryRenames`, then
/// [`DirectoryRenameMode::Conflict`].
fn resolve_directory_renames(
    repo: &Repository,
    override_mode: Option<DirectoryRenameMode>,
) -> Result<DirectoryRenameMode> {
    override_mode.map_or_else(|| DirectoryRenameMode::from_repo(repo), Ok)
}

/// Options for [`integrate_branch_with_options`] (pull fast-forward toggle).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IntegrateBranchOptions {
    /// When `false`, a fast-forward is not performed even when `other_oid` is a
    /// descendant of `into_oid`; a merge commit is recorded instead.
    pub allow_fast_forward: bool,
}

impl Default for IntegrateBranchOptions {
    fn default() -> Self {
        Self {
            allow_fast_forward: true,
        }
    }
}

/// Options for [`predict_merge`] and [`write_merge_tree`].
#[derive(Clone, Debug)]
pub struct MergePredictionOptions {
    /// When `false`, a fast-forward is not considered even when `other_oid` is a
    /// descendant of `into_oid`; a three-way merge is simulated instead. Ignored by
    /// [`write_merge_tree`], which always merges.
    pub allow_fast_forward: bool,
    /// When `true`, [`write_merge_tree`] merges commits with no merge base over the empty
    /// tree, like Git's `--allow-unrelated-histories`; when `false` it fails with
    /// [`Error::UnrelatedHistories`]. [`predict_merge`] always reports
    /// [`MergePrediction::Unrelated`] for such commits.
    pub allow_unrelated_histories: bool,
    /// Merge-favor policy for the simulated three-way merge (ours/theirs/normal).
    pub favor: MergeFavor,
    /// Whitespace handling for the simulated three-way merge.
    pub whitespace: WhitespaceMergeOptions,
    /// Label for the current side in conflict markers (`<<<<<<< HEAD` by default).
    pub ours_label: String,
    /// Label for the incoming side in conflict-marker metadata (presentation only).
    pub theirs_label: String,
    /// Whether files one side added inside a directory the other side renamed follow the
    /// rename; when unset, `merge.directoryRenames` decides ([`DirectoryRenameMode::from_repo`]).
    pub directory_renames: Option<DirectoryRenameMode>,
}

impl Default for MergePredictionOptions {
    fn default() -> Self {
        Self {
            allow_fast_forward: true,
            allow_unrelated_histories: false,
            favor: MergeFavor::default(),
            whitespace: WhitespaceMergeOptions::default(),
            ours_label: "HEAD".into(),
            theirs_label: "branch".into(),
            directory_renames: None,
        }
    }
}

/// In-memory prediction of merging `other_oid` into the commit `into_oid`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergePrediction {
    /// The current tip already contains the other side.
    UpToDate,
    /// The current tip could fast-forward to the other side.
    FastForward,
    /// A three-way merge would succeed; `tree` is the merged result tree OID.
    Clean {
        /// Merged tree OID: the same id `git merge-tree --write-tree` prints.
        ///
        /// The tree is **not** in the object database after [`predict_merge`] returns (its new
        /// trees and blobs were only held in memory), so it cannot be committed, diffed or
        /// read. Use [`write_merge_tree`] when the merged tree must be stored.
        tree: ObjectId,
    },
    /// A three-way merge would stop with conflicts.
    Conflicts {
        /// Conflicted paths and kinds (same classification as a real merge).
        conflicts: Vec<Conflict>,
    },
    /// The two commits share no common history.
    Unrelated,
}

/// Predict merging `other_oid` into `into_oid` without touching refs, the index,
/// merge state files, or the working tree.
///
/// Object writes from the merge are routed through the ODB in-memory overlay and
/// discarded before return, so the on-disk object store is unchanged. That includes the
/// tree reported by [`MergePrediction::Clean`]; call [`write_merge_tree`] to store it.
///
/// # Errors
///
/// Propagates object read and merge failures. Does not require a clean worktree.
pub fn predict_merge(
    repo: &Repository,
    into_oid: ObjectId,
    other_oid: ObjectId,
    options: &MergePredictionOptions,
) -> Result<MergePrediction> {
    if into_oid == other_oid || is_ancestor(repo, other_oid, into_oid)? {
        return Ok(MergePrediction::UpToDate);
    }

    if options.allow_fast_forward && is_ancestor(repo, into_oid, other_oid)? {
        return Ok(MergePrediction::FastForward);
    }

    let Some(base_oid) = first_merge_base(repo, into_oid, other_oid)? else {
        return Ok(MergePrediction::Unrelated);
    };
    let base_tree = repo.odb().commit_tree(&base_oid)?;

    let _overlay = MemOverlayGuard::enter(repo.odb());
    let merged = merge_commit_trees(repo, base_tree, into_oid, other_oid, options)?;
    if tree_merge_has_conflicts(&merged) {
        return Ok(MergePrediction::Conflicts {
            conflicts: conflicts_from_tree_merge(&merged),
        });
    }
    let tree = materialized_merge_result_tree(repo.odb(), &merged)?;
    Ok(MergePrediction::Clean { tree })
}

/// One unmerged index entry of a [`WrittenMergeTree`]: the `<mode> <oid> <stage> <path>`
/// rows `git merge-tree --write-tree` prints after the tree id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeTreeStage {
    /// Git file mode of this side (`0o100644`, `0o100755`, `0o120000`, `0o160000`).
    pub mode: u32,
    /// Blob (or gitlink commit) of this side; already in the object database.
    pub oid: ObjectId,
    /// `1` for the merge base, `2` for ours (`into`), `3` for theirs (`other`).
    pub stage: u8,
    /// Repository-relative path as raw bytes.
    pub path: Vec<u8>,
}

/// A three-way merge result stored in the object database ([`write_merge_tree`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WrittenMergeTree {
    /// Merged tree, present in the object database. Conflicted files hold conflict-marker
    /// content, exactly like the tree `git merge-tree --write-tree` writes.
    pub tree: ObjectId,
    /// Conflicted paths and kinds; empty when the merge is clean.
    pub conflicts: Vec<Conflict>,
    /// Unmerged entries (stages 1–3) sorted by path, then stage; empty when the merge is clean.
    pub stages: Vec<MergeTreeStage>,
}

impl WrittenMergeTree {
    /// Whether the merge finished without conflicts, so [`Self::tree`] can be committed as is.
    #[must_use]
    pub fn is_clean(&self) -> bool {
        self.conflicts.is_empty() && self.stages.is_empty()
    }
}

/// Three-way merge `other_oid` into `into_oid` and store the resulting tree, without touching
/// refs, the index, merge state files or the working tree (the library form of
/// `git merge-tree --write-tree`).
///
/// Works in bare repositories. Unlike [`predict_merge`], every new tree and blob the merge
/// creates is written to the object database before return, so a clean result can be
/// committed directly with `NewCommit::new(tree, ..).with_parents(vec![into_oid, other_oid])`.
/// On conflicts the tree is still written, with conflict markers in the conflicted files, and
/// [`WrittenMergeTree::stages`] lists the unmerged entries.
///
/// A merge is always computed: [`MergePredictionOptions::allow_fast_forward`] is ignored, and
/// when one commit contains the other the result is the newer commit's tree. With several merge
/// bases (criss-cross history) the first one is used, as in [`predict_merge`]. When `options`
/// allows unrelated histories, a missing merge base is treated as the empty tree. If the
/// repository handle already has an in-memory write overlay active, the new objects stay in
/// that outer overlay instead of being written to disk.
///
/// # Parameters
///
/// - `repo`: repository to merge in.
/// - `into_oid`: commit merged into (stage 2, "ours").
/// - `other_oid`: commit merged in (stage 3, "theirs").
/// - `options`: favor, whitespace, conflict labels and unrelated-history policy.
///
/// # Errors
///
/// - [`Error::UnrelatedHistories`] when the commits share no merge base and
///   [`MergePredictionOptions::allow_unrelated_histories`] is `false`.
/// - Object read, merge and object write failures are propagated.
pub fn write_merge_tree(
    repo: &Repository,
    into_oid: ObjectId,
    other_oid: ObjectId,
    options: &MergePredictionOptions,
) -> Result<WrittenMergeTree> {
    let base_tree = match first_merge_base(repo, into_oid, other_oid)? {
        Some(base_oid) => repo.odb().commit_tree(&base_oid)?,
        None if options.allow_unrelated_histories => repo.odb().empty_tree_oid()?,
        None => {
            return Err(Error::UnrelatedHistories {
                ours: into_oid,
                theirs: other_oid,
            })
        }
    };

    let merged = merge_commit_trees(repo, base_tree, into_oid, other_oid, options)?;
    let tree = materialized_merge_result_tree(repo.odb(), &merged)?;

    let stages = merged
        .index
        .entries()
        .iter()
        .filter(|entry| entry.stage() != 0)
        .map(|entry| MergeTreeStage {
            mode: entry.mode,
            oid: entry.oid,
            stage: entry.stage(),
            path: entry.path.clone(),
        })
        .collect();
    Ok(WrittenMergeTree {
        tree,
        conflicts: conflicts_from_tree_merge(&merged),
        stages,
    })
}

fn first_merge_base(
    repo: &Repository,
    into_oid: ObjectId,
    other_oid: ObjectId,
) -> Result<Option<ObjectId>> {
    Ok(merge_bases_first_vs_rest(repo, into_oid, &[other_oid])?
        .into_iter()
        .next())
}

/// Three-way merge the trees of `into_oid` and `other_oid` over `base_tree`, labelling conflicts
/// from `options`. New objects go wherever the ODB currently writes (disk, or an active overlay).
fn merge_commit_trees(
    repo: &Repository,
    base_tree: ObjectId,
    into_oid: ObjectId,
    other_oid: ObjectId,
    options: &MergePredictionOptions,
) -> Result<TreeMergeOutput> {
    let into_tree = repo.odb().commit_tree(&into_oid)?;
    let other_tree = repo.odb().commit_tree(&other_oid)?;
    let presentation = TreeMergeConflictPresentation {
        label_ours: &options.ours_label,
        label_theirs: crate::merge_trees::TheirsConflictLabel::Fixed(&options.theirs_label),
        df_directory_ours_commit: Some(into_oid),
        df_directory_theirs_commit: Some(other_oid),
        ..TreeMergeConflictPresentation::default()
    };
    merge_trees_three_way(
        repo,
        base_tree,
        into_tree,
        other_tree,
        options.favor,
        options.whitespace,
        None,
        presentation,
        resolve_directory_renames(repo, options.directory_renames)?,
    )
}

/// Planned merge of `other_oid` into `into_oid` without touching refs, the index, merge state,
/// or the working tree (same in-memory three-way merge as [`predict_merge`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MergeDryRunPlan {
    /// The current tip already contains the other side.
    UpToDate,
    /// The branch ref would move to `tip` (fast-forward).
    FastForward {
        /// Tip commit the current branch would become.
        tip: ObjectId,
        /// Stored `change-id` on `tip` when present.
        change_id: Option<ChangeId>,
    },
    /// `--ff-only` would refuse because histories diverged.
    RefusedNotFf,
    /// A two-parent merge commit would be recorded (tree merge already succeeded).
    MergeCommit {
        /// Parent commits of the merge commit (current tip, then merged branch).
        parents: Vec<ObjectId>,
    },
    /// The three-way merge would stop with conflicts.
    Conflicts {
        /// Conflicted paths and kinds (same classification as a real merge).
        conflicts: Vec<Conflict>,
    },
}

/// Predict integrating `other_oid` into the commit at `into_oid` using [`MergeOptions`], without
/// mutating the repository.
///
/// # Errors
///
/// Propagates object read and merge failures. Returns [`Error::Message`] when histories are
/// unrelated and [`MergeOptions::allow_unrelated`] is false.
pub fn plan_branch_merge(
    repo: &Repository,
    into_oid: ObjectId,
    other_oid: ObjectId,
    label: &str,
    options: &MergeOptions,
) -> Result<MergeDryRunPlan> {
    if into_oid == other_oid || is_ancestor(repo, other_oid, into_oid)? {
        return Ok(MergeDryRunPlan::UpToDate);
    }

    let ff_possible = is_ancestor(repo, into_oid, other_oid)?;
    if matches!(options.fast_forward, FastForwardPolicy::Only) && !ff_possible {
        return Ok(MergeDryRunPlan::RefusedNotFf);
    }

    if should_take_fast_forward(options, ff_possible) {
        return Ok(MergeDryRunPlan::FastForward {
            tip: other_oid,
            change_id: stored_change_id_for_commit(repo, other_oid)?,
        });
    }

    let prediction_opts = MergePredictionOptions {
        allow_fast_forward: false,
        allow_unrelated_histories: options.allow_unrelated,
        favor: options.favor,
        whitespace: WhitespaceMergeOptions::default(),
        theirs_label: label.to_owned(),
        directory_renames: options.directory_renames,
        ..MergePredictionOptions::default()
    };
    match predict_merge(repo, into_oid, other_oid, &prediction_opts)? {
        MergePrediction::UpToDate | MergePrediction::FastForward => Ok(MergeDryRunPlan::UpToDate),
        MergePrediction::Clean { .. } => Ok(MergeDryRunPlan::MergeCommit {
            parents: vec![into_oid, other_oid],
        }),
        MergePrediction::Conflicts { conflicts } => Ok(MergeDryRunPlan::Conflicts { conflicts }),
        MergePrediction::Unrelated => Err(Error::Message(format!(
            "'{label}' has no common history with the current branch"
        ))),
    }
}

/// What kind of name a merge source was given by ([`resolve_merge_source`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MergeSourceKind {
    /// A local branch (`refs/heads/<name>`).
    LocalBranch,
    /// A remote-tracking branch (`refs/remotes/<name>`).
    RemoteBranch,
    /// A tag (`refs/tags/<name>`), lightweight or annotated.
    Tag,
    /// Any other revision expression: an object id, `HEAD~2`, `ORIG_HEAD`, `v1.0^`, a full
    /// refname, and so on.
    Commit,
}

/// The commit a merge brings in, and how its name was resolved ([`resolve_merge_source`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MergeSource {
    /// The commit to merge (annotated tags already peeled).
    pub oid: ObjectId,
    /// Which namespace matched the spec.
    pub kind: MergeSourceKind,
}

/// Resolve the argument of a merge (`spec`) to the commit it names.
///
/// Branch names win over other meanings: `refs/heads/<spec>` is tried first, then
/// `refs/remotes/<spec>`, then `refs/tags/<spec>`. Anything else goes through the revision
/// parser, so object ids (full or abbreviated), `ORIG_HEAD`, `topic~3` and `origin/main^2`
/// all work. Annotated tags are peeled to the commit they name. Range expressions (`a..b`, `a...b`)
/// do not name a single commit and are reported as not found. Ref names can contain literal
/// braces: `foo{bar` is a valid source, while `foo{bar...main` is still a range.
/// Dots within selectors such as `main^{/release..candidate}` do not form a range.
///
/// # Parameters
///
/// - `repo`: repository to resolve in.
/// - `spec`: the merge argument as the user wrote it.
///
/// # Returns
///
/// The commit and the [`MergeSourceKind`] of the name that matched.
///
/// # Errors
///
/// - [`Error::RevisionNotFound`] when `spec` names nothing.
/// - [`Error::UnexpectedObjectKind`] when `spec` names (or a tag peels to) a tree or blob.
/// - Object database errors (missing or corrupt objects behind a ref) are propagated.
pub fn resolve_merge_source(repo: &Repository, spec: &str) -> Result<MergeSource> {
    let named = [
        ("refs/heads/", MergeSourceKind::LocalBranch),
        ("refs/remotes/", MergeSourceKind::RemoteBranch),
        ("refs/tags/", MergeSourceKind::Tag),
    ]
    .into_iter()
    .find_map(|(prefix, kind)| {
        refs::resolve_ref(repo.git_dir(), &format!("{prefix}{spec}"))
            .ok()
            .map(|oid| (oid, kind))
    });
    // A full-length hex id parses without an object lookup, so a missing object only shows up
    // when peeling; that is still "names nothing", unlike a ref pointing at a missing object.
    let not_found = |err: Error| match err {
        Error::ObjectNotFound(_)
        | Error::RevParse(
            RevParseError::InvalidObjectName { .. }
            | RevParseError::RevisionOutOfRange { .. }
            | RevParseError::AmbiguousArgument { .. }
            | RevParseError::NoSuchBranch { .. },
        ) => Error::RevisionNotFound(spec.to_owned()),
        other => other,
    };
    let (peeled, actual, kind) = match named {
        Some((oid, kind)) => {
            let (peeled, actual) = repo.odb().peel_tags(oid)?;
            (peeled, actual, kind)
        }
        None => {
            // The revision parser resolves `a...b` to a merge base; a range never names the
            // commit to merge.
            if crate::rev_parse::is_top_level_range(spec) {
                return Err(Error::RevisionNotFound(spec.to_owned()));
            }
            let oid = crate::rev_parse::resolve_revision_without_index_dwim(repo, spec)
                .map_err(not_found)?;
            let (peeled, actual) = repo.odb().peel_tags(oid).map_err(not_found)?;
            (peeled, actual, MergeSourceKind::Commit)
        }
    };
    if actual != ObjectKind::Commit {
        return Err(Error::UnexpectedObjectKind {
            oid: peeled,
            expected: ObjectKind::Commit,
            actual,
        });
    }
    Ok(MergeSource { oid: peeled, kind })
}

/// Enable the ODB mem overlay for the scope of a [`predict_merge`] call without disturbing
/// an overlay already active on the shared [`Repository`] handle.
pub(crate) struct MemOverlayGuard<'a> {
    odb: &'a crate::objects::odb::Odb,
    enabled_here: bool,
}

impl<'a> MemOverlayGuard<'a> {
    pub(crate) fn enter(odb: &'a crate::objects::odb::Odb) -> Self {
        let already_active = odb.is_mem_overlay_active();
        if !already_active {
            odb.enable_mem_overlay();
        }
        Self {
            odb,
            enabled_here: !already_active,
        }
    }
}

impl Drop for MemOverlayGuard<'_> {
    fn drop(&mut self) {
        if self.enabled_here {
            self.odb.disable_mem_overlay();
        }
    }
}

impl From<IntegrateBranchOptions> for MergeOptions {
    fn from(options: IntegrateBranchOptions) -> Self {
        Self {
            fast_forward: if options.allow_fast_forward {
                FastForwardPolicy::Allow
            } else {
                FastForwardPolicy::Never
            },
            ..Self::default()
        }
    }
}

/// Result of integrating another branch into the current one ([`integrate_branch`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IntegrateBranchOutcome {
    /// The current branch already contains the other tip.
    UpToDate,
    /// The current branch fast-forwarded to the other tip.
    FastForward {
        /// New branch tip after the fast-forward.
        oid: ObjectId,
        /// Stored `change-id` on the fast-forward tip when present.
        change_id: Option<ChangeId>,
    },
    /// A merge commit was created without conflicts.
    Merged {
        /// New merge commit OID.
        oid: ObjectId,
        /// Stored `change-id` on the merge commit when present.
        change_id: Option<ChangeId>,
    },
    /// The merge has conflicts; the repository is left in a merge-in-progress state.
    Conflicts {
        /// Conflicted paths in repository-relative form, sorted and deduplicated.
        paths: Vec<String>,
        /// Per-path conflict classification (same order as `paths` after sorting).
        details: Vec<Conflict>,
    },
    /// A `--squash` merge applied the merged tree and wrote `SQUASH_MSG`.
    Squashed,
    /// A `--no-commit` merge applied the merged tree and recorded merge state.
    Stopped,
}

/// Integrate `other_oid` into the branch `into_ref` (currently at `into_oid`).
///
/// On success without conflicts, updates the branch ref, index, and worktree. On
/// conflicts, records `MERGE_HEAD` / `ORIG_HEAD` / `MERGE_MSG`, writes conflict
/// markers and a partially merged index, and leaves the branch ref unchanged.
///
/// The work-tree update reports [`crate::progress::ProgressPhase::CheckingOutFiles`] to
/// `progress`. `cancel` (or [`ProgressSink::should_cancel`]) is checked before the work tree is
/// touched and throughout the checkout; once the checkout completed, the index, merge state and
/// branch update always follow, so a cancel never leaves the branch behind a finished checkout.
///
/// # Errors
///
/// Propagates merge, checkout, ref, and I/O failures. Returns [`Error::WouldOverwrite`]
/// when local or untracked paths would be overwritten by the merge tree, and
/// [`Error::DirtyWorktree`] when the worktree is not clean but no specific paths were
/// collected. Returns [`Error::Message`] when the histories are unrelated or `into_ref`
/// no longer points at `into_oid` (checked before the worktree is touched, and again
/// when the ref moves).
/// Returns [`Error::Cancelled`] when cancelled; the branch, `HEAD`, the index and the merge
/// state are unchanged, and a cancel during the checkout rolls the work tree back.
pub fn integrate_branch(
    repo: &Repository,
    into_ref: &str,
    into_oid: ObjectId,
    other_oid: ObjectId,
    label: &str,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<IntegrateBranchOutcome> {
    integrate_branch_with(
        repo,
        into_ref,
        into_oid,
        other_oid,
        label,
        &MergeOptions::default(),
        progress,
        cancel,
    )
}

/// Integrate `other_oid` into the branch at `into_ref` with explicit merge options.
///
/// Before a clean merge records its commit, runs `pre-merge-commit`, then
/// `prepare-commit-msg .git/MERGE_MSG merge` and `commit-msg .git/MERGE_MSG` with `MERGE_HEAD`
/// recorded, as Git does ([`MergeOptions::verify`] skips `pre-merge-commit` and `commit-msg`).
/// A message hook may rewrite the message, and `pre-merge-commit` may stage changes that the
/// commit then includes. None of these run for a fast-forward, a squash, conflicts or
/// [`MergeCommitMode::NoCommit`].
///
/// After a fast-forward or merge commit, runs `post-merge 0`; after a squash, `post-merge 1`
/// (unless [`MergeOptions::hooks`] is [`PostOperationHooks::Skip`]). Like Git, the hook does not
/// run when the branch is already up to date, when the merge stops on conflicts, or for
/// [`MergeCommitMode::NoCommit`]. Its outcome never fails the merge.
///
/// # Errors
///
/// Same as [`integrate_branch`], plus [`Error::NotFastForward`] when
/// [`FastForwardPolicy::Only`] cannot fast-forward, and [`Error::Hook`] when
/// `pre-merge-commit`, `prepare-commit-msg` or `commit-msg` refuses. A refused merge leaves the
/// merged index and work tree with `MERGE_HEAD`, `ORIG_HEAD` and `MERGE_MSG` recorded and the
/// branch unchanged: finish it with a commit ([`continue_merge`]) or [`abort_branch_merge`].
#[allow(clippy::too_many_arguments)]
pub fn integrate_branch_with(
    repo: &Repository,
    into_ref: &str,
    into_oid: ObjectId,
    other_oid: ObjectId,
    label: &str,
    options: &MergeOptions,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<IntegrateBranchOutcome> {
    let outcome = integrate_branch_without_hooks(
        repo, into_ref, into_oid, other_oid, label, options, progress, cancel,
    )?;
    if options.hooks.enabled() {
        match outcome {
            IntegrateBranchOutcome::FastForward { .. } | IntegrateBranchOutcome::Merged { .. } => {
                run_post_merge(repo, false);
            }
            IntegrateBranchOutcome::Squashed => {
                run_post_merge(repo, true);
            }
            IntegrateBranchOutcome::UpToDate
            | IntegrateBranchOutcome::Conflicts { .. }
            | IntegrateBranchOutcome::Stopped => {}
        }
    }
    // Like Git, `post-merge` still sees the merge state the message hooks saw.
    if matches!(outcome, IntegrateBranchOutcome::Merged { .. }) {
        clear_merge_state(repo.git_dir())?;
    }
    Ok(outcome)
}

#[allow(clippy::too_many_arguments)]
fn integrate_branch_without_hooks(
    repo: &Repository,
    into_ref: &str,
    into_oid: ObjectId,
    other_oid: ObjectId,
    label: &str,
    options: &MergeOptions,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<IntegrateBranchOutcome> {
    if into_oid == other_oid || is_ancestor(repo, other_oid, into_oid)? {
        write_orig_head(repo, into_oid)?;
        return Ok(IntegrateBranchOutcome::UpToDate);
    }
    ensure_branch_tip(repo, into_ref, Some(into_oid))?;
    poll_cancel(progress, cancel)?;
    // Like Git, every merge attempt past this point records where it started, including a
    // refused fast-forward-only merge and one that stops on conflicts.
    write_orig_head(repo, into_oid)?;

    let into_tree = repo.odb().commit_tree(&into_oid)?;
    let other_tree = repo.odb().commit_tree(&other_oid)?;
    let ff_possible = is_ancestor(repo, into_oid, other_oid)?;

    if matches!(options.fast_forward, FastForwardPolicy::Only) && !ff_possible {
        return Err(Error::NotFastForward);
    }

    if should_take_fast_forward(options, ff_possible) {
        if matches!(options.commit, MergeCommitMode::Squash) {
            merge_checkout_tree_transition(repo, Some(&into_tree), &other_tree, progress, cancel)?;
            let mut snapshot = crate::porcelain::worktree_guard::load_worktree_snapshot(repo)?;
            let ff_index =
                compose_fast_forward_index(repo, other_tree, into_tree, &snapshot.index)?;
            snapshot.index = ff_index;
            repo.write_index(&mut snapshot.index)?;
            write_squash_msg_file(repo, into_oid, other_oid)?;
            return Ok(IntegrateBranchOutcome::Squashed);
        }

        merge_checkout_tree_transition(repo, Some(&into_tree), &other_tree, progress, cancel)?;
        move_branch(
            repo,
            into_ref,
            into_oid,
            other_oid,
            &format!("merge {label}: fast-forward"),
        )?;
        return Ok(IntegrateBranchOutcome::FastForward {
            oid: other_oid,
            change_id: stored_change_id_for_commit(repo, other_oid)?,
        });
    }

    let merge_base = merge_bases_first_vs_rest(repo, into_oid, &[other_oid])?;
    let label_base = if let Some(base_oid) = merge_base.first().copied() {
        crate::commit_pretty::abbrev_hex(&base_oid, 7)
    } else if options.allow_unrelated {
        "empty tree".to_owned()
    } else {
        return Err(Error::Message(format!(
            "'{label}' has no common history with the current branch"
        )));
    };
    let base_tree = if let Some(base_oid) = merge_base.into_iter().next() {
        repo.odb().commit_tree(&base_oid)?
    } else {
        empty_tree_oid(repo)?
    };

    let style = resolve_merge_conflict_style(repo, options.conflict_style);
    let presentation = TreeMergeConflictPresentation {
        label_theirs: crate::merge_trees::TheirsConflictLabel::Fixed(label),
        label_base: &label_base,
        df_directory_ours_commit: Some(into_oid),
        df_directory_theirs_commit: Some(other_oid),
        style,
        ..TreeMergeConflictPresentation::default()
    };
    let merged = merge_trees_three_way(
        repo,
        base_tree,
        into_tree,
        other_tree,
        options.favor,
        WhitespaceMergeOptions::default(),
        None,
        presentation,
        resolve_directory_renames(repo, options.directory_renames)?,
    )?;
    poll_cancel(progress, cancel)?;

    if tree_merge_has_conflicts(&merged) {
        let details = conflicts_from_tree_merge(&merged);
        let paths: Vec<String> = details.iter().map(|c| c.path.clone()).collect();
        let materialized = materialized_merge_result_tree(repo.odb(), &merged)?;
        ensure_merge_tree_transition_allowed(repo, Some(&into_tree), &materialized)?;
        apply_conflict_merge_worktree(repo, &into_tree, &merged, progress, cancel)?;
        let merge_msg = merge_message_text(label, options.message.as_deref());
        if matches!(options.commit, MergeCommitMode::Squash) {
            write_squash_msg_file(repo, into_oid, other_oid)?;
            write_squash_conflict_merge_msg(repo.git_dir(), &paths, options.message.as_deref())?;
        } else {
            record_merge_in_progress(repo.git_dir(), other_oid, merge_msg)?;
        }
        return Ok(IntegrateBranchOutcome::Conflicts { paths, details });
    }

    let commit_preflight = if matches!(options.commit, MergeCommitMode::Commit) {
        let config = repo.config()?;
        Some(MergeCommitPreflight {
            author: strict_commit_identity(repo, IdentRole::Author)?,
            committer: strict_commit_identity(repo, IdentRole::Committer)?,
            config,
        })
    } else {
        None
    };

    merge_checkout_tree_transition(
        repo,
        Some(&into_tree),
        &merged.result_tree,
        progress,
        cancel,
    )?;
    let mut lock = repo.lock_index()?;
    let mut snapshot = crate::porcelain::worktree_guard::load_worktree_snapshot(repo)?;
    finalize_clean_tree_merge_index(repo, &mut snapshot.index, &merged)?;
    write_index_after_merge_checkout(repo, &mut snapshot.index, &mut lock)?;

    match options.commit {
        MergeCommitMode::Squash => {
            write_squash_msg_file(repo, into_oid, other_oid)?;
            Ok(IntegrateBranchOutcome::Squashed)
        }
        MergeCommitMode::NoCommit => {
            record_merge_in_progress(
                repo.git_dir(),
                other_oid,
                merge_message_text(label, options.message.as_deref()),
            )?;
            write_merge_mode_for_no_commit(
                repo.git_dir(),
                matches!(options.fast_forward, FastForwardPolicy::Never),
            )?;
            Ok(IntegrateBranchOutcome::Stopped)
        }
        MergeCommitMode::Commit => {
            drop(lock);
            let preflight = commit_preflight
                .ok_or_else(|| Error::Message("merge commit preflight missing".into()))?;
            let config = preflight.config;
            let (tree, message) = run_merge_commit_hooks(
                repo,
                options.verify,
                other_oid,
                merged.result_tree,
                merge_message_text(label, options.message.as_deref()),
            )?;
            let mut commit = CommitData {
                tree,
                parents: vec![into_oid, other_oid],
                author: preflight.author,
                committer: preflight.committer,
                author_raw: Vec::new(),
                committer_raw: Vec::new(),
                encoding: None,
                message,
                raw_message: None,
                extra_headers: Vec::new(),
            };
            let policy = ChangeIdPolicy::from_config(config.as_ref());
            let oid = stamp_change_id_on_new_commit(repo, &policy, &mut commit)
                .and_then(|()| write_commit_object(repo, &commit, None))
                .and_then(|oid| {
                    move_branch(repo, into_ref, into_oid, oid, &format!("merge {label}"))
                        .map(|()| oid)
                })
                .inspect_err(|_| {
                    let _ = clear_merge_state(repo.git_dir());
                })?;
            Ok(IntegrateBranchOutcome::Merged {
                oid,
                change_id: change_id(&commit),
            })
        }
    }
}

/// Like [`integrate_branch`], with explicit fast-forward policy for [`pull`](crate::porcelain::pull).
///
/// # Errors
///
/// Same as [`integrate_branch_with`].
#[allow(clippy::too_many_arguments)]
pub fn integrate_branch_with_options(
    repo: &Repository,
    into_ref: &str,
    into_oid: ObjectId,
    other_oid: ObjectId,
    label: &str,
    options: IntegrateBranchOptions,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<IntegrateBranchOutcome> {
    integrate_branch_with(
        repo,
        into_ref,
        into_oid,
        other_oid,
        label,
        &options.into(),
        progress,
        cancel,
    )
}

struct MergeCommitPreflight {
    author: String,
    committer: String,
    config: std::sync::Arc<ConfigSet>,
}

fn should_take_fast_forward(options: &MergeOptions, ff_possible: bool) -> bool {
    if !ff_possible {
        return false;
    }
    if matches!(options.fast_forward, FastForwardPolicy::Never) {
        return false;
    }
    !matches!(options.commit, MergeCommitMode::NoCommit)
}

fn merge_message_text(label: &str, override_message: Option<&str>) -> String {
    if let Some(msg) = override_message {
        return normalize_commit_message(msg).unwrap_or_else(|_| format!("Merge {label}\n"));
    }
    format!("Merge {label}\n")
}

/// Write `MERGE_MODE` for `--no-commit`, matching Git's bytes (empty file or `no-ff` without newline).
fn write_merge_mode_for_no_commit(git_dir: &Path, no_ff: bool) -> Result<()> {
    let bytes = if no_ff { b"no-ff".as_slice() } else { b"" };
    fs::write(git_dir.join("MERGE_MODE"), bytes).map_err(Error::Io)
}

fn write_squash_conflict_merge_msg(
    git_dir: &Path,
    paths: &[String],
    override_message: Option<&str>,
) -> Result<()> {
    let mut body = String::new();
    if let Some(msg) = override_message.filter(|m| !m.trim().is_empty()) {
        body.push_str(msg.trim());
        if !body.ends_with('\n') {
            body.push('\n');
        }
    } else {
        body.push('\n');
    }
    body.push_str("# Conflicts:\n");
    for path in paths {
        body.push_str("#\t");
        body.push_str(path);
        body.push('\n');
    }
    fs::write(git_dir.join("MERGE_MSG"), body).map_err(Error::Io)
}

fn write_squash_msg_file(repo: &Repository, into_oid: ObjectId, other_oid: ObjectId) -> Result<()> {
    let body = format_git_squash_msg(repo, into_oid, other_oid)?;
    fs::write(repo.git_dir().join("SQUASH_MSG"), body).map_err(Error::Io)
}

fn format_git_squash_msg(
    repo: &Repository,
    into_oid: ObjectId,
    other_oid: ObjectId,
) -> Result<String> {
    let (_, mut commits) = walk_commits_reachable_excluding_ancestors_of(
        repo,
        std::slice::from_ref(&other_oid),
        std::slice::from_ref(&into_oid),
        ReachableWalkLimit::Unlimited,
    )?;
    commits.reverse();
    let mut out = String::from("Squashed commit of the following:\n\n");
    for oid in commits {
        let obj = repo.odb().read(&oid)?;
        let commit = parse_commit(&obj.data)?;
        out.push_str(&format!("commit {}\n", oid.to_hex()));
        out.push_str(&format!("Author: {}\n", squash_author_line(&commit.author)));
        out.push_str(&format!("Date:   {}\n\n", squash_date_line(&commit.author)));
        for line in commit.message.lines() {
            out.push_str(&format!("    {line}\n"));
        }
        out.push('\n');
    }
    Ok(out)
}

fn squash_author_line(author: &str) -> String {
    let Some(lt) = author.find('<') else {
        return author.trim().to_owned();
    };
    let Some(gt) = author[lt..].find('>') else {
        return author.trim().to_owned();
    };
    let name = author[..lt].trim();
    let email = &author[lt..=lt + gt];
    format!("{name} {email}")
}

fn squash_date_line(author: &str) -> String {
    let Some(parsed) = parse_signature_times(author) else {
        return String::new();
    };
    let offset_str = &author[parsed.tz_hhmm_range.clone()];
    let Ok(dt) =
        time::OffsetDateTime::from_unix_timestamp(parsed.unix_seconds + parsed.tz_offset_secs)
    else {
        return String::new();
    };
    let weekday = match dt.weekday() {
        time::Weekday::Monday => "Mon",
        time::Weekday::Tuesday => "Tue",
        time::Weekday::Wednesday => "Wed",
        time::Weekday::Thursday => "Thu",
        time::Weekday::Friday => "Fri",
        time::Weekday::Saturday => "Sat",
        time::Weekday::Sunday => "Sun",
    };
    let month = match dt.month() {
        time::Month::January => "Jan",
        time::Month::February => "Feb",
        time::Month::March => "Mar",
        time::Month::April => "Apr",
        time::Month::May => "May",
        time::Month::June => "Jun",
        time::Month::July => "Jul",
        time::Month::August => "Aug",
        time::Month::September => "Sep",
        time::Month::October => "Oct",
        time::Month::November => "Nov",
        time::Month::December => "Dec",
    };
    format!(
        "{weekday} {month} {} {:02}:{:02}:{:02} {} {offset_str}",
        dt.day(),
        dt.hour(),
        dt.minute(),
        dt.second(),
        dt.year()
    )
}

fn stored_change_id_for_commit(repo: &Repository, oid: ObjectId) -> Result<Option<ChangeId>> {
    let obj = repo.odb().read(&oid)?;
    Ok(change_id(&parse_commit(&obj.data)?))
}

/// Options for [`continue_merge`].
#[derive(Debug, Clone)]
pub struct ContinueOptions {
    /// When set, replaces the message from `MERGE_MSG` (comment lines stripped).
    pub message: Option<String>,
    /// Author of the merge commit; `None` uses the repository's author identity
    /// ([`Repository::identity`]).
    pub author: Option<Signature>,
    /// Committer of the merge commit; `None` uses the repository's committer identity.
    pub committer: Option<Signature>,
}

/// Result of [`continue_merge`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContinueOutcome {
    /// New merge commit OID.
    pub oid: ObjectId,
    /// Stored `change-id` on the merge commit when present.
    pub change_id: Option<ChangeId>,
}

/// Failure modes for [`continue_merge`].
#[derive(Debug, Error)]
pub enum ContinueMergeError {
    /// No `MERGE_HEAD` (or other merge sentinel) is recorded.
    #[error("there is no merge in progress")]
    NoMergeInProgress,
    /// Stage-1/2/3 entries remain in the index.
    #[error("you still have unmerged paths: {}", paths.join(", "))]
    UnmergedPaths {
        /// Repository-relative paths still in conflict stages.
        paths: Vec<String>,
    },
    /// Work tree content is resolved but the index still has conflict stages (`commit.autoStage=false`).
    #[error("resolved in the work tree but not staged: {}", paths.join(", "))]
    ResolvedNotStaged {
        /// Repository-relative paths cleared of conflict markers but not staged.
        paths: Vec<String>,
    },
    /// The resolved message would be empty after cleanup.
    #[error("empty commit message")]
    EmptyMessage,
    /// Underlying repository or commit failure.
    #[error(transparent)]
    Repository(#[from] Error),
}

/// Finish an in-progress merge after conflicts are resolved or after `--no-commit`.
///
/// Builds a merge commit from the current index tree with parents `HEAD` and each
/// `MERGE_HEAD`, clears merge state (including autostash and rerere), and updates
/// the checked-out branch. Auto-staging reports [`crate::progress::ProgressPhase::StagingFiles`]
/// and polls `cancel`, with the same cancel points as [`crate::porcelain::commit::create_commit`].
///
/// # Errors
///
/// Returns [`ContinueMergeError::NoMergeInProgress`] when no merge is active,
/// [`ContinueMergeError::UnmergedPaths`] when conflict stages remain, or propagates
/// commit and I/O failures (including [`Error::Cancelled`]) as [`ContinueMergeError::Repository`].
pub fn continue_merge(
    repo: &Repository,
    options: &ContinueOptions,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> std::result::Result<ContinueOutcome, ContinueMergeError> {
    let merge_heads = read_merge_heads(repo.git_dir())?;
    if merge_heads.is_empty() {
        return Err(ContinueMergeError::NoMergeInProgress);
    }

    let config = repo.config().map_err(ContinueMergeError::Repository)?;
    let auto_stage = default_commit_scope_from_config(config.as_ref()) == CommitScope::AutoStage;

    let mut index = repo.load_index().map_err(ContinueMergeError::Repository)?;
    if auto_stage {
        stage_for_commit_on_index(repo, &mut index, progress, cancel, false)
            .map_err(ContinueMergeError::Repository)?;
    }
    if index.has_unmerged_entries() {
        let paths = unmerged_index_paths(&index);
        if !auto_stage {
            let resolved = resolved_not_staged_paths(repo, &index, &paths);
            if !resolved.is_empty() {
                return Err(ContinueMergeError::ResolvedNotStaged { paths: resolved });
            }
        }
        return Err(ContinueMergeError::UnmergedPaths { paths });
    }

    let message = resolve_continue_merge_message(repo.git_dir(), options.message.as_deref())?;
    let req = CommitRequest {
        message,
        message_from_merge: options.message.is_none(),
        author: options.author.clone(),
        committer: options.committer.clone(),
        allow_empty: false,
        ..Default::default()
    };
    let outcome = create_commit_with_loaded_index(repo, &mut index, &req, progress, cancel)
        .map_err(ContinueMergeError::Repository)?;
    Ok(ContinueOutcome {
        oid: outcome.oid,
        change_id: outcome.change_id,
    })
}

fn resolve_continue_merge_message(
    git_dir: &Path,
    override_message: Option<&str>,
) -> std::result::Result<String, ContinueMergeError> {
    if let Some(raw) = override_message {
        return normalize_commit_message(raw).map_err(|_| ContinueMergeError::EmptyMessage);
    }

    let Some(raw) = read_merge_msg(git_dir).map_err(ContinueMergeError::Repository)? else {
        return Err(ContinueMergeError::EmptyMessage);
    };
    let processed = stripspace_process(
        raw.as_bytes(),
        &StripspaceMode::StripComments("#".to_owned()),
    );
    let message = String::from_utf8(processed).map_err(|_| ContinueMergeError::EmptyMessage)?;
    if message.trim().is_empty() {
        return Err(ContinueMergeError::EmptyMessage);
    }
    let mut message = message;
    if !message.ends_with('\n') {
        message.push('\n');
    }
    Ok(message)
}

fn unmerged_index_paths(index: &Index) -> Vec<String> {
    let mut paths: Vec<String> = index
        .entries
        .iter()
        .filter(|e| e.stage() != 0)
        .map(|e| String::from_utf8_lossy(&e.path).into_owned())
        .collect();
    paths.sort();
    paths.dedup();
    paths
}

fn resolved_not_staged_paths(repo: &Repository, index: &Index, unmerged: &[String]) -> Vec<String> {
    let work_tree = match repo.work_tree() {
        Some(wt) => wt,
        None => return Vec::new(),
    };
    let Ok(rules) = WorktreeRules::from_repository(repo, index) else {
        return Vec::new();
    };
    let mut resolved = Vec::new();
    for path in unmerged {
        let raw_path = path.as_bytes();
        let abs = work_tree.join(path);
        let Ok(meta) = std::fs::symlink_metadata(&abs) else {
            continue;
        };
        let idx_mode = index
            .entries
            .iter()
            .find(|e| e.path == raw_path && e.stage() != 0)
            .map(|e| e.mode)
            .unwrap_or(0o100644);
        if !crate::rerere::worktree_metadata_needs_conflict_marker_inspection(&meta, idx_mode) {
            continue;
        }
        let Ok(wt_bytes) = std::fs::read(&abs) else {
            continue;
        };
        let marker_size = rules
            .file_attrs(path, false)
            .effective_conflict_marker_size();
        if !crate::rerere::worktree_bytes_have_unresolved_conflict_markers(&wt_bytes, marker_size) {
            resolved.push(path.clone());
        }
    }
    resolved.sort();
    resolved
}

/// Abort an in-progress merge, restoring index and worktree to
/// [`read_orig_head_for_repository`].
///
/// A merge autostash recorded in `MERGE_AUTOSTASH` (left by a pull whose merge commit a hook
/// refused) is applied again afterwards, as `git merge --abort` does.
///
/// # Errors
///
/// Returns [`Error::Message`] when no merge is in progress, or propagates checkout and I/O errors.
pub fn abort_branch_merge(repo: &Repository) -> Result<()> {
    let git_dir = repo.git_dir();
    let in_merge = !read_merge_heads(git_dir)?.is_empty();
    let squash_conflict =
        git_dir.join("SQUASH_MSG").is_file() && git_dir.join("MERGE_MSG").is_file();
    if !in_merge && !squash_conflict {
        return Err(Error::Message(
            "there is no merge in progress — nothing to abort".into(),
        ));
    }
    restore_pre_merge_state(repo)
}

fn restore_pre_merge_state(repo: &Repository) -> Result<()> {
    let orig = read_orig_head_for_repository(repo)?
        .ok_or_else(|| Error::Message("merge in progress but ORIG_HEAD is missing".into()))?;
    let head_tree = repo.odb().commit_tree(&orig)?;

    let old_index = repo.load_index()?;
    let from_tree = write_tree_from_index(repo.odb(), &old_index, "")?;
    let mut clean_index = index_from_tree_with_worktree_stats(repo, &head_tree)?;
    // `from_tree` leaves out unmerged paths, so the diff never deletes a conflicted file the
    // merge wrote at a path the pre-merge commit does not have.
    let mut conflict_only: Vec<&[u8]> = old_index
        .entries()
        .iter()
        .filter(|e| e.stage() != 0 && clean_index.get(&e.path, 0).is_none())
        .map(|e| e.path.as_slice())
        .collect();
    conflict_only.dedup();
    repo.write_index(&mut clean_index)?;
    let changes = diff_trees(repo.odb(), Some(&from_tree), Some(&head_tree), "")?;
    checkout::checkout_tree_changes(repo, &changes)?;
    if let Some(work_tree) = repo.work_tree() {
        for path in conflict_only {
            let abs = crate::index::worktree_path_from_index_rel(work_tree, path);
            if abs.symlink_metadata().is_ok_and(|meta| !meta.is_dir()) {
                fs::remove_file(&abs)?;
                checkout::remove_empty_parent_dirs(work_tree, &abs);
            }
        }
    }
    let autostash = fs::read_to_string(repo.git_dir().join("MERGE_AUTOSTASH")).ok();
    clear_merge_state(repo.git_dir())?;
    if let Some(oid) = autostash
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        crate::porcelain::stash::restore_operation_autostash(repo, &ObjectId::from_hex(oid)?)?;
    }
    Ok(())
}

fn merge_overwrite_error_message(paths: &[String]) -> Error {
    if paths.is_empty() {
        Error::dirty_worktree(crate::error::WorktreeOperation::Merge, Vec::new())
    } else {
        let mut paths = paths.to_vec();
        paths.sort();
        paths.dedup();
        Error::WouldOverwrite {
            reason: OverwriteReason::LocalChanges,
            paths,
            message: "local changes would be overwritten by merge".into(),
        }
    }
}

fn map_tree_transition_prepare_error_for_merge(err: TreeTransitionPrepareError) -> Error {
    match err {
        TreeTransitionPrepareError::OverwritePaths(paths) => merge_overwrite_error_message(&paths),
        TreeTransitionPrepareError::Failed(err) => err,
    }
}

fn ensure_merge_tree_transition_allowed(
    repo: &Repository,
    from_tree: Option<&ObjectId>,
    to_tree: &ObjectId,
) -> Result<()> {
    prepare_tree_checkout(repo, from_tree, to_tree)?;
    match verify_tree_transition_allow_local(repo, from_tree, to_tree) {
        Ok(()) => Ok(()),
        Err(TreeTransitionVerifyError::WouldOverwrite(paths)) => {
            Err(merge_overwrite_error_message(&paths))
        }
        Err(TreeTransitionVerifyError::Failed(err)) => Err(err),
    }
}

fn merge_checkout_tree_transition(
    repo: &Repository,
    from_tree: Option<&ObjectId>,
    to_tree: &ObjectId,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<()> {
    prepare_tree_checkout(repo, from_tree, to_tree)?;
    let prepared = prepare_tree_transition_allow_local(repo, from_tree, to_tree, &HashSet::new())
        .map_err(map_tree_transition_prepare_error_for_merge)?;
    checkout_prepared_tree_transition_for_merge(repo, prepared, progress, cancel)
}

fn empty_tree_oid(repo: &Repository) -> Result<ObjectId> {
    repo.odb().empty_tree_oid()
}

fn conflict_path_set(merged: &TreeMergeOutput) -> BTreeSet<Vec<u8>> {
    let mut set = BTreeSet::new();
    set.extend(merged.conflict_content.keys().cloned());
    for entry in merged.index.entries() {
        if entry.stage() != 0 {
            set.insert(entry.path.clone());
        }
    }
    set
}

/// Write the conflicted merge result to the index and work tree.
///
/// Checks `cancel` before the index is written. A cancel during the checkout returns
/// [`Error::Cancelled`] after the checkout rolled the work tree back and the previous index
/// was put back, so no conflict stages are left without merge state.
pub(crate) fn apply_conflict_merge_worktree(
    repo: &Repository,
    head_tree: &ObjectId,
    merged: &TreeMergeOutput,
    progress: &mut dyn ProgressSink,
    cancel: &dyn Cancel,
) -> Result<()> {
    let work_tree = repo
        .work_tree()
        .ok_or_else(|| Error::PathError("cannot update a bare repository's working tree".into()))?;
    let materialized = materialized_merge_result_tree(repo.odb(), merged)?;
    let prepared =
        prepare_tree_transition_allow_local(repo, Some(head_tree), &materialized, &HashSet::new())
            .map_err(map_tree_transition_prepare_error_for_merge)?;
    let preserve_worktree_paths = prepared.preserve_worktree_paths().clone();
    let conflict_paths = conflict_path_set(merged);
    let mut index = repo.load_index()?;
    apply_tree_merge_output_to_index(&mut index, merged);
    if index.has_unmerged_entries() {
        index.clear_cache_tree();
    }
    poll_cancel(progress, cancel)?;
    let index_path = repo.index_path();
    let previous_index = fs::read(&index_path).ok();
    repo.write_index(&mut index)?;

    let stage0_tree = write_tree_from_index(repo.odb(), &index, "")?;
    let changes = diff_trees(repo.odb(), Some(head_tree), Some(&stage0_tree), "")?;
    let filtered: Vec<_> = changes
        .into_iter()
        .filter(|change| {
            let path = change
                .new_path
                .as_deref()
                .or(change.old_path.as_deref())
                .unwrap_or("");
            !conflict_paths.contains(path.as_bytes()) && !preserve_worktree_paths.contains(path)
        })
        .collect();
    if let Err(err) = checkout::checkout_tree_changes_reporting(repo, &filtered, progress, cancel) {
        if matches!(err, Error::Cancelled) {
            match &previous_index {
                Some(bytes) => fs::write(&index_path, bytes)?,
                None => fs::remove_file(&index_path)?,
            }
        }
        return Err(err);
    }

    let rules = WorktreeRules::from_repository(repo, &index)?;
    for (path, oid) in &merged.conflict_content {
        let mode = index
            .get(path, 2)
            .or_else(|| index.get(path, 3))
            .map(|e| e.mode)
            .unwrap_or(0o100644);
        let rel = String::from_utf8_lossy(path);
        checkout::write_smudged_blob_to_worktree(repo, work_tree, &rules, rel.as_ref(), oid, mode)?;
    }
    refresh_stage0_index_stats_from_worktree(repo, work_tree, &mut index)?;
    repo.write_index(&mut index)?;
    Ok(())
}

fn record_merge_in_progress(git_dir: &Path, other_oid: ObjectId, merge_msg: String) -> Result<()> {
    fs::write(
        git_dir.join("MERGE_HEAD"),
        format!("{}\n", other_oid.to_hex()),
    )
    .map_err(Error::Io)?;
    fs::write(git_dir.join("MERGE_MSG"), merge_msg).map_err(Error::Io)?;
    Ok(())
}

/// Run the hooks Git runs before a clean merge records its commit, after the merged index and
/// work tree are written: `pre-merge-commit` (unless `verify` skips it), then, with the merge
/// state recorded, `prepare-commit-msg <MERGE_MSG> merge` and `commit-msg <MERGE_MSG>` (unless
/// `verify` skips it).
///
/// Returns the tree to commit, rebuilt from the index when `pre-merge-commit` ran (it may have
/// staged changes), and the message, read back from `MERGE_MSG` when a message hook ran.
///
/// # Errors
///
/// [`Error::Hook`] when a hook refuses or cannot start, [`Error::IndexUnmerged`] when
/// `pre-merge-commit` left conflict stages, and I/O errors. On any error the merge state
/// (`MERGE_HEAD`, `ORIG_HEAD`, `MERGE_MSG` with `message`) is left recorded and the branch is
/// unchanged, so the merge can be finished with a commit or abandoned with an abort.
fn run_merge_commit_hooks(
    repo: &Repository,
    verify: HookPolicy,
    other_oid: ObjectId,
    tree: ObjectId,
    message: String,
) -> Result<(ObjectId, String)> {
    let git_dir = repo.git_dir();
    let index_path = repo.index_path();
    let env = CommitHookEnv {
        index_file: Some(&index_path),
        git_editor: Some(":"),
        git_prefix: None,
        extra_env: &[],
    };
    let run = || -> Result<(ObjectId, String)> {
        let mut tree = tree;
        if verify != HookPolicy::SkipVerify {
            let name = HookName::PreMergeCommit.as_str();
            if run_commit_hook(repo, name, &[], None, &env)?.check(name)? {
                let index = repo.load_index()?;
                if index.has_unmerged_entries() {
                    return Err(Error::IndexUnmerged);
                }
                tree = write_tree_from_index(repo.odb(), &index, "")?;
            }
        }
        record_merge_in_progress(git_dir, other_oid, message.clone())?;
        let edited = run_commit_message_hooks(
            repo,
            &git_dir.join("MERGE_MSG"),
            MessageSource::Merge,
            verify,
            &env,
            &mut Vec::new(),
        )?;
        Ok((tree, edited.unwrap_or_else(|| message.clone())))
    };
    match run() {
        Ok(result) => Ok(result),
        Err(err) => {
            record_merge_in_progress(git_dir, other_oid, message)?;
            Err(err)
        }
    }
}

fn strict_commit_identity(repo: &Repository, role: IdentRole) -> Result<String> {
    Ok(repo.identity(role, repo.identity_now())?.header_line())
}

fn move_branch(
    repo: &Repository,
    refname: &str,
    old: ObjectId,
    new: ObjectId,
    reason: &str,
) -> Result<()> {
    update_checked_out_branch(repo, refname, Some(old), new, reason)
}

/// Refuse to touch the work tree when `branch_ref` no longer points at `expected` (`None`:
/// the branch must not exist), so a concurrent ref update is reported before anything changes.
pub(crate) fn ensure_branch_tip(
    repo: &Repository,
    branch_ref: &str,
    expected: Option<ObjectId>,
) -> Result<()> {
    let current = repo.refs().resolve(branch_ref).ok();
    refs::verify_branch_commit_cas(expected, current, branch_ref)
}

/// Point the checked-out branch `branch_ref` from `expected_old` (`None`: unborn) at `new`
/// with a compare-and-swap through the repository's ref store, then append branch and `HEAD`
/// reflog lines (per `core.logAllRefUpdates`) stamped with the repository's committer identity.
///
/// The reflog lines are appended rather than written in the ref transaction, because the
/// files store reloads and rewrites a ref's whole reflog when a transaction logs to it. Once
/// the ref has moved the operation has happened, so a failed append is reported as
/// [`Warning::ReflogNotWritten`] on the repository's diagnostics sink instead of an error.
///
/// # Errors
///
/// Config load and compare-and-swap failures, all before the ref changes.
pub(crate) fn update_checked_out_branch(
    repo: &Repository,
    branch_ref: &str,
    expected_old: Option<ObjectId>,
    new: ObjectId,
    reason: &str,
) -> Result<()> {
    let config = repo.config()?;
    let identity =
        resolve_loose_committer_identity_with(repo.environment(), &config, repo.identity_now());
    refs::commit_ref_update_on_store(
        repo.refs(),
        RefUpdate {
            name: branch_ref.to_owned(),
            new_value: Some(RawRef::Direct(new)),
            expected: expected_old.map_or(Expected::Missing, Expected::Oid),
            reflog: None,
            flags: RefUpdateFlags::default(),
        },
    )?;
    let old = expected_old.unwrap_or_else(crate::diff::zero_oid);
    for name in [branch_ref, "HEAD"] {
        let autocreate = refs::should_autocreate_reflog_with_config(&config, repo.git_dir(), name);
        if let Err(err) = refs::append_reflog_on_store(
            repo.refs(),
            name,
            &old,
            &new,
            &identity,
            reason,
            autocreate,
            &config,
        ) {
            repo.diagnostics().warn(Warning::ReflogNotWritten {
                refname: name.to_owned(),
                detail: err.to_string(),
            });
        }
    }
    Ok(())
}

#[cfg(test)]
mod integrate_tests {
    use std::collections::HashSet;

    use super::*;
    use crate::environment::RepositoryOptions;
    use crate::index::{Index, IndexEntry, MODE_REGULAR};
    use std::collections::BTreeMap;

    fn index_entry(path: &str, stage: u8) -> IndexEntry {
        let mut entry = IndexEntry {
            ctime_sec: 0,
            ctime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
            dev: 0,
            ino: 0,
            mode: MODE_REGULAR,
            uid: 0,
            gid: 0,
            size: 0,
            oid: crate::diff::zero_oid(),
            flags: 0,
            flags_extended: None,
            path: path.as_bytes().to_vec(),
            base_index_pos: 0,
        };
        entry.set_stage(stage);
        entry
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn reduce_octopus_merge_heads_drops_ancestor() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("f.txt"), "a\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "a"]);
        let a: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("a");
        std::fs::write(tmp.path().join("f.txt"), "b\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "b"]);
        let b: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("b");
        let (oids, names) =
            reduce_octopus_merge_heads(&repo, &[a, b], &["a".into(), "b".into()]).expect("reduce");
        assert_eq!(oids, vec![b]);
        assert_eq!(names, vec!["b".to_owned()]);
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn compose_fast_forward_index_keeps_staged_additions() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("tracked.txt"), "v1\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "tracked.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "head"]);
        let head: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("head");
        let head_tree = repo.odb().commit_tree(&head).expect("head tree");
        std::fs::write(tmp.path().join("tracked.txt"), "v2\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "tracked.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "target"]);
        let target_tree = repo
            .odb()
            .commit_tree(
                &grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
                    .trim()
                    .parse()
                    .expect("target"),
            )
            .expect("target tree");
        std::fs::write(tmp.path().join("new.txt"), "staged\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "new.txt"]);
        let index = repo.load_index().expect("index");
        let ff = compose_fast_forward_index(&repo, target_tree, head_tree, &index).expect("ff");
        assert!(ff.get(b"new.txt", 0).is_some());
        assert!(ff.get(b"tracked.txt", 0).is_some());
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn predict_merge_mem_overlay_guard_restores_outer_scope() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q", "-b", "main"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("f.txt"), "a\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "one"]);
        let head: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("head");
        grit_test_support::git(tmp.path(), &["branch", "topic"]);
        std::fs::write(tmp.path().join("f.txt"), "b\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "two"]);
        let tip: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("tip");
        grit_test_support::git(tmp.path(), &["checkout", "main"]);

        repo.odb().enable_mem_overlay();
        assert!(repo.odb().is_mem_overlay_active());
        let _ =
            predict_merge(&repo, head, tip, &MergePredictionOptions::default()).expect("predict");
        assert!(
            repo.odb().is_mem_overlay_active(),
            "outer mem overlay must stay active after predict_merge"
        );
        repo.odb().disable_mem_overlay();
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn write_merge_tree_keeps_objects_in_outer_overlay() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let git = |args: &[&str]| grit_test_support::git(tmp.path(), args);
        git(&["init", "-q", "-b", "main"]);
        std::fs::write(tmp.path().join("f.txt"), "1\n2\n3\n4\n5\n6\n").expect("write");
        git(&["add", "f.txt"]);
        git(&["commit", "-qm", "base"]);
        git(&["switch", "-qc", "topic"]);
        std::fs::write(tmp.path().join("f.txt"), "one\n2\n3\n4\n5\n6\n").expect("write");
        git(&["commit", "-qam", "topic"]);
        git(&["switch", "-q", "main"]);
        std::fs::write(tmp.path().join("f.txt"), "1\n2\n3\n4\n5\nsix\n").expect("write");
        git(&["commit", "-qam", "main"]);
        let oid =
            |spec: &str| -> ObjectId { git(&["rev-parse", spec]).trim().parse().expect("oid") };
        let (main, topic) = (oid("main"), oid("topic"));
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");

        repo.odb().enable_mem_overlay();
        let loose_before = repo.odb().count_loose_objects().expect("count");
        let written = write_merge_tree(&repo, main, topic, &MergePredictionOptions::default())
            .expect("write_merge_tree");
        assert!(written.is_clean());
        assert!(repo.odb().is_mem_overlay_active());
        assert_eq!(
            repo.odb().count_loose_objects().expect("count"),
            loose_before
        );
        assert!(repo.odb().exists(&written.tree));

        repo.odb().disable_mem_overlay();
        assert!(!repo.odb().exists(&written.tree));
        let written = write_merge_tree(&repo, main, topic, &MergePredictionOptions::default())
            .expect("write_merge_tree");
        assert!(!repo.odb().is_mem_overlay_active());
        assert!(repo.odb().count_loose_objects().expect("count") > loose_before);
        assert!(repo.odb().exists(&written.tree));
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn integrate_branch_fast_forward_and_up_to_date() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q", "-b", "main"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("f.txt"), "v1\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "one"]);
        let head: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("head");
        grit_test_support::git(tmp.path(), &["checkout", "-q", "-b", "topic"]);
        std::fs::write(tmp.path().join("f.txt"), "v2\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "two"]);
        let tip: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("tip");
        grit_test_support::git(tmp.path(), &["checkout", "main"]);
        let up = integrate_branch(
            &repo,
            "refs/heads/main",
            head,
            head,
            "topic",
            &mut crate::progress::NullProgress,
            &crate::progress::NeverCancel,
        )
        .expect("up");
        assert_eq!(up, IntegrateBranchOutcome::UpToDate);
        let ff = integrate_branch(
            &repo,
            "refs/heads/main",
            head,
            tip,
            "topic",
            &mut crate::progress::NullProgress,
            &crate::progress::NeverCancel,
        )
        .expect("ff");
        assert!(matches!(ff, IntegrateBranchOutcome::FastForward { .. }));
    }

    #[test]
    fn compose_octopus_final_index_carries_staged_paths() {
        let mut pre = Index::new();
        pre.add_or_replace(index_entry("staged.txt", 0));
        let mut final_index = Index::new();
        final_index.add_or_replace(index_entry("merged.txt", 0));
        compose_octopus_final_index(&pre, &mut final_index);
        assert!(final_index.get(b"staged.txt", 0).is_some());
        assert!(final_index.get(b"merged.txt", 0).is_some());
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn tree_to_index_entries_and_map_roundtrip() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("a.txt"), "a\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "a.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "c"]);
        let tree: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD^{tree}"])
            .trim()
            .parse()
            .expect("tree");
        let entries = tree_to_index_entries(&repo, &tree, "").expect("entries");
        let map = tree_to_map(entries.clone());
        assert_eq!(map.len(), entries.len());
    }

    #[test]
    fn tree_merge_conflict_paths_unions_markers_and_unmerged_index() {
        let mut index = Index::new();
        index.add_or_replace(index_entry("b.txt", 1));
        index.add_or_replace(index_entry("b.txt", 2));
        let mut conflict_content = BTreeMap::new();
        conflict_content.insert(b"a.txt".to_vec(), crate::diff::zero_oid());
        let merged = TreeMergeOutput {
            index,
            conflict_content,
            result_tree: crate::diff::zero_oid(),
            touched_paths: HashSet::new(),
            rename_conflicts: Vec::new(),
            directory_rename_conflicts: Vec::new(),
        };
        let paths: Vec<String> = conflicts_from_tree_merge(&merged)
            .into_iter()
            .map(|c| c.path)
            .collect();
        assert_eq!(paths, vec!["a.txt".to_owned(), "b.txt".to_owned()]);
        assert!(tree_merge_has_conflicts(&merged));
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn integrate_branch_merged_without_conflicts() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q", "-b", "main"]);
        grit_test_support::git(tmp.path(), &["config", "user.name", "Test"]);
        grit_test_support::git(tmp.path(), &["config", "user.email", "t@example.com"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("shared.txt"), "base\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "shared.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "base"]);
        grit_test_support::git(tmp.path(), &["switch", "-c", "topic"]);
        std::fs::write(tmp.path().join("shared.txt"), "topic\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "shared.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "topic"]);
        let topic: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "topic"])
            .trim()
            .parse()
            .expect("topic");
        grit_test_support::git(tmp.path(), &["checkout", "main"]);
        std::fs::write(tmp.path().join("main-only.txt"), "main\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "main-only.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "main"]);
        let main: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("main");
        let outcome = integrate_branch(
            &repo,
            "refs/heads/main",
            main,
            topic,
            "topic",
            &mut crate::progress::NullProgress,
            &crate::progress::NeverCancel,
        )
        .expect("merge");
        let IntegrateBranchOutcome::Merged { oid, .. } = outcome else {
            panic!("expected clean merge, got {outcome:?}");
        };
        let tip: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "refs/heads/main"])
            .trim()
            .parse()
            .expect("tip");
        assert_eq!(tip, oid);
        grit_test_support::git(tmp.path(), &["fsck", "--strict"]);
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn integrate_branch_conflicts_then_abort() {
        let tmp = tempfile::tempdir().expect("tempdir");
        grit_test_support::git(tmp.path(), &["init", "-q", "-b", "main"]);
        let repo =
            Repository::discover(Some(tmp.path()), &RepositoryOptions::empty()).expect("repo");
        std::fs::write(tmp.path().join("f.txt"), "base\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "base"]);
        grit_test_support::git(tmp.path(), &["switch", "-c", "topic"]);
        std::fs::write(tmp.path().join("f.txt"), "theirs\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "theirs"]);
        let topic: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "topic"])
            .trim()
            .parse()
            .expect("topic");
        grit_test_support::git(tmp.path(), &["checkout", "main"]);
        std::fs::write(tmp.path().join("f.txt"), "ours\n").expect("write");
        grit_test_support::git(tmp.path(), &["add", "f.txt"]);
        grit_test_support::git(tmp.path(), &["commit", "-m", "ours"]);
        let main: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("main");
        let outcome = integrate_branch(
            &repo,
            "refs/heads/main",
            main,
            topic,
            "topic",
            &mut crate::progress::NullProgress,
            &crate::progress::NeverCancel,
        )
        .expect("merge");
        let IntegrateBranchOutcome::Conflicts { paths, .. } = outcome else {
            panic!("expected conflicts, got {outcome:?}");
        };
        assert!(paths.iter().any(|p| p == "f.txt"));
        assert!(tmp.path().join(".git/MERGE_HEAD").exists());
        abort_branch_merge(&repo).expect("abort");
        assert!(!tmp.path().join(".git/MERGE_HEAD").exists());
        let tip: ObjectId = grit_test_support::git(tmp.path(), &["rev-parse", "HEAD"])
            .trim()
            .parse()
            .expect("tip");
        assert_eq!(tip, main);
    }

    #[test]
    fn continue_merge_errors_list_paths_plainly() {
        let paths = vec!["f.txt".to_owned(), "dir/g h.txt".to_owned()];
        let unmerged = ContinueMergeError::UnmergedPaths {
            paths: paths.clone(),
        }
        .to_string();
        assert_eq!(
            unmerged,
            "you still have unmerged paths: f.txt, dir/g h.txt"
        );
        let unstaged = ContinueMergeError::ResolvedNotStaged { paths }.to_string();
        assert_eq!(
            unstaged,
            "resolved in the work tree but not staged: f.txt, dir/g h.txt"
        );
        for message in [unmerged, unstaged] {
            assert!(!message.contains(['[', ']', '"']), "{message}");
        }
    }
}