sley-remote 0.2.0

Callable fetch, push, clone, and ls-remote orchestration over the sley transport and object stack.
Documentation
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
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
//! Callable push orchestration for HTTP(S) and local (`file://`/path) remotes.
//!
//! [`push`] sequences the moved transport plumbing ([`crate::http`],
//! [`crate::local`]) and the protocol codecs ([`sley_protocol`]) into the full
//! push flow: it advertises the remote's refs, plans the receive-pack commands
//! for the requested refspecs, rejects non-fast-forward updates (unless forced),
//! builds the packfile of the objects the remote is missing, sends the
//! receive-pack request, and parses the report-status. Everything is taken as
//! explicit parameters — `git_dir`, `common_git_dir`, the [`ObjectFormat`], the
//! repository [`GitConfig`], the already-resolved destination, the push refspecs,
//! a [`PushOptions`], and the seam objects ([`CredentialProvider`],
//! [`ProgressSink`]) — so it never reads process-global state, parses arguments,
//! or prints. The structured result ([`PushOutcome`]) carries the executed
//! receive-pack commands and the remote's report-status for the caller to format
//! into git's "To <remote>" summary and to drive any set-upstream config write.
//!
//! SSH push still lives in the CLI; only HTTP and local move here. The
//! push-planning helpers are shared (the CLI's SSH path calls the same `pub`
//! functions) so there is a single implementation.

use std::collections::HashMap;
#[cfg(feature = "http")]
use std::io::Read;
use std::path::{Path, PathBuf};

use sley_config::GitConfig;
use sley_core::{GitError, ObjectFormat, ObjectId, Result};
use sley_object::{Commit, ObjectType};
use sley_odb::{FileObjectDatabase, ObjectReader, collect_reachable_object_ids};
#[cfg(feature = "http")]
use sley_protocol::{
    GitService, ReceivePackFeatures, ReceivePackPushRequestOptions, parse_receive_pack_features,
    read_receive_pack_report_status, smart_http_rpc_request_content_type,
    smart_http_rpc_result_content_type,
};
use sley_protocol::{
    PushSourceRef, ReceivePackCommand, ReceivePackCommandStatus, ReceivePackPushRequest,
    ReceivePackReportStatus, ReceivePackRequest, ReceivePackUnpackStatus, RefAdvertisement,
    RefSpec, parse_refspec, plan_push_commands,
};

use crate::pack::push_pack_roots;
#[cfg(feature = "http")]
use crate::pack::{PushPackRequest, build_receive_pack_body};
use sley_refs::{FileRefStore, Ref, RefTarget};
use sley_transport::RemoteUrl;
#[cfg(feature = "http")]
use sley_transport::{HttpClient, http_smart_rpc_url};

use crate::{CredentialProvider, ProgressSink};

/// How a push delivers refs and objects to the remote.
///
/// The caller resolves the remote (URL rewriting, `pushurl` selection,
/// repository discovery — all process-state dependent) and hands `push` a
/// concrete transport.
pub enum PushDestination {
    /// A smart-HTTP(S) remote at the given already-resolved URL.
    Http(RemoteUrl),
    /// An SSH remote at the given already-resolved URL. Pushed by spawning `ssh`
    /// (the credential seam is unused — the `ssh` program owns authentication).
    Ssh(RemoteUrl),
    /// A native anonymous `git://` remote at the given already-resolved URL.
    Git(RemoteUrl),
    /// A local repository served in-process from `git_dir`.
    Local {
        /// The remote repository's `$GIT_DIR`.
        git_dir: PathBuf,
        /// The remote repository's common `$GIT_DIR` (object format source).
        common_git_dir: PathBuf,
    },
}

/// Controls for a [`push`] run, mirroring the `git push` flags the CLI parses
/// that affect the wire/planning behavior the library owns.
///
/// `set-upstream` (`-u`) is intentionally absent: it only writes
/// `branch.<name>.remote`/`merge` config, which is a caller concern (the library
/// returns the executed commands in [`PushOutcome::commands`] so the caller can
/// drive that write). Atomic / push-options / thin are likewise absent because
/// the CLI's HTTP and local push paths accept but do not act on them today; this
/// stays a faithful refactor of the existing behavior.
#[derive(Debug, Clone, Copy, Default)]
pub struct PushOptions {
    /// Suppress the per-command side-effect of negotiating the `quiet`
    /// receive-pack capability (matching `git push --quiet`). Output suppression
    /// itself is a caller concern — the library always returns the outcome.
    pub quiet: bool,
    /// Force every update, bypassing the non-fast-forward check. Per-refspec `+`
    /// forces are honored independently of this flag.
    pub force: bool,
}

/// One caller-authored receive-pack command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushCommand {
    /// The object id to install at `dst`, or `None` for a delete.
    pub src: Option<ObjectId>,
    /// Full destination ref name.
    pub dst: String,
    /// The expected remote old object id. `None` lowers to the zero oid, which
    /// receive-pack treats as create-only for updates and unconditional for
    /// deletes.
    pub expected_old: Option<ObjectId>,
    /// Bypass the non-fast-forward check for this command. This mirrors a
    /// refspec-local leading `+`; [`PushOptions::force`] still forces every
    /// command in the plan.
    pub force: bool,
}

/// A typed push action that preserves the caller's exact old/new/delete intent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PushAction {
    Create {
        dst: String,
        new: ObjectId,
    },
    Update {
        dst: String,
        old: ObjectId,
        new: ObjectId,
    },
    Delete {
        dst: String,
        old: Option<ObjectId>,
    },
}

impl From<PushAction> for PushCommand {
    fn from(value: PushAction) -> Self {
        match value {
            PushAction::Create { dst, new } => Self {
                src: Some(new),
                dst,
                expected_old: None,
                force: false,
            },
            PushAction::Update { dst, old, new } => Self {
                src: Some(new),
                dst,
                expected_old: Some(old),
                force: false,
            },
            PushAction::Delete { dst, old } => Self {
                src: None,
                dst,
                expected_old: old,
                force: false,
            },
        }
    }
}

/// A caller-authored push plan. This is distinct from [`PushPlan`], which is a
/// negotiated, executable transport token returned by [`plan_push`].
#[derive(Debug, Clone)]
pub struct PushActionPlan {
    pub commands: Vec<PushCommand>,
    pub pack_objects: Vec<ObjectId>,
    pub options: PushOptions,
}

impl PushActionPlan {
    pub fn from_actions(actions: Vec<PushAction>, options: PushOptions) -> Self {
        Self {
            commands: actions.into_iter().map(PushCommand::from).collect(),
            pack_objects: Vec::new(),
            options,
        }
    }

    pub fn from_commands(commands: Vec<PushCommand>, options: PushOptions) -> Self {
        Self {
            commands,
            pack_objects: Vec::new(),
            options,
        }
    }

    pub fn from_commands_and_infer_pack_roots(
        commands: Vec<PushCommand>,
        options: PushOptions,
    ) -> Self {
        let mut pack_objects = Vec::new();
        for command in &commands {
            let Some(src) = command.src.as_ref() else {
                continue;
            };
            if !pack_objects.contains(src) {
                pack_objects.push(*src);
            }
        }
        Self {
            commands,
            pack_objects,
            options,
        }
    }
}

/// The structured result of a [`push`].
#[derive(Debug, Clone, Default)]
pub struct PushOutcome {
    /// The receive-pack commands that were executed, in planning order. Each
    /// carries the ref name and its old/new object id; the caller formats these
    /// into git's "To <remote>" summary and uses them to drive set-upstream.
    /// Empty when nothing matched the refspecs (a no-op push).
    pub commands: Vec<ReceivePackCommand>,
    /// The remote's report-status, when one was requested and received (i.e. the
    /// remote advertised `report-status`). `None` when report-status was not
    /// negotiated. Already validated: a failed unpack or a rejected ref is
    /// surfaced as an `Err` from [`push`], not returned here.
    pub report: Option<ReceivePackReportStatus>,
}

/// Per-ref outcome of a push, mirroring git's `enum ref_status` so the CLI can
/// reproduce `transport_print_push_status` byte-for-byte. `Ok` covers create,
/// update, forced update, and delete (disambiguated by the old/new ids on the
/// owning [`PushReportRef`]); the remaining variants are the rejection reasons.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PushRefStatus {
    /// The update was (or would be, under `--dry-run`) applied.
    Ok,
    /// The ref was already at the requested value; nothing to do.
    UpToDate,
    /// Local-side rejection: a non-forced non-fast-forward branch update.
    RejectNonFastForward,
    /// `--force-with-lease`/`--force-if-includes` expectation was not met.
    RejectStale,
    /// `--force-if-includes`: tracking ref was updated but not integrated.
    RejectRemoteUpdated,
    /// Non-forced tag update where the remote tag already exists.
    RejectAlreadyExists,
    /// The receive-pack side reported `ng <ref> <message>`.
    RemoteReject(String),
    /// Part of an `--atomic` push that failed because a sibling ref was rejected.
    AtomicPushFailed,
}

/// One ref's line in git's push status report. Carries everything
/// `print_one_push_report` needs: the source ("from") ref, the destination
/// ("to") ref, the old/new object ids, whether the update was forced, whether it
/// is a deletion, and the classified [`PushRefStatus`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushReportRef {
    /// The local source ref name (git's `ref->peer_ref->name`), e.g.
    /// `refs/heads/main`. `None` for a deletion (git prints `:dst`).
    pub src: Option<String>,
    /// The destination ref name (git's `ref->name`), e.g. `refs/heads/main`.
    pub dst: String,
    /// The remote's old object id for `dst` (zero for a create).
    pub old_id: ObjectId,
    /// The object id installed at `dst` (zero for a delete).
    pub new_id: ObjectId,
    /// True when the update overwrote a non-fast-forward (git's `forced_update`).
    pub forced: bool,
    /// The classified outcome.
    pub status: PushRefStatus,
}

impl PushReportRef {
    /// Whether this ref is a deletion (new id is the zero oid).
    pub fn is_deletion(&self) -> bool {
        self.new_id.is_null()
    }

    /// Whether this ref's status counts as a push error (git's `push_had_errors`:
    /// anything that is not `Ok`/`UpToDate`/none).
    pub fn had_error(&self) -> bool {
        !matches!(self.status, PushRefStatus::Ok | PushRefStatus::UpToDate)
    }
}

/// The full result of a push as git's transport layer models it: every ref's
/// classified status, ready to be rendered into the "To <url>" report and used
/// to decide the process exit code and the `pull-before-push` advice.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PushStatusReport {
    /// Every requested ref, in planning order.
    pub refs: Vec<PushReportRef>,
}

impl PushStatusReport {
    /// True when any ref was rejected (git's overall push error flag).
    pub fn had_errors(&self) -> bool {
        self.refs.iter().any(PushReportRef::had_error)
    }

    /// True when at least one ref was actually updated (git's
    /// `transport_refs_pushed`): used to print "Everything up-to-date".
    pub fn refs_pushed(&self) -> bool {
        self.refs.iter().any(|reference| {
            reference.old_id != reference.new_id && matches!(reference.status, PushRefStatus::Ok)
        })
    }
}

/// Fully resolved inputs for a [`push`] run.
#[derive(Clone, Copy)]
pub struct PushRequest<'a> {
    /// Local repository `$GIT_DIR`.
    pub git_dir: &'a Path,
    /// Local repository common `$GIT_DIR`, used for object access.
    pub common_git_dir: &'a Path,
    /// Local repository object format.
    pub format: ObjectFormat,
    /// Local repository config snapshot.
    pub config: &'a GitConfig,
    /// Remote name or source string, used for diagnostics.
    pub remote: &'a str,
    /// Already-resolved push destination.
    pub destination: &'a PushDestination,
    /// Refspecs requested by the caller.
    pub refspecs: &'a [String],
    /// Push behavior flags.
    pub options: &'a PushOptions,
}

/// Fully resolved inputs for a caller-authored exact push plan.
#[derive(Clone, Copy)]
pub struct PushActionRequest<'a> {
    /// Local repository `$GIT_DIR`.
    pub git_dir: &'a Path,
    /// Local repository common `$GIT_DIR`, used for object access.
    pub common_git_dir: &'a Path,
    /// Local repository object format.
    pub format: ObjectFormat,
    /// Local repository config snapshot.
    pub config: &'a GitConfig,
    /// Remote name or source string, used for diagnostics.
    pub remote: &'a str,
    /// Already-resolved push destination.
    pub destination: &'a PushDestination,
    /// Caller-authored exact push plan.
    pub plan: &'a PushActionPlan,
}

/// Mutable seams used while pushing.
pub struct PushServices<'a> {
    /// Credential source for authenticated transports.
    pub credentials: &'a mut dyn CredentialProvider,
    /// Progress sink reserved for future push progress.
    pub progress: &'a mut dyn ProgressSink,
}

/// A push after ref negotiation and command planning, but before any ref update
/// is sent or applied.
pub struct PushPlan {
    /// The receive-pack commands that will be executed if the caller proceeds.
    pub commands: Vec<ReceivePackCommand>,
    execution: PushExecution,
}

enum PushExecution {
    Noop,
    #[cfg(feature = "http")]
    Http {
        remote_url: RemoteUrl,
        features: ReceivePackFeatures,
        advertisements: Vec<RefAdvertisement>,
        pack_objects: Vec<ObjectId>,
    },
    Ssh(crate::ssh::SshPushPlan),
    Git(crate::git::GitPushPlan),
    Local {
        remote_git_dir: PathBuf,
        remote_common_git_dir: PathBuf,
        remote_refs: Vec<RefAdvertisement>,
        command_forces: Vec<(ReceivePackCommand, bool)>,
        pack_objects: Vec<ObjectId>,
    },
}

/// Push `refspecs` to a resolved `destination` from the repository at `git_dir`.
///
/// Performs the work the CLI's `push_http_repository`/`push_local_repository`
/// did: advertises the remote's refs, plans the receive-pack commands for
/// `refspecs`, rejects non-fast-forward branch updates (unless forced), builds
/// the pack of objects the remote lacks, sends the receive-pack request, parses
/// and validates the report-status, and returns the executed commands. `remote`
/// is the remote/argument the caller resolved `destination` from (used only for
/// error messages here).
///
/// Returns the structured [`PushOutcome`]; never prints or returns
/// `GitError::Exit`. A still-`None` report in the outcome means the remote did
/// not advertise `report-status`. Set-upstream config and the "To <remote>"
/// summary are the caller's job, driven from [`PushOutcome::commands`].
pub fn push(request: PushRequest<'_>, mut services: PushServices<'_>) -> Result<PushOutcome> {
    let plan = plan_push(request, &mut services)?;
    execute_push_plan(request, &mut services, plan)
}

/// Push a caller-authored exact plan, preserving its old/new/delete command ids.
pub fn push_actions(
    request: PushActionRequest<'_>,
    mut services: PushServices<'_>,
) -> Result<PushOutcome> {
    let plan = plan_push_actions(request, &mut services)?;
    execute_push_action_plan(request, &mut services, plan)
}

/// Negotiate with the remote and compute the receive-pack command list without
/// sending a pack or applying a ref update.
pub fn plan_push(request: PushRequest<'_>, services: &mut PushServices<'_>) -> Result<PushPlan> {
    // `config` and `progress` are part of the seam (mirroring `fetch`) but the
    // current push flow drives credentials from the caller-built provider and
    // returns its summary in `PushOutcome` rather than streaming progress, so
    // progress is not consumed yet. Kept named for the public API and future use.
    let _ = &mut services.progress;
    crate::protocol::check_transport_allowed(
        scheme_for_push_destination(request.destination),
        Some(request.config),
        None,
    )
    .map_err(crate::protocol::transport_policy_git_error)?;
    match request.destination {
        #[cfg(feature = "http")]
        PushDestination::Http(remote_url) => plan_push_http(PushHttpRequest {
            git_dir: request.git_dir,
            common_git_dir: request.common_git_dir,
            format: request.format,
            remote_url,
            refspecs: request.refspecs,
            options: request.options,
            credentials: services.credentials,
        }),
        #[cfg(not(feature = "http"))]
        PushDestination::Http(_) => Err(GitError::Unsupported(
            "HTTP transport is not enabled in this build".into(),
        )),
        PushDestination::Ssh(remote_url) => {
            let plan = crate::ssh::plan_push_ssh(crate::ssh::SshPushRequest {
                git_dir: request.git_dir,
                common_git_dir: request.common_git_dir,
                format: request.format,
                remote: remote_url,
                refspecs: request.refspecs,
                force: request.options.force,
            })?;
            let commands = plan.commands.clone();
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Ssh(plan)
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
        PushDestination::Git(remote_url) => {
            let plan = crate::git::plan_push_git(crate::git::GitPushRequest {
                git_dir: request.git_dir,
                common_git_dir: request.common_git_dir,
                format: request.format,
                remote: remote_url,
                refspecs: request.refspecs,
                force: request.options.force,
            })?;
            let commands = plan.commands.clone();
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Git(plan)
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
        PushDestination::Local {
            git_dir: remote_git_dir,
            common_git_dir: remote_common_git_dir,
        } => plan_push_local(PushLocalRequest {
            git_dir: request.git_dir,
            common_git_dir: request.common_git_dir,
            format: request.format,
            remote: request.remote,
            remote_git_dir,
            remote_common_git_dir,
            refspecs: request.refspecs,
            options: request.options,
        }),
    }
}

/// Negotiate with the remote and bind a caller-authored exact push plan to a
/// transport execution token.
pub fn plan_push_actions(
    request: PushActionRequest<'_>,
    services: &mut PushServices<'_>,
) -> Result<PushPlan> {
    let _ = &mut services.progress;
    crate::protocol::check_transport_allowed(
        scheme_for_push_destination(request.destination),
        Some(request.config),
        None,
    )
    .map_err(crate::protocol::transport_policy_git_error)?;
    let commands = receive_pack_commands_from_action_plan(request.format, request.plan)?;
    let command_forces = commands
        .iter()
        .cloned()
        .zip(request.plan.commands.iter())
        .map(|(command, planned)| (command, request.plan.options.force || planned.force))
        .collect::<Vec<_>>();
    match request.destination {
        #[cfg(feature = "http")]
        PushDestination::Http(remote_url) => {
            let client = crate::http::new_http_client();
            let discovered = crate::http::http_service_advertisements(
                &client,
                remote_url,
                request.format,
                GitService::ReceivePack,
                services.credentials,
            )?;
            let advertisement_set = discovered.set;
            let features = advertised_receive_pack_features(&advertisement_set.refs)?;
            verify_remote_object_format(&features, request.format)?;
            let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, request.format);
            reject_non_fast_forward_pushes(&local_db, request.format, &command_forces)?;
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Http {
                    remote_url: remote_url.clone(),
                    features,
                    advertisements: advertisement_set.refs,
                    pack_objects: request.plan.pack_objects.clone(),
                }
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
        #[cfg(not(feature = "http"))]
        PushDestination::Http(_) => Err(GitError::Unsupported(
            "HTTP transport is not enabled in this build".into(),
        )),
        PushDestination::Ssh(remote_url) => {
            let plan = crate::ssh::plan_push_ssh_commands(crate::ssh::SshPushCommandsRequest {
                common_git_dir: request.common_git_dir,
                format: request.format,
                remote: remote_url,
                command_forces: command_forces.clone(),
                pack_objects: request.plan.pack_objects.clone(),
            })?;
            let commands = plan.commands.clone();
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Ssh(plan)
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
        PushDestination::Git(remote_url) => {
            let plan = crate::git::plan_push_git_commands(crate::git::GitPushCommandsRequest {
                common_git_dir: request.common_git_dir,
                format: request.format,
                remote: remote_url,
                command_forces: command_forces.clone(),
                pack_objects: request.plan.pack_objects.clone(),
            })?;
            let commands = plan.commands.clone();
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Git(plan)
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
        PushDestination::Local {
            git_dir: remote_git_dir,
            common_git_dir: remote_common_git_dir,
        } => {
            let remote_format = crate::object_format_for_git_dir(remote_common_git_dir)?;
            if remote_format != request.format {
                return Err(GitError::InvalidObjectId(format!(
                    "remote repository uses {}, local repository uses {}",
                    remote_format.name(),
                    request.format.name()
                )));
            }
            let remote_refs =
                crate::local::local_fetch_advertisements(remote_git_dir, request.format)?;
            let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, request.format);
            reject_non_fast_forward_pushes(&local_db, request.format, &command_forces)?;
            let execution = if commands.is_empty() {
                PushExecution::Noop
            } else {
                PushExecution::Local {
                    remote_git_dir: remote_git_dir.to_path_buf(),
                    remote_common_git_dir: remote_common_git_dir.to_path_buf(),
                    remote_refs,
                    command_forces,
                    pack_objects: request.plan.pack_objects.clone(),
                }
            };
            Ok(PushPlan {
                commands,
                execution,
            })
        }
    }
}

fn scheme_for_push_destination(destination: &PushDestination) -> &'static str {
    match destination {
        PushDestination::Http(remote) => crate::protocol::transport_scheme_for_remote(remote),
        PushDestination::Ssh(remote) => crate::protocol::transport_scheme_for_remote(remote),
        PushDestination::Git(remote) => crate::protocol::transport_scheme_for_remote(remote),
        PushDestination::Local { .. } => "file",
    }
}

/// Execute a previously planned push.
pub fn execute_push_plan(
    request: PushRequest<'_>,
    services: &mut PushServices<'_>,
    plan: PushPlan,
) -> Result<PushOutcome> {
    let _ = (request.config, request.remote);
    let _ = &mut services.progress;
    if plan.commands.is_empty() {
        return Ok(PushOutcome::default());
    }
    match plan.execution {
        PushExecution::Noop => Ok(PushOutcome::default()),
        #[cfg(feature = "http")]
        PushExecution::Http {
            remote_url,
            features,
            advertisements,
            pack_objects,
        } => execute_push_http(
            request,
            services.credentials,
            plan.commands,
            remote_url,
            features,
            advertisements,
            pack_objects,
        ),
        PushExecution::Ssh(plan) => crate::ssh::execute_push_ssh_plan(request, plan),
        PushExecution::Git(plan) => crate::git::execute_push_git_plan(request, plan),
        PushExecution::Local {
            remote_git_dir,
            remote_common_git_dir,
            remote_refs,
            command_forces,
            pack_objects,
        } => execute_push_local(
            request,
            plan.commands,
            remote_git_dir,
            remote_common_git_dir,
            remote_refs,
            command_forces,
            pack_objects,
        ),
    }
}

/// Execute a previously negotiated exact push plan.
pub fn execute_push_action_plan(
    request: PushActionRequest<'_>,
    services: &mut PushServices<'_>,
    plan: PushPlan,
) -> Result<PushOutcome> {
    let refspecs: &[String] = &[];
    execute_push_plan(
        PushRequest {
            git_dir: request.git_dir,
            common_git_dir: request.common_git_dir,
            format: request.format,
            config: request.config,
            remote: request.remote,
            destination: request.destination,
            refspecs,
            options: &request.plan.options,
        },
        services,
        plan,
    )
}

/// Push to a smart-HTTP(S) remote: advertise via receive-pack info/refs, plan,
/// build the pack, POST the receive-pack RPC, and validate the report-status.
#[cfg(feature = "http")]
struct PushHttpRequest<'a> {
    git_dir: &'a Path,
    common_git_dir: &'a Path,
    format: ObjectFormat,
    remote_url: &'a RemoteUrl,
    refspecs: &'a [String],
    options: &'a PushOptions,
    credentials: &'a mut dyn CredentialProvider,
}

#[cfg(feature = "http")]
fn plan_push_http(request: PushHttpRequest<'_>) -> Result<PushPlan> {
    let PushHttpRequest {
        git_dir,
        common_git_dir,
        format,
        remote_url,
        refspecs,
        options,
        credentials,
    } = request;
    let client = crate::http::new_http_client();
    let discovered = crate::http::http_service_advertisements(
        &client,
        remote_url,
        format,
        GitService::ReceivePack,
        credentials,
    )?;
    let advertisement_set = discovered.set;
    let features = advertised_receive_pack_features(&advertisement_set.refs)?;
    verify_remote_object_format(&features, format)?;

    let local_store = FileRefStore::new(git_dir, format);
    let mut local_refs = local_push_source_refs(&local_store, format)?;
    add_revision_push_sources(git_dir, format, refspecs, &mut local_refs);
    let command_forces = plan_push_command_forces(
        format,
        &local_refs,
        &advertisement_set.refs,
        refspecs,
        options.force,
    )?;
    let local_db = FileObjectDatabase::from_git_dir(common_git_dir, format);
    reject_non_fast_forward_pushes(&local_db, format, &command_forces)?;
    let commands = commands_from_forces(&command_forces);
    let execution = if commands.is_empty() {
        PushExecution::Noop
    } else {
        PushExecution::Http {
            remote_url: remote_url.clone(),
            features,
            advertisements: advertisement_set.refs,
            pack_objects: Vec::new(),
        }
    };
    Ok(PushPlan {
        commands,
        execution,
    })
}

#[cfg(feature = "http")]
fn execute_push_http(
    request: PushRequest<'_>,
    credentials: &mut dyn CredentialProvider,
    commands: Vec<ReceivePackCommand>,
    remote_url: RemoteUrl,
    features: ReceivePackFeatures,
    advertisements: Vec<RefAdvertisement>,
    pack_objects: Vec<ObjectId>,
) -> Result<PushOutcome> {
    let client = crate::http::new_http_client();
    let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, request.format);
    let body = build_receive_pack_body(&PushPackRequest {
        local_db: &local_db,
        format: request.format,
        commands: &commands,
        pack_objects: &pack_objects,
        remote_advertisements: &advertisements,
        features: &features,
        options: receive_pack_push_options(&features, request.format, request.options.quiet),
        thin: false,
    })?;
    let url = http_smart_rpc_url(&remote_url, GitService::ReceivePack)?;
    let content_type = smart_http_rpc_request_content_type(GitService::ReceivePack)?;
    let mut response = crate::http::http_send_with_auth(&remote_url, credentials, |auth| {
        client.post(
            &url,
            &content_type,
            &crate::http::http_authorization_headers(auth),
            &body,
        )
    })?;
    crate::http::http_check_status(&response, &url)?;
    crate::http::http_validate_content_type(
        &response,
        &smart_http_rpc_result_content_type(GitService::ReceivePack)?,
    )?;

    let report = if features.report_status {
        let report = read_receive_pack_report_status(&mut response.body)?;
        validate_receive_pack_report(&report)?;
        Some(report)
    } else {
        let mut sink = Vec::new();
        response.body.read_to_end(&mut sink)?;
        None
    };
    Ok(PushOutcome { commands, report })
}

/// Push to a local repository served in-process: advertise from the remote
/// `git_dir`, plan, build the pack against the remote's reachable objects, and
/// apply the receive-pack request directly.
struct PushLocalRequest<'a> {
    git_dir: &'a Path,
    common_git_dir: &'a Path,
    format: ObjectFormat,
    remote: &'a str,
    remote_git_dir: &'a Path,
    remote_common_git_dir: &'a Path,
    refspecs: &'a [String],
    options: &'a PushOptions,
}

fn plan_push_local(request: PushLocalRequest<'_>) -> Result<PushPlan> {
    let PushLocalRequest {
        git_dir,
        common_git_dir,
        format,
        remote,
        remote_git_dir,
        remote_common_git_dir,
        refspecs,
        options,
    } = request;
    let _ = remote;
    let remote_format = crate::object_format_for_git_dir(remote_common_git_dir)?;
    if remote_format != format {
        return Err(GitError::InvalidObjectId(format!(
            "remote repository uses {}, local repository uses {}",
            remote_format.name(),
            format.name()
        )));
    }

    let local_store = FileRefStore::new(git_dir, format);
    let mut local_refs = local_push_source_refs(&local_store, format)?;
    add_revision_push_sources(git_dir, format, refspecs, &mut local_refs);
    let remote_refs = crate::local::local_fetch_advertisements(remote_git_dir, format)?;
    let command_forces =
        plan_push_command_forces(format, &local_refs, &remote_refs, refspecs, options.force)?;
    let local_db = FileObjectDatabase::from_git_dir(common_git_dir, format);
    reject_non_fast_forward_pushes(&local_db, format, &command_forces)?;
    let commands = commands_from_forces(&command_forces);
    let execution = if commands.is_empty() {
        PushExecution::Noop
    } else {
        PushExecution::Local {
            remote_git_dir: remote_git_dir.to_path_buf(),
            remote_common_git_dir: remote_common_git_dir.to_path_buf(),
            remote_refs,
            command_forces,
            pack_objects: Vec::new(),
        }
    };
    Ok(PushPlan {
        commands,
        execution,
    })
}

fn execute_push_local(
    request: PushRequest<'_>,
    commands: Vec<ReceivePackCommand>,
    remote_git_dir: PathBuf,
    remote_common_git_dir: PathBuf,
    remote_refs: Vec<RefAdvertisement>,
    _command_forces: Vec<(ReceivePackCommand, bool)>,
    pack_objects: Vec<ObjectId>,
) -> Result<PushOutcome> {
    let remote_excluded_tips = remote_refs
        .iter()
        .map(|reference| reference.oid)
        .collect::<Vec<_>>();
    let starts = push_pack_roots(&commands, &pack_objects);
    let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, request.format);
    let remote_db = FileObjectDatabase::from_git_dir(&remote_common_git_dir, request.format);
    let remote_excluded =
        collect_reachable_object_ids(&remote_db, request.format, remote_excluded_tips)?;
    let packfile = if starts.is_empty() {
        Vec::new()
    } else {
        b"PACK".to_vec()
    };
    let receive_request = ReceivePackPushRequest {
        commands: ReceivePackRequest {
            shallow: Vec::new(),
            commands: commands.clone(),
            capabilities: Vec::new(),
        },
        push_options: None,
        packfile,
    };
    let report = crate::local::receive_pack_reachable_pack_into_local_repository(
        &remote_git_dir,
        request.format,
        &receive_request,
        &local_db,
        starts,
        remote_excluded,
    )?;
    validate_receive_pack_report(&report)?;
    Ok(PushOutcome {
        commands,
        report: Some(report),
    })
}

/// Fully resolved inputs for a status-reporting push to a local repository.
pub struct PushReportRequest<'a> {
    /// Local repository `$GIT_DIR`.
    pub git_dir: &'a Path,
    /// Local repository common `$GIT_DIR`, used for object access.
    pub common_git_dir: &'a Path,
    /// Local repository object format.
    pub format: ObjectFormat,
    /// The remote repository's `$GIT_DIR`.
    pub remote_git_dir: &'a Path,
    /// The remote repository's common `$GIT_DIR`.
    pub remote_common_git_dir: &'a Path,
    /// Refspecs requested by the caller (already URL/repo resolved).
    pub refspecs: &'a [String],
    /// Force every update (the `--force` flag).
    pub force: bool,
    /// `--atomic`: send nothing if any ref would be rejected.
    pub atomic: bool,
    /// `--dry-run`: classify and report, but do not send or update.
    pub dry_run: bool,
    /// Per-ref `--force-with-lease` expectations: `(dst, expected_old)`. An
    /// `expected_old` of `None` means "the remote ref must not exist".
    pub force_with_lease: &'a [(String, Option<ObjectId>)],
    /// `--force-with-lease` with no per-ref value: lease every pushed ref against
    /// its remote-tracking ref (git's implicit cas). The expected value per dst
    /// is supplied via [`Self::force_with_lease`]; this flag only governs whether
    /// a lease was requested at all (used for the "no actual ref" diagnostics).
    pub force_with_lease_default: bool,
    /// `--force-if-includes`: for tracking-based leases, reject when the current
    /// remote tip is not included in the local branch's reflog/history.
    pub force_if_includes: bool,
    /// Receive-pack-side config values supplied by the invoked receive-pack
    /// command, e.g. `--receive-pack="git -c receive.denyDeletes=false receive-pack"`.
    pub receive_config_overrides: &'a [(String, String)],
}

/// Push to a local repository, returning git's per-ref status report instead of
/// failing on the first rejection. Performs the client-side checks git's
/// send-pack does — non-fast-forward and `--force-with-lease` (stale info) — then
/// (unless `--dry-run`) sends the surviving commands and folds the receive-pack
/// report-status back into each ref. With `--atomic`, a single client-side
/// rejection turns every other ref into [`PushRefStatus::AtomicPushFailed`] and
/// nothing is sent. The caller renders the report and derives the exit code.
pub fn push_local_with_report(
    request: PushReportRequest<'_>,
    _config: &GitConfig,
) -> Result<PushStatusReport> {
    let format = request.format;
    let remote_format = crate::object_format_for_git_dir(request.remote_common_git_dir)?;
    if remote_format != format {
        return Err(GitError::InvalidObjectId(format!(
            "remote repository uses {}, local repository uses {}",
            remote_format.name(),
            format.name()
        )));
    }
    let local_store = FileRefStore::new(request.git_dir, format);
    let mut local_refs = local_push_source_refs(&local_store, format)?;
    add_revision_push_sources(request.git_dir, format, request.refspecs, &mut local_refs);
    let remote_refs = crate::local::local_fetch_advertisements(request.remote_git_dir, format)?;
    let planned = plan_push_command_sources(
        format,
        &local_refs,
        &remote_refs,
        request.refspecs,
        request.force,
    )?;
    let local_db = FileObjectDatabase::from_git_dir(request.common_git_dir, format);
    let remote_config =
        sley_config::read_repo_config(request.remote_git_dir, None).unwrap_or_default();

    // Classify each planned command the way git's send-pack does, collecting
    // rejections rather than bailing on the first one.
    let mut refs: Vec<PushReportRef> = Vec::new();
    for plan in &planned {
        let status = classify_push_command(
            &local_db,
            format,
            plan,
            &request,
            &remote_config,
            request.remote_git_dir,
        )?;
        // git's `forced_update` reflects either an actual rewind or a rejection
        // reason (e.g. stale lease) that was overridden by --force.
        let stale_lease_overridden = plan.force && lease_expectation_mismatch(&request, plan);
        let forced = matches!(status, PushRefStatus::Ok)
            && !plan.command.old_id.is_null()
            && !plan.command.new_id.is_null()
            && (stale_lease_overridden
                || if plan.command.name.starts_with("refs/heads/") {
                    !is_fast_forward(
                        &local_db,
                        format,
                        &plan.command.old_id,
                        &plan.command.new_id,
                    )?
                } else {
                    plan.force
                });
        refs.push(PushReportRef {
            src: plan.source.clone(),
            dst: plan.command.name.clone(),
            old_id: plan.command.old_id,
            new_id: plan.command.new_id,
            forced,
            status,
        });
    }

    let any_local_reject = refs.iter().any(|reference| {
        matches!(
            reference.status,
            PushRefStatus::RejectNonFastForward
                | PushRefStatus::RejectStale
                | PushRefStatus::RejectRemoteUpdated
                | PushRefStatus::RejectAlreadyExists
        )
    });

    // `--atomic`: if any ref was rejected client-side, send nothing and mark all
    // would-be-OK refs as atomic-push-failed (git's REF_STATUS_ATOMIC_PUSH_FAILED).
    // UpToDate refs are *not* converted — git leaves them reported as up to date.
    if request.atomic && any_local_reject {
        for reference in &mut refs {
            if matches!(reference.status, PushRefStatus::Ok) {
                reference.status = PushRefStatus::AtomicPushFailed;
            }
        }
        return Ok(PushStatusReport { refs });
    }

    if request.dry_run {
        return Ok(PushStatusReport { refs });
    }

    // Send only the commands that survived client-side checks.
    let send: Vec<ReceivePackCommand> = refs
        .iter()
        .filter(|reference| {
            matches!(reference.status, PushRefStatus::Ok) && reference.old_id != reference.new_id
        })
        .map(|reference| ReceivePackCommand {
            old_id: reference.old_id,
            new_id: reference.new_id,
            name: reference.dst.clone(),
        })
        .collect();

    if !send.is_empty() {
        let remote_excluded_tips: Vec<ObjectId> =
            remote_refs.iter().map(|reference| reference.oid).collect();
        let pack_objects: Vec<ObjectId> = Vec::new();
        let starts = push_pack_roots(&send, &pack_objects);
        let remote_db = FileObjectDatabase::from_git_dir(request.remote_common_git_dir, format);
        let remote_excluded =
            collect_reachable_object_ids(&remote_db, format, remote_excluded_tips)?;
        let packfile = if starts.is_empty() {
            Vec::new()
        } else {
            b"PACK".to_vec()
        };
        let receive_request = ReceivePackPushRequest {
            commands: ReceivePackRequest {
                shallow: Vec::new(),
                commands: send.clone(),
                capabilities: Vec::new(),
            },
            push_options: None,
            packfile,
        };
        let report = crate::local::receive_pack_reachable_pack_into_local_repository(
            request.remote_git_dir,
            format,
            &receive_request,
            &local_db,
            starts,
            remote_excluded,
        )?;
        // Fold the receive-pack ng reports back onto the matching refs.
        if let ReceivePackUnpackStatus::Error(message) = &report.unpack {
            for reference in &mut refs {
                if matches!(reference.status, PushRefStatus::Ok) {
                    reference.status =
                        PushRefStatus::RemoteReject(format!("unpacker error: {message}"));
                }
            }
        }
        for command_status in &report.commands {
            if let ReceivePackCommandStatus::Ng { name, message } = command_status {
                for reference in &mut refs {
                    if reference.dst == *name && matches!(reference.status, PushRefStatus::Ok) {
                        reference.status = PushRefStatus::RemoteReject(message.clone());
                    }
                }
            }
        }
    }

    Ok(PushStatusReport { refs })
}

/// Classify one planned command into git's send-pack pre-flight status: an
/// up-to-date no-op, a non-fast-forward rejection, a `--force-with-lease` stale
/// rejection, or `Ok` (the command will be sent).
fn classify_push_command(
    local_db: &FileObjectDatabase,
    format: ObjectFormat,
    plan: &PlannedPushCommand,
    request: &PushReportRequest<'_>,
    config: &GitConfig,
    remote_git_dir: &Path,
) -> Result<PushRefStatus> {
    let command = &plan.command;

    if receive_ref_is_hidden(config, request.receive_config_overrides, &command.name) {
        let reason = if command.new_id.is_null() {
            "deny deleting a hidden ref"
        } else {
            "deny updating a hidden ref"
        };
        return Ok(PushRefStatus::RemoteReject(reason.to_string()));
    }

    // No change: the remote already has exactly this value (and it is not a
    // create-from-nothing of a non-existent ref). git reports UPTODATE.
    if command.old_id == command.new_id && !command.new_id.is_null() {
        return Ok(PushRefStatus::UpToDate);
    }

    if command.new_id.is_null() && !command.old_id.is_null() {
        if receive_config_bool(config, request.receive_config_overrides, "denydeletes")
            .unwrap_or(false)
        {
            return Ok(PushRefStatus::RemoteReject(
                "deletion prohibited".to_string(),
            ));
        }
        if receive_denies_current_branch_delete(format, command, config, request, remote_git_dir)? {
            return Ok(PushRefStatus::RemoteReject(
                "deletion of the current branch prohibited".to_string(),
            ));
        }
    }

    if !request.dry_run && receive_denies_current_branch(format, command, config, remote_git_dir)? {
        return Ok(PushRefStatus::RemoteReject(
            "branch is currently checked out".to_string(),
        ));
    }

    if command.name.starts_with("refs/heads/") && !command.new_id.is_null() {
        let object = local_db.read_object(&command.new_id)?;
        if object.object_type != ObjectType::Commit {
            return Ok(PushRefStatus::RemoteReject(
                "invalid new value provided".to_string(),
            ));
        }
    }

    // `--force-with-lease`: the remote's current value must match the lease, or
    // the push is rejected as stale info — checked before the non-ff gate and
    // independent of `--force`.
    if let Some((_, expected)) = request
        .force_with_lease
        .iter()
        .find(|(dst, _)| *dst == command.name)
    {
        let actual = if command.old_id.is_null() {
            None
        } else {
            Some(command.old_id)
        };
        if *expected != actual {
            if plan.force {
                return Ok(PushRefStatus::Ok);
            }
            return Ok(PushRefStatus::RejectStale);
        }
        if request.force_if_includes
            && !command.old_id.is_null()
            && (command.new_id.is_null()
                || !is_fast_forward(local_db, format, &command.old_id, &command.new_id)?)
            && force_if_includes_rejects(
                local_db,
                format,
                request.git_dir,
                &command.name,
                &command.old_id,
            )?
        {
            if plan.force {
                return Ok(PushRefStatus::Ok);
            }
            return Ok(PushRefStatus::RejectRemoteUpdated);
        }
        // A satisfied lease forces the update.
        return Ok(PushRefStatus::Ok);
    }

    if command.name.starts_with("refs/heads/")
        && !command.old_id.is_null()
        && !command.new_id.is_null()
        && !is_fast_forward(local_db, format, &command.old_id, &command.new_id)?
        && receive_config_bool(
            config,
            request.receive_config_overrides,
            "denynonfastforwards",
        )
        .unwrap_or(false)
    {
        return Ok(PushRefStatus::RemoteReject(format!(
            "denying non-fast-forward {} (you should pull first)",
            command.name
        )));
    }

    // Non-fast-forward branch update: rejected unless forced. Creations,
    // deletions, and non-branch refs skip this gate (matching git's send-pack).
    if !plan.force
        && command.name.starts_with("refs/tags/")
        && !command.old_id.is_null()
        && !command.new_id.is_null()
    {
        return Ok(PushRefStatus::RejectAlreadyExists);
    }

    if !plan.force
        && command.name.starts_with("refs/heads/")
        && !command.old_id.is_null()
        && !command.new_id.is_null()
        && !is_fast_forward(local_db, format, &command.old_id, &command.new_id)?
    {
        return Ok(PushRefStatus::RejectNonFastForward);
    }

    Ok(PushRefStatus::Ok)
}

fn receive_ref_is_hidden(
    config: &GitConfig,
    overrides: &[(String, String)],
    refname: &str,
) -> bool {
    let mut hide_refs = Vec::new();
    hide_refs.extend(hidden_ref_values(config, "transfer", None));
    hide_refs.extend(hidden_ref_values(config, "receive", None));
    hide_refs.extend(
        overrides
            .iter()
            .filter(|(key, _)| key.eq_ignore_ascii_case("hiderefs"))
            .map(|(_, value)| trim_hidden_ref_pattern(value)),
    );
    ref_is_hidden_by_patterns(refname, &hide_refs)
}

fn hidden_ref_values(config: &GitConfig, section: &str, subsection: Option<&str>) -> Vec<String> {
    config
        .get_all(section, subsection, "hiderefs")
        .into_iter()
        .flatten()
        .map(trim_hidden_ref_pattern)
        .collect()
}

fn trim_hidden_ref_pattern(value: &str) -> String {
    value.trim_end_matches('/').to_string()
}

fn ref_is_hidden_by_patterns(refname: &str, patterns: &[String]) -> bool {
    for pattern in patterns.iter().rev() {
        let mut pattern = pattern.as_str();
        let negated = pattern.strip_prefix('!').is_some();
        if negated {
            pattern = &pattern[1..];
        }
        if let Some(rest) = pattern.strip_prefix('^') {
            pattern = rest;
        }
        if hidden_ref_pattern_matches(refname, pattern) {
            return !negated;
        }
    }
    false
}

fn hidden_ref_pattern_matches(refname: &str, pattern: &str) -> bool {
    refname
        .strip_prefix(pattern)
        .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
}

fn lease_expectation_mismatch(request: &PushReportRequest<'_>, plan: &PlannedPushCommand) -> bool {
    let command = &plan.command;
    let actual = if command.old_id.is_null() {
        None
    } else {
        Some(command.old_id)
    };
    request
        .force_with_lease
        .iter()
        .find(|(dst, _)| *dst == command.name)
        .is_some_and(|(_, expected)| *expected != actual)
}

fn force_if_includes_rejects(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    git_dir: &Path,
    local_ref: &str,
    remote_old: &ObjectId,
) -> Result<bool> {
    let store = FileRefStore::new(git_dir, format);
    let mut candidates = Vec::new();
    match store.read_ref(local_ref)? {
        Some(RefTarget::Direct(oid)) => candidates.push(oid),
        Some(RefTarget::Symbolic(target)) => {
            if let Some(RefTarget::Direct(oid)) = store.read_ref(&target)? {
                candidates.push(oid);
            }
        }
        None => return Ok(false),
    }
    for entry in store.read_reflog(local_ref)? {
        if !entry.new_oid.is_null() {
            candidates.push(entry.new_oid);
        }
    }
    candidates.sort();
    candidates.dedup();
    for candidate in candidates {
        if candidate == *remote_old {
            return Ok(false);
        }
        if let Ok(ancestors) = ancestor_depths(db, format, &candidate)
            && ancestors.contains_key(remote_old)
        {
            return Ok(false);
        }
    }
    Ok(true)
}

fn receive_config_bool(
    config: &GitConfig,
    overrides: &[(String, String)],
    key: &str,
) -> Option<bool> {
    overrides
        .iter()
        .rev()
        .find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))
        .and_then(|(_, value)| sley_config::parse_config_bool(value))
        .or_else(|| config.get_bool("receive", None, key))
}

fn receive_denies_current_branch(
    format: ObjectFormat,
    command: &ReceivePackCommand,
    config: &GitConfig,
    remote_git_dir: &Path,
) -> Result<bool> {
    if command.new_id.is_null() {
        return Ok(false);
    }
    if !command.name.starts_with("refs/heads/") {
        return Ok(false);
    }
    let deny = config
        .get("receive", None, "denycurrentbranch")
        .unwrap_or("refuse");
    let denies = matches!(
        deny.to_ascii_lowercase().as_str(),
        "true" | "yes" | "on" | "1" | "refuse"
    );
    if !denies {
        return Ok(false);
    }
    if sley_worktree::worktree_root_for_git_dir(remote_git_dir)?.is_none() {
        return Ok(false);
    }
    let store = FileRefStore::new(remote_git_dir, format);
    Ok(matches!(
        store.read_ref("HEAD")?,
        Some(RefTarget::Symbolic(target)) if target == command.name
    ))
}

fn receive_targets_current_branch(
    format: ObjectFormat,
    command: &ReceivePackCommand,
    remote_git_dir: &Path,
) -> Result<bool> {
    if !command.name.starts_with("refs/heads/") {
        return Ok(false);
    }
    if sley_worktree::worktree_root_for_git_dir(remote_git_dir)?.is_none() {
        return Ok(false);
    }
    let store = FileRefStore::new(remote_git_dir, format);
    Ok(matches!(
        store.read_ref("HEAD")?,
        Some(RefTarget::Symbolic(target)) if target == command.name
    ))
}

fn receive_denies_current_branch_delete(
    format: ObjectFormat,
    command: &ReceivePackCommand,
    config: &GitConfig,
    request: &PushReportRequest<'_>,
    remote_git_dir: &Path,
) -> Result<bool> {
    if !receive_targets_current_branch(format, command, remote_git_dir)? {
        return Ok(false);
    }
    let deny = request
        .receive_config_overrides
        .iter()
        .rev()
        .find(|(candidate, _)| candidate.eq_ignore_ascii_case("denydeletecurrent"))
        .map(|(_, value)| value.as_str())
        .or_else(|| config.get("receive", None, "denydeletecurrent"))
        .unwrap_or("refuse");
    Ok(!matches!(
        deny.to_ascii_lowercase().as_str(),
        "ignore" | "warn" | "false" | "no" | "off" | "0"
    ))
}

/// Whether `old` is an ancestor of `new` (a fast-forward). A walk from `new`;
/// `old` reachable ⇒ fast-forward.
fn is_fast_forward(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    old: &ObjectId,
    new: &ObjectId,
) -> Result<bool> {
    let ancestors = ancestor_depths(db, format, new)?;
    Ok(ancestors.contains_key(old))
}

/// Parse the receive-pack features from the leading ref advertisement (the empty
/// default when the remote advertised no refs).
#[cfg(feature = "http")]
fn advertised_receive_pack_features(
    advertisements: &[RefAdvertisement],
) -> Result<ReceivePackFeatures> {
    advertisements
        .first()
        .map(|advertisement| parse_receive_pack_features(&advertisement.capabilities))
        .transpose()
        .map(Option::unwrap_or_default)
}

/// Reject a push whose object format disagrees with the remote's advertised
/// `object-format`, and require the advertisement for any non-SHA-1 push.
#[cfg(feature = "http")]
fn verify_remote_object_format(features: &ReceivePackFeatures, format: ObjectFormat) -> Result<()> {
    if let Some(remote_format) = features.object_format {
        if remote_format != format {
            return Err(GitError::InvalidObjectId(format!(
                "remote repository uses {}, local repository uses {}",
                remote_format.name(),
                format.name()
            )));
        }
    } else if format != ObjectFormat::Sha1 {
        return Err(GitError::InvalidObjectId(format!(
            "remote repository did not advertise object-format for {} push",
            format.name()
        )));
    }
    Ok(())
}

/// The receive-pack push-request options for the negotiated `features`, matching
/// git: report-status when advertised, ofs-delta when advertised, `quiet` only
/// when both requested and advertised, and the advertised object-format only when
/// the local repository's `format` is not SHA-1.
#[cfg(feature = "http")]
fn receive_pack_push_options(
    features: &ReceivePackFeatures,
    format: ObjectFormat,
    quiet: bool,
) -> ReceivePackPushRequestOptions {
    ReceivePackPushRequestOptions {
        report_status: features.report_status,
        ofs_delta: features.ofs_delta,
        quiet: quiet && features.quiet,
        object_format: features
            .object_format
            .filter(|_| format != ObjectFormat::Sha1),
        ..ReceivePackPushRequestOptions::default()
    }
}

/// Plan the receive-pack commands for `refspecs`, pairing each with whether it is
/// forced (the global `force` flag or the refspec's own `+`). Each refspec is
/// normalized then planned independently so per-refspec force is preserved,
/// matching the CLI.
pub(crate) fn plan_push_command_forces(
    format: ObjectFormat,
    local_refs: &[PushSourceRef],
    remote_refs: &[RefAdvertisement],
    refspecs: &[String],
    force: bool,
) -> Result<Vec<(ReceivePackCommand, bool)>> {
    let parsed_refspecs = refspecs
        .iter()
        .map(|refspec| {
            let normalized = normalize_push_refspec_for_sources(refspec, local_refs, remote_refs)?;
            parse_refspec(&normalized)
        })
        .collect::<Result<Vec<_>>>()?;
    let mut command_forces = Vec::new();
    for refspec in &parsed_refspecs {
        for command in plan_push_commands(
            format,
            local_refs,
            remote_refs,
            std::slice::from_ref(refspec),
        )? {
            command_forces.push((command, force || refspec.force));
        }
    }
    Ok(command_forces)
}

/// One planned push command paired with its forcing flag and the local source
/// ref it came from (git's `ref->peer_ref`). A delete carries `source: None`.
struct PlannedPushCommand {
    command: ReceivePackCommand,
    force: bool,
    source: Option<String>,
}

/// Like [`plan_push_command_forces`], but also records the local source ref each
/// command resolved from so the status report can print the `from -> to` line.
/// The source is the normalized refspec source name; a delete (`:dst`) has no
/// source. A pattern refspec re-derives each expanded command's source from its
/// destination by reversing the wildcard substitution.
fn plan_push_command_sources(
    format: ObjectFormat,
    local_refs: &[PushSourceRef],
    remote_refs: &[RefAdvertisement],
    refspecs: &[String],
    force: bool,
) -> Result<Vec<PlannedPushCommand>> {
    let mut planned = Vec::new();
    for refspec in refspecs {
        let normalized = normalize_push_refspec_for_sources(refspec, local_refs, remote_refs)?;
        let parsed = parse_refspec(&normalized)?;
        let commands = plan_push_commands(
            format,
            local_refs,
            remote_refs,
            std::slice::from_ref(&parsed),
        )?;
        for command in commands {
            let source = push_command_source_name(&parsed, &command);
            planned.push(PlannedPushCommand {
                command,
                force: force || parsed.force,
                source,
            });
        }
    }
    Ok(planned)
}

/// Recover the local source ref name for one planned `command` from its owning
/// `refspec`. Deletes (no `src`) return `None`. A wildcard pattern reverses the
/// substitution: the command's destination minus the pattern's destination
/// affix yields the matched stem, which slots into the pattern's source affix.
fn push_command_source_name(refspec: &RefSpec, command: &ReceivePackCommand) -> Option<String> {
    let src = refspec.src.as_deref()?;
    if !refspec.pattern {
        return Some(src.to_string());
    }
    let (src_prefix, src_suffix) = src.split_once('*')?;
    let dst = refspec.dst.as_deref()?;
    let (dst_prefix, dst_suffix) = dst.split_once('*')?;
    let stem = command
        .name
        .strip_prefix(dst_prefix)
        .and_then(|rest| rest.strip_suffix(dst_suffix))?;
    Some(format!("{src_prefix}{stem}{src_suffix}"))
}

pub(crate) fn add_revision_push_sources(
    git_dir: &Path,
    format: ObjectFormat,
    refspecs: &[String],
    local_refs: &mut Vec<PushSourceRef>,
) {
    for refspec in refspecs {
        let refspec = refspec.strip_prefix('+').unwrap_or(refspec);
        let src = refspec.split_once(':').map_or(refspec, |(src, _)| src);
        if src.is_empty() || src == "HEAD" {
            continue;
        }
        if src.starts_with("refs/") && local_refs.iter().any(|reference| reference.name == src) {
            continue;
        }
        if local_refs.iter().any(|reference| {
            reference.name == src
                || reference.name == format!("refs/heads/{src}")
                || reference.name == format!("refs/tags/{src}")
        }) {
            continue;
        }
        if let Ok(oid) = sley_rev::resolve_revision(git_dir, format, src)
            && !local_refs.iter().any(|reference| reference.name == src)
        {
            local_refs.push(PushSourceRef {
                name: src.to_string(),
                oid,
            });
        }
    }
}

fn normalize_push_refspec_for_sources(
    refspec: &str,
    local_refs: &[PushSourceRef],
    remote_refs: &[RefAdvertisement],
) -> Result<String> {
    let (force, refspec) = refspec
        .strip_prefix('+')
        .map_or((false, refspec), |refspec| (true, refspec));
    let normalized = if let Some((src, dst)) = refspec.split_once(':') {
        let (src, src_kind) = normalize_push_source_refname(src, local_refs);
        let dst = if src.is_empty() {
            normalize_push_delete_destination_refname(dst, remote_refs)?
        } else {
            normalize_push_destination_refname(dst, src_kind, remote_refs)?
        };
        if !src.is_empty() && !dst.contains('*') && push_destination_is_onelevel_under_refs(&dst) {
            return Err(GitError::Command(format!(
                "destination refspec {dst} is not a valid ref"
            )));
        }
        format!("{src}:{dst}")
    } else {
        let (name, _) = normalize_push_source_refname(refspec, local_refs);
        // A colon-less refspec re-uses the source's *resolved* full name as the
        // implicit destination (git's `match_explicit`: a NULL dst resolves to
        // the matched source ref). That full name is then disambiguated against
        // the remote's existing refs, so `git push <remote> frotz` (a tag)
        // lands on `refs/tags/frotz` even when the remote also has a same-named
        // branch.
        let dst = match count_refspec_match_dst(&name, remote_refs) {
            DstMatch::Unique(matched) => matched.to_string(),
            DstMatch::None => name.clone(),
            DstMatch::Ambiguous => {
                return Err(GitError::Command(format!(
                    "dst refspec {name} matches more than one"
                )));
            }
        };
        format!("{name}:{dst}")
    };
    Ok(if force {
        format!("+{normalized}")
    } else {
        normalized
    })
}

/// git's `refname_match`: true when `full_name` equals `abbrev` expanded by one
/// of the `ref_rev_parse_rules`. Returns the matched rule's rank (higher = more
/// specific) so the caller can replicate git's strong/weak distinction.
fn refname_match_rank(abbrev: &str, full_name: &str) -> Option<usize> {
    const RULES: [&str; 6] = [
        "{}",
        "refs/{}",
        "refs/tags/{}",
        "refs/heads/{}",
        "refs/remotes/{}",
        "refs/remotes/{}/HEAD",
    ];
    for (idx, rule) in RULES.iter().enumerate() {
        let (prefix, suffix) = rule.split_once("{}").unwrap_or((rule, ""));
        if full_name == format!("{prefix}{abbrev}{suffix}") {
            return Some(RULES.len() - idx);
        }
    }
    None
}

/// The outcome of git's `count_refspec_match` for a push destination.
enum DstMatch<'a> {
    /// Exactly one acceptable match (one strong, or zero strong + one weak).
    Unique(&'a str),
    /// No remote ref matched — the caller should `guess_ref` or use the literal.
    None,
    /// More than one match — git dies with "dst refspec … matches more than one".
    Ambiguous,
}

/// git's `count_refspec_match` for a push destination: find the unique existing
/// remote ref that `pattern` resolves to, distinguishing strong matches (full
/// name, top-level, or a head/tag) from weak ones (a partial match outside
/// heads/tags, e.g. `origin/main` → `refs/remotes/origin/main`). One strong
/// match wins outright; with no strong match a single weak match is used; more
/// than one acceptable match is ambiguous.
fn count_refspec_match_dst<'a>(pattern: &str, remote_refs: &'a [RefAdvertisement]) -> DstMatch<'a> {
    let patlen = pattern.len();
    let mut strong: Option<&str> = None;
    let mut strong_count = 0usize;
    let mut weak: Option<&str> = None;
    let mut weak_count = 0usize;
    for advert in remote_refs {
        let name = advert.name.as_str();
        if refname_match_rank(pattern, name).is_none() {
            continue;
        }
        let namelen = name.len();
        let is_weak = namelen != patlen
            && patlen + 5 != namelen
            && !name.starts_with("refs/heads/")
            && !name.starts_with("refs/tags/");
        if is_weak {
            weak = Some(name);
            weak_count += 1;
        } else {
            strong = Some(name);
            strong_count += 1;
        }
    }
    match (strong_count, weak_count, strong, weak) {
        (1, _, Some(matched), _) => DstMatch::Unique(matched),
        (0, 1, _, Some(matched)) => DstMatch::Unique(matched),
        (0, 0, _, _) => DstMatch::None,
        _ => DstMatch::Ambiguous,
    }
}

#[derive(Clone, Copy)]
enum PushSourceKind {
    Branch,
    Tag,
    /// A source ref that resolves but is neither under `refs/heads/` nor
    /// `refs/tags/` (e.g. `HEAD`, a fully-qualified `refs/...` name). git's
    /// `guess_ref` still guesses `refs/heads/<dst>` for these.
    Other,
    /// A source that is NOT a ref at all (a raw object id or a rev-expression
    /// like `main^`). git's `guess_ref` resolves nothing for these, so an
    /// unqualified destination cannot be guessed and the push is rejected.
    Unqualifiable,
}

fn normalize_push_source_refname(
    name: &str,
    local_refs: &[PushSourceRef],
) -> (String, PushSourceKind) {
    // `@` is git's documented alias for `HEAD`; like `HEAD` it resolves to a
    // branch, so `guess_ref` can still qualify an unqualified destination.
    if name.is_empty() || name == "HEAD" || name == "@" || name.starts_with("refs/") {
        return (name.to_string(), PushSourceKind::Other);
    }
    let branch = format!("refs/heads/{name}");
    let tag = format!("refs/tags/{name}");
    let has_branch = local_refs.iter().any(|reference| reference.name == branch);
    let has_tag = local_refs.iter().any(|reference| reference.name == tag);
    if has_tag && !has_branch {
        (tag, PushSourceKind::Tag)
    } else if has_branch {
        (branch, PushSourceKind::Branch)
    } else if local_refs.iter().any(|reference| reference.name == name) {
        // A literal match outside heads/tags/HEAD/refs is a revision source
        // injected by `add_revision_push_sources` (an oid or `main^`-style
        // expression) — not a ref, so a partial dst cannot be guessed.
        (name.to_string(), PushSourceKind::Unqualifiable)
    } else {
        (branch, PushSourceKind::Branch)
    }
}

fn normalize_push_delete_destination_refname(
    name: &str,
    remote_refs: &[RefAdvertisement],
) -> Result<String> {
    if name.is_empty() || name == "HEAD" || name.starts_with("refs/") {
        return Ok(name.to_string());
    }
    match count_refspec_match_dst(name, remote_refs) {
        DstMatch::Unique(matched) => Ok(matched.to_string()),
        DstMatch::Ambiguous => Err(GitError::Command(format!(
            "dst refspec {name} matches more than one"
        ))),
        DstMatch::None => Err(GitError::reference_not_found(format!("remote ref {name}"))),
    }
}

fn normalize_push_destination_refname(
    name: &str,
    src_kind: PushSourceKind,
    remote_refs: &[RefAdvertisement],
) -> Result<String> {
    if name.is_empty() || name == "HEAD" || name.starts_with("refs/") {
        return Ok(name.to_string());
    }
    // git's `match_explicit`: a partial destination first resolves against the
    // remote's existing refs (so `main:origin/main` lands on the existing
    // `refs/remotes/origin/main`); an ambiguous match is fatal; only when
    // nothing matches does it fall back to `guess_ref`'s heads/tags choice
    // driven by the source ref's kind.
    match count_refspec_match_dst(name, remote_refs) {
        DstMatch::Unique(matched) => Ok(matched.to_string()),
        DstMatch::Ambiguous => Err(GitError::Command(format!(
            "dst refspec {name} matches more than one"
        ))),
        DstMatch::None => match src_kind {
            PushSourceKind::Tag => Ok(format!("refs/tags/{name}")),
            PushSourceKind::Branch | PushSourceKind::Other => Ok(format!("refs/heads/{name}")),
            // git's `guess_ref` returns NULL for a non-ref source, so the
            // unqualified destination is unresolvable (the "destination is not a
            // full refname … you must fully qualify the ref" error).
            PushSourceKind::Unqualifiable => Err(GitError::Command(format!(
                "the destination you provided is not a full refname (i.e., starting with \"refs/\"); unable to guess the destination for {name}"
            ))),
        },
    }
}

fn push_destination_is_onelevel_under_refs(name: &str) -> bool {
    name.strip_prefix("refs/")
        .is_some_and(|rest| !rest.contains('/'))
}

/// The planned commands, dropping the per-command force flags.
fn commands_from_forces(command_forces: &[(ReceivePackCommand, bool)]) -> Vec<ReceivePackCommand> {
    command_forces
        .iter()
        .map(|(command, _)| command.clone())
        .collect()
}

fn receive_pack_commands_from_action_plan(
    format: ObjectFormat,
    plan: &PushActionPlan,
) -> Result<Vec<ReceivePackCommand>> {
    let zero = ObjectId::null(format);
    for oid in &plan.pack_objects {
        if oid.format() != format {
            return Err(GitError::InvalidObjectId(format!(
                "push pack object {oid} has {} object id for {} repository",
                oid.format().name(),
                format.name()
            )));
        }
    }
    plan.commands
        .iter()
        .map(|command| {
            let old_id = command.expected_old.unwrap_or(zero);
            let new_id = command.src.unwrap_or(zero);
            if old_id.format() != format {
                return Err(GitError::InvalidObjectId(format!(
                    "push command {} expected old has {} object id for {} repository",
                    command.dst,
                    old_id.format().name(),
                    format.name()
                )));
            }
            if new_id.format() != format {
                return Err(GitError::InvalidObjectId(format!(
                    "push command {} new id has {} object id for {} repository",
                    command.dst,
                    new_id.format().name(),
                    format.name()
                )));
            }
            Ok(ReceivePackCommand {
                old_id,
                new_id,
                name: command.dst.clone(),
            })
        })
        .collect()
}

/// Validate a receive-pack report-status, surfacing a failed unpack or any
/// rejected ref as an error (matching git's exit-failure message form).
pub fn validate_receive_pack_report(report: &ReceivePackReportStatus) -> Result<()> {
    if let ReceivePackUnpackStatus::Error(message) = &report.unpack {
        return Err(GitError::Command(format!(
            "failed to push some refs: unpack failed: {message}"
        )));
    }
    for status in &report.commands {
        if let ReceivePackCommandStatus::Ng { name, message } = status {
            return Err(GitError::Command(format!(
                "failed to push {name}: {message}"
            )));
        }
    }
    Ok(())
}

/// The push-source refs a local repository can match refspecs against: every ref
/// resolved to its object id, plus the short `refs/heads/`*and `refs/tags/`*
/// aliases, plus `HEAD`. Errors if any ref's object id does not match `format`.
pub fn local_push_source_refs(
    store: &FileRefStore,
    format: ObjectFormat,
) -> Result<Vec<PushSourceRef>> {
    let mut refs = Vec::new();
    for reference in store.list_refs()? {
        let Some((oid, _)) = resolve_for_each_ref_target(store, &reference)? else {
            continue;
        };
        if oid.format() != format {
            return Err(GitError::InvalidObjectId(format!(
                "local ref {} has {} object id for {} repository",
                reference.name,
                oid.format().name(),
                format.name()
            )));
        }
        refs.push(PushSourceRef {
            name: reference.name.clone(),
            oid,
        });
        if let Some(short) = reference.name.strip_prefix("refs/heads/") {
            refs.push(PushSourceRef {
                name: short.to_string(),
                oid,
            });
        }
        if let Some(short) = reference.name.strip_prefix("refs/tags/") {
            refs.push(PushSourceRef {
                name: short.to_string(),
                oid,
            });
        }
    }
    if let Some(target) = store.read_ref("HEAD")? {
        let head = Ref {
            name: "HEAD".to_string(),
            target,
        };
        if let Some((oid, _)) = resolve_for_each_ref_target(store, &head)?
            && oid.format() == format
        {
            refs.push(PushSourceRef {
                name: "HEAD".to_string(),
                oid,
            });
        }
    }
    Ok(refs)
}

/// Normalize a push refspec, expanding short names to `refs/heads/<name>` on both
/// sides and supplying the source as the destination when none is given, while
/// preserving a leading `+` force marker.
pub fn normalize_push_refspec(refspec: &str) -> String {
    let (force, refspec) = refspec
        .strip_prefix('+')
        .map_or((false, refspec), |refspec| (true, refspec));
    let normalized = if let Some((src, dst)) = refspec.split_once(':') {
        let src = normalize_push_refname(src);
        let dst = normalize_push_refname(dst);
        format!("{src}:{dst}")
    } else {
        let name = normalize_push_refname(refspec);
        format!("{name}:{name}")
    };
    if force {
        format!("+{normalized}")
    } else {
        normalized
    }
}

/// Expand a short push ref name to `refs/heads/<name>`, leaving empty names,
/// `HEAD`, and already-qualified `refs/`* names untouched.
pub fn normalize_push_refname(name: &str) -> String {
    if name.is_empty() || name == "HEAD" || name.starts_with("refs/") {
        name.to_string()
    } else {
        format!("refs/heads/{name}")
    }
}

/// Reject any non-forced branch update whose old tip is not an ancestor of the
/// new tip (a non-fast-forward). Forced updates, non-branch refs, and
/// creations/deletions are skipped.
pub fn reject_non_fast_forward_pushes(
    local_db: &FileObjectDatabase,
    format: ObjectFormat,
    command_forces: &[(ReceivePackCommand, bool)],
) -> Result<()> {
    for (command, force) in command_forces {
        if *force
            || !command.name.starts_with("refs/heads/")
            || command.old_id.is_null()
            || command.new_id.is_null()
        {
            continue;
        }
        let ancestors = ancestor_depths(local_db, format, &command.new_id)?;
        if !ancestors.contains_key(&command.old_id) {
            let short = command.name.trim_start_matches("refs/heads/");
            return Err(GitError::Command(format!(
                "failed to push some refs: non-fast-forward update to {short}"
            )));
        }
    }
    Ok(())
}

/// The depth of every commit reachable from `start` (a breadth-first ancestry
/// walk). Used to test fast-forwardness: `start`'s ancestors include `start`
/// itself at depth zero. Errors if a reachable object is not a commit.
fn ancestor_depths(
    db: &FileObjectDatabase,
    format: ObjectFormat,
    start: &ObjectId,
) -> Result<HashMap<ObjectId, usize>> {
    let mut depths = HashMap::new();
    let mut pending = std::collections::VecDeque::from([(start.clone(), 0usize)]);
    while let Some((oid, depth)) = pending.pop_front() {
        if depths.get(&oid).is_some_and(|existing| *existing <= depth) {
            continue;
        }
        depths.insert(oid, depth);
        let object = db.read_object(&oid)?;
        if object.object_type != ObjectType::Commit {
            return Err(GitError::InvalidObject(format!(
                "expected commit {oid}, found {}",
                object.object_type.as_str()
            )));
        }
        let commit = Commit::parse_ref(format, &object.body)?;
        for parent in commit.parents {
            pending.push_back((parent, depth + 1));
        }
    }
    Ok(depths)
}

/// Resolve a (possibly symbolic) ref target to its object id, following up to
/// five levels of symbolic indirection, returning the first symbolic name seen.
fn resolve_for_each_ref_target(
    store: &FileRefStore,
    reference: &Ref,
) -> Result<Option<(ObjectId, Option<String>)>> {
    let mut target = reference.target.clone();
    let mut symref = None;
    for _ in 0..5 {
        match target {
            RefTarget::Direct(oid) => return Ok(Some((oid, symref))),
            RefTarget::Symbolic(name) => {
                symref.get_or_insert_with(|| name.clone());
                let Some(next) = store.read_ref(&name)? else {
                    return Ok(None);
                };
                target = next;
            }
        }
    }
    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::atomic::{AtomicU64, Ordering};

    use sley_formats::RepositoryLayout;
    use sley_object::{Commit, EncodedObject, ObjectType, Tree};
    use sley_odb::{FileObjectDatabase, ObjectWriter};
    use sley_protocol::{ReceivePackCommandStatus, ReceivePackUnpackStatus};
    use sley_refs::{RefTarget, RefUpdate};

    use crate::{NoCredentials, SilentProgress};

    static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn temp_repo(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "sley-remote-push-{name}-{}-{}",
            std::process::id(),
            TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = fs::remove_dir_all(&dir);
        RepositoryLayout::init_at(&dir, ObjectFormat::Sha1, false)
            .expect("test repository should initialize");
        dir.join(".git")
    }

    fn write_commit(git_dir: &Path, parents: Vec<ObjectId>, message: &str) -> ObjectId {
        let format = ObjectFormat::Sha1;
        let db = FileObjectDatabase::from_git_dir(git_dir, format);
        let tree = db
            .write_object(EncodedObject::new(
                ObjectType::Tree,
                Tree { entries: vec![] }.write(),
            ))
            .expect("tree should write");
        let identity = b"Test User <test@example.invalid> 1 +0000".to_vec();
        db.write_object(EncodedObject::new(
            ObjectType::Commit,
            Commit {
                tree,
                parents,
                author: identity.clone(),
                committer: identity,
                encoding: None,
                message: format!("{message}\n").into_bytes(),
            }
            .write(),
        ))
        .expect("commit should write")
    }

    fn set_ref(git_dir: &Path, name: &str, target: RefTarget) {
        let store = FileRefStore::new(git_dir, ObjectFormat::Sha1);
        let mut tx = store.transaction();
        tx.update(RefUpdate {
            name: name.to_string(),
            expected: None,
            new: target,
            reflog: None,
        });
        tx.commit().expect("ref should update");
    }

    fn default_options() -> PushOptions {
        PushOptions {
            quiet: true,
            force: false,
        }
    }

    #[test]
    fn push_action_plan_infers_pack_roots_from_non_delete_commands() {
        let repo = temp_repo("action-plan-infer-roots");
        let first = write_commit(&repo, Vec::new(), "first");
        let second = write_commit(&repo, vec![first], "second");

        let plan = PushActionPlan::from_commands_and_infer_pack_roots(
            vec![
                PushCommand {
                    src: Some(first),
                    dst: "refs/heads/main".into(),
                    expected_old: None,
                    force: false,
                },
                PushCommand {
                    src: Some(second),
                    dst: "refs/heads/topic".into(),
                    expected_old: Some(first),
                    force: true,
                },
            ],
            default_options(),
        );

        assert_eq!(plan.pack_objects, vec![first, second]);
        assert!(!plan.commands[0].force);
        assert!(plan.commands[1].force);
    }

    #[test]
    fn push_action_plan_inferred_pack_roots_exclude_deletes() {
        let repo = temp_repo("action-plan-delete-roots");
        let old = write_commit(&repo, Vec::new(), "old");
        let new = write_commit(&repo, vec![old], "new");

        let plan = PushActionPlan::from_commands_and_infer_pack_roots(
            vec![
                PushCommand {
                    src: None,
                    dst: "refs/heads/remove".into(),
                    expected_old: Some(old),
                    force: false,
                },
                PushCommand {
                    src: Some(new),
                    dst: "refs/heads/keep".into(),
                    expected_old: Some(old),
                    force: false,
                },
            ],
            default_options(),
        );

        assert_eq!(plan.pack_objects, vec![new]);
    }

    #[test]
    fn push_action_plan_inferred_pack_roots_dedupe_first_seen_order() {
        let repo = temp_repo("action-plan-dedupe-roots");
        let first = write_commit(&repo, Vec::new(), "first");
        let second = write_commit(&repo, Vec::new(), "second");

        let plan = PushActionPlan::from_commands_and_infer_pack_roots(
            vec![
                PushCommand {
                    src: Some(second),
                    dst: "refs/heads/second".into(),
                    expected_old: None,
                    force: false,
                },
                PushCommand {
                    src: Some(first),
                    dst: "refs/heads/first".into(),
                    expected_old: None,
                    force: false,
                },
                PushCommand {
                    src: Some(second),
                    dst: "refs/tags/second".into(),
                    expected_old: None,
                    force: false,
                },
                PushCommand {
                    src: Some(first),
                    dst: "refs/tags/first".into(),
                    expected_old: None,
                    force: false,
                },
            ],
            default_options(),
        );

        assert_eq!(plan.pack_objects, vec![second, first]);
    }

    fn push_local_actions(
        local: &Path,
        remote: &Path,
        plan: &PushActionPlan,
    ) -> Result<PushOutcome> {
        let destination = PushDestination::Local {
            git_dir: remote.to_path_buf(),
            common_git_dir: remote.to_path_buf(),
        };
        let config = GitConfig::default();
        let mut credentials = NoCredentials;
        let mut progress = SilentProgress;
        push_actions(
            PushActionRequest {
                git_dir: local,
                common_git_dir: local,
                format: ObjectFormat::Sha1,
                config: &config,
                remote: "origin",
                destination: &destination,
                plan,
            },
            PushServices {
                credentials: &mut credentials,
                progress: &mut progress,
            },
        )
    }

    #[test]
    fn local_push_returns_success_report_status_and_updates_ref() {
        let local = temp_repo("local-success");
        let remote = temp_repo("remote-success");
        let base = write_commit(&local, Vec::new(), "base");
        let tip = write_commit(&local, vec![base], "tip");
        set_ref(&local, "refs/heads/main", RefTarget::Direct(tip));
        set_ref(
            &local,
            "HEAD",
            RefTarget::Symbolic("refs/heads/main".into()),
        );
        let destination = PushDestination::Local {
            git_dir: remote.clone(),
            common_git_dir: remote.clone(),
        };
        let refspecs = vec!["refs/heads/main:refs/heads/main".to_string()];
        let options = default_options();
        let request = PushRequest {
            git_dir: &local,
            common_git_dir: &local,
            format: ObjectFormat::Sha1,
            config: &GitConfig::default(),
            remote: "origin",
            destination: &destination,
            refspecs: &refspecs,
            options: &options,
        };
        let mut credentials = NoCredentials;
        let mut progress = SilentProgress;

        let outcome = push(
            request,
            PushServices {
                credentials: &mut credentials,
                progress: &mut progress,
            },
        )
        .expect("push should succeed");

        assert_eq!(outcome.commands.len(), 1);
        let report = outcome.report.expect("local receive-pack reports status");
        assert!(matches!(report.unpack, ReceivePackUnpackStatus::Ok));
        assert!(matches!(
            report.commands.as_slice(),
            [ReceivePackCommandStatus::Ok { name }] if name == "refs/heads/main"
        ));
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(tip))
        );
    }

    #[test]
    fn local_push_actions_preserves_exact_old_new_update() {
        let local = temp_repo("actions-update-local");
        let remote = temp_repo("actions-update-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let tip = write_commit(&local, vec![base], "tip");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(base));
        let plan = PushActionPlan::from_actions(
            vec![PushAction::Update {
                dst: "refs/heads/main".into(),
                old: base,
                new: tip,
            }],
            default_options(),
        );

        let outcome = push_local_actions(&local, &remote, &plan).expect("push actions");

        assert_eq!(outcome.commands.len(), 1);
        assert_eq!(outcome.commands[0].old_id, base);
        assert_eq!(outcome.commands[0].new_id, tip);
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(tip))
        );
    }

    #[test]
    fn local_push_actions_honors_per_command_force() {
        let local = temp_repo("actions-command-force-local");
        let remote = temp_repo("actions-command-force-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let unrelated = write_commit(&local, Vec::new(), "unrelated");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(base));

        let unforced = PushActionPlan::from_commands(
            vec![PushCommand {
                src: Some(unrelated),
                dst: "refs/heads/main".into(),
                expected_old: Some(base),
                force: false,
            }],
            default_options(),
        );
        let err = push_local_actions(&local, &remote, &unforced)
            .expect_err("non-fast-forward should reject without command force");
        assert!(err.to_string().contains("non-fast-forward"));

        let forced = PushActionPlan::from_commands(
            vec![PushCommand {
                src: Some(unrelated),
                dst: "refs/heads/main".into(),
                expected_old: Some(base),
                force: true,
            }],
            default_options(),
        );
        let outcome = push_local_actions(&local, &remote, &forced).expect("command force pushes");

        assert_eq!(outcome.commands.len(), 1);
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(unrelated))
        );
    }

    #[test]
    fn local_push_actions_command_force_is_precise_for_non_ff_validation() {
        let local = temp_repo("actions-command-force-precise-local");
        let remote = temp_repo("actions-command-force-precise-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let forced_unrelated = write_commit(&local, Vec::new(), "forced unrelated");
        let unforced_unrelated = write_commit(&local, Vec::new(), "unforced unrelated");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(base));
        set_ref(&remote, "refs/heads/topic", RefTarget::Direct(base));
        let plan = PushActionPlan::from_commands_and_infer_pack_roots(
            vec![
                PushCommand {
                    src: Some(forced_unrelated),
                    dst: "refs/heads/main".into(),
                    expected_old: Some(base),
                    force: true,
                },
                PushCommand {
                    src: Some(unforced_unrelated),
                    dst: "refs/heads/topic".into(),
                    expected_old: Some(base),
                    force: false,
                },
            ],
            default_options(),
        );

        let err = push_local_actions(&local, &remote, &plan)
            .expect_err("only the forced command should bypass non-fast-forward validation");

        assert!(err.to_string().contains("non-fast-forward update to topic"));
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(base))
        );
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/topic")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(base))
        );
    }

    #[test]
    fn local_push_actions_stale_update_old_rejects_without_mutating() {
        let local = temp_repo("actions-stale-local");
        let remote = temp_repo("actions-stale-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let tip = write_commit(&local, vec![base], "tip");
        let concurrent = write_commit(&remote, vec![base], "concurrent");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(concurrent));
        let plan = PushActionPlan::from_actions(
            vec![PushAction::Update {
                dst: "refs/heads/main".into(),
                old: base,
                new: tip,
            }],
            default_options(),
        );

        let err = push_local_actions(&local, &remote, &plan).expect_err("stale old rejects");

        assert!(err.to_string().contains("expected ref refs/heads/main"));
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(concurrent))
        );
    }

    #[test]
    fn local_push_actions_stale_delete_old_rejects_without_mutating() {
        let local = temp_repo("actions-delete-local");
        let remote = temp_repo("actions-delete-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let concurrent = write_commit(&remote, vec![base], "concurrent");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(concurrent));
        let plan = PushActionPlan::from_actions(
            vec![PushAction::Delete {
                dst: "refs/heads/main".into(),
                old: Some(base),
            }],
            default_options(),
        );

        let err = push_local_actions(&local, &remote, &plan).expect_err("stale delete rejects");

        assert!(err.to_string().contains("expected ref refs/heads/main"));
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(concurrent))
        );
    }

    #[test]
    fn local_push_actions_create_rejects_existing_ref() {
        let local = temp_repo("actions-create-local");
        let remote = temp_repo("actions-create-remote");
        let base = write_commit(&local, Vec::new(), "base");
        let remote_base = write_commit(&remote, Vec::new(), "base");
        assert_eq!(remote_base, base);
        let tip = write_commit(&local, vec![base], "tip");
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(base));
        let plan = PushActionPlan::from_actions(
            vec![PushAction::Create {
                dst: "refs/heads/main".into(),
                new: tip,
            }],
            default_options(),
        );

        let err = push_local_actions(&local, &remote, &plan).expect_err("create must be absent");

        assert!(
            err.to_string()
                .contains("expected ref refs/heads/main to not already exist")
        );
        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(base))
        );
    }

    #[test]
    fn report_status_rejection_is_an_error() {
        let report = ReceivePackReportStatus {
            unpack: ReceivePackUnpackStatus::Ok,
            commands: vec![ReceivePackCommandStatus::Ng {
                name: "refs/heads/main".into(),
                message: "hook declined".into(),
            }],
        };

        let err = validate_receive_pack_report(&report).expect_err("ng report should fail");

        assert!(err.to_string().contains("hook declined"));
    }

    #[test]
    fn failed_local_push_does_not_partially_mutate_remote_ref() {
        let local = temp_repo("local-rejected");
        let remote = temp_repo("remote-rejected");
        let base = write_commit(&local, Vec::new(), "base");
        let planned = write_commit(&local, vec![base], "planned");
        let concurrent = write_commit(&local, vec![base], "concurrent");
        set_ref(&local, "refs/heads/main", RefTarget::Direct(planned));
        set_ref(
            &local,
            "HEAD",
            RefTarget::Symbolic("refs/heads/main".into()),
        );
        set_ref(&remote, "refs/heads/main", RefTarget::Direct(base));
        let destination = PushDestination::Local {
            git_dir: remote.clone(),
            common_git_dir: remote.clone(),
        };
        let refspecs = vec!["refs/heads/main:refs/heads/main".to_string()];
        let options = default_options();
        let request = PushRequest {
            git_dir: &local,
            common_git_dir: &local,
            format: ObjectFormat::Sha1,
            config: &GitConfig::default(),
            remote: "origin",
            destination: &destination,
            refspecs: &refspecs,
            options: &options,
        };
        let mut credentials = NoCredentials;
        let mut progress = SilentProgress;
        let mut services = PushServices {
            credentials: &mut credentials,
            progress: &mut progress,
        };
        let plan = plan_push(request, &mut services).expect("push should plan");

        set_ref(&remote, "refs/heads/main", RefTarget::Direct(concurrent));
        let _err = execute_push_plan(request, &mut services, plan)
            .expect_err("stale old id should reject the ref update");

        let remote_refs = FileRefStore::new(&remote, ObjectFormat::Sha1);
        assert_eq!(
            remote_refs
                .read_ref("refs/heads/main")
                .expect("remote ref should read"),
            Some(RefTarget::Direct(concurrent))
        );
    }
}