vcs-git 0.5.0

Automate the Git CLI from Rust through process execution.
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
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(rustdoc::broken_intra_doc_links)]
//! `vcs-git` — automate Git from Rust by driving the `git` CLI.
//!
//! It shells out to the installed `git` binary and parses its output into typed
//! values — so you get *git's own* behaviour, config, and credential handling,
//! not a reimplementation of the object format. Async throughout, structured
//! errors, and mockable. Every command runs inside an OS **job** (via
//! [`processkit`]) so a `git` subprocess tree can never be orphaned, and honours
//! an optional per-client [timeout](Git::default_timeout).
//!
//! # The surface
//!
//! - **[`GitApi`]** — the object-safe trait every operation lives on. Depend on
//!   `&dyn GitApi` (or generically on `impl GitApi`) so a test can swap the real
//!   client for a double. Methods take the working directory as the first
//!   argument and return typed results ([`StatusEntry`], [`Branch`], [`Commit`],
//!   [`FileDiff`], [`BlameLine`], …) or a structured [`Error`].
//! - **[`Git`]** — the real client. [`Git::new`] uses the job-backed runner;
//!   [`Git::with_runner`] injects a fake one for tests. It is generic over the
//!   [`ProcessRunner`] seam, defaulting to the production runner.
//! - **[`GitAt`]** — a cwd-bound view ([`Git::at`]) whose methods drop the
//!   leading `dir`, so `git.at(dir).status()` reads as `git.status(dir)` — handy
//!   when one client drives one checkout.
//! - **Builder specs** for the multi-option commands — [`CommitPaths`],
//!   [`MergeCommit`] / [`MergeNoCommit`], [`GitPush`], [`CloneSpec`],
//!   [`WorktreeAdd`], [`AnnotatedTag`] — each `#[non_exhaustive]`, built with a
//!   constructor + chained setters, named after the flags they emit.
//! - **[`conflict`]** — a typed conflict-marker model: parse marker soup into
//!   structured regions, re-render byte-exact, and resolve to a chosen side.
//! - **[`Git::hardened`]** — a profile for untrusted repositories (hooks off,
//!   `GIT_*` scrubbed, system config skipped); see the [`guide::security`] guide.
//!
//! # Recipes
//!
//! Read state — depend on the trait so the same code takes a real client or a mock:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_git::{Git, GitApi};
//! # async fn demo() -> Result<(), processkit::Error> {
//! let git = Git::new();
//! let dir = Path::new(".");
//! let branch = git.current_branch(dir).await?;        // the checked-out branch
//! let dirty = !git.status(dir).await?.is_empty();     // any uncommitted change?
//! # let _ = (branch, dirty); Ok(()) }
//! ```
//!
//! Mutate through the builder specs — `fetch` retries transient network failures:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_git::{CommitPaths, Git, GitApi, GitPush};
//! # async fn demo(git: &Git) -> Result<(), processkit::Error> {
//! let dir = Path::new(".");
//! git.fetch(dir).await?;
//! git.commit_paths(dir, CommitPaths::new(["src/a.rs"], "wip")).await?;
//! git.push(dir, GitPush::branch("feature").set_upstream()).await?;
//! # Ok(()) }
//! ```
//!
//! # Testing
//!
//! Two seams: enable the **`mock`** feature for a `mockall`-generated
//! `MockGitApi` (stub whole methods), or inject a
//! [`ScriptedRunner`](processkit::ScriptedRunner) with [`Git::with_runner`] to
//! exercise the *real* argv-building and parsing against canned output. The
//! cross-cutting testing patterns live in
//! [vcs-testkit's guide](https://docs.rs/vcs-testkit/latest/vcs_testkit/guide/testing/).
//!
//! # Safety
//!
//! Every caller value placed in a bare positional argv slot is refused before
//! spawning if it is empty or starts with `-` (git would parse it as a flag);
//! flag-value slots (`-b <name>`) are consumed verbatim and don't need it. For
//! eager validation at an input boundary, the [`RefName`] / [`RevSpec`] newtypes
//! validate up front. Paths always go through `--` / pathspec.
//!
//! # In-depth guide
//!
//! Beyond this page, this crate ships a full how-to guide — rendered on docs.rs
//! from `docs/`. See the [`guide`] module (and its
//! [`security`](crate::guide::security) / [`conflicts`](crate::guide::conflicts)
//! sub-guides).

use std::path::{Path, PathBuf};
use std::time::Duration;

use processkit::ProcessRunner;
// Re-export the processkit types that appear in this crate's public API, so
// consumers needn't depend on processkit directly. (`Error`/`Result`/`ProcessResult`
// are in scope here too via this `pub use`.)
pub use processkit::{Error, ProcessResult, Result};
// Re-exported under the `cancellation` feature so a consumer can name the token
// for `default_cancel_on` without taking a direct `processkit` dependency.
#[cfg(feature = "cancellation")]
#[cfg_attr(docsrs, doc(cfg(feature = "cancellation")))]
pub use processkit::CancellationToken;

pub mod conflict;
mod parse;
pub use parse::{BlameLine, Branch, BranchStatus, Commit, StatusEntry, Worktree};
// The git-format diff model + parser and the version type are shared with
// `vcs-jj` (identical output) — re-exported so `vcs_git::FileDiff`,
// `vcs_git::parse_diff`, `vcs_git::GitVersion`, … still resolve.
pub use vcs_diff::{
    ChangeKind, DiffLine, DiffStat, FileDiff, Hunk, Version as GitVersion, parse_diff,
};
// The error classifiers live in the shared plumbing crate — re-exported so
// `vcs_git::is_merge_conflict`, … still resolve.
pub use vcs_cli_support::{is_merge_conflict, is_nothing_to_commit, is_transient_fetch_error};

/// Name of the underlying CLI binary this crate drives.
pub const BINARY: &str = "git";

/// What a [`GitApi::diff`] / [`GitApi::diff_text`] call compares.
///
/// `#[non_exhaustive]` so more comparison shapes can be added later.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DiffSpec {
    /// All tracked working-tree changes vs the last commit (`git diff HEAD`),
    /// staged or not, excluding untracked files.
    WorkingTree,
    /// A specific revision or range, e.g. `main..HEAD` or `HEAD~1` (`git diff <rev>`).
    Rev(String),
}

/// Options for [`GitApi::worktree_add`] (`git worktree add`).
///
/// `#[non_exhaustive]`, so build it through [`WorktreeAdd::checkout`] /
/// [`WorktreeAdd::create_branch`] rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct WorktreeAdd {
    /// Filesystem path for the new worktree.
    pub path: PathBuf,
    /// Create and check out this new branch (`-b <name>`); `None` checks out an
    /// existing ref.
    pub new_branch: Option<String>,
    /// The commit/branch to base the worktree on; `None` defaults to `HEAD`.
    pub commitish: Option<String>,
    /// Register the worktree without populating its files (`--no-checkout`) — the
    /// caller fills the working tree itself (e.g. a copy-on-write clone).
    pub no_checkout: bool,
}

impl WorktreeAdd {
    /// A worktree at `path` checking out an existing `commitish` (e.g. a branch):
    /// `git worktree add <path> <commitish>`.
    pub fn checkout(path: impl Into<PathBuf>, commitish: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            new_branch: None,
            commitish: Some(commitish.into()),
            no_checkout: false,
        }
    }

    /// A worktree at `path` creating a new branch `name` based on `commitish`:
    /// `git worktree add -b <name> <path> <commitish>`.
    pub fn create_branch(
        path: impl Into<PathBuf>,
        name: impl Into<String>,
        commitish: impl Into<String>,
    ) -> Self {
        Self {
            path: path.into(),
            new_branch: Some(name.into()),
            commitish: Some(commitish.into()),
            no_checkout: false,
        }
    }

    /// Register the worktree without checking out its files (`--no-checkout`),
    /// for a caller that populates the working tree itself.
    pub fn no_checkout(mut self) -> Self {
        self.no_checkout = true;
        self
    }
}

/// Options for [`GitApi::push`] (`git push`).
///
/// `#[non_exhaustive]`, so build it through [`GitPush::branch`] /
/// [`GitPush::refspec`] rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GitPush {
    /// Remote to push to (defaults to `origin`).
    pub remote: String,
    /// The refspec — a bare branch name, or `local:remote_branch`.
    pub refspec: String,
    /// Set the pushed branch as the upstream (`-u`).
    pub set_upstream: bool,
}

impl GitPush {
    /// Push branch `name` to `origin` under the same name (`git push origin <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            remote: "origin".to_string(),
            refspec: name.into(),
            set_upstream: false,
        }
    }

    /// Push `local` to a differently-named `remote_branch`
    /// (`git push origin <local>:<remote_branch>`).
    pub fn refspec(local: impl AsRef<str>, remote_branch: impl AsRef<str>) -> Self {
        Self {
            remote: "origin".to_string(),
            refspec: format!("{}:{}", local.as_ref(), remote_branch.as_ref()),
            set_upstream: false,
        }
    }

    /// Push to a non-default remote.
    pub fn remote(mut self, remote: impl Into<String>) -> Self {
        self.remote = remote.into();
        self
    }

    /// Record the pushed branch as the local branch's upstream (`-u`).
    pub fn set_upstream(mut self) -> Self {
        self.set_upstream = true;
        self
    }
}

/// Options for [`GitApi::clone_repo`] (`git clone`).
///
/// `#[non_exhaustive]`, so build it through [`CloneSpec::new`] and the chained
/// setters rather than a struct literal.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CloneSpec {
    /// Check out this branch instead of the remote's default (`--branch`).
    pub branch: Option<String>,
    /// Shallow-clone to this many commits (`--depth`). git silently ignores
    /// the flag for a plain local-path source (warns, still clones fully);
    /// use a `file://` URL to shallow-clone locally.
    pub depth: Option<u32>,
    /// Create a bare repository (`--bare`).
    pub bare: bool,
}

impl CloneSpec {
    /// A plain full clone of the remote's default branch.
    pub fn new() -> Self {
        Self::default()
    }

    /// Check out `branch` instead of the remote's default (`--branch`).
    pub fn branch(mut self, branch: impl Into<String>) -> Self {
        self.branch = Some(branch.into());
        self
    }

    /// Shallow-clone to `depth` commits (`--depth`); see the field doc for the
    /// local-path caveat.
    pub fn depth(mut self, depth: u32) -> Self {
        self.depth = Some(depth);
        self
    }

    /// Clone as a bare repository (`--bare`).
    pub fn bare(mut self) -> Self {
        self.bare = true;
        self
    }
}

/// Options for [`GitApi::commit_paths`] (`git commit --only`).
///
/// `#[non_exhaustive]`, so build it through [`CommitPaths::new`] and the chained
/// setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CommitPaths {
    /// The exact paths whose working-tree content to commit (`--only -- <paths>`).
    pub paths: Vec<PathBuf>,
    /// The commit message (`-m`).
    pub message: String,
    /// Amend the previous commit instead of creating a new one (`--amend`).
    pub amend: bool,
}

impl CommitPaths {
    /// Commit exactly `paths`' working-tree content with `message`
    /// (`git commit -m <message> --only -- <paths>`).
    pub fn new(
        paths: impl IntoIterator<Item = impl Into<PathBuf>>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            paths: paths.into_iter().map(Into::into).collect(),
            message: message.into(),
            amend: false,
        }
    }

    /// Amend the previous commit instead of creating a new one (`--amend`).
    pub fn amend(mut self) -> Self {
        self.amend = true;
        self
    }
}

/// Options for [`GitApi::merge_commit`] (`git merge` that commits the result).
///
/// `#[non_exhaustive]`, so build it through [`MergeCommit::branch`] and the
/// chained setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MergeCommit {
    /// The branch to merge in.
    pub branch: String,
    /// Always create a merge commit, even when a fast-forward was possible
    /// (`--no-ff`).
    pub no_ff: bool,
    /// The merge commit message (`-m`); `None` takes the default message
    /// non-interactively (`--no-edit`).
    pub message: Option<String>,
}

impl MergeCommit {
    /// Merge `name` taking the default merge message non-interactively
    /// (`git merge --no-edit <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            branch: name.into(),
            no_ff: false,
            message: None,
        }
    }

    /// Always create a merge commit, even when a fast-forward was possible
    /// (`--no-ff`).
    pub fn no_ff(mut self) -> Self {
        self.no_ff = true;
        self
    }

    /// Use `m` as the merge commit message (`-m`).
    pub fn message(mut self, m: impl Into<String>) -> Self {
        self.message = Some(m.into());
        self
    }
}

/// Options for [`GitApi::merge_no_commit`] (`git merge --no-commit`).
///
/// `#[non_exhaustive]`, so build it through [`MergeNoCommit::branch`] and the
/// chained setters rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct MergeNoCommit {
    /// The branch to merge in.
    pub branch: String,
    /// Stage the squashed result without recording `MERGE_HEAD` (`--squash`);
    /// takes precedence over `no_ff` (git rejects the pair).
    pub squash: bool,
    /// Always record a real (abortable) merge, even when a fast-forward was
    /// possible (`--no-ff`).
    pub no_ff: bool,
}

impl MergeNoCommit {
    /// Merge `name` but stop before committing (`git merge --no-commit <name>`).
    pub fn branch(name: impl Into<String>) -> Self {
        Self {
            branch: name.into(),
            squash: false,
            no_ff: false,
        }
    }

    /// Stage the squashed result without recording `MERGE_HEAD` (`--squash`).
    pub fn squash(mut self) -> Self {
        self.squash = true;
        self
    }

    /// Always record a real (abortable) merge, even when a fast-forward was
    /// possible (`--no-ff`).
    pub fn no_ff(mut self) -> Self {
        self.no_ff = true;
        self
    }
}

/// Options for [`GitApi::tag_create_annotated`] (`git tag -a`).
///
/// `#[non_exhaustive]`, so build it through [`AnnotatedTag::new`] and the chained
/// setter rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AnnotatedTag {
    /// The tag name.
    pub name: String,
    /// The tag message (`-m`).
    pub message: String,
    /// The revision to tag (`<rev>`); `None` tags `HEAD`.
    pub rev: Option<String>,
}

impl AnnotatedTag {
    /// An annotated tag `name` with `message` at `HEAD`
    /// (`git tag -a <name> -m <message>`).
    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            message: message.into(),
            rev: None,
        }
    }

    /// Tag `r` instead of `HEAD`.
    pub fn rev(mut self, r: impl Into<String>) -> Self {
        self.rev = Some(r.into());
        self
    }
}

/// A pre-validated git reference name (branch/tag/remote), for callers that
/// accept names from untrusted input (UIs, bots, agents) and want to fail
/// early with a clear error. The dir-taking methods stay `&str` — they apply
/// the same flag-injection guard internally — so this type is **optional**
/// up-front validation, not a required wrapper.
///
/// Rules follow the load-bearing core of `git check-ref-format`: non-empty,
/// no leading `-` or `.`, no `..`, no control characters or space, none of
/// `~ ^ : ? * [ \`, no trailing `/` or `.lock`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RefName(String);

impl RefName {
    /// Validate `name` as a reference name.
    pub fn new(name: impl Into<String>) -> Result<Self> {
        let name = name.into();
        let bad = name.is_empty()
            || name.starts_with('-')
            || name.starts_with('.')
            || name.ends_with('/')
            || name.ends_with(".lock")
            || name.contains("..")
            || name
                .chars()
                .any(|c| c.is_control() || " ~^:?*[\\".contains(c));
        if bad {
            return Err(Error::Spawn {
                program: BINARY.to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    format!("invalid git reference name: {name:?}"),
                ),
            });
        }
        Ok(RefName(name))
    }

    /// The validated name.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RefName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// A pre-validated revision/range expression (`HEAD~2`, `main..feature`).
/// Deliberately *minimal* — git's revision grammar is too rich to validate
/// here — it only guarantees the expression is non-empty and cannot be parsed
/// as a flag (no leading `-`), matching the internal guard the dir-taking
/// methods apply anyway. Optional up-front validation for untrusted input.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RevSpec(String);

impl RevSpec {
    /// Validate `rev` as a revision/range expression (non-empty, no leading `-`).
    pub fn new(rev: impl Into<String>) -> Result<Self> {
        let rev = rev.into();
        reject_flag_like("revision", &rev)?;
        Ok(RevSpec(rev))
    }

    /// The validated expression.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for RevSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// What the installed `git` binary supports, probed via
/// [`GitApi::capabilities`]. A value type — the client holds no state, so
/// probe once and keep the result (callers cache it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct GitCapabilities {
    /// The binary's parsed version.
    pub version: GitVersion,
}

/// The oldest git major this crate is written against. Validated on 2.54;
/// expected to work from ≥ 2.30 — but only the *major* is hard-gated, because
/// a false "unsupported" on an untested-but-fine 2.2x would be worse than the
/// argv error git itself would give. (Contrast vcs-jj, whose floor is precise:
/// its parsers were empirically validated against one jj release.)
const MIN_SUPPORTED_MAJOR: u64 = 2;

impl GitCapabilities {
    /// Whether the binary meets the supported floor (major ≥ 2).
    pub fn is_supported(&self) -> bool {
        self.version.major >= MIN_SUPPORTED_MAJOR
    }

    /// Error unless [`is_supported`](Self::is_supported) — a clear "needs git
    /// ≥ 2, found 1.9.5" instead of a cryptic argv failure later.
    pub fn ensure_supported(&self) -> Result<()> {
        if self.is_supported() {
            return Ok(());
        }
        Err(Error::Spawn {
            program: BINARY.to_string(),
            source: std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!(
                    "vcs-git requires git >= {MIN_SUPPORTED_MAJOR} (validated on 2.54), \
                     found {}",
                    self.version
                ),
            ),
        })
    }
}

/// The Git operations this crate exposes — the interface consumers code against
/// and mock in tests.
///
/// **Injection safety:** every method that places a caller-supplied name,
/// revision, range, remote, or URL in a positional argv slot rejects a value
/// that is empty or begins with `-` (it would be parsed as a flag) with an
/// [`Error::Spawn`] *before* spawning. Flag-value slots (`-m <msg>`,
/// `--branch <b>`), filesystem path arguments (`--`-separated pathspecs, plus
/// worktree paths and clone destinations — typed `Path`, caller-trusted), and
/// the `run`/`run_raw` escape hatches are not guarded. For eager validation at
/// an input boundary, see [`RefName`] / [`RevSpec`].
#[cfg_attr(feature = "mock", mockall::automock)]
#[async_trait::async_trait]
pub trait GitApi: Send + Sync {
    /// Run `git <args>` in the current directory, returning trimmed stdout
    /// (throws on a non-zero exit). A raw escape hatch for unmodelled commands.
    async fn run(&self, args: &[String]) -> Result<String>;
    /// Like [`GitApi::run`] but never errors on a non-zero exit — returns the
    /// captured [`ProcessResult`].
    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>>;
    /// Installed Git version (`git --version`).
    async fn version(&self) -> Result<String>;
    /// The installed binary's parsed version, as [`GitCapabilities`]
    /// (`git --version`). A value type — probe once and keep it; an
    /// unrecognisable version string is an [`Error::Parse`].
    async fn capabilities(&self) -> Result<GitCapabilities>;
    /// Working-tree status (`git status --porcelain=v1 -z`).
    async fn status(&self, dir: &Path) -> Result<Vec<StatusEntry>>;
    /// Raw porcelain status text (`git status --porcelain=v1`) — the unparsed
    /// counterpart of [`status`](GitApi::status), mirroring `vcs_jj` `status_text`.
    async fn status_text(&self, dir: &Path) -> Result<String>;
    /// Like [`status`](GitApi::status) but ignoring untracked files
    /// (`git status --porcelain=v1 -z --untracked-files=no`) — "is the *tracked*
    /// tree dirty", staged or not.
    async fn status_tracked(&self, dir: &Path) -> Result<Vec<StatusEntry>>;
    /// A combined branch + working-tree snapshot in **one** spawn
    /// (`git status --porcelain=v2 --branch -z`): HEAD, branch, upstream,
    /// ahead/behind, and change counts — the data a prompt/status-bar needs
    /// without N round-trips. See [`BranchStatus`].
    async fn branch_status(&self, dir: &Path) -> Result<BranchStatus>;
    /// Paths with unresolved merge conflicts, repo-relative with `/` separators
    /// (`git diff --name-only --diff-filter=U -z`). Empty when there are none.
    async fn conflicted_files(&self, dir: &Path) -> Result<Vec<String>>;
    /// Current branch name (`git rev-parse --abbrev-ref HEAD`).
    async fn current_branch(&self, dir: &Path) -> Result<String>;
    /// Local branches, current one flagged (`git branch`).
    async fn branches(&self, dir: &Path) -> Result<Vec<Branch>>;
    /// Latest `max` commits, newest first (`git log`).
    async fn log(&self, dir: &Path, max: usize) -> Result<Vec<Commit>>;
    /// Commits in `range`, newest first, up to `max` (`git log <range>`).
    async fn log_range(&self, dir: &Path, range: &str, max: usize) -> Result<Vec<Commit>>;
    /// Resolve a revision to a full hash (`git rev-parse <rev>`).
    async fn rev_parse(&self, dir: &Path, rev: &str) -> Result<String>;
    /// Resolve a revision to its abbreviated hash (`git rev-parse --short <rev>`) —
    /// e.g. to label a detached HEAD.
    async fn rev_parse_short(&self, dir: &Path, rev: &str) -> Result<String>;
    /// Initialise a repository (`git init`).
    async fn init(&self, dir: &Path) -> Result<()>;
    /// Stage `paths` (`git add -- <paths>`).
    async fn add(&self, dir: &Path, paths: &[PathBuf]) -> Result<()>;
    /// Commit staged changes (`git commit -m`).
    async fn commit(&self, dir: &Path, message: &str) -> Result<()>;
    /// Create a branch without switching to it (`git branch <name>`).
    async fn create_branch(&self, dir: &Path, name: &str) -> Result<()>;
    /// Switch to a branch or revision (`git checkout <reference>`).
    async fn checkout(&self, dir: &Path, reference: &str) -> Result<()>;
    /// Check out a commit as a detached HEAD (`git checkout --detach <commit>`).
    async fn checkout_detach(&self, dir: &Path, commit: &str) -> Result<()>;
    /// Commit exactly the spec's paths' working-tree content, ignoring the index
    /// (`git commit [--amend] -m <message> --only -- <paths>`); see [`CommitPaths`].
    async fn commit_paths(&self, dir: &Path, spec: CommitPaths) -> Result<()>;
    /// The last commit's full message (`git log -1 --format=%B`) — e.g. to
    /// pre-fill an amend.
    async fn last_commit_message(&self, dir: &Path) -> Result<String>;
    /// Whether `HEAD` is unborn — a fresh repo with no commits yet
    /// (`git rev-parse --verify -q HEAD`, exit-code mapped).
    async fn is_unborn(&self, dir: &Path) -> Result<bool>;
    /// Whether the working tree has no unstaged modifications to **tracked** files
    /// (`git diff --quiet`). Untracked files are *not* counted — this is not a full
    /// "is the working tree clean?" check; use [`status`](GitApi::status) for that.
    async fn diff_is_empty(&self, dir: &Path) -> Result<bool>;

    // --- Discovery / identity ------------------------------------------------

    /// The repository's common git directory (`rev-parse --git-common-dir`) —
    /// stable across linked worktrees.
    async fn common_dir(&self, dir: &Path) -> Result<PathBuf>;
    /// This worktree's git directory (`rev-parse --git-dir`).
    async fn git_dir(&self, dir: &Path) -> Result<PathBuf>;
    /// Resolve a revision to a commit hash, peeling tags
    /// (`rev-parse --verify <rev>^{commit}`).
    async fn resolve_commit(&self, dir: &Path, rev: &str) -> Result<String>;
    /// The remote's default branch from `symbolic-ref refs/remotes/origin/HEAD`
    /// (short name only); `None` when `origin/HEAD` is unset.
    async fn remote_head_branch(&self, dir: &Path) -> Result<Option<String>>;
    /// Whether a local branch exists (`show-ref --verify --quiet refs/heads/<name>`).
    async fn branch_exists(&self, dir: &Path, name: &str) -> Result<bool>;
    /// Whether `origin` has `name`, without fetching (`ls-remote origin
    /// refs/heads/<name>` — the fully-qualified ref, so `foo` can't tail-match
    /// `bar/foo`). Runs with `GIT_TERMINAL_PROMPT=0` and a 10s timeout so a missing
    /// credential or a flaky network can't hang the call.
    async fn remote_branch_exists(&self, dir: &Path, name: &str) -> Result<bool>;
    /// A remote's URL (`remote get-url <remote>`).
    async fn remote_url(&self, dir: &Path, remote: &str) -> Result<String>;
    /// The current branch's upstream, e.g. `Some("origin/main")`
    /// (`rev-parse --abbrev-ref --symbolic-full-name @{u}`); `None` when unset.
    async fn upstream(&self, dir: &Path) -> Result<Option<String>>;
    /// Branch names on `remote`, without fetching
    /// (`ls-remote --heads <remote>`).
    async fn remote_branches(&self, dir: &Path, remote: &str) -> Result<Vec<String>>;

    // --- Branches ------------------------------------------------------------

    /// Whether `branch` is fully merged into `target` (`branch --merged <target>`).
    async fn is_merged(&self, dir: &Path, branch: &str, target: &str) -> Result<bool>;
    /// Set `branch`'s upstream to `upstream` (e.g. `origin/main`)
    /// (`branch --set-upstream-to=<upstream> <branch>`).
    async fn set_upstream(&self, dir: &Path, branch: &str, upstream: &str) -> Result<()>;
    /// Delete a local branch (`branch -d`, or `-D` when `force`).
    async fn delete_branch(&self, dir: &Path, name: &str, force: bool) -> Result<()>;
    /// Rename a local branch (`branch -m <old> <new>`).
    async fn rename_branch(&self, dir: &Path, old: &str, new: &str) -> Result<()>;
    /// Count commits in a range (`rev-list --count <range>`).
    async fn rev_list_count(&self, dir: &Path, range: &str) -> Result<usize>;
    /// Whether a diff range is empty (`diff --quiet <range>`).
    async fn diff_range_is_empty(&self, dir: &Path, range: &str) -> Result<bool>;
    /// Aggregate change stats for a range (`diff --shortstat <range>`). Named to
    /// match `vcs_jj::JjApi::diff_stat`.
    async fn diff_stat(&self, dir: &Path, range: &str) -> Result<DiffStat>;
    /// Raw git-format unified diff text for `spec`
    /// (`diff <spec> --no-color --no-ext-diff -M`) — stable machine output.
    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String>;
    /// Parsed per-file unified diff for `spec`, layered on [`diff_text`](GitApi::diff_text).
    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>>;

    // --- In-progress state ---------------------------------------------------

    /// Whether the index has no staged changes (`diff --cached --quiet`).
    async fn staged_is_empty(&self, dir: &Path) -> Result<bool>;
    /// Whether a rebase is in progress (a `rebase-merge`/`rebase-apply` dir exists
    /// under the git dir).
    async fn is_rebase_in_progress(&self, dir: &Path) -> Result<bool>;
    /// Whether a merge is in progress (a `MERGE_HEAD` exists under the git dir).
    async fn is_merge_in_progress(&self, dir: &Path) -> Result<bool>;

    // --- Mutations -----------------------------------------------------------

    /// Fetch from the default remote (`fetch --quiet`), with `GIT_TERMINAL_PROMPT=0`.
    /// Transient (network) failures are retried (3 attempts, 500 ms backoff).
    async fn fetch(&self, dir: &Path) -> Result<()>;
    /// Fetch from a *named* remote (`fetch --quiet <remote>`), with
    /// `GIT_TERMINAL_PROMPT=0`. Transient failures are retried like
    /// [`fetch`](GitApi::fetch).
    async fn fetch_from(&self, dir: &Path, remote: &str) -> Result<()>;
    /// Fetch a single branch from `origin` into its remote-tracking ref
    /// (`fetch --quiet origin refs/heads/<b>:refs/remotes/origin/<b>`), with
    /// `GIT_TERMINAL_PROMPT=0`. Transient failures are retried (3×, 500 ms).
    async fn fetch_remote_branch(&self, dir: &Path, branch: &str) -> Result<()>;
    /// Push to a remote (`push [-u] <remote> <refspec>`); see [`GitPush`].
    async fn push(&self, dir: &Path, spec: GitPush) -> Result<()>;
    /// Stage a branch's changes without committing (`merge --squash <branch>`).
    async fn merge_squash(&self, dir: &Path, branch: &str) -> Result<()>;
    /// Merge a branch (`merge [--no-ff] [-m <msg> | --no-edit] <branch>`); with no
    /// message it takes the default merge message non-interactively (`--no-edit`).
    /// See [`MergeCommit`].
    async fn merge_commit(&self, dir: &Path, spec: MergeCommit) -> Result<()>;
    /// Merge a branch but stop before committing, so the result can be inspected
    /// (`merge --no-commit [--squash | --no-ff] <branch>`). With `no_ff` (and not
    /// `squash`) git records `MERGE_HEAD`, so the in-progress merge is abortable
    /// via [`merge_abort`](GitApi::merge_abort) — the dry-run pattern. With
    /// `squash`, git stages the squashed result but records **no** `MERGE_HEAD`,
    /// so it is *not* an abortable merge: undo it with
    /// [`reset_merge`](GitApi::reset_merge) / [`reset_hard`](GitApi::reset_hard),
    /// not `merge_abort`. See [`MergeNoCommit`].
    async fn merge_no_commit(&self, dir: &Path, spec: MergeNoCommit) -> Result<()>;
    /// Abort an in-progress merge (`merge --abort`).
    async fn merge_abort(&self, dir: &Path) -> Result<()>;
    /// Finish a merge after resolving conflicts (`commit --no-edit`).
    async fn merge_continue(&self, dir: &Path) -> Result<()>;
    /// Undo an in-progress (or just-staged) merge: `reset --merge` resets the
    /// index and the merge-touched working-tree files back to `HEAD` and drops
    /// `MERGE_HEAD`, **discarding the merge's changes** while keeping unrelated
    /// unstaged edits. Use it after `merge_squash` / `merge_no_commit(squash)`,
    /// where there is no `MERGE_HEAD` for `merge_abort` to act on.
    async fn reset_merge(&self, dir: &Path) -> Result<()>;
    /// Hard-reset the working tree to a revision (`reset --hard <rev>`).
    async fn reset_hard(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Rebase the current branch onto `onto` (`rebase <onto>`); the editor is
    /// suppressed (`GIT_EDITOR=true`) so it never hangs a headless caller.
    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()>;
    /// Abort an in-progress rebase (`rebase --abort`).
    async fn rebase_abort(&self, dir: &Path) -> Result<()>;
    /// Continue a rebase after resolving conflicts (`rebase --continue`); the
    /// editor is suppressed (`GIT_EDITOR=true`) so the message-confirm never hangs.
    async fn rebase_continue(&self, dir: &Path) -> Result<()>;
    /// Stash the working tree (`stash push`, `--include-untracked` when asked) —
    /// e.g. to save state before a copy-on-write restore.
    async fn stash_push(&self, dir: &Path, include_untracked: bool) -> Result<()>;
    /// Restore the most recent stash and drop it (`stash pop`).
    async fn stash_pop(&self, dir: &Path) -> Result<()>;

    // --- Worktrees -----------------------------------------------------------

    /// List worktrees (`worktree list --porcelain`).
    async fn worktree_list(&self, dir: &Path) -> Result<Vec<Worktree>>;
    /// Add a worktree (`worktree add [-b <branch>] <path> [<commitish>]`).
    async fn worktree_add(&self, dir: &Path, spec: WorktreeAdd) -> Result<()>;
    /// Remove a worktree (`worktree remove [--force] <path>`).
    async fn worktree_remove(&self, dir: &Path, path: &Path, force: bool) -> Result<()>;
    /// Move a worktree (`worktree move <from> <to>`).
    async fn worktree_move(&self, dir: &Path, from: &Path, to: &Path) -> Result<()>;
    /// Prune stale worktree admin entries (`worktree prune`).
    async fn worktree_prune(&self, dir: &Path) -> Result<()>;

    // --- Clone / tags / inspection --------------------------------------------

    /// Clone `url` into `dest` (`git clone <url> <dest>` + [`CloneSpec`] flags).
    /// Runs without a working directory — pass an **absolute** `dest`.
    async fn clone_repo(&self, url: &str, dest: &Path, spec: CloneSpec) -> Result<()>;
    /// Create a lightweight tag at `rev` (`tag <name> [<rev>]`; `None` = HEAD).
    async fn tag_create(&self, dir: &Path, name: &str, rev: Option<String>) -> Result<()>;
    /// Create an annotated tag (`tag -a <name> -m <message> [<rev>]`); see
    /// [`AnnotatedTag`].
    async fn tag_create_annotated(&self, dir: &Path, spec: AnnotatedTag) -> Result<()>;
    /// Tag names, sorted by git's default ordering (`tag --list`).
    async fn tag_list(&self, dir: &Path) -> Result<Vec<String>>;
    /// Delete a tag (`tag -d <name>`).
    async fn tag_delete(&self, dir: &Path, name: &str) -> Result<()>;
    /// A file's content at a revision (`git show <rev>:<path>`). `path` is
    /// repo-relative; backslashes are normalised to `/` (git requires it).
    /// Content is decoded **lossily** — binary files come back mangled rather
    /// than erroring.
    async fn show_file(&self, dir: &Path, rev: &str, path: &str) -> Result<String>;
    /// The value of a config key, or `None` when unset (`config --get <key>`,
    /// whose exit 1 covers both "unset" and "no such section" — git doesn't
    /// distinguish). A multi-valued key errors; read those via `run`.
    async fn config_get(&self, dir: &Path, key: &str) -> Result<Option<String>>;
    /// Set a config key in the repository's local config (`config <key> <value>`).
    async fn config_set(&self, dir: &Path, key: &str, value: &str) -> Result<()>;
    /// Add a remote (`remote add <name> <url>`).
    async fn remote_add(&self, dir: &Path, name: &str, url: &str) -> Result<()>;
    /// Change a remote's URL (`remote set-url <name> <url>`).
    async fn remote_set_url(&self, dir: &Path, name: &str, url: &str) -> Result<()>;
    /// Per-line authorship of `path` (`blame --line-porcelain [<rev>] -- <path>`;
    /// `None` = the working tree's HEAD).
    async fn blame(&self, dir: &Path, path: &str, rev: Option<String>) -> Result<Vec<BlameLine>>;

    // --- Sequencer -------------------------------------------------------------

    /// Apply a commit onto the current branch (`cherry-pick <rev>`). A conflict
    /// surfaces as an error classified by [`is_merge_conflict`].
    async fn cherry_pick(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Revert a commit with the default message (`revert --no-edit <rev>`).
    async fn revert(&self, dir: &Path, rev: &str) -> Result<()>;
    /// Skip the current patch of a paused rebase (`rebase --skip`). Mainly for
    /// the `apply` backend's "nothing to commit" stop — the default `merge`
    /// backend auto-drops emptied patches on `--continue`.
    async fn rebase_skip(&self, dir: &Path) -> Result<()>;
}

processkit::cli_client!(
    /// The real Git client. Generic over the [`ProcessRunner`] so tests can inject
    /// a fake process executor; `Git::new()` uses the real job-backed runner.
    pub struct Git => BINARY
);

#[async_trait::async_trait]
impl<R: ProcessRunner> GitApi for Git<R> {
    async fn run(&self, args: &[String]) -> Result<String> {
        self.core.run(self.core.command(args)).await
    }

    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>> {
        self.core.output(self.core.command(args)).await
    }

    async fn version(&self) -> Result<String> {
        self.core.run(self.core.command(["--version"])).await
    }

    async fn capabilities(&self) -> Result<GitCapabilities> {
        let raw = self.version().await?;
        let version = parse::parse_git_version(&raw).ok_or_else(|| Error::Parse {
            program: BINARY.to_string(),
            message: format!("unrecognisable `git --version` output: {raw:?}"),
        })?;
        Ok(GitCapabilities { version })
    }

    async fn status(&self, dir: &Path) -> Result<Vec<StatusEntry>> {
        self.core
            .parse(
                self.core
                    .command_in(dir, ["status", "--porcelain=v1", "-z"]),
                parse::parse_porcelain,
            )
            .await
    }

    async fn status_text(&self, dir: &Path) -> Result<String> {
        self.core
            .run(self.core.command_in(dir, ["status", "--porcelain=v1"]))
            .await
    }

    async fn branch_status(&self, dir: &Path) -> Result<BranchStatus> {
        // `GIT_OPTIONAL_LOCKS=0`: skip the opportunistic index refresh-write a
        // `status` may otherwise persist. This is the snapshot/poll primitive —
        // a filesystem watcher re-querying through it must not have the query
        // itself dirty `.git/index` and re-trigger the watch (verified: with
        // optional locks off, a re-query writes nothing).
        self.core
            .parse(
                self.core
                    .command_in(dir, ["status", "--porcelain=v2", "--branch", "-z"])
                    .env("GIT_OPTIONAL_LOCKS", "0"),
                parse::parse_porcelain_v2,
            )
            .await
    }

    async fn status_tracked(&self, dir: &Path) -> Result<Vec<StatusEntry>> {
        self.core
            .parse(
                self.core.command_in(
                    dir,
                    ["status", "--porcelain=v1", "-z", "--untracked-files=no"],
                ),
                parse::parse_porcelain,
            )
            .await
    }

    async fn conflicted_files(&self, dir: &Path) -> Result<Vec<String>> {
        // `-z` keeps special-character paths literal (no C-style quoting).
        self.core
            .parse(
                self.core
                    .command_in(dir, ["diff", "--name-only", "--diff-filter=U", "-z"]),
                parse::parse_nul_paths,
            )
            .await
    }

    async fn current_branch(&self, dir: &Path) -> Result<String> {
        self.core
            .run(
                self.core
                    .command_in(dir, ["rev-parse", "--abbrev-ref", "HEAD"]),
            )
            .await
    }

    async fn branches(&self, dir: &Path) -> Result<Vec<Branch>> {
        // `--no-column`: a user's `column.ui = always` would columnate several
        // names onto one line even when piped, corrupting the line parser.
        self.core
            .parse(
                self.core.command_in(dir, ["branch", "--no-column"]),
                parse::parse_branches,
            )
            .await
    }

    async fn log(&self, dir: &Path, max: usize) -> Result<Vec<Commit>> {
        let n = format!("-n{max}");
        self.core
            .parse(
                self.core.command_in(
                    dir,
                    [
                        "log",
                        n.as_str(),
                        "-z",
                        "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s",
                    ],
                ),
                parse::parse_log,
            )
            .await
    }

    async fn log_range(&self, dir: &Path, range: &str, max: usize) -> Result<Vec<Commit>> {
        reject_flag_like("range", range)?;
        let n = format!("-n{max}");
        self.core
            .parse(
                self.core.command_in(
                    dir,
                    [
                        "log",
                        range,
                        n.as_str(),
                        "-z",
                        "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s",
                    ],
                ),
                parse::parse_log,
            )
            .await
    }

    async fn rev_parse(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        self.core
            .run(self.core.command_in(dir, ["rev-parse", rev]))
            .await
    }

    async fn rev_parse_short(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        self.core
            .run(self.core.command_in(dir, ["rev-parse", "--short", rev]))
            .await
    }

    async fn init(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["init"]))
            .await
    }

    async fn add(&self, dir: &Path, paths: &[PathBuf]) -> Result<()> {
        // `--` separates the pathspecs so a path can never be read as an option.
        let mut command = self.core.command_in(dir, ["add", "--"]);
        for path in paths {
            command = command.arg(path);
        }
        self.core.run_unit(command).await
    }

    async fn commit(&self, dir: &Path, message: &str) -> Result<()> {
        // C locale: a failure's output feeds `is_nothing_to_commit`.
        self.core
            .run_unit(c_locale(
                self.core.command_in(dir, ["commit", "-m", message]),
            ))
            .await
    }

    async fn create_branch(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("branch name", name)?;
        self.core
            .run_unit(self.core.command_in(dir, ["branch", name]))
            .await
    }

    async fn checkout(&self, dir: &Path, reference: &str) -> Result<()> {
        reject_flag_like("reference", reference)?;
        self.core
            .run_unit(self.core.command_in(dir, ["checkout", reference]))
            .await
    }

    async fn checkout_detach(&self, dir: &Path, commit: &str) -> Result<()> {
        reject_flag_like("commit", commit)?;
        self.core
            .run_unit(self.core.command_in(dir, ["checkout", "--detach", commit]))
            .await
    }

    async fn commit_paths(&self, dir: &Path, spec: CommitPaths) -> Result<()> {
        // `--only -- <paths>` commits exactly these paths' working-tree content
        // regardless of the index; `--` keeps a path from being read as an option.
        // C locale: a failure's output feeds `is_nothing_to_commit`.
        let mut command = c_locale(self.core.command_in(dir, ["commit"]));
        if spec.amend {
            command = command.arg("--amend");
        }
        command = command.arg("-m").arg(spec.message).arg("--only").arg("--");
        for path in &spec.paths {
            command = command.arg(path);
        }
        self.core.run_unit(command).await
    }

    async fn last_commit_message(&self, dir: &Path) -> Result<String> {
        self.core
            .run(self.core.command_in(dir, ["log", "-1", "--format=%B"]))
            .await
    }

    async fn is_unborn(&self, dir: &Path) -> Result<bool> {
        // `rev-parse --verify -q HEAD` resolves HEAD quietly: 0 = a commit exists
        // (not unborn), 1 = no commit yet (unborn). `probe` maps those to a bool
        // and surfaces anything else (e.g. 128, not a repo) as `Error::Exit`.
        Ok(!self
            .core
            .probe(
                self.core
                    .command_in(dir, ["rev-parse", "--verify", "-q", "HEAD"]),
            )
            .await?)
    }

    async fn diff_is_empty(&self, dir: &Path) -> Result<bool> {
        // `git diff --quiet` is an exit-code answer: 0 = clean (empty), 1 = dirty;
        // `probe` errors on any other code / timeout / signal.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--quiet"]))
            .await
    }

    async fn common_dir(&self, dir: &Path) -> Result<PathBuf> {
        Ok(PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-common-dir"]))
                .await?,
        ))
    }

    async fn git_dir(&self, dir: &Path) -> Result<PathBuf> {
        Ok(PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-dir"]))
                .await?,
        ))
    }

    async fn resolve_commit(&self, dir: &Path, rev: &str) -> Result<String> {
        reject_flag_like("revision", rev)?;
        // `^{commit}` peels an annotated tag down to the commit it points at.
        let spec = format!("{rev}^{{commit}}");
        self.core
            .run(
                self.core
                    .command_in(dir, ["rev-parse", "--verify", spec.as_str()]),
            )
            .await
    }

    async fn remote_head_branch(&self, dir: &Path) -> Result<Option<String>> {
        // `--quiet` makes an unset origin/HEAD a silent non-zero exit (no `fatal:`
        // on stderr); that's "no default branch", not an error — so inspect the
        // code rather than `?`.
        let res = self
            .core
            .output(
                self.core
                    .command_in(dir, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]),
            )
            .await?;
        if res.code() == Some(0) {
            // "refs/remotes/origin/main" → "main"; strip the whole ref prefix so a
            // slashed default branch (e.g. "release/v2") survives intact.
            let out = res.stdout().trim();
            Ok(Some(
                out.strip_prefix("refs/remotes/origin/")
                    .unwrap_or(out)
                    .to_string(),
            ))
        } else {
            Ok(None)
        }
    }

    async fn branch_exists(&self, dir: &Path, name: &str) -> Result<bool> {
        let refname = format!("refs/heads/{name}");
        // `show-ref --verify --quiet` is an exit-code answer: 0 = exists, 1 = not.
        self.core
            .probe(
                self.core
                    .command_in(dir, ["show-ref", "--verify", "--quiet", refname.as_str()]),
            )
            .await
    }

    async fn remote_branch_exists(&self, dir: &Path, name: &str) -> Result<bool> {
        // No credential prompt, bounded wait: a missing helper or a flaky network
        // must not hang the call. `output` reports a timeout as a flagged result
        // (non-zero exit) rather than erroring, so an unreachable remote reads as
        // "absent" (`false`) — the best-effort answer a probe wants. A genuine
        // spawn failure (no `git`) still surfaces as an error.
        //
        // Query the *fully-qualified* ref: `ls-remote origin <name>` tail-matches
        // path components, so a bare `foo` would also match `refs/heads/bar/foo`.
        // `refs/heads/<name>` matches only the exact branch.
        let refname = format!("refs/heads/{name}");
        let cmd = self
            .core
            .command_in(dir, ["ls-remote", "origin", refname.as_str()])
            .env("GIT_TERMINAL_PROMPT", "0")
            .timeout(Duration::from_secs(10));
        let res = self.core.output(cmd).await?;
        Ok(res.code() == Some(0) && !res.stdout().trim().is_empty())
    }

    async fn remote_url(&self, dir: &Path, remote: &str) -> Result<String> {
        reject_flag_like("remote name", remote)?;
        self.core
            .run(self.core.command_in(dir, ["remote", "get-url", remote]))
            .await
    }

    async fn upstream(&self, dir: &Path) -> Result<Option<String>> {
        // `@{u}` resolves the configured upstream; with no upstream the command
        // exits non-zero — surface that as `None` rather than an error.
        match self
            .core
            .output(self.core.command_in(
                dir,
                ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
            ))
            .await?
        {
            res if res.code() == Some(0) => {
                let name = res.stdout().trim();
                Ok((!name.is_empty()).then(|| name.to_string()))
            }
            _ => Ok(None),
        }
    }

    async fn remote_branches(&self, dir: &Path, remote: &str) -> Result<Vec<String>> {
        reject_flag_like("remote name", remote)?;
        // `GIT_TERMINAL_PROMPT=0`: a remote needing credentials must fail fast,
        // never block on an interactive auth prompt.
        let cmd = self
            .core
            .command_in(dir, ["ls-remote", "--heads", remote])
            .env("GIT_TERMINAL_PROMPT", "0");
        self.core.parse(cmd, parse::parse_ls_remote_heads).await
    }

    async fn is_merged(&self, dir: &Path, branch: &str, target: &str) -> Result<bool> {
        reject_flag_like("branch", branch)?;
        reject_flag_like("target", target)?;
        // `--no-column`: under `column.ui = always` git would pack several names
        // per line even when piped, and the marker-stripping compare below would
        // never match (a false "not merged").
        let out = self
            .core
            .run(
                self.core
                    .command_in(dir, ["branch", "--merged", target, "--no-column"]),
            )
            .await?;
        // Each line is a fixed 2-column marker (`  `/`* `/`+ `) then the name;
        // drop exactly those two columns rather than trimming a char class (which
        // would over-strip a name that legitimately began with the marker char).
        Ok(out
            .lines()
            .filter_map(|line| line.get(2..))
            .any(|b| b == branch))
    }

    async fn set_upstream(&self, dir: &Path, branch: &str, upstream: &str) -> Result<()> {
        reject_flag_like("branch name", branch)?;
        let flag = format!("--set-upstream-to={upstream}");
        self.core
            .run_unit(self.core.command_in(dir, ["branch", flag.as_str(), branch]))
            .await
    }

    async fn delete_branch(&self, dir: &Path, name: &str, force: bool) -> Result<()> {
        reject_flag_like("branch name", name)?;
        let flag = if force { "-D" } else { "-d" };
        self.core
            .run_unit(self.core.command_in(dir, ["branch", flag, name]))
            .await
    }

    async fn rename_branch(&self, dir: &Path, old: &str, new: &str) -> Result<()> {
        reject_flag_like("branch name", old)?;
        reject_flag_like("branch name", new)?;
        self.core
            .run_unit(self.core.command_in(dir, ["branch", "-m", old, new]))
            .await
    }

    async fn rev_list_count(&self, dir: &Path, range: &str) -> Result<usize> {
        reject_flag_like("range", range)?;
        self.core
            .try_parse(
                self.core.command_in(dir, ["rev-list", "--count", range]),
                |s| {
                    s.trim().parse::<usize>().map_err(|e| Error::Parse {
                        program: BINARY.to_string(),
                        message: e.to_string(),
                    })
                },
            )
            .await
    }

    async fn diff_range_is_empty(&self, dir: &Path, range: &str) -> Result<bool> {
        reject_flag_like("range", range)?;
        // `diff --quiet <range>`: 0 = empty range, 1 = has changes.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--quiet", range]))
            .await
    }

    async fn diff_stat(&self, dir: &Path, range: &str) -> Result<DiffStat> {
        reject_flag_like("range", range)?;
        self.core
            .parse(
                self.core.command_in(dir, ["diff", "--shortstat", range]),
                parse::parse_shortstat,
            )
            .await
    }

    async fn diff_text(&self, dir: &Path, spec: DiffSpec) -> Result<String> {
        // The target is a single positional arg: `HEAD` for the working tree, or
        // the caller's revision/range. `-M` enables rename detection; `--no-color`
        // / `--no-ext-diff` keep the output stable and machine-parseable.
        let target = match spec {
            DiffSpec::WorkingTree => {
                // On an unborn repo `HEAD` doesn't resolve (`git diff HEAD` errors);
                // diff against the empty tree so a pre-first-commit working tree
                // still yields its additions instead of a hard failure.
                if self.is_unborn(dir).await? {
                    EMPTY_TREE.to_string()
                } else {
                    "HEAD".to_string()
                }
            }
            DiffSpec::Rev(rev) => {
                reject_flag_like("revision", &rev)?;
                rev
            }
        };
        // The explicit prefixes pin the `a/`…`b/` form the shared parser extracts
        // paths from — a user's `diff.noprefix` / `diff.mnemonicPrefix` config
        // would otherwise change the headers and make every file silently vanish
        // from the parse. (Command-line prefixes override both config options.)
        self.core
            .run(self.core.command_in(
                dir,
                [
                    "diff",
                    target.as_str(),
                    "--no-color",
                    "--no-ext-diff",
                    "-M",
                    "--src-prefix=a/",
                    "--dst-prefix=b/",
                ],
            ))
            .await
    }

    async fn diff(&self, dir: &Path, spec: DiffSpec) -> Result<Vec<FileDiff>> {
        let text = self.diff_text(dir, spec).await?;
        Ok(parse_diff(&text))
    }

    async fn staged_is_empty(&self, dir: &Path) -> Result<bool> {
        // `diff --cached --quiet`: 0 = nothing staged, 1 = staged changes.
        self.core
            .probe(self.core.command_in(dir, ["diff", "--cached", "--quiet"]))
            .await
    }

    async fn is_rebase_in_progress(&self, dir: &Path) -> Result<bool> {
        let git_dir = self.resolved_git_dir(dir).await?;
        Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())
    }

    async fn is_merge_in_progress(&self, dir: &Path) -> Result<bool> {
        Ok(self
            .resolved_git_dir(dir)
            .await?
            .join("MERGE_HEAD")
            .exists())
    }

    async fn fetch(&self, dir: &Path) -> Result<()> {
        // `GIT_TERMINAL_PROMPT=0` so a remote needing credentials fails fast
        // rather than blocking on an interactive prompt — matching the other
        // remote ops (`fetch_remote_branch`, `push`, `remote_branch_exists`).
        // Fetch is idempotent, so `retry` replays it on a transient failure
        // (DNS/timeout/dropped connection); a non-transient error fails at once.
        // C locale: the retry decision classifies the failure's message.
        let cmd = c_locale(self.core.command_in(dir, ["fetch", "--quiet"]))
            .env("GIT_TERMINAL_PROMPT", "0")
            .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error);
        self.core.run_unit(cmd).await
    }

    async fn fetch_from(&self, dir: &Path, remote: &str) -> Result<()> {
        // A leading-`-` remote is a bare positional here — and a flag like
        // `--upload-pack=<cmd>` would run an arbitrary local program for a
        // local/ext transport, so this guard is load-bearing for security.
        reject_flag_like("remote", remote)?;
        // Same containment as `fetch` (prompt off, C locale, transient retry),
        // with the remote named explicitly.
        let cmd = c_locale(self.core.command_in(dir, ["fetch", "--quiet", remote]))
            .env("GIT_TERMINAL_PROMPT", "0")
            .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error);
        self.core.run_unit(cmd).await
    }

    async fn fetch_remote_branch(&self, dir: &Path, branch: &str) -> Result<()> {
        let refspec = format!("refs/heads/{branch}:refs/remotes/origin/{branch}");
        let cmd = c_locale(
            self.core
                .command_in(dir, ["fetch", "--quiet", "origin", refspec.as_str()]),
        )
        .env("GIT_TERMINAL_PROMPT", "0")
        .retry(FETCH_ATTEMPTS, FETCH_BACKOFF, is_transient_fetch_error);
        self.core.run_unit(cmd).await
    }

    async fn push(&self, dir: &Path, spec: GitPush) -> Result<()> {
        reject_flag_like("remote", &spec.remote)?;
        reject_flag_like("refspec", &spec.refspec)?;
        let mut args: Vec<&str> = vec!["push"];
        if spec.set_upstream {
            args.push("-u");
        }
        args.push(spec.remote.as_str());
        args.push(spec.refspec.as_str());
        let cmd = self
            .core
            .command_in(dir, args)
            .env("GIT_TERMINAL_PROMPT", "0");
        self.core.run_unit(cmd).await
    }

    async fn merge_squash(&self, dir: &Path, branch: &str) -> Result<()> {
        reject_flag_like("branch", branch)?;
        self.core
            .run_unit(self.core.command_in(dir, ["merge", "--squash", branch]))
            .await
    }

    async fn merge_commit(&self, dir: &Path, spec: MergeCommit) -> Result<()> {
        reject_flag_like("branch", &spec.branch)?;
        let mut args: Vec<&str> = vec!["merge"];
        if spec.no_ff {
            args.push("--no-ff");
        }
        if let Some(msg) = spec.message.as_deref() {
            args.push("-m");
            args.push(msg);
        } else {
            // No message → take the default merge message non-interactively
            // instead of opening `$EDITOR` (which would hang a headless caller).
            args.push("--no-edit");
        }
        args.push(&spec.branch);
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(c_locale(self.core.command_in(dir, args)))
            .await
    }

    async fn merge_no_commit(&self, dir: &Path, spec: MergeNoCommit) -> Result<()> {
        reject_flag_like("branch", &spec.branch)?;
        let mut args: Vec<&str> = vec!["merge", "--no-commit"];
        // `--squash` and `--no-ff` are mutually exclusive (git rejects the pair);
        // a squash never fast-forwards anyway, so it takes precedence.
        if spec.squash {
            args.push("--squash");
        } else if spec.no_ff {
            args.push("--no-ff");
        }
        args.push(&spec.branch);
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(c_locale(self.core.command_in(dir, args)))
            .await
    }

    async fn merge_abort(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["merge", "--abort"])))
            .await
    }

    async fn merge_continue(&self, dir: &Path) -> Result<()> {
        // `--no-edit` already reuses the prepared MERGE_MSG; `no_editor` is a
        // headless backstop so a commit hook re-opening the editor can't hang.
        // C locale: the failure output feeds the classifiers (a still-conflicted
        // tree reports "nothing to commit"-adjacent / conflict messages).
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["commit", "--no-edit"]),
            )))
            .await
    }

    async fn reset_merge(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["reset", "--merge"]))
            .await
    }

    async fn reset_hard(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        self.core
            .run_unit(self.core.command_in(dir, ["reset", "--hard", rev]))
            .await
    }

    async fn rebase(&self, dir: &Path, onto: &str) -> Result<()> {
        reject_flag_like("rebase target", onto)?;
        // Force a no-op editor so a rebase that would open `$EDITOR` (reword, or
        // the message-confirm on `--continue`) never hangs a headless caller.
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", onto]),
            )))
            .await
    }

    async fn rebase_abort(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(c_locale(self.core.command_in(dir, ["rebase", "--abort"])))
            .await
    }

    async fn rebase_continue(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", "--continue"]),
            )))
            .await
    }

    async fn stash_push(&self, dir: &Path, include_untracked: bool) -> Result<()> {
        let mut command = self.core.command_in(dir, ["stash", "push"]);
        if include_untracked {
            command = command.arg("--include-untracked");
        }
        self.core.run_unit(command).await
    }

    async fn stash_pop(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["stash", "pop"]))
            .await
    }

    async fn worktree_list(&self, dir: &Path) -> Result<Vec<Worktree>> {
        self.core
            .parse(
                self.core
                    .command_in(dir, ["worktree", "list", "--porcelain"]),
                parse::parse_worktree_porcelain,
            )
            .await
    }

    async fn worktree_add(&self, dir: &Path, spec: WorktreeAdd) -> Result<()> {
        if let Some(name) = spec.new_branch.as_deref() {
            reject_flag_like("branch name", name)?;
        }
        if let Some(commitish) = spec.commitish.as_deref() {
            reject_flag_like("commit-ish", commitish)?;
        }
        let mut command = self.core.command_in(dir, ["worktree", "add"]);
        if let Some(name) = spec.new_branch.as_deref() {
            command = command.arg("-b").arg(name);
        }
        if spec.no_checkout {
            command = command.arg("--no-checkout");
        }
        command = command.arg(&spec.path);
        if let Some(commitish) = spec.commitish.as_deref() {
            command = command.arg(commitish);
        }
        self.core.run_unit(command).await
    }

    async fn worktree_remove(&self, dir: &Path, path: &Path, force: bool) -> Result<()> {
        let mut command = self.core.command_in(dir, ["worktree", "remove"]);
        if force {
            command = command.arg("--force");
        }
        command = command.arg(path);
        self.core.run_unit(command).await
    }

    async fn worktree_move(&self, dir: &Path, from: &Path, to: &Path) -> Result<()> {
        let command = self
            .core
            .command_in(dir, ["worktree", "move"])
            .arg(from)
            .arg(to);
        self.core.run_unit(command).await
    }

    async fn worktree_prune(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(self.core.command_in(dir, ["worktree", "prune"]))
            .await
    }

    async fn clone_repo(&self, url: &str, dest: &Path, spec: CloneSpec) -> Result<()> {
        // A leading-`-` url is a bare positional — `git clone --upload-pack=<cmd>`
        // would run an arbitrary local program. A real URL never leads with `-`,
        // so this guard has no false positives.
        reject_flag_like("url", url)?;
        // No working directory: clone creates `dest` itself, so `dest` should
        // be absolute (a relative path would resolve against this process' cwd).
        let mut command = self.core.command(["clone"]);
        if let Some(branch) = spec.branch.as_deref() {
            command = command.arg("--branch").arg(branch);
        }
        if let Some(depth) = spec.depth {
            command = command.arg("--depth").arg(depth.to_string());
        }
        if spec.bare {
            command = command.arg("--bare");
        }
        let command = command.arg(url).arg(dest).env("GIT_TERMINAL_PROMPT", "0");
        self.core.run_unit(command).await
    }

    async fn tag_create(&self, dir: &Path, name: &str, rev: Option<String>) -> Result<()> {
        reject_flag_like("tag name", name)?;
        if let Some(rev) = rev.as_deref() {
            reject_flag_like("revision", rev)?;
        }
        let mut args = vec!["tag", name];
        if let Some(rev) = rev.as_deref() {
            args.push(rev);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn tag_create_annotated(&self, dir: &Path, spec: AnnotatedTag) -> Result<()> {
        reject_flag_like("tag name", &spec.name)?;
        if let Some(rev) = spec.rev.as_deref() {
            reject_flag_like("revision", rev)?;
        }
        let mut args = vec!["tag", "-a", &spec.name, "-m", &spec.message];
        if let Some(rev) = spec.rev.as_deref() {
            args.push(rev);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn tag_list(&self, dir: &Path) -> Result<Vec<String>> {
        // `--no-column`: a user's `column.ui = always` would pack several tags
        // onto one line even when piped, corrupting the one-per-line split.
        let out = self
            .core
            .run(self.core.command_in(dir, ["tag", "--list", "--no-column"]))
            .await?;
        Ok(out.lines().map(str::to_string).collect())
    }

    async fn tag_delete(&self, dir: &Path, name: &str) -> Result<()> {
        reject_flag_like("tag name", name)?;
        self.core
            .run_unit(self.core.command_in(dir, ["tag", "-d", name]))
            .await
    }

    async fn show_file(&self, dir: &Path, rev: &str, path: &str) -> Result<String> {
        // A leading-`-` rev makes the whole `<rev>:<path>` token start with `-`,
        // so git would parse it as a flag — guard it before building the spec.
        reject_flag_like("revision", rev)?;
        // git rejects backslash separators in the `<rev>:<path>` spec ("exists
        // on disk, but not in <rev>") — normalise for Windows callers. Only on
        // Windows: on Unix a backslash is a legal filename byte, and rewriting
        // it would make a literal `a\b.txt` unresolvable.
        #[cfg(windows)]
        let path = path.replace('\\', "/");
        let spec = format!("{rev}:{path}");
        self.core
            .run(self.core.command_in(dir, ["show", spec.as_str()]))
            .await
    }

    async fn config_get(&self, dir: &Path, key: &str) -> Result<Option<String>> {
        reject_flag_like("config key", key)?;
        let res = self
            .core
            .output(self.core.command_in(dir, ["config", "--get", key]))
            .await?;
        match res.code() {
            // Exit 1 = unset (git lumps "no such key/section" in here too).
            Some(1) => Ok(None),
            Some(0) => Ok(Some(res.stdout().trim_end().to_string())),
            _ => {
                res.ensure_success()?;
                Ok(None) // unreachable: a non-zero exit always errors above.
            }
        }
    }

    async fn config_set(&self, dir: &Path, key: &str, value: &str) -> Result<()> {
        reject_flag_like("config key", key)?;
        self.core
            .run_unit(self.core.command_in(dir, ["config", key, value]))
            .await
    }

    async fn remote_add(&self, dir: &Path, name: &str, url: &str) -> Result<()> {
        reject_flag_like("remote name", name)?;
        reject_flag_like("url", url)?;
        self.core
            .run_unit(self.core.command_in(dir, ["remote", "add", name, url]))
            .await
    }

    async fn remote_set_url(&self, dir: &Path, name: &str, url: &str) -> Result<()> {
        reject_flag_like("remote name", name)?;
        reject_flag_like("url", url)?;
        self.core
            .run_unit(self.core.command_in(dir, ["remote", "set-url", name, url]))
            .await
    }

    async fn blame(&self, dir: &Path, path: &str, rev: Option<String>) -> Result<Vec<BlameLine>> {
        let mut args = vec!["blame", "--line-porcelain"];
        if let Some(rev) = rev.as_deref() {
            // A standalone positional rev with a leading `-` would be any blame
            // flag (`-s`, `--reverse`, `-L…`) — guard before the `--`.
            reject_flag_like("revision", rev)?;
            args.push(rev);
        }
        args.push("--");
        args.push(path);
        self.core
            .parse(
                self.core.command_in(dir, args),
                parse::parse_blame_porcelain,
            )
            .await
    }

    async fn cherry_pick(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        // No editor opens non-interactively, but keep the headless backstop.
        // C locale: a conflict's output feeds `is_merge_conflict`.
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["cherry-pick", rev]),
            )))
            .await
    }

    async fn revert(&self, dir: &Path, rev: &str) -> Result<()> {
        reject_flag_like("revision", rev)?;
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["revert", "--no-edit", rev]),
            )))
            .await
    }

    async fn rebase_skip(&self, dir: &Path) -> Result<()> {
        self.core
            .run_unit(no_editor(c_locale(
                self.core.command_in(dir, ["rebase", "--skip"]),
            )))
            .await
    }
}

// --- Internal helpers --------------------------------------------------------
//
// The error classifiers (`is_merge_conflict`/`is_nothing_to_commit`/
// `is_transient_fetch_error`), the fetch-retry policy, and the argv injection
// guard now live in the shared `vcs-cli-support` crate (re-exported at the top of
// this module); what remains here is git-specific.

/// Git's well-known empty-tree object id — a stable stand-in for `HEAD` when
/// diffing the working tree of an unborn (no-commits-yet) repository. Public so a
/// caller can diff/stat a pre-first-commit working tree against it directly.
pub const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// Total attempts / fixed backoff for a transient-retried `fetch` — the shared
/// policy from `vcs-cli-support`, aliased so the retry call sites read locally.
const FETCH_ATTEMPTS: u32 = vcs_cli_support::FETCH_ATTEMPTS;
const FETCH_BACKOFF: Duration = vcs_cli_support::FETCH_BACKOFF;

/// Point git's editor at a no-op so any command that would open `$EDITOR`
/// (a rebase reword, the message-confirm on `rebase --continue`) succeeds
/// non-interactively instead of hanging a headless caller.
fn no_editor(cmd: processkit::Command) -> processkit::Command {
    cmd.env("GIT_EDITOR", "true")
        .env("GIT_SEQUENCE_EDITOR", "true")
}

/// Force the C locale on a command whose output feeds the error classifiers
/// (`is_merge_conflict`, `is_nothing_to_commit`, `is_transient_fetch_error`):
/// they match untranslated English substrings, and a localized git would emit
/// translated messages, silently turning a classified failure (conflict /
/// clean-tree / transient) into an unclassified one.
fn c_locale(cmd: processkit::Command) -> processkit::Command {
    cmd.env("LC_ALL", "C")
}

/// Injection guard for bare positional argv slots — delegates to the shared
/// [`vcs_cli_support::reject_flag_like`], naming this crate's binary so the
/// ~45 call sites stay `reject_flag_like(what, value)`.
fn reject_flag_like(what: &str, value: &str) -> Result<()> {
    vcs_cli_support::reject_flag_like(BINARY, what, value)
}

impl<R: ProcessRunner> Git<R> {
    /// Run `git <args>` over string slices — `git.run_args(&["status", "-s"])`
    /// without allocating a `Vec<String>`. Inherent (not on the object-safe
    /// trait), so it can take `&[&str]`; forwards to the same path as
    /// [`GitApi::run`].
    pub async fn run_args(&self, args: &[&str]) -> Result<String> {
        self.core.run(self.core.command(args)).await
    }

    /// Like [`run_args`](Git::run_args) but never errors on a non-zero exit
    /// (mirrors [`GitApi::run_raw`]).
    pub async fn run_raw_args(&self, args: &[&str]) -> Result<ProcessResult<String>> {
        self.core.output(self.core.command(args)).await
    }

    /// Bind this client to `dir`, returning a [`GitAt`] handle whose methods omit
    /// the `dir` argument: `git.at(dir).status()` runs [`status`](GitApi::status)
    /// against `dir`. The dir-taking [`GitApi`] methods stay on [`Git`] for
    /// driving many directories (e.g. linked worktrees) from one client.
    pub fn at<'a>(&'a self, dir: &'a Path) -> GitAt<'a, R> {
        GitAt { git: self, dir }
    }

    /// Harden this client for driving repositories it didn't create: running
    /// `git` inside an untrusted checkout executes that repository's hooks and
    /// honours its config — arbitrary code execution by default. The profile
    /// (applied to **every** command this client runs):
    ///
    /// - **Disables hooks** — `core.hooksPath=/dev/null` pinned via git's
    ///   env-based config (`GIT_CONFIG_COUNT`/`KEY_n`/`VALUE_n`, git ≥ 2.31;
    ///   verified to suppress hooks on Windows too) — and `core.fsmonitor`
    ///   (a config-driven daemon launch).
    /// - **Removes inherited repo redirectors** so a poisoned parent
    ///   environment can't point commands at another repository: `GIT_DIR`,
    ///   `GIT_WORK_TREE`, `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`,
    ///   `GIT_ALTERNATE_OBJECT_DIRECTORIES`, `GIT_NAMESPACE`,
    ///   `GIT_CEILING_DIRECTORIES`, `GIT_CONFIG_PARAMETERS`,
    ///   `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`.
    /// - **Skips system config** (`GIT_CONFIG_NOSYSTEM=1`) and keeps terminal
    ///   prompts off everywhere (`GIT_TERMINAL_PROMPT=0`).
    ///
    /// What it does NOT do: sandbox the git binary itself, or stop the repo's
    /// *content* from being malicious. In a **colocated jj repo**, git hooks
    /// only run when *git* commands run — harden the `Git` client; `Jj` needs
    /// no equivalent (jj has no repo-local hooks; see the vcs-jj docs).
    ///
    /// Chainable — `Git::with_runner(rec).harden()` works in tests; use
    /// [`Git::hardened()`](Git::hardened) for the common case.
    pub fn harden(self) -> Self {
        let removed = [
            "GIT_DIR",
            "GIT_WORK_TREE",
            "GIT_INDEX_FILE",
            "GIT_OBJECT_DIRECTORY",
            "GIT_ALTERNATE_OBJECT_DIRECTORIES",
            "GIT_NAMESPACE",
            "GIT_CEILING_DIRECTORIES",
            "GIT_CONFIG_PARAMETERS",
            "GIT_CONFIG_GLOBAL",
            "GIT_CONFIG_SYSTEM",
        ];
        let mut hardened = self;
        for key in removed {
            hardened = hardened.default_env_remove(key);
        }
        hardened
            .default_env("GIT_CONFIG_NOSYSTEM", "1")
            .default_env("GIT_TERMINAL_PROMPT", "0")
            .default_env("GIT_CONFIG_COUNT", "2")
            .default_env("GIT_CONFIG_KEY_0", "core.hooksPath")
            .default_env("GIT_CONFIG_VALUE_0", "/dev/null")
            .default_env("GIT_CONFIG_KEY_1", "core.fsmonitor")
            .default_env("GIT_CONFIG_VALUE_1", "false")
    }

    /// Switch to `branch`, carrying uncommitted changes (tracked *and*
    /// untracked) across via the stash: `stash push -u` → `checkout` →
    /// `stash pop`. A clean tree skips the stash round-trip entirely — a
    /// `stash push` there would save nothing and the later pop would pop an
    /// older, unrelated stash.
    ///
    /// Failure behaviour:
    /// - `checkout` fails (atomic — the working copy stays on the original
    ///   branch): the stash is popped back to restore the original state, and
    ///   the checkout error is returned. If that restoring pop *also* fails,
    ///   the changes stay safe in the stash (`git stash list`).
    /// - `stash pop` on the target branch conflicts: the error is returned with
    ///   the target branch checked out; git keeps the stash entry, so the
    ///   changes can be resolved or re-applied manually.
    ///
    /// Inherent (not on the object-safe trait): a composed operation, not a 1:1
    /// CLI verb — mock the underlying `status`/`stash_*`/`checkout` instead.
    pub async fn switch_with_stash(&self, dir: &Path, branch: &str) -> Result<()> {
        // Untracked-inclusive guard to match `stash push -u`: "dirty" must mean
        // the same thing to the guard and to the stash.
        if self.status(dir).await?.is_empty() {
            return self.checkout(dir, branch).await;
        }
        self.stash_push(dir, true).await?;
        match self.checkout(dir, branch).await {
            Ok(()) => self.stash_pop(dir).await,
            Err(err) => {
                // A failed checkout is atomic — we are still on the original
                // branch, so popping restores the exact pre-call state. If the
                // pop fails too, the stash entry is preserved for the caller.
                let _ = self.stash_pop(dir).await;
                Err(err)
            }
        }
    }

    /// `git_dir` resolved to an absolute path — `rev-parse --git-dir` may report
    /// it relative to `dir` (e.g. `.git`), which the filesystem probes need joined.
    async fn resolved_git_dir(&self, dir: &Path) -> Result<PathBuf> {
        let git_dir = PathBuf::from(
            self.core
                .run(self.core.command_in(dir, ["rev-parse", "--git-dir"]))
                .await?,
        );
        Ok(if git_dir.is_absolute() {
            git_dir
        } else {
            dir.join(git_dir)
        })
    }
}

impl Git {
    /// A hardened real (job-backed) client — `Git::new().harden()`; see
    /// [`harden`](Git::harden) for what the profile does.
    pub fn hardened() -> Self {
        Self::new().harden()
    }
}

/// A [`Git`] client with a working directory bound, so calls drop the leading
/// `dir` argument — `git.at(dir).status()` is `git.status(dir)`. Construct one
/// with [`Git::at`] (or, through the facade, `vcs_core::Repo::git_at`). Cheap to
/// copy: it only borrows the client and the path.
pub struct GitAt<'a, R: ProcessRunner = processkit::JobRunner> {
    git: &'a Git<R>,
    dir: &'a Path,
}

// Hand-written rather than derived: the view only holds two references, so it is
// `Copy` for *every* runner. `#[derive(Copy)]` would add a spurious `R: Copy`
// bound that the real default `JobRunner` doesn't satisfy, silently dropping
// `Copy` on the production `Repo::git_at()` handle.
impl<R: ProcessRunner> Clone for GitAt<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<R: ProcessRunner> Copy for GitAt<'_, R> {}

/// Generate [`GitAt`] forwarders from a method list: `bare` methods forward
/// verbatim, `dir` methods inject `self.dir` as the first argument.
macro_rules! git_at_forwarders {
    (
        bare { $( fn $bn:ident( $($ba:ident: $bt:ty),* $(,)? ) -> $br:ty; )* }
        dir  { $( fn $dn:ident( $($da:ident: $dt:ty),* $(,)? ) -> $dr:ty; )* }
    ) => {
        impl<'a, R: ProcessRunner> GitAt<'a, R> {
            $(
                #[doc = concat!("Bound form of [`Git`]'s `", stringify!($bn), "`.")]
                pub async fn $bn(&self, $($ba: $bt),*) -> $br {
                    self.git.$bn($($ba),*).await
                }
            )*
            $(
                #[doc = concat!("Bound form of [`Git`]'s `", stringify!($dn), "` (with `dir` pre-bound).")]
                pub async fn $dn(&self, $($da: $dt),*) -> $dr {
                    self.git.$dn(self.dir, $($da),*).await
                }
            )*
        }
    };
}

git_at_forwarders! {
    bare {
        fn run(args: &[String]) -> Result<String>;
        fn run_raw(args: &[String]) -> Result<ProcessResult<String>>;
        fn run_args(args: &[&str]) -> Result<String>;
        fn run_raw_args(args: &[&str]) -> Result<ProcessResult<String>>;
        fn version() -> Result<String>;
        fn capabilities() -> Result<GitCapabilities>;
        fn clone_repo(url: &str, dest: &Path, spec: CloneSpec) -> Result<()>;
    }
    dir {
        fn status() -> Result<Vec<StatusEntry>>;
        fn status_text() -> Result<String>;
        fn status_tracked() -> Result<Vec<StatusEntry>>;
        fn branch_status() -> Result<BranchStatus>;
        fn conflicted_files() -> Result<Vec<String>>;
        fn current_branch() -> Result<String>;
        fn branches() -> Result<Vec<Branch>>;
        fn log(max: usize) -> Result<Vec<Commit>>;
        fn log_range(range: &str, max: usize) -> Result<Vec<Commit>>;
        fn rev_parse(rev: &str) -> Result<String>;
        fn rev_parse_short(rev: &str) -> Result<String>;
        fn init() -> Result<()>;
        fn add(paths: &[PathBuf]) -> Result<()>;
        fn commit(message: &str) -> Result<()>;
        fn create_branch(name: &str) -> Result<()>;
        fn checkout(reference: &str) -> Result<()>;
        fn checkout_detach(commit: &str) -> Result<()>;
        fn commit_paths(spec: CommitPaths) -> Result<()>;
        fn last_commit_message() -> Result<String>;
        fn is_unborn() -> Result<bool>;
        fn diff_is_empty() -> Result<bool>;
        fn common_dir() -> Result<PathBuf>;
        fn git_dir() -> Result<PathBuf>;
        fn resolve_commit(rev: &str) -> Result<String>;
        fn remote_head_branch() -> Result<Option<String>>;
        fn branch_exists(name: &str) -> Result<bool>;
        fn remote_branch_exists(name: &str) -> Result<bool>;
        fn remote_url(remote: &str) -> Result<String>;
        fn upstream() -> Result<Option<String>>;
        fn remote_branches(remote: &str) -> Result<Vec<String>>;
        fn is_merged(branch: &str, target: &str) -> Result<bool>;
        fn set_upstream(branch: &str, upstream: &str) -> Result<()>;
        fn delete_branch(name: &str, force: bool) -> Result<()>;
        fn rename_branch(old: &str, new: &str) -> Result<()>;
        fn rev_list_count(range: &str) -> Result<usize>;
        fn diff_range_is_empty(range: &str) -> Result<bool>;
        fn diff_stat(range: &str) -> Result<DiffStat>;
        fn diff_text(spec: DiffSpec) -> Result<String>;
        fn diff(spec: DiffSpec) -> Result<Vec<FileDiff>>;
        fn staged_is_empty() -> Result<bool>;
        fn is_rebase_in_progress() -> Result<bool>;
        fn is_merge_in_progress() -> Result<bool>;
        fn fetch() -> Result<()>;
        fn fetch_from(remote: &str) -> Result<()>;
        fn fetch_remote_branch(branch: &str) -> Result<()>;
        fn push(spec: GitPush) -> Result<()>;
        fn merge_squash(branch: &str) -> Result<()>;
        fn merge_commit(spec: MergeCommit) -> Result<()>;
        fn merge_no_commit(spec: MergeNoCommit) -> Result<()>;
        fn merge_abort() -> Result<()>;
        fn merge_continue() -> Result<()>;
        fn reset_merge() -> Result<()>;
        fn reset_hard(rev: &str) -> Result<()>;
        fn rebase(onto: &str) -> Result<()>;
        fn rebase_abort() -> Result<()>;
        fn rebase_continue() -> Result<()>;
        fn stash_push(include_untracked: bool) -> Result<()>;
        fn stash_pop() -> Result<()>;
        fn switch_with_stash(branch: &str) -> Result<()>;
        fn worktree_list() -> Result<Vec<Worktree>>;
        fn worktree_add(spec: WorktreeAdd) -> Result<()>;
        fn worktree_remove(path: &Path, force: bool) -> Result<()>;
        fn worktree_move(from: &Path, to: &Path) -> Result<()>;
        fn worktree_prune() -> Result<()>;
        fn tag_create(name: &str, rev: Option<String>) -> Result<()>;
        fn tag_create_annotated(spec: AnnotatedTag) -> Result<()>;
        fn tag_list() -> Result<Vec<String>>;
        fn tag_delete(name: &str) -> Result<()>;
        fn show_file(rev: &str, path: &str) -> Result<String>;
        fn config_get(key: &str) -> Result<Option<String>>;
        fn config_set(key: &str, value: &str) -> Result<()>;
        fn remote_add(name: &str, url: &str) -> Result<()>;
        fn remote_set_url(name: &str, url: &str) -> Result<()>;
        fn blame(path: &str, rev: Option<String>) -> Result<Vec<BlameLine>>;
        fn cherry_pick(rev: &str) -> Result<()>;
        fn revert(rev: &str) -> Result<()>;
        fn rebase_skip() -> Result<()>;
    }
}

/// Synchronous, best-effort helpers for contexts that cannot `.await` — chiefly
/// a `Drop` guard. They shell out through `std::process` directly (no async, no
/// job-containment), so reserve them for short-lived cleanup.
pub mod blocking {
    use std::path::Path;
    use std::process::Command;

    /// Remove a worktree synchronously (`git worktree remove [--force] <path>`).
    pub fn worktree_remove(dir: &Path, path: &Path, force: bool) -> std::io::Result<()> {
        let mut cmd = Command::new(super::BINARY);
        cmd.current_dir(dir).args(["worktree", "remove"]);
        if force {
            cmd.arg("--force");
        }
        cmd.arg(path);
        let status = cmd.status()?;
        if status.success() {
            Ok(())
        } else {
            Err(std::io::Error::other(format!(
                "`git worktree remove` exited with {status}"
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use processkit::{RecordingRunner, Reply, ScriptedRunner};

    #[test]
    fn binary_name_is_git() {
        assert_eq!(BINARY, "git");
    }

    // Compile-time guard: the bound view must stay `Copy` for the *default*
    // `JobRunner` (the production `Repo::git_at()` handle), not just for the
    // `&RecordingRunner` the other tests use. A derived `Copy` would regress this.
    #[allow(dead_code)]
    fn bound_view_is_copy_for_default_runner() {
        fn assert_copy<T: Copy>() {}
        assert_copy::<GitAt<'static, processkit::JobRunner>>();
    }

    // The bound view (`git.at(dir)`) must produce byte-identical argv to the
    // dir-taking call (`git.method(dir, …)`) — the forwarder injects `self.dir`
    // in the right place and nothing else changes.
    #[tokio::test]
    async fn bound_view_matches_dir_taking_calls() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);

        // A method with trailing args (dir injected first).
        git.merge_commit(dir, MergeCommit::branch("feat").no_ff())
            .await
            .unwrap();
        git.at(dir)
            .merge_commit(MergeCommit::branch("feat").no_ff())
            .await
            .unwrap();
        // A method taking a path arg after dir.
        git.worktree_remove(dir, Path::new("/wt"), true)
            .await
            .unwrap();
        git.at(dir)
            .worktree_remove(Path::new("/wt"), true)
            .await
            .unwrap();
        // One of the new query methods.
        git.conflicted_files(dir).await.unwrap();
        git.at(dir).conflicted_files().await.unwrap();
        // One of the §4 additions.
        git.tag_delete(dir, "v1").await.unwrap();
        git.at(dir).tag_delete("v1").await.unwrap();

        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), calls[1].args_str());
        assert_eq!(calls[2].args_str(), calls[3].args_str());
        assert_eq!(calls[4].args_str(), calls[5].args_str());
        assert_eq!(calls[6].args_str(), calls[7].args_str());
        // The bound calls also carried the bound dir as their working directory.
        assert_eq!(calls[1].cwd.as_deref(), Some(dir.as_os_str()));
        assert_eq!(calls[3].cwd.as_deref(), Some(dir.as_os_str()));
    }

    // Hermetic: the real status() command-building + porcelain parsing run
    // against a scripted runner — no `git` binary needed, so this runs on CI.
    #[tokio::test]
    async fn status_parses_scripted_output() {
        // `-z` output: NUL-delimited records, raw paths.
        let git =
            Git::with_runner(ScriptedRunner::new().on(["status"], Reply::ok(" M a.rs\0?? b.rs\0")));
        let entries = git.status(Path::new(".")).await.expect("status");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].code, " M");
        assert_eq!(entries[1].path, "b.rs");
    }

    // `status_tracked` is `status` minus untracked files — same parser, extra flag.
    #[tokio::test]
    async fn status_tracked_excludes_untracked_flag() {
        let rec = RecordingRunner::replying(Reply::ok(" M a.rs\0"));
        let git = Git::with_runner(&rec);
        let entries = git.status_tracked(Path::new(".")).await.expect("status");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].code, " M");
        assert_eq!(
            rec.only_call().args_str(),
            ["status", "--porcelain=v1", "-z", "--untracked-files=no"]
        );
    }

    // `branch_status` builds the porcelain v2 + branch + -z argv and parses the
    // combined header/entry output in one call.
    #[tokio::test]
    async fn branch_status_builds_v2_branch_args_and_parses() {
        let out = concat!(
            "# branch.oid abc\0",
            "# branch.head main\0",
            "# branch.upstream origin/main\0",
            "# branch.ab +1 -0\0",
            "1 .M N... 100644 100644 100644 1 2 a.rs\0",
            "? new.txt\0",
        );
        let rec = RecordingRunner::replying(Reply::ok(out));
        let git = Git::with_runner(&rec);
        let s = git
            .branch_status(Path::new("."))
            .await
            .expect("branch_status");
        assert_eq!(
            rec.only_call().args_str(),
            ["status", "--porcelain=v2", "--branch", "-z"]
        );
        // The poll primitive must not itself write the index (and re-trigger a
        // filesystem watcher re-querying through it).
        assert!(rec.only_call().envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_OPTIONAL_LOCKS")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
        assert_eq!(s.branch.as_deref(), Some("main"));
        assert_eq!(s.upstream.as_deref(), Some("origin/main"));
        assert_eq!((s.ahead, s.behind), (Some(1), Some(0)));
        assert_eq!(s.tracked_changes, 1);
        assert_eq!(s.untracked, 1);
        assert!(s.is_dirty());
    }

    // `conflicted_files` lists unmerged paths NUL-delimited (no quoting).
    #[tokio::test]
    async fn conflicted_files_builds_args_and_parses_nul_list() {
        let rec = RecordingRunner::replying(Reply::ok("a.rs\0sub/spaced name.rs\0"));
        let git = Git::with_runner(&rec);
        let paths = git
            .conflicted_files(Path::new("."))
            .await
            .expect("conflicted_files");
        assert_eq!(paths, ["a.rs", "sub/spaced name.rs"]);
        assert_eq!(
            rec.only_call().args_str(),
            ["diff", "--name-only", "--diff-filter=U", "-z"]
        );
    }

    #[tokio::test]
    async fn rev_parse_short_builds_short_flag() {
        let rec = RecordingRunner::replying(Reply::ok("a1b2c3d\n"));
        let git = Git::with_runner(&rec);
        let out = git.rev_parse_short(Path::new("/r"), "HEAD").await.unwrap();
        assert_eq!(out, "a1b2c3d");
        assert_eq!(rec.only_call().args_str(), ["rev-parse", "--short", "HEAD"]);
    }

    // A non-zero exit surfaces as a structured `Error::Exit`.
    #[tokio::test]
    async fn nonzero_exit_is_structured_error() {
        let git = Git::with_runner(
            ScriptedRunner::new().on(["status"], Reply::fail(128, "not a git repository")),
        );
        match git.status(Path::new(".")).await.unwrap_err() {
            Error::Exit { code, stderr, .. } => {
                assert_eq!(code, 128);
                assert!(stderr.contains("not a git repository"), "{stderr}");
            }
            other => panic!("expected Exit, got {other:?}"),
        }
    }

    // diff_is_empty maps the raw exit code itself: 0 → clean, 1 → dirty, and
    // anything else is a real failure surfaced as Error::Exit.
    #[tokio::test]
    async fn diff_is_empty_maps_exit_codes() {
        let clean = Git::with_runner(ScriptedRunner::new().on(["diff", "--quiet"], Reply::ok("")));
        assert!(clean.diff_is_empty(Path::new(".")).await.unwrap());

        let dirty =
            Git::with_runner(ScriptedRunner::new().on(["diff", "--quiet"], Reply::fail(1, "")));
        assert!(!dirty.diff_is_empty(Path::new(".")).await.unwrap());

        let broken = Git::with_runner(
            ScriptedRunner::new().on(["diff", "--quiet"], Reply::fail(128, "fatal: not a repo")),
        );
        assert!(matches!(
            broken.diff_is_empty(Path::new(".")).await.unwrap_err(),
            Error::Exit { code: 128, .. }
        ));
    }

    // `add` must insert `--` before the pathspecs so a path can never be parsed
    // as an option. No fallback rule: the run only matches if `add --` was built.
    #[tokio::test]
    async fn add_inserts_pathspec_separator() {
        let git = Git::with_runner(ScriptedRunner::new().on(["add", "--"], Reply::ok("")));
        git.add(Path::new("."), &[PathBuf::from("f.rs")])
            .await
            .expect("add should build `add -- <paths>`");
    }

    #[tokio::test]
    async fn worktree_list_parses_porcelain() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["worktree", "list"],
            Reply::ok("worktree /repo\nHEAD abc\nbranch refs/heads/main\n"),
        ));
        let wts = git.worktree_list(Path::new(".")).await.expect("list");
        assert_eq!(wts.len(), 1);
        assert_eq!(wts[0].branch.as_deref(), Some("main"));
        assert_eq!(wts[0].head.as_deref(), Some("abc"));
    }

    // The new-branch worktree must build `worktree add -b <name> <path> <base>`,
    // in that exact order; only the full argv is scripted (no fallback).
    #[tokio::test]
    async fn worktree_add_builds_branch_path_and_base() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_add(
            Path::new("/repo"),
            WorktreeAdd::create_branch("/wt", "feature", "main"),
        )
        .await
        .expect("worktree add");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "add", "-b", "feature", "/wt", "main"]
        );
    }

    #[tokio::test]
    async fn worktree_remove_passes_force_then_path() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_remove(Path::new("/repo"), Path::new("/wt"), true)
            .await
            .expect("remove");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "remove", "--force", "/wt"]
        );
    }

    // `--no-checkout` must land between `-b <name>` and the path.
    #[tokio::test]
    async fn worktree_add_no_checkout_inserts_flag() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.worktree_add(
            Path::new("/repo"),
            WorktreeAdd::checkout("/wt", "main").no_checkout(),
        )
        .await
        .expect("worktree add");
        assert_eq!(
            rec.only_call().args_str(),
            ["worktree", "add", "--no-checkout", "/wt", "main"]
        );
    }

    #[tokio::test]
    async fn checkout_detach_builds_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.checkout_detach(Path::new("."), "abc123")
            .await
            .expect("detach");
        assert_eq!(
            rec.only_call().args_str(),
            ["checkout", "--detach", "abc123"]
        );
    }

    // Partial amend commit must build `commit --amend -m <msg> --only -- <paths>`.
    #[tokio::test]
    async fn commit_paths_builds_only_amend_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.commit_paths(
            Path::new("."),
            CommitPaths::new([PathBuf::from("a.rs"), PathBuf::from("b.rs")], "msg").amend(),
        )
        .await
        .expect("commit_paths");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "commit", "--amend", "-m", "msg", "--only", "--", "a.rs", "b.rs"
            ]
        );
    }

    // is_unborn maps the rev-parse exit code: 0 → has commits (false), 1 →
    // unborn (true), anything else is a structured error.
    #[tokio::test]
    async fn is_unborn_maps_exit_codes() {
        let born = Git::with_runner(ScriptedRunner::new().on(["rev-parse"], Reply::ok("abc\n")));
        assert!(!born.is_unborn(Path::new(".")).await.unwrap());
        let unborn = Git::with_runner(ScriptedRunner::new().on(["rev-parse"], Reply::fail(1, "")));
        assert!(unborn.is_unborn(Path::new(".")).await.unwrap());
        let broken =
            Git::with_runner(ScriptedRunner::new().on(["rev-parse"], Reply::fail(128, "boom")));
        assert!(matches!(
            broken.is_unborn(Path::new(".")).await.unwrap_err(),
            Error::Exit { code: 128, .. }
        ));
    }

    #[tokio::test]
    async fn log_range_builds_range_and_format() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.log_range(Path::new("."), "main..HEAD", 5)
            .await
            .expect("log_range");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "log",
                "main..HEAD",
                "-n5",
                "-z",
                "--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s"
            ]
        );
    }

    #[tokio::test]
    async fn stash_push_adds_include_untracked() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.stash_push(Path::new("."), true).await.expect("stash");
        assert_eq!(
            rec.only_call().args_str(),
            ["stash", "push", "--include-untracked"]
        );
    }

    // `diff_text` for the working tree must build `diff HEAD` plus the stable
    // machine-output flags, in order.
    #[tokio::test]
    async fn diff_text_builds_working_tree_args() {
        // The `rev-parse` unborn probe replies exit 0 (HEAD resolves), so the diff
        // targets HEAD. The probe is the first call; the diff is the last.
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.diff_text(Path::new("."), DiffSpec::WorkingTree)
            .await
            .expect("diff_text");
        assert_eq!(
            rec.calls().last().unwrap().args_str(),
            [
                "diff",
                "HEAD",
                "--no-color",
                "--no-ext-diff",
                "-M",
                // Pin the parser's `a/`…`b/` headers against a user's
                // `diff.noprefix`/`diff.mnemonicPrefix` config.
                "--src-prefix=a/",
                "--dst-prefix=b/",
            ]
        );
    }

    // On an unborn repo the working-tree diff targets the empty tree instead of
    // the unresolvable `HEAD`, so it returns additions rather than erroring. The
    // diff rule only matches the empty-tree argv, so a `HEAD` target would miss it.
    #[tokio::test]
    async fn diff_text_working_tree_uses_empty_tree_when_unborn() {
        let git = Git::with_runner(
            ScriptedRunner::new()
                .on(["rev-parse"], Reply::fail(1, "")) // unborn: HEAD doesn't resolve
                .on(["diff", EMPTY_TREE], Reply::ok("EMPTY")),
        );
        let out = git
            .diff_text(Path::new("."), DiffSpec::WorkingTree)
            .await
            .expect("diff_text");
        assert_eq!(out, "EMPTY");
    }

    // Hermetic: real diff() arg-building (`Rev`) + the ported parser against
    // canned git-format output.
    #[tokio::test]
    async fn diff_parses_scripted_output() {
        let out = "diff --git a/m b/m\n--- a/m\n+++ b/m\n@@ -1 +1 @@\n-a\n+b\n";
        let git = Git::with_runner(ScriptedRunner::new().on(["diff"], Reply::ok(out)));
        let files = git
            .diff(Path::new("."), DiffSpec::Rev("HEAD~1".into()))
            .await
            .expect("diff");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "m");
        assert_eq!(files[0].change, ChangeKind::Modified);
    }

    #[tokio::test]
    async fn branch_exists_maps_exit_codes() {
        let yes = Git::with_runner(ScriptedRunner::new().on(["show-ref"], Reply::ok("")));
        assert!(yes.branch_exists(Path::new("."), "main").await.unwrap());
        let no = Git::with_runner(ScriptedRunner::new().on(["show-ref"], Reply::fail(1, "")));
        assert!(!no.branch_exists(Path::new("."), "nope").await.unwrap());
    }

    // The full ref prefix is stripped but a slashed default branch survives; an
    // unset origin/HEAD (non-zero exit) is `None`, not an error.
    #[tokio::test]
    async fn remote_head_branch_strips_prefix_and_keeps_slashes() {
        let simple = Git::with_runner(
            ScriptedRunner::new().on(["symbolic-ref"], Reply::ok("refs/remotes/origin/main\n")),
        );
        assert_eq!(
            simple
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("main")
        );

        let slashed = Git::with_runner(ScriptedRunner::new().on(
            ["symbolic-ref"],
            Reply::ok("refs/remotes/origin/release/v2\n"),
        ));
        assert_eq!(
            slashed
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .as_deref(),
            Some("release/v2")
        );

        let unset =
            Git::with_runner(ScriptedRunner::new().on(["symbolic-ref"], Reply::fail(1, "")));
        assert!(
            unset
                .remote_head_branch(Path::new("."))
                .await
                .unwrap()
                .is_none()
        );
    }

    // remote_branch_exists must pass `GIT_TERMINAL_PROMPT=0` and treat empty
    // stdout as "absent".
    #[tokio::test]
    async fn remote_branch_exists_sets_env_and_reads_stdout() {
        let rec = RecordingRunner::replying(Reply::ok("abc123\trefs/heads/main\n"));
        let git = Git::with_runner(&rec);
        assert!(
            git.remote_branch_exists(Path::new("/repo"), "main")
                .await
                .unwrap()
        );
        let call = rec.only_call();
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
        // Exact-ref query — a bare `main` would tail-match `bar/main`.
        assert_eq!(call.args_str(), ["ls-remote", "origin", "refs/heads/main"]);

        let empty = Git::with_runner(ScriptedRunner::new().on(["ls-remote"], Reply::ok("")));
        assert!(
            !empty
                .remote_branch_exists(Path::new("."), "x")
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn diff_stat_parses_counts() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["diff", "--shortstat"],
            Reply::ok(" 2 files changed, 5 insertions(+), 1 deletion(-)\n"),
        ));
        let stat = git.diff_stat(Path::new("."), "main..HEAD").await.unwrap();
        assert_eq!(
            (stat.files_changed, stat.insertions, stat.deletions),
            (2, 5, 1)
        );
    }

    #[tokio::test]
    async fn status_text_returns_raw_porcelain() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["status", "--porcelain=v1"],
            Reply::ok(" M a.rs\n?? b.rs\n"),
        ));
        let text = git.status_text(Path::new(".")).await.expect("status_text");
        assert!(text.contains(" M a.rs") && text.contains("?? b.rs"));
    }

    #[tokio::test]
    async fn run_args_forwards_str_slices() {
        let git = Git::with_runner(ScriptedRunner::new().on(["status", "-s"], Reply::ok("ok\n")));
        assert_eq!(git.run_args(&["status", "-s"]).await.unwrap(), "ok");
    }

    #[tokio::test]
    async fn merge_commit_builds_no_ff_and_message() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.merge_commit(
            Path::new("/r"),
            MergeCommit::branch("feature").no_ff().message("merge it"),
        )
        .await
        .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["merge", "--no-ff", "-m", "merge it", "feature"]
        );
    }

    // No message → `--no-edit` (default message, non-interactive) instead of `$EDITOR`.
    #[tokio::test]
    async fn merge_commit_without_message_uses_no_edit() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.merge_commit(Path::new("/r"), MergeCommit::branch("feature"))
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["merge", "--no-edit", "feature"]
        );
    }

    // rebase/rebase_continue force a no-op editor so a headless caller never hangs.
    #[tokio::test]
    async fn rebase_suppresses_editor() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.rebase(Path::new("/r"), "main").await.unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["rebase", "main"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_EDITOR")
                && v.as_deref().and_then(|o| o.to_str()) == Some("true")
        }));
    }

    #[tokio::test]
    async fn push_builds_set_upstream_remote_refspec() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(
            Path::new("/r"),
            GitPush::refspec("feat", "feature").set_upstream(),
        )
        .await
        .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["push", "-u", "origin", "feat:feature"]
        );
    }

    // The common bare-branch push: `push origin <branch>` (no `-u`), with prompts
    // off so a credential-needing remote fails fast instead of hanging.
    #[tokio::test]
    async fn push_bare_branch_builds_origin_branch_prompt_off() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(Path::new("/r"), GitPush::branch("feature"))
            .await
            .unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["push", "origin", "feature"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
    }

    // `.remote()` swaps the remote token in place.
    #[tokio::test]
    async fn push_remote_override_swaps_remote() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.push(
            Path::new("/r"),
            GitPush::branch("feature").remote("upstream"),
        )
        .await
        .unwrap();
        assert_eq!(rec.only_call().args_str(), ["push", "upstream", "feature"]);
    }

    #[tokio::test]
    async fn upstream_maps_unset_to_none() {
        let set =
            Git::with_runner(ScriptedRunner::new().on(["rev-parse"], Reply::ok("origin/main\n")));
        assert_eq!(
            set.upstream(Path::new(".")).await.unwrap().as_deref(),
            Some("origin/main")
        );
        let unset = Git::with_runner(ScriptedRunner::new().on(["rev-parse"], Reply::fail(128, "")));
        assert!(unset.upstream(Path::new(".")).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn set_upstream_builds_branch_flag() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.set_upstream(Path::new("/r"), "feat", "origin/feature")
            .await
            .unwrap();
        assert_eq!(
            rec.only_call().args_str(),
            ["branch", "--set-upstream-to=origin/feature", "feat"]
        );
    }

    #[tokio::test]
    async fn remote_branches_parses_ls_remote() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["ls-remote"],
            Reply::ok("aaa\trefs/heads/main\nbbb\trefs/heads/feat/x\n"),
        ));
        let branches = git.remote_branches(Path::new("."), "origin").await.unwrap();
        assert_eq!(branches, ["main", "feat/x"]);
    }

    #[tokio::test]
    async fn delete_branch_force_uses_capital_d() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.delete_branch(Path::new("/r"), "old", true)
            .await
            .unwrap();
        assert_eq!(rec.only_call().args_str(), ["branch", "-D", "old"]);
    }

    // `branch --merged` marks the current branch with `*` and a branch checked out
    // in another worktree with `+`; both must still match after marker stripping.
    #[tokio::test]
    async fn is_merged_strips_branch_markers() {
        let git = Git::with_runner(ScriptedRunner::new().on(
            ["branch", "--merged"],
            Reply::ok("  main\n* feature\n+ wt-branch\n"),
        ));
        for name in ["main", "feature", "wt-branch"] {
            assert!(
                git.is_merged(Path::new("."), name, "main").await.unwrap(),
                "{name} should be reported merged"
            );
        }
        assert!(
            !git.is_merged(Path::new("."), "absent", "main")
                .await
                .unwrap()
        );
    }

    // `fetch` must disable the credential prompt so it fails fast (never hangs) on
    // a remote needing auth — matching the other remote ops.
    #[tokio::test]
    async fn fetch_disables_terminal_prompt() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.fetch(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["fetch", "--quiet"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));
    }

    // A transient failure (DNS/network) is retried up to FETCH_ATTEMPTS times.
    #[tokio::test]
    async fn fetch_retries_transient_failures() {
        let rec = RecordingRunner::replying(Reply::fail(
            128,
            "fatal: unable to access: Could not resolve host: example.com",
        ));
        let git = Git::with_runner(&rec);
        assert!(git.fetch(Path::new("/r")).await.is_err());
        assert_eq!(rec.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // A non-transient failure fails fast — no retry.
    #[tokio::test]
    async fn fetch_does_not_retry_permanent_failures() {
        let rec = RecordingRunner::replying(Reply::fail(1, "fatal: couldn't find remote ref"));
        let git = Git::with_runner(&rec);
        assert!(git.fetch(Path::new("/r")).await.is_err());
        assert_eq!(rec.calls().len(), 1);
    }

    // Client-level cancellation (processkit 0.8 `cancellation` feature) on a
    // *retried* op: a `fetch` built on a client with `default_cancel_on(token)`
    // parks until the token fires, then surfaces `Error::Cancelled` — and because
    // cancellation is **terminal** (not transient), the fetch-retry does NOT
    // replay it (one spawn, not FETCH_ATTEMPTS). Hermetic via `Reply::pending()`
    // on a paused clock.
    #[cfg(feature = "cancellation")]
    #[tokio::test(start_paused = true)]
    async fn fetch_cancels_and_does_not_retry() {
        use processkit::CancellationToken;
        let token = CancellationToken::new();
        let rec = RecordingRunner::new(ScriptedRunner::new().on(["fetch"], Reply::pending()));
        let git = Git::with_runner(&rec).default_cancel_on(token.clone());
        let call = git.fetch(Path::new("/r"));
        tokio::pin!(call);
        assert!(
            tokio::time::timeout(std::time::Duration::from_secs(3600), &mut call)
                .await
                .is_err(),
            "fetch must park until the token fires"
        );
        token.cancel();
        assert!(matches!(call.await.unwrap_err(), Error::Cancelled { .. }));
        assert_eq!(
            rec.calls().len(),
            1,
            "cancellation is terminal — the fetch-retry must not replay it"
        );
    }

    // The injection guard: a flag-shaped value in any exposed positional slot
    // must be refused BEFORE anything spawns.
    #[tokio::test]
    async fn flag_like_positionals_are_rejected_before_spawning() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        let dir = Path::new("/r");

        assert!(git.checkout(dir, "-evil").await.is_err());
        assert!(git.create_branch(dir, "--force").await.is_err());
        assert!(git.delete_branch(dir, "-D", false).await.is_err());
        assert!(git.rename_branch(dir, "ok", "-bad").await.is_err());
        assert!(
            git.merge_commit(dir, MergeCommit::branch("-evil"))
                .await
                .is_err()
        );
        assert!(
            git.merge_no_commit(dir, MergeNoCommit::branch("-evil").no_ff())
                .await
                .is_err()
        );
        assert!(git.merge_squash(dir, "-evil").await.is_err());
        assert!(git.rebase(dir, "-i").await.is_err());
        assert!(git.cherry_pick(dir, "-n").await.is_err());
        assert!(git.revert(dir, "-evil").await.is_err());
        assert!(git.tag_create(dir, "-d", None).await.is_err());
        assert!(
            git.tag_create(dir, "ok", Some("-evil".into()))
                .await
                .is_err()
        );
        assert!(git.tag_delete(dir, "-evil").await.is_err());
        assert!(git.remote_add(dir, "-evil", "url").await.is_err());
        assert!(git.remote_set_url(dir, "-evil", "url").await.is_err());
        assert!(git.set_upstream(dir, "-evil", "origin/x").await.is_err());
        assert!(git.log_range(dir, "-evil", 5).await.is_err());
        assert!(git.rev_list_count(dir, "-evil").await.is_err());
        assert!(git.diff_stat(dir, "-evil").await.is_err());
        assert!(git.diff_range_is_empty(dir, "-evil").await.is_err());
        assert!(
            git.diff_text(dir, DiffSpec::Rev("-evil".into()))
                .await
                .is_err()
        );
        assert!(git.rev_parse(dir, "-evil").await.is_err());
        assert!(git.rev_parse_short(dir, "-evil").await.is_err());
        assert!(git.resolve_commit(dir, "-evil").await.is_err());
        assert!(git.reset_hard(dir, "-evil").await.is_err());
        assert!(git.checkout_detach(dir, "-evil").await.is_err());
        assert!(git.config_set(dir, "-evil", "v").await.is_err());
        assert!(
            git.push(dir, GitPush::branch("-evil")).await.is_err(),
            "refspec guard"
        );
        // Embedded-token-prefix and standalone-rev positionals:
        assert!(git.show_file(dir, "-evil", "f.txt").await.is_err());
        assert!(git.blame(dir, "f.txt", Some("-s".into())).await.is_err());
        assert!(git.remote_url(dir, "-evil").await.is_err());
        assert!(git.remote_branches(dir, "-evil").await.is_err());
        assert!(git.fetch_from(dir, "--upload-pack=x").await.is_err());
        // URL positionals (a leading-`-` url is an RCE-class flag injection).
        assert!(
            git.clone_repo("--upload-pack=x", Path::new("/d"), CloneSpec::new())
                .await
                .is_err()
        );
        assert!(git.remote_add(dir, "ok", "--upload-pack=x").await.is_err());
        assert!(git.remote_set_url(dir, "ok", "-evil").await.is_err());
        assert!(git.is_merged(dir, "-evil", "main").await.is_err());
        assert!(git.config_get(dir, "-evil").await.is_err());
        assert!(
            git.worktree_add(
                dir,
                WorktreeAdd::create_branch(Path::new("/wt"), "-evil", "HEAD")
            )
            .await
            .is_err()
        );
        // Empty values are refused too.
        assert!(git.checkout(dir, "").await.is_err());

        assert!(
            rec.calls().is_empty(),
            "nothing may spawn: {:?}",
            rec.calls()
        );

        // …and legitimate values still pass through unchanged.
        git.checkout(dir, "feature/x").await.expect("checkout");
        assert_eq!(rec.only_call().args_str(), ["checkout", "feature/x"]);
    }

    // The hardened profile lands its env pairs/removals on EVERY command, and
    // composes with per-command env like GIT_TERMINAL_PROMPT.
    #[tokio::test]
    async fn harden_applies_env_profile_to_every_command() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec).harden();
        git.status(Path::new("/r")).await.expect("status");
        git.fetch(Path::new("/r")).await.expect("fetch");

        for call in rec.calls() {
            let has = |k: &str, v: &str| {
                call.envs.iter().any(|(key, val)| {
                    key.to_str() == Some(k) && val.as_deref().and_then(|o| o.to_str()) == Some(v)
                })
            };
            let removed = |k: &str| {
                call.envs
                    .iter()
                    .any(|(key, val)| key.to_str() == Some(k) && val.is_none())
            };
            assert!(has("GIT_CONFIG_NOSYSTEM", "1"), "{:?}", call.args_str());
            assert!(has("GIT_CONFIG_KEY_0", "core.hooksPath"));
            assert!(has("GIT_CONFIG_VALUE_0", "/dev/null"));
            assert!(has("GIT_TERMINAL_PROMPT", "0"));
            assert!(removed("GIT_DIR"), "GIT_DIR scrubbed");
            assert!(removed("GIT_CONFIG_GLOBAL"), "global config scrubbed");
        }
    }

    // RefName/RevSpec accept/reject tables.
    #[test]
    fn ref_name_and_rev_spec_validate() {
        for ok in ["main", "feature/x", "v1.2.3", "a-b_c"] {
            assert!(RefName::new(ok).is_ok(), "{ok}");
        }
        for bad in [
            "", "-evil", ".hidden", "a..b", "a b", "a~b", "a^b", "a:b", "a?b", "a*b", "a[b",
            "a\\b", "end/", "x.lock",
        ] {
            assert!(RefName::new(bad).is_err(), "{bad:?} must be rejected");
        }
        assert!(RevSpec::new("HEAD~2").is_ok());
        assert!(RevSpec::new("main..feature").is_ok());
        assert!(RevSpec::new("-evil").is_err());
        assert!(RevSpec::new("").is_err());
    }

    // capabilities parses real-world version shapes (incl. the Windows build
    // trailer) and gates on the major floor only.
    #[tokio::test]
    async fn capabilities_parse_and_gate_versions() {
        let gh = Git::with_runner(
            ScriptedRunner::new().on(["--version"], Reply::ok("git version 2.54.0.windows.1\n")),
        );
        let caps = gh.capabilities().await.expect("capabilities");
        assert_eq!(caps.version.to_string(), "2.54.0");
        assert!(caps.is_supported());
        caps.ensure_supported().expect("supported");

        // Two-part versions parse (patch defaults to 0); an ancient major fails
        // the gate with a clear message.
        let old = Git::with_runner(
            ScriptedRunner::new().on(["--version"], Reply::ok("git version 1.9\n")),
        );
        let caps = old.capabilities().await.expect("capabilities");
        assert_eq!(
            caps.version,
            GitVersion {
                major: 1,
                minor: 9,
                patch: 0
            }
        );
        let err = caps.ensure_supported().expect_err("unsupported");
        // The message must name the floor and the found version.
        let Error::Spawn { source, .. } = &err else {
            panic!("expected Spawn, got {err:?}");
        };
        let message = source.to_string();
        assert!(message.contains(">= 2"), "names the floor: {message}");
        assert!(
            message.contains("1.9.0"),
            "names the found version: {message}"
        );

        // Garbage output is a parse error, not a silent zero version.
        let garbage =
            Git::with_runner(ScriptedRunner::new().on(["--version"], Reply::ok("not a version")));
        assert!(matches!(
            garbage.capabilities().await.unwrap_err(),
            Error::Parse { .. }
        ));
    }

    // clone_repo is dir-less and appends only the requested flags.
    #[tokio::test]
    async fn clone_repo_builds_flags_and_runs_dirless() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.clone_repo(
            "https://example.com/r.git",
            Path::new("/dest"),
            CloneSpec::new().branch("main").depth(1).bare(),
        )
        .await
        .expect("clone");
        let call = rec.only_call();
        assert_eq!(
            call.args_str(),
            [
                "clone",
                "--branch",
                "main",
                "--depth",
                "1",
                "--bare",
                "https://example.com/r.git",
                "/dest"
            ]
        );
        assert_eq!(call.cwd, None, "clone runs without a working directory");

        let bare = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&bare);
        git.clone_repo("u", Path::new("/d"), CloneSpec::new())
            .await
            .expect("clone");
        assert_eq!(bare.only_call().args_str(), ["clone", "u", "/d"]);
    }

    #[tokio::test]
    async fn tag_methods_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.tag_create(Path::new("/r"), "v1", None).await.unwrap();
        git.tag_create(Path::new("/r"), "v1", Some("abc".into()))
            .await
            .unwrap();
        git.tag_create_annotated(Path::new("/r"), AnnotatedTag::new("v2", "notes"))
            .await
            .unwrap();
        git.tag_delete(Path::new("/r"), "v1").await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["tag", "v1"]);
        assert_eq!(calls[1].args_str(), ["tag", "v1", "abc"]);
        assert_eq!(calls[2].args_str(), ["tag", "-a", "v2", "-m", "notes"]);
        assert_eq!(calls[3].args_str(), ["tag", "-d", "v1"]);
    }

    #[tokio::test]
    async fn tag_list_splits_lines() {
        let git =
            Git::with_runner(ScriptedRunner::new().on(["tag", "--list"], Reply::ok("v1\nv2.0\n")));
        assert_eq!(git.tag_list(Path::new(".")).await.unwrap(), ["v1", "v2.0"]);
    }

    // The line-parsed list commands must pass `--no-column`: a user's
    // `column.ui = always` would pack several names per line even when piped.
    #[tokio::test]
    async fn list_commands_disable_column_output() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.branches(Path::new(".")).await.unwrap();
        git.is_merged(Path::new("."), "b", "main").await.unwrap();
        git.tag_list(Path::new(".")).await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["branch", "--no-column"]);
        assert_eq!(
            calls[1].args_str(),
            ["branch", "--merged", "main", "--no-column"]
        );
        assert_eq!(calls[2].args_str(), ["tag", "--list", "--no-column"]);
    }

    // Commands whose failure output feeds the error classifiers must force the
    // C locale — a translated message would defeat the substring matching.
    #[tokio::test]
    async fn classified_commands_force_c_locale() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.commit(Path::new("."), "msg").await.unwrap();
        git.merge_commit(Path::new("."), MergeCommit::branch("b"))
            .await
            .unwrap();
        git.cherry_pick(Path::new("."), "abc").await.unwrap();
        git.fetch(Path::new(".")).await.unwrap();
        for call in rec.calls() {
            assert!(
                call.envs.iter().any(|(k, v)| {
                    k.to_str() == Some("LC_ALL")
                        && v.as_deref().and_then(|o| o.to_str()) == Some("C")
                }),
                "{:?} should force LC_ALL=C",
                call.args_str()
            );
        }
    }

    // The `<rev>:<path>` spec requires forward slashes — Windows callers may
    // hand in backslashes. The normalisation is Windows-only.
    #[cfg(windows)]
    #[tokio::test]
    async fn show_file_normalises_path_separators() {
        let rec = RecordingRunner::replying(Reply::ok("content\n"));
        let git = Git::with_runner(&rec);
        let out = git
            .show_file(Path::new("/r"), "HEAD", "sub\\dir\\f.txt")
            .await
            .expect("show_file");
        assert_eq!(out, "content");
        assert_eq!(rec.only_call().args_str(), ["show", "HEAD:sub/dir/f.txt"]);
    }

    // On Unix a backslash is a legal filename byte — the spec must pass through
    // verbatim so a literal `a\b.txt` stays resolvable.
    #[cfg(not(windows))]
    #[tokio::test]
    async fn show_file_keeps_backslashes_on_unix() {
        let rec = RecordingRunner::replying(Reply::ok("content\n"));
        let git = Git::with_runner(&rec);
        git.show_file(Path::new("/r"), "HEAD", "sub\\dir\\f.txt")
            .await
            .expect("show_file");
        assert_eq!(rec.only_call().args_str(), ["show", "HEAD:sub\\dir\\f.txt"]);
    }

    // config --get: exit 0 → Some(value), exit 1 → None (unset), other → error.
    #[tokio::test]
    async fn config_get_maps_exit_codes() {
        let set =
            Git::with_runner(ScriptedRunner::new().on(["config", "--get"], Reply::ok("Alice\n")));
        assert_eq!(
            set.config_get(Path::new("."), "user.name").await.unwrap(),
            Some("Alice".to_string())
        );
        let unset =
            Git::with_runner(ScriptedRunner::new().on(["config", "--get"], Reply::fail(1, "")));
        assert_eq!(
            unset.config_get(Path::new("."), "user.name").await.unwrap(),
            None
        );
        // A multi-valued key (exit 2) or worse is a real error.
        let multi = Git::with_runner(
            ScriptedRunner::new().on(["config", "--get"], Reply::fail(2, "multiple values")),
        );
        assert!(
            multi
                .config_get(Path::new("."), "remote.all")
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn blame_builds_rev_before_pathspec_separator() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.blame(Path::new("/r"), "src/lib.rs", Some("HEAD~1".into()))
            .await
            .unwrap();
        git.blame(Path::new("/r"), "src/lib.rs", None)
            .await
            .unwrap();
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["blame", "--line-porcelain", "HEAD~1", "--", "src/lib.rs"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["blame", "--line-porcelain", "--", "src/lib.rs"]
        );
    }

    // revert must never open an editor: --no-edit plus the env backstop.
    #[tokio::test]
    async fn sequencer_methods_suppress_editors() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.revert(Path::new("/r"), "abc").await.unwrap();
        git.cherry_pick(Path::new("/r"), "abc").await.unwrap();
        git.rebase_skip(Path::new("/r")).await.unwrap();
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["revert", "--no-edit", "abc"]);
        assert_eq!(calls[1].args_str(), ["cherry-pick", "abc"]);
        assert_eq!(calls[2].args_str(), ["rebase", "--skip"]);
        for call in &calls {
            assert!(
                call.envs
                    .iter()
                    .any(|(k, _)| k.to_str() == Some("GIT_EDITOR")),
                "editor suppressed on {:?}",
                call.args_str()
            );
        }
    }

    #[tokio::test]
    async fn remote_add_and_set_url_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.remote_add(Path::new("/r"), "up", "https://x/y.git")
            .await
            .unwrap();
        git.remote_set_url(Path::new("/r"), "up", "https://x/z.git")
            .await
            .unwrap();
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["remote", "add", "up", "https://x/y.git"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["remote", "set-url", "up", "https://x/z.git"]
        );
    }

    // Dirty tree: stash -u → checkout → pop, in that order.
    #[tokio::test]
    async fn switch_with_stash_round_trips_dirty_tree() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["status"], Reply::ok(" M a.rs\0"))
                .on(["stash", "push"], Reply::ok(""))
                .on(["checkout"], Reply::ok(""))
                .on(["stash", "pop"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        git.switch_with_stash(Path::new("/r"), "feature")
            .await
            .expect("switch");
        let calls = rec.calls();
        assert_eq!(calls.len(), 4);
        assert_eq!(
            calls[1].args_str(),
            ["stash", "push", "--include-untracked"]
        );
        assert_eq!(calls[2].args_str(), ["checkout", "feature"]);
        assert_eq!(calls[3].args_str(), ["stash", "pop"]);
    }

    // A clean tree skips the stash round-trip — a no-op `stash push` would make
    // the later pop grab an older, unrelated stash.
    #[tokio::test]
    async fn switch_with_stash_skips_stash_on_clean_tree() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["status"], Reply::ok(""))
                .on(["checkout"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        git.switch_with_stash(Path::new("/r"), "feature")
            .await
            .expect("switch");
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert!(calls.iter().all(|c| c.args_str()[0] != "stash"));
    }

    // A failed checkout pops the stash back (we are still on the original
    // branch) and surfaces the checkout error.
    #[tokio::test]
    async fn switch_with_stash_restores_on_checkout_failure() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["status"], Reply::ok(" M a.rs\0"))
                .on(["stash", "push"], Reply::ok(""))
                .on(["checkout"], Reply::fail(1, "error: pathspec 'nope'"))
                .on(["stash", "pop"], Reply::ok("")),
        );
        let git = Git::with_runner(&rec);
        let err = git
            .switch_with_stash(Path::new("/r"), "nope")
            .await
            .expect_err("checkout error must surface");
        assert!(matches!(err, Error::Exit { .. }));
        let calls = rec.calls();
        assert_eq!(calls.len(), 4);
        assert_eq!(calls[3].args_str(), ["stash", "pop"], "restoring pop ran");
    }

    // `fetch_from` names the remote, keeps the prompt off, and shares the
    // transient retry.
    #[tokio::test]
    async fn fetch_from_builds_args_and_retries() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let git = Git::with_runner(&rec);
        git.fetch_from(Path::new("/r"), "upstream")
            .await
            .expect("fetch_from");
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["fetch", "--quiet", "upstream"]);
        assert!(call.envs.iter().any(|(k, v)| {
            k.to_str() == Some("GIT_TERMINAL_PROMPT")
                && v.as_deref().and_then(|o| o.to_str()) == Some("0")
        }));

        let failing = RecordingRunner::replying(Reply::fail(128, "fatal: Connection timed out"));
        let git = Git::with_runner(&failing);
        assert!(git.fetch_from(Path::new("/r"), "upstream").await.is_err());
        assert_eq!(failing.calls().len(), FETCH_ATTEMPTS as usize);
    }

    // The consumer-facing mock seam: a function depending on `&dyn GitApi` is
    // tested with a generated mock.
    #[cfg(feature = "mock")]
    #[tokio::test]
    async fn consumer_mocks_the_interface() {
        async fn on_branch(git: &dyn GitApi, want: &str) -> bool {
            git.current_branch(Path::new(".")).await.unwrap() == want
        }
        let mut mock = MockGitApi::new();
        mock.expect_current_branch()
            .returning(|_| Ok("main".to_string()));
        assert!(on_branch(&mock, "main").await);
    }
}

// Long-form how-to guides, rendered from this crate's docs/*.md on docs.rs.
#[doc = include_str!("../docs/git.md")]
#[allow(rustdoc::broken_intra_doc_links)]
pub mod guide {
    #[doc = include_str!("../docs/security.md")]
    #[allow(rustdoc::broken_intra_doc_links)]
    pub mod security {}
    #[doc = include_str!("../docs/conflicts.md")]
    #[allow(rustdoc::broken_intra_doc_links)]
    pub mod conflicts {}
}