wsb 0.253.6349

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
use crate::fleet::config::gitmodules::validate_gitmodules_structure;
use crate::prelude::*;
use anyhow::{bail, Context, Result};
use gix::bstr::BString;
use gix::remote;
use gix::status;
use gix::status::index_worktree;
use gix::status::index_worktree::iter::Summary as IndexWorktreeSummary;
use gix::status::plumbing::index_as_worktree::{Change as WorktreeChange, EntryStatus};
use ignore::WalkBuilder;
use std::collections::BTreeSet;
use std::fs;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BranchKind {
    Local,
    Remote,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FileStatusKind {
    Staged,
    Modified,
    Untracked,
    Ignored,
    Deleted,
    Renamed,
    Conflict,
}

#[derive(Debug, Clone)]
pub struct StatusEntry {
    pub path: String,
    pub status: FileStatusKind,
    /// This path is a SUBMODULE whose recorded commit differs from the child's
    /// own HEAD — a gitlink that has moved, not an edit to a file in this
    /// repository.
    ///
    /// Reported because the two are different kinds of pending change and
    /// callers want different things from them. `wsb ship` must refuse both: a
    /// published commit that does not record where its children sit is not
    /// reproducible. `wsb pull` must be blocked by neither on its own — a
    /// container whose only difference is its children's positions is the
    /// ORDINARY state of this fleet, since the children are pulled by the same
    /// command, and skipping it left the container's own commits unpulled
    /// forever.
    ///
    /// `git status --ignore-submodules=all` is the same distinction.
    pub submodule_pointer: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushOutcome {
    Updated,
    UpToDate,
}

/// The environment variables through which git re-targets a command at a
/// specific repository, overriding the directory the command was pointed at.
///
/// The variable naming the wsb that started a git command.
///
/// Read by the pre-commit hook, so the update it runs is done by the wsb doing
/// the committing rather than by whichever one is on PATH. Absent when git was
/// started by a person, and the hook then uses PATH — which is right, because
/// then there is no other wsb to prefer.
pub const SELF_ENV: &str = "WSB_SELF";

/// Git exports these to every hook it runs, so everything a hook launches
/// inherits them. `GIT_DIR` in particular beats both `-C` and `current_dir`:
///
/// ```text
/// $ git -C b tag -l                    → v9.9.9
/// $ GIT_DIR=a/.git git -C b tag -l     → (nothing)
/// ```
///
/// So a `git ls-remote` aimed at project B, launched from project A's pre-commit
/// hook, queries A and then truthfully reports that it found no tags. That is
/// how `latest_remote_version` resolved to a sibling project's newest tag — or
/// to nothing at all — whenever a template was rendered by a commit instead of
/// by hand, while the same render run from a shell was correct. The silent case
/// is the dangerous one: when the wrong repository happens to answer with a
/// plausible version, a pin is stamped from it and nothing fails.
pub const REPO_SCOPING_ENV: &[&str] = &[
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_COMMON_DIR",
    "GIT_INDEX_FILE",
    "GIT_OBJECT_DIRECTORY",
    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
    "GIT_NAMESPACE",
    "GIT_PREFIX",
];

/// The environment variables through which git describes *the operation in
/// progress* — who is committing, when, and with which `-c` overrides.
///
/// A real pre-commit hook is handed all of these:
///
/// ```text
/// GIT_AUTHOR_NAME=Outer User
/// GIT_AUTHOR_EMAIL=outer@example.com
/// GIT_AUTHOR_DATE=@981173106 +0000
/// GIT_CONFIG_PARAMETERS='user.name'='Leaked Identity'   # from `git -c user.name=…`
/// ```
///
/// They belong to one commit in one repository. Carried into a commit wsb makes
/// in a *different* repository they overrule that repository's own identity —
/// `GIT_AUTHOR_*` outranks its config, and `GIT_CONFIG_PARAMETERS` outranks it
/// twice over, since `-c` beats even local config. A `wsb commit` launched from
/// a hook would stamp every submodule with the outer commit's author and its
/// timestamp, which is wrong quietly and permanently: a bad author date is not
/// something anyone notices until much later.
///
/// Cleared, each repository answers for itself: identity resolves from its own
/// config, and a repository with none configured fails loudly rather than
/// borrowing somebody else's.
///
/// Deliberately absent: `GIT_EDITOR`, which a hook sets to `:` precisely so
/// nothing it launches opens an interactive editor, and `GIT_EXEC_PATH`, which
/// locates git's own helper programs. Neither names a repository, an identity,
/// or a configuration, and dropping either makes things worse rather than
/// better. Variables an operator sets deliberately for the whole run —
/// `GIT_CONFIG_COUNT`/`KEY`/`VALUE`, `GIT_SSH_COMMAND`, credential settings —
/// are also left alone: git does not propagate them, so their presence is a
/// choice rather than a leak.
pub const INVOCATION_SCOPING_ENV: &[&str] = &[
    "GIT_AUTHOR_NAME",
    "GIT_AUTHOR_EMAIL",
    "GIT_AUTHOR_DATE",
    "GIT_COMMITTER_NAME",
    "GIT_COMMITTER_EMAIL",
    "GIT_COMMITTER_DATE",
    "GIT_CONFIG_PARAMETERS",
];

/// Every variable a subprocess must not inherit from the git invocation that
/// launched wsb.
pub fn inherited_git_env() -> impl Iterator<Item = &'static &'static str> {
    REPO_SCOPING_ENV.iter().chain(INVOCATION_SCOPING_ENV)
}

/// Build a subprocess that inherits no part of the git invocation that launched
/// wsb — neither which repository it was working in ([`REPO_SCOPING_ENV`]) nor
/// whose operation it was ([`INVOCATION_SCOPING_ENV`]).
///
/// Use this for anything that can reach git: directly, or through a build
/// script, a package manager, or a user-supplied script. Everything wsb spawns
/// names the directory it acts on and the repository it commits to, so
/// inheriting any of these can only ever point it somewhere else.
///
/// The variables are cleared on the child only, never process-wide: wsb reads
/// `GIT_DIR` itself to recognise that it is running inside a hook, so scrubbing
/// its own environment would fix the targeting and break the detection.
pub fn command_without_repo_scope(
    program: impl AsRef<std::ffi::OsStr>,
) -> crate::output::Command {
    let mut command = crate::output::Command::new(program);
    for variable in inherited_git_env() {
        command.env_remove(variable);
    }
    // Which wsb is driving, for the hooks git runs underneath, and for the
    // build scripts that call back into it. See [`self_variables`].
    for (name, path) in self_variables(running_wsb().as_deref()) {
        command.env(name, path);
    }
    command
}

/// A program named by its bare NAME, as this platform starts it.
///
/// On Windows a bare name may be a `.cmd` — `npm` is `npm.cmd` — which
/// `CreateProcess` does not start, and `Command` looks for `<name>.exe` only:
/// installing the JavaScript mirrors' dependencies failed on a Windows guest
/// with `cannot run npm …: program not found`, npm on PATH the whole time. The
/// decision is the test runner's (`interpreter_for`): what the file IS says
/// what reads it.
pub fn program_without_repo_scope(name: &str) -> crate::output::Command {
    let resolved = crate::report::which(name);
    match interpreter_for(resolved.as_deref(), cfg!(windows)) {
        Interpreter::CommandInterpreter => {
            let mut command = command_without_repo_scope("cmd");
            command.arg("/c").arg(resolved.expect("named by the decision"));
            command
        }
        _ => command_without_repo_scope(name),
    }
}

/// What has to read a program for it to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Interpreter {
    /// It starts itself: an executable, or a script on a system with shebangs.
    None,
    /// `cmd /c` — a `.cmd` or `.bat`, which is the command interpreter's.
    CommandInterpreter,
    /// The POSIX shell — a `.sh`, on a system that has no shebang to read.
    PosixShell,
}

/// Which interpreter a resolved program needs, decided by what the file IS.
///
/// Split from building the command so the DECISION can be tested on any host.
/// It is a claim about the target platform, not about the one running the
/// tests, and a `#[cfg]` in the middle of it would make the Windows answer
/// unobservable from a mac — which is exactly how the `.sh` case shipped
/// broken.
///
/// `windows` is the platform the command will run on. On a POSIX system a `.sh`
/// needs nothing: the execute bit and the shebang are both real, so the script
/// starts itself, and wrapping it in a shell would hide which program ran.
pub(crate) fn interpreter_for(resolved: Option<&str>, windows: bool) -> Interpreter {
    let Some(path) = resolved.map(str::to_ascii_lowercase) else {
        return Interpreter::None;
    };
    if path.ends_with(".cmd") || path.ends_with(".bat") {
        return Interpreter::CommandInterpreter;
    }
    if windows && path.ends_with(".sh") {
        return Interpreter::PosixShell;
    }
    Interpreter::None
}

/// The wsb executable this process IS, when it is one.
///
/// Announced by the binary at start-up rather than read from
/// `current_exe()` here. `current_exe()` answers for whatever process links
/// this library — a test binary, a build script, the daemon — and the two
/// variables below are handed to children that will EXECUTE what they name.
/// A test binary that named itself made git run the pre-commit hook as
/// `<test-binary> update --quiet --git-add`, and sixteen fleet-diff tests
/// failed on `error: Unrecognized option: 'git-add'` — a commit refused by a
/// hook running a program that was never wsb.
static RUNNING_WSB: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();

/// Say that this process is that wsb. Called once, by the binary.
pub fn announce_running_wsb(path: PathBuf) {
    let _ = RUNNING_WSB.set(path);
}

fn running_wsb() -> Option<PathBuf> {
    RUNNING_WSB.get().cloned()
}

/// The variables naming the wsb a child should come back to, if any.
///
/// `WSB_SELF` is read by the pre-commit hook, so the update it runs is done by
/// the wsb doing the committing rather than by whichever one is on PATH. That
/// is not hypothetical: a checkpoint from a build tree met the installed wsb
/// in its own hook, which met the build tree's daemon, and all thirty-seven
/// repositories refused with "the running daemon is wsb X and this is wsb Y".
/// The command doing the committing could not commit.
///
/// `WSB_BIN` is the same fact for the build scripts that call back into it. A
/// script resolving `wsb` on PATH finds whichever was installed last, which is
/// how a build signs a bundle with a different version of the tool than the
/// one driving it.
///
/// NONE of them when this process is not wsb. Absent is a state both readers
/// already handle — the hook falls back to PATH, which is right because then
/// there is no other wsb to prefer, and a script that needs `WSB_BIN` fails
/// hard rather than guessing. A WRONG value is handled by neither.
pub fn self_variables(running: Option<&Path>) -> Vec<(&'static str, PathBuf)> {
    match running {
        Some(path) => vec![(SELF_ENV, path.to_path_buf()), ("WSB_BIN", path.to_path_buf())],
        None => Vec::new(),
    }
}

/// The index of the commit currently being prepared, when it belongs to `repo`.
///
/// This is the one thing wsb must inherit rather than refuse. A pre-commit hook
/// is handed `GIT_INDEX_FILE` naming the index the commit in progress is being
/// built in, and `wsb update --git-add` exists precisely to put the regenerated
/// `version.txt` into *that* commit. Staging into the repository's default index
/// instead would leave the file out of the commit that triggered the hook.
///
/// It is honoured only for the repository the index actually belongs to. A fleet
/// commit launched from a superproject's hook stages many repositories, and
/// writing each one into the superproject's pending index would corrupt the
/// commit being prepared. When the index cannot be attributed to a repository at
/// all this fails rather than guessing, since both answers are destructive in
/// different directions.
fn pending_index_for(repo: &gix::Repository) -> Result<Option<std::ffi::OsString>> {
    let Some(raw) = std::env::var_os("GIT_INDEX_FILE") else {
        return Ok(None);
    };

    // Git resolves a relative GIT_INDEX_FILE against the working directory, so
    // this must too — a hook is commonly handed the bare `.git/index`.
    let named = PathBuf::from(&raw);
    let absolute = if named.is_absolute() {
        named
    } else {
        std::env::current_dir()
            .context("Cannot resolve a relative GIT_INDEX_FILE without a current directory")?
            .join(named)
    };

    // The index file itself may not exist yet; its directory does.
    let parent = absolute
        .parent()
        .with_context(|| format!("GIT_INDEX_FILE '{}' names no file", absolute.display()))?;
    let directory = crate::platform::canonicalize(parent)
        .with_context(|| {
            format!(
                "GIT_INDEX_FILE names '{}', whose directory does not exist, so it \
                 cannot be attributed to a repository",
                absolute.display()
            )
        })?;

    // The index must live in THIS repository's git dir — exactly, not under
    // it.
    //
    // `starts_with` was the bug, and a bad one. A submodule's git dir lives
    // INSIDE the superproject's: `fabricloom`'s index is
    // `<root>/.git/modules/fabricloom/index`, which starts with the root's
    // `.git`. So when a commit in a submodule ran the pre-commit hook, git
    // handed it that submodule's `GIT_INDEX_FILE`, wsb resolved the workspace
    // to the SUPERPROJECT, rendered the superproject's templates — and this
    // said yes, staging `mg-test/harness/guest-requirements.txt`, `version.txt`
    // and two more root files into the SUBMODULE's index.
    //
    // Those entries name blobs in the root's object database, which the
    // submodule does not have. The submodule was then unable to build trees at
    // all, and the superproject's own commit failed with
    //
    //     error: invalid object 100644 7e76d99… for 'mg-test/harness/…'
    //     error: Error building trees
    //
    // naming a file whose repository was not the one being committed.
    //
    // Exact equality is right for every case there is: a plain repository's
    // index sits in its git dir, a submodule's in its own, and a linked
    // worktree's in `.git/worktrees/<name>` — which IS that worktree's git
    // dir. The common dir is deliberately not accepted: in a linked worktree
    // it is the main `.git`, and taking the main worktree's index for this
    // one is the same class of mistake in a different direction.
    let Ok(mine) = crate::platform::canonicalize(&repo.git_dir()) else {
        return Ok(None);
    };
    if directory == mine {
        return Ok(Some(raw));
    }
    Ok(None)
}

/// A `git add` that writes to the commit being prepared, when there is one.
///
/// Everything else wsb runs is an independent operation and uses
/// [`git_command`]; staging is the sole place that deliberately continues the
/// invocation that launched it. See [`pending_index_for`].
fn git_add_command(repo: &gix::Repository) -> Result<crate::output::Command> {
    let mut command = git_command();
    if let Some(index) = pending_index_for(repo)? {
        command.env("GIT_INDEX_FILE", index);
    }
    Ok(command)
}

/// A `git` command aimed only by the directory it is given.
///
/// Every `git` subprocess in wsb is built here. Constructing one directly
/// reintroduces the inheritance described on [`REPO_SCOPING_ENV`], which
/// `subprocess_isolation_tests` fails the build over.
pub fn git_command() -> crate::output::Command {
    command_without_repo_scope("git") // NAMES-GIT: the one place
}

pub fn discover_repo(path: &Path) -> Result<gix::Repository> {
    gix::discover(path)
        .with_context(|| format!("Failed to discover git repository from {}", path.display()))
}

pub fn is_git_repository(path: &Path) -> bool {
    gix::discover(path).is_ok()
}

pub fn repo_root(path: &Path) -> Result<PathBuf> {
    let repo = discover_repo(path)?;
    repo.workdir()
        .map(Path::to_path_buf)
        .or_else(|| repo.git_dir().parent().map(Path::to_path_buf))
        .context("Discovered repository does not expose a usable root path")
}

pub fn init_repository(path: &Path) -> Result<gix::Repository> {
    let output = git_command()
        .args(["init"])
        .current_dir(path)
        .output()
        .context("Failed to execute git init")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git init failed: {}", stderr.trim());
    }

    open_repo(path)
}

pub fn configure_local_user(repo: &gix::Repository, name: &str, email: &str) -> Result<()> {
    let config_path = repo.git_dir().join("config");
    let existing = fs::read_to_string(&config_path).with_context(|| {
        format!(
            "Failed to read repository config at {}",
            config_path.display()
        )
    })?;
    let user_block = format!("[user]\n\tname = {name}\n\temail = {email}\n");
    let updated = replace_or_append_config_section(&existing, "user", &user_block);
    fs::write(&config_path, updated).with_context(|| {
        format!(
            "Failed to write repository config at {}",
            config_path.display()
        )
    })
}

pub fn open_repo(path: &Path) -> Result<gix::Repository> {
    gix::open(path).with_context(|| format!("Failed to open git repository at {}", path.display()))
}

pub fn current_branch(repo: &gix::Repository) -> Result<String> {
    let head = repo.head().context("Failed to read HEAD")?;
    if head.is_detached() {
        bail!("Detached HEAD");
    }

    let name = head
        .referent_name()
        .context("HEAD is not attached to a branch")?
        .shorten()
        .to_string();
    Ok(name)
}

pub fn is_detached_head(repo: &gix::Repository) -> Result<bool> {
    Ok(repo.head().context("Failed to read HEAD")?.is_detached())
}

pub fn remote_url(repo: &gix::Repository, remote_name: &str) -> Result<String> {
    let remote = repo
        .find_remote(remote_name)
        .with_context(|| format!("Remote '{remote_name}' not found"))?;
    let url = remote
        .url(remote::Direction::Fetch)
        .context("Remote does not have a fetch URL configured")?;
    Ok(url.to_bstring().to_string())
}

pub fn branch_exists(repo: &gix::Repository, branch_name: &str, kind: BranchKind) -> Result<bool> {
    let full_name = match kind {
        BranchKind::Local => format!("refs/heads/{branch_name}"),
        BranchKind::Remote => format!("refs/remotes/{branch_name}"),
    };
    Ok(repo
        .try_find_reference(full_name.as_str())
        .context("Failed to query branch reference")?
        .is_some())
}

pub fn local_branches(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut branches: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .local_branches()
        .context("Failed to list local branches")?
        .flatten()
        .map(|branch| branch.name().shorten().to_string())
        .collect();
    branches.sort();
    Ok(branches)
}

pub fn remote_branches(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut branches: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .remote_branches()
        .context("Failed to list remote branches")?
        .flatten()
        .map(|branch| branch.name().shorten().to_string())
        .collect();
    branches.sort();
    Ok(branches)
}

pub fn remotes(repo: &gix::Repository) -> Result<Vec<String>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote listing")?;

    let output = git_command()
        .args(["remote"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git remote")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git remote failed: {}", stderr.trim());
    }

    let remotes: Vec<String> = String::from_utf8(output.stdout)
        .context("git remote output is not valid UTF-8")?
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect();

    if remotes.is_empty() {
        bail!("No remotes configured");
    }

    Ok(remotes)
}

pub fn is_clean(repo: &gix::Repository) -> Result<bool> {
    let entries = status_entries(repo)?;
    Ok(entries
        .iter()
        .all(|entry| entry.status == FileStatusKind::Ignored))
}

pub fn has_uncommitted_changes(entries: &[StatusEntry]) -> bool {
    entries
        .iter()
        .any(|entry| entry.status != FileStatusKind::Ignored)
}

/// Returns the unified diff of `rel_path` against HEAD (worktree vs last commit).
/// For staged files, includes both staged and unstaged changes relative to HEAD.
/// Returns an empty string if the path has no changes relative to HEAD.
pub fn diff_file(repo: &gix::Repository, rel_path: &str) -> Result<String> {
    let workdir = repo
        .workdir()
        .context("bare repositories are not supported for diff")?;

    // `git diff HEAD -- <path>` covers unstaged changes against HEAD.
    // `git diff --cached HEAD -- <path>` covers staged changes against HEAD.
    // Running both and concatenating gives the full picture from HEAD.
    let unstaged = git_command()
        .args(["diff", "HEAD", "--", rel_path])
        .current_dir(workdir)
        .output()
        .context("failed to execute git diff")?;

    if !unstaged.status.success() {
        let stderr = String::from_utf8_lossy(&unstaged.stderr);
        bail!("git diff failed: {}", stderr.trim());
    }

    let unstaged_text =
        String::from_utf8(unstaged.stdout).context("git diff output is not valid UTF-8")?;

    // If unstaged already has output we are done — it covers the worktree vs HEAD.
    // If empty, the file may be fully staged; check the index vs HEAD.
    if !unstaged_text.is_empty() {
        return Ok(unstaged_text);
    }

    let staged = git_command()
        .args(["diff", "--cached", "HEAD", "--", rel_path])
        .current_dir(workdir)
        .output()
        .context("failed to execute git diff --cached")?;

    if !staged.status.success() {
        let stderr = String::from_utf8_lossy(&staged.stderr);
        bail!("git diff --cached failed: {}", stderr.trim());
    }

    String::from_utf8(staged.stdout).context("git diff --cached output is not valid UTF-8")
}

/// Returns `true` if `dir` (an absolute path) contains at least one file that
/// is **not** gitignored.  Uses the `ignore` crate which honours nested
/// `.gitignore` files.  An empty directory (or one with only empty subdirs)
/// returns `false`.
fn dir_has_non_ignored_files(dir: &Path) -> bool {
    if !dir.is_dir() {
        return true; // not a directory → treat as real content
    }
    let walker = WalkBuilder::new(dir)
        .hidden(false) // don't skip dotfiles — git doesn't
        .git_ignore(true) // respect .gitignore
        .git_global(true) // respect global gitignore
        .git_exclude(true) // respect .git/info/exclude
        .build();
    for entry in walker {
        let Ok(entry) = entry else { continue };
        if entry.file_type().is_some_and(|kind| kind.is_file()) {
            return true;
        }
    }
    false
}

/// Whether an untracked dirwalk entry is something git would actually report.
///
/// gix emits a directory as untracked even when it holds nothing git could ever
/// track — it is empty, contains only empty subdirectories, or everything in it
/// is ignored. Git has no concept of an empty directory and reports none of
/// these, so neither do we.
///
/// `workdir` is the working directory `entry.rela_path` is relative to.
fn untracked_entry_is_reportable(workdir: &Path, entry: &gix::dir::Entry) -> bool {
    if entry.disk_kind.is_some_and(|kind| kind.is_dir()) {
        dir_has_non_ignored_files(&workdir.join(entry.rela_path.to_string()))
    } else {
        true
    }
}

/// Whether a submodule gix reported as modified has actually changed.
///
/// gix marks a submodule modified when anything at all turns up in its worktree
/// walk, including an untracked directory that git would never report. Without
/// this check a repository calls its own submodule dirty while reporting that
/// same submodule as clean when asked about it directly — and `pull` then skips
/// a tree that has nothing to lose.
///
/// `workdir` is the submodule's own working directory.
fn submodule_modification_is_reportable(workdir: &Path, status: &gix::submodule::Status) -> bool {
    // The gitlink pointing somewhere other than the checked-out HEAD is a real
    // change no matter what the worktree looks like.
    if status.index_id != status.checked_out_head_id {
        return true;
    }
    match &status.changes {
        // The walk was skipped: no clone, or no worktree. Not a local change.
        None => false,
        Some(changes) => changes
            .iter()
            .any(|item| status_item_is_reportable(workdir, item)),
    }
}

/// Whether one status item is a change git would report.
///
/// Submodule changes nest — a submodule's own changes are themselves status
/// items — so this recurses, and the same rules decide at every depth.
fn status_item_is_reportable(workdir: &Path, item: &status::Item) -> bool {
    match item {
        // A difference between HEAD and the index is always a staged change.
        status::Item::TreeIndex(_) => true,
        status::Item::IndexWorktree(item) => match item {
            index_worktree::Item::Modification {
                rela_path, status, ..
            } => match status {
                EntryStatus::Change(WorktreeChange::SubmoduleModification(submodule)) => {
                    submodule_modification_is_reportable(
                        &workdir.join(rela_path.to_string()),
                        submodule,
                    )
                }
                _ => true,
            },
            index_worktree::Item::DirectoryContents { entry, .. } => match entry.status {
                gix::dir::entry::Status::Untracked => untracked_entry_is_reportable(workdir, entry),
                // Ignored content is not a change, and tracked or pruned entries
                // are not reported as one.
                gix::dir::entry::Status::Ignored(_)
                | gix::dir::entry::Status::Tracked
                | gix::dir::entry::Status::Pruned => false,
            },
            index_worktree::Item::Rewrite { .. } => true,
        },
    }
}

pub fn status_entries(repo: &gix::Repository) -> Result<Vec<StatusEntry>> {
    // gix status reads .gitmodules internally. Validate it first so we can
    // surface a clear, actionable error instead of a cryptic parse failure.
    if let Some(workdir) = repo.workdir() {
        let gitmodules = workdir.join(".gitmodules");
        if gitmodules.exists() {
            let bytes = std::fs::read(&gitmodules)
                .with_context(|| format!("failed to read {}", gitmodules.display()))?;
            validate_gitmodules_structure(&bytes, &gitmodules)?;
        }
    }

    // Track staged paths (TreeIndex) and worktree paths separately so we can
    // classify correctly.  A path in TreeIndex only → Staged.  A path in
    // IndexWorktree only → Modified/Untracked/etc.  A path in both → Modified
    // (has both staged and unstaged changes — the unstaged state dominates for
    // display purposes, matching VS Code behaviour).
    let workdir = repo
        .workdir()
        .context("bare repository has no working directory")?
        .to_path_buf();

    let mut staged: BTreeSet<String> = BTreeSet::new();
    let mut worktree: std::collections::BTreeMap<String, FileStatusKind> =
        std::collections::BTreeMap::new();
    // The paths that are submodules whose gitlink has moved.
    let mut submodules: BTreeSet<String> = BTreeSet::new();

    let mut platform = repo
        .status(gix::progress::Discard)
        .context("Failed to initialise status")?;
    platform.dirwalk_options_mut(|opts| {
        // Collapse ignored entries to directory level (e.g. "target/" instead of
        // individual files inside it).
        opts.set_emit_ignored(Some(gix::dir::walk::EmissionMode::CollapseDirectory));
        // Collapse untracked entries to directory level.  This prevents reporting
        // directories as "untracked" when they only contain ignored files or empty
        // subdirectories — matching what `git status` actually reports.
        opts.set_emit_untracked(gix::dir::walk::EmissionMode::CollapseDirectory);
    });

    let iter = platform
        .into_iter(Vec::<BString>::new())
        .context("Failed to compute repository status")?;
    for item in iter {
        match item.context("Failed to inspect status entry")? {
            status::Item::TreeIndex(change) => match change {
                gix::diff::index::Change::Addition { location, .. }
                | gix::diff::index::Change::Modification { location, .. } => {
                    staged.insert(location.to_string());
                }
                gix::diff::index::Change::Deletion { location, .. } => {
                    worktree.insert(location.to_string(), FileStatusKind::Deleted);
                }
                gix::diff::index::Change::Rewrite {
                    source_location,
                    location,
                    ..
                } => {
                    worktree.insert(source_location.to_string(), FileStatusKind::Deleted);
                    worktree.insert(location.to_string(), FileStatusKind::Renamed);
                }
            },
            status::Item::IndexWorktree(entry) => match entry {
                index_worktree::Item::Modification {
                    ref rela_path,
                    status: ref entry_status,
                    ..
                } => {
                    // A submodule gix calls modified may hold nothing git would
                    // report. Decided by the same rules used for this repository's
                    // own entries, so a submodule is never dirty here and clean
                    // when inspected directly.
                    if let EntryStatus::Change(WorktreeChange::SubmoduleModification(submodule)) =
                        entry_status
                    {
                        if !submodule_modification_is_reportable(
                            &workdir.join(rela_path.to_string()),
                            submodule,
                        ) {
                            continue;
                        }
                        // Remembered so the entry can say what KIND of pending
                        // change it is. A moved gitlink and an edited file both
                        // arrive here as `Modified`, and callers need to tell
                        // them apart.
                        submodules.insert(rela_path.to_string());
                    }

                    match entry.summary() {
                        Some(IndexWorktreeSummary::Conflict) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Conflict);
                        }
                        Some(IndexWorktreeSummary::Removed) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Deleted);
                        }
                        Some(IndexWorktreeSummary::TypeChange)
                        | Some(IndexWorktreeSummary::Modified)
                        | Some(IndexWorktreeSummary::Copied) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Modified);
                        }
                        Some(IndexWorktreeSummary::IntentToAdd) => {
                            staged.insert(rela_path.to_string());
                        }
                        Some(IndexWorktreeSummary::Added) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Untracked);
                        }
                        Some(IndexWorktreeSummary::Renamed) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Renamed);
                        }
                        None => {}
                    }
                }
                index_worktree::Item::DirectoryContents {
                    entry,
                    collapsed_directory_status: _,
                } => {
                    let status = match entry.status {
                        gix::dir::entry::Status::Untracked => {
                            if untracked_entry_is_reportable(&workdir, &entry) {
                                Some(FileStatusKind::Untracked)
                            } else {
                                None
                            }
                        }
                        gix::dir::entry::Status::Ignored(_) => Some(FileStatusKind::Ignored),
                        gix::dir::entry::Status::Tracked | gix::dir::entry::Status::Pruned => None,
                    };

                    if let Some(status) = status {
                        worktree.insert(entry.rela_path.to_string(), status);
                    }
                }
                index_worktree::Item::Rewrite {
                    dirwalk_entry,
                    source,
                    ..
                } => {
                    worktree.insert(dirwalk_entry.rela_path.to_string(), FileStatusKind::Renamed);
                    worktree.insert(source.rela_path().to_string(), FileStatusKind::Deleted);
                }
            },
        }
    }

    // Merge: worktree status wins if a path is in both sets.
    let mut result: std::collections::BTreeMap<String, FileStatusKind> =
        std::collections::BTreeMap::new();

    for path in &staged {
        if let Some(wt_status) = worktree.get(path) {
            // Path has both staged and worktree changes — show worktree kind
            result.insert(path.clone(), *wt_status);
        } else {
            result.insert(path.clone(), FileStatusKind::Staged);
        }
    }
    for (path, kind) in &worktree {
        result.entry(path.clone()).or_insert(*kind);
    }

    Ok(result
        .into_iter()
        .map(|(path, status)| StatusEntry {
            submodule_pointer: submodules.contains(&path),
            path,
            status,
        })
        .collect())
}

pub fn get_default_branch(repo: &gix::Repository) -> Result<String> {
    for branch in ["main", "master"] {
        if branch_exists(repo, branch, BranchKind::Local)? {
            return Ok(branch.to_string());
        }
    }
    local_branches(repo)?
        .into_iter()
        .next()
        .context("No branches found")
}

pub fn fetch(repo: &gix::Repository, remote_name: Option<&str>) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;

    let remote = remote_name.unwrap_or("origin");
    let output = git_command()
        .args(["fetch", remote])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git fetch")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git fetch failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn fetch_remote_branch(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;
    let refspec = format!("{branch_name}:refs/remotes/{remote_name}/{branch_name}");

    let output = git_command()
        .args(["fetch", remote_name, &refspec])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to execute git fetch for {remote_name}/{branch_name}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git fetch failed for {remote_name}/{branch_name}: {}",
            stderr.trim()
        );
    }

    Ok(())
}

pub fn fetch_all(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;

    let output = git_command()
        .args(["fetch", "--all"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git fetch --all")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git fetch --all failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn remote_branch_head(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<Option<gix::ObjectId>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote inspection")?;
    let ref_name = format!("refs/heads/{branch_name}");

    let output = git_command()
        .args(["ls-remote", "--heads", remote_name, &ref_name])
        .current_dir(workdir)
        .output()
        .with_context(|| {
            format!("Failed to execute git ls-remote for {remote_name}/{branch_name}")
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git ls-remote failed for {remote_name}/{branch_name}: {}",
            stderr.trim()
        );
    }

    let stdout =
        String::from_utf8(output.stdout).context("git ls-remote output is not valid UTF-8")?;
    let line = stdout.trim();
    if line.is_empty() {
        return Ok(None);
    }

    let oid_text = line
        .split_whitespace()
        .next()
        .context("git ls-remote output did not contain an object id")?;
    let oid = gix::ObjectId::from_hex(oid_text.as_bytes())
        .with_context(|| format!("Remote object id '{oid_text}' is invalid"))?;
    Ok(Some(oid))
}

pub fn remote_refs(
    repo: &gix::Repository,
    remote_name: &str,
) -> Result<Vec<(String, gix::ObjectId)>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote inspection")?;

    let output = git_command()
        .args(["ls-remote", "--heads", "--tags", remote_name])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to execute git ls-remote for {remote_name}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git ls-remote failed for {remote_name}: {}", stderr.trim());
    }

    let stdout =
        String::from_utf8(output.stdout).context("git ls-remote output is not valid UTF-8")?;
    let mut refs = Vec::new();
    for line in stdout.lines().filter(|line| !line.trim().is_empty()) {
        let mut fields = line.split_whitespace();
        let oid_text = fields
            .next()
            .context("git ls-remote output did not contain an object id")?;
        let ref_name = fields
            .next()
            .context("git ls-remote output did not contain a ref name")?;
        if ref_name.ends_with("^{}") {
            continue;
        }
        let oid = gix::ObjectId::from_hex(oid_text.as_bytes())
            .with_context(|| format!("Remote object id '{oid_text}' is invalid"))?;
        refs.push((ref_name.to_string(), oid));
    }
    Ok(refs)
}

pub fn local_remote_tracking_head(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<Option<gix::ObjectId>> {
    let ref_name = format!("refs/remotes/{remote_name}/{branch_name}");
    match repo.try_find_reference(ref_name.as_str()) {
        Ok(Some(mut reference)) => Ok(Some(
            reference
                .peel_to_id()
                .context("Failed to peel local remote-tracking reference")?
                .detach(),
        )),
        Ok(None) => Ok(None),
        Err(err) => {
            Err(anyhow::Error::from(err)
                .context("Failed to inspect local remote-tracking reference"))
        }
    }
}

pub fn current_branch_remote(repo: &gix::Repository, default_remote: &str) -> Result<String> {
    let head = repo.head().context("Failed to read HEAD")?;
    let branch = head
        .referent_name()
        .context("Detached HEAD is not supported")?;
    if let Some(remote) = repo
        .branch_remote(branch.shorten(), gix::remote::Direction::Fetch)
        .transpose()
        .context("Failed to determine branch remote")?
    {
        return remote
            .name()
            .and_then(|name| name.as_symbol())
            .map(ToOwned::to_owned)
            .context("Remote name must be symbolic");
    }
    repo.find_remote(default_remote)
        .with_context(|| format!("Remote '{default_remote}' not found"))?;
    Ok(default_remote.to_string())
}

/// Where a branch stands against its remote.
///
/// Four states, because a boolean cannot express the fifth thing that actually
/// happens: BOTH sides having commits the other does not. `wsb pull` used to
/// ask "are there incoming commits" and read a diverged branch as "no" — so a
/// tree that was one commit behind and one commit ahead was reported as
/// nothing to do, and the summary said everything succeeded while the
/// superproject stayed behind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemoteState {
    /// The remote has no such branch. Everything here is outgoing.
    NoRemoteBranch,
    UpToDate,
    /// The remote's commits descend from this branch: a fast-forward.
    Behind { incoming: u32 },
    /// This branch's commits descend from the remote's: nothing to take.
    Ahead { outgoing: u32 },
    /// Both sides moved. Behind AND ahead: there is something to take, and it
    /// cannot be taken by fast-forward.
    Diverged { incoming: u32, outgoing: u32 },
}

impl RemoteState {
    /// Whether there are commits on the remote this branch does not have.
    ///
    /// True for a diverged branch — which is the whole point of this type.
    pub fn has_incoming(self) -> bool {
        matches!(self, Self::Behind { .. } | Self::Diverged { .. })
    }

    /// Whether this branch has commits the remote does not.
    pub fn has_outgoing(self) -> bool {
        matches!(
            self,
            Self::NoRemoteBranch | Self::Ahead { .. } | Self::Diverged { .. }
        )
    }

    pub fn describe(self) -> String {
        match self {
            Self::NoRemoteBranch => "no such branch on the remote".to_string(),
            Self::UpToDate => "up to date".to_string(),
            Self::Behind { incoming } => format!("{incoming} commit(s) behind"),
            Self::Ahead { outgoing } => format!("{outgoing} commit(s) ahead"),
            Self::Diverged {
                incoming,
                outgoing,
            } => format!("diverged: {incoming} incoming, {outgoing} local"),
        }
    }
}

/// Fetch the branch's remote counterpart, then say where the branch stands.
///
/// The fetch is not an optimisation, it is what makes the answer knowable:
/// ancestry is a question about commits, and a commit this clone has never
/// downloaded cannot answer it. The previous version asked `ls-remote` for the
/// remote tip and then tried to compute a merge base against that object —
/// which is not in the object database until something fetches it. It
/// therefore failed with "Cannot prove remote branch 'origin/main' is ahead of
/// local HEAD" for every repository whose HEAD was not exactly its last-known
/// remote tip, i.e. every repository with a local commit.
pub fn remote_state(repo: &gix::Repository, remote_name: Option<&str>) -> Result<RemoteState> {
    let branch = current_branch(repo)?;
    let remote = current_branch_remote(repo, remote_name.unwrap_or("origin"))?;

    if let Err(fetch_error) = fetch_remote_branch(repo, &remote, &branch) {
        // A branch that is not on the remote is a STATE, not a failure — it is
        // what an unpushed branch looks like. Anything else is a real fetch
        // failure and is reported as one rather than read as "nothing there".
        return match remote_branch_head(repo, &remote, &branch) {
            Ok(None) => Ok(RemoteState::NoRemoteBranch),
            _ => Err(fetch_error),
        };
    }

    let head_id = repo.head_id().context("Failed to resolve HEAD")?.detach();
    let tracking = format!("refs/remotes/{remote}/{branch}");
    let Some(tracking_id) = local_remote_tracking_head(repo, &remote, &branch)? else {
        // The fetch succeeded, so the ref it writes must exist. Its absence is
        // not a state to reason further from.
        bail!("git fetch left no {tracking} to compare against");
    };

    if head_id == tracking_id {
        return Ok(RemoteState::UpToDate);
    }

    let merge_base = repo
        .merge_base(head_id, tracking_id)
        .with_context(|| format!("Failed to compute merge base against {tracking}"))?;
    let (outgoing, incoming) = commit_gap(repo, &tracking)?;

    Ok(if merge_base == head_id {
        RemoteState::Behind { incoming }
    } else if merge_base == tracking_id {
        RemoteState::Ahead { outgoing }
    } else {
        RemoteState::Diverged {
            incoming,
            outgoing,
        }
    })
}

/// How many commits each side has that the other does not: `(local, remote)`.
///
/// Through `git rev-list --left-right --count`, which is exact across merges —
/// an ancestor walk that stops at the first sight of the other tip counts
/// commits reachable by another parent as well.
fn commit_gap(repo: &gix::Repository, tracking: &str) -> Result<(u32, u32)> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote comparison")?;
    let range = format!("HEAD...{tracking}");
    let output = git_command()
        .args(["rev-list", "--left-right", "--count", &range])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git rev-list")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git rev-list failed for {range}: {}", stderr.trim());
    }
    let text = String::from_utf8(output.stdout).context("git rev-list output is not valid UTF-8")?;
    let mut counts = text.split_whitespace();
    let left = counts
        .next()
        .and_then(|v| v.parse().ok())
        .with_context(|| format!("git rev-list gave no local count for {range}"))?;
    let right = counts
        .next()
        .and_then(|v| v.parse().ok())
        .with_context(|| format!("git rev-list gave no remote count for {range}"))?;
    Ok((left, right))
}

pub fn has_fetchable_updates(repo: &gix::Repository, all_remotes: bool) -> Result<bool> {
    let remote_names = if all_remotes {
        remotes(repo)?
    } else {
        vec!["origin".to_string()]
    };

    for remote in remote_names {
        repo.find_remote(remote.as_str())
            .with_context(|| format!("Remote '{remote}' not found"))?;
        for (remote_ref, remote_id) in remote_refs(repo, &remote)? {
            let Some(branch_name) = remote_ref.strip_prefix("refs/heads/") else {
                return Ok(true);
            };
            match local_remote_tracking_head(repo, &remote, branch_name)? {
                Some(local_id) if local_id == remote_id => {}
                _ => return Ok(true),
            }
        }
    }

    Ok(false)
}

/// What a pull did, or why it did nothing.
///
/// A pull that took nothing is not a pull that failed, and a pull that COULD
/// NOT take what is there is neither — the three used to collapse into one
/// "skipped", which is how a diverged superproject was reported as up to date.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PullOutcome {
    NoRemoteBranch,
    UpToDate,
    /// Took the incoming commits. `discarded` names local changes thrown away
    /// to make room and `restored` names ones set aside and put back; both are
    /// empty unless the caller asked for one of those.
    FastForwarded {
        commits: u32,
        discarded: Vec<String>,
        restored: Vec<String>,
    },
    Rebased { commits: u32 },
    /// Nothing to take; this branch is ahead of the remote.
    Ahead { outgoing: u32 },
    /// There are commits to take and they cannot be fast-forwarded. NOT an
    /// error — the working tree is untouched and valid — and NOT nothing to
    /// do. The caller must say so.
    Diverged { incoming: u32, outgoing: u32 },
    /// The incoming commits rewrite files this tree has changed, so the merge
    /// would throw those changes away and git refused. Nothing happened; these
    /// are the files in the way.
    ///
    /// A state rather than an error because it is ordinary and it is fixable:
    /// this workspace regenerates `version.txt` and the manifests beside it on
    /// every build, so a machine that has built since its last pull meets this
    /// every time.
    LocalChangesBlock {
        incoming: u32,
        paths: Vec<String>,
        /// Blocking paths git does not track. These are NOT discardable by
        /// [`PullOptions::overwrite_local`] — git holds no copy to restore, so
        /// deleting them is unrecoverable and is left to a person.
        untracked: Vec<String>,
    },
    /// The incoming commits were taken, but the set-aside local changes could
    /// not be replayed on top of them: the same lines moved on both sides.
    ///
    /// Nothing is lost — the changes are in the named stash entry — and
    /// nothing is left half-applied: the conflicted paths were returned to the
    /// merged content.
    AutostashConflict {
        incoming: u32,
        paths: Vec<String>,
        /// The stash entry holding the local changes.
        stash: String,
    },
}

/// How a pull should behave where it has a choice.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullOptions {
    /// Replay local commits on top of incoming ones instead of refusing a
    /// diverged branch.
    pub rebase: bool,
    /// Throw away local changes to the files the incoming commits rewrite, and
    /// only those files. Everything else this tree has changed is left alone —
    /// "get past this" must not mean "reset my working tree".
    pub overwrite_local: bool,
    /// Set those same changes aside, take the incoming commits, and put them
    /// back on top. Keeps what `overwrite_local` throws away.
    pub autostash: bool,
}

/// Fetch, then take what can be taken.
///
/// One fetch, one decision: [`remote_state`] already brought the remote's
/// commits into this clone, so the merge below is a local operation and cannot
/// disagree with the state that chose it.
pub fn pull(repo: &gix::Repository, options: PullOptions) -> Result<PullOutcome> {
    let state = remote_state(repo, None)?;
    Ok(match state {
        RemoteState::NoRemoteBranch => PullOutcome::NoRemoteBranch,
        RemoteState::UpToDate => PullOutcome::UpToDate,
        RemoteState::Ahead { outgoing } => PullOutcome::Ahead { outgoing },
        // A rebase of a branch that is merely behind IS a fast-forward, and
        // running `git rebase` for it would rewrite nothing while reporting
        // something else.
        RemoteState::Behind { incoming } => take_incoming(repo, incoming, options)?,
        RemoteState::Diverged {
            incoming,
            outgoing,
        } => {
            if options.rebase {
                rebase_onto_tracking(repo)?;
                PullOutcome::Rebased { commits: incoming }
            } else {
                PullOutcome::Diverged {
                    incoming,
                    outgoing,
                }
            }
        }
    })
}

/// Fast-forward, and deal with local changes standing in the way.
fn take_incoming(
    repo: &gix::Repository,
    incoming: u32,
    options: PullOptions,
) -> Result<PullOutcome> {
    let blocked = match fast_forward_to_tracking(repo) {
        Ok(()) => {
            return Ok(PullOutcome::FastForwarded {
                commits: incoming,
                discarded: Vec::new(),
                restored: Vec::new(),
            })
        }
        // Only THIS refusal is a working-tree collision. Any other failure is
        // a real one and is raised, not translated into a state.
        Err(err) => match overwritten_paths(&err.to_string()) {
            Some(paths) => paths,
            None => return Err(err),
        },
    };

    let (tracked, untracked) = split_tracked(repo, &blocked)?;

    // An untracked file whose content is EXACTLY what the merge would write is
    // not work in the way, and refusing over it helps nobody: after the merge
    // that path holds those bytes either way. This is the ordinary state after
    // peer continuity has carried a file that the other machine then
    // committed — the content arrived first, and git will not overwrite an
    // untracked file with an identical one.
    //
    // Removed only when the bytes match, and only for a path the merge itself
    // is bringing. Anything else is work, and work is never removed here.
    let identical = identical_incoming(repo, &untracked)?;
    if !identical.is_empty() && identical.len() == untracked.len() {
        for path in &identical {
            let absolute = repo
                .workdir()
                .ok_or_else(|| anyhow::anyhow!("bare repositories have no working tree"))?
                .join(path);
            std::fs::remove_file(&absolute)
                .with_context(|| format!("cannot remove {}", absolute.display()))?;
        }
        if tracked.is_empty() {
            // Nothing else was in the way: the merge can proceed as it would
            // have if those files had never been written.
            fast_forward_to_tracking(repo)?;
            return Ok(PullOutcome::FastForwarded {
                commits: incoming,
                discarded: Vec::new(),
                restored: Vec::new(),
            });
        }
    }
    let untracked: Vec<String> = untracked
        .into_iter()
        .filter(|path| !identical.contains(path))
        .collect();
    // An untracked file cannot be set aside or thrown away on anyone's behalf:
    // git holds no copy of it, so both options would be unrecoverable.
    if untracked.is_empty() && options.autostash {
        return autostash_then_take(repo, incoming, &tracked);
    }
    if untracked.is_empty() && options.overwrite_local {
        // Restore exactly the blocking paths from HEAD — index and working
        // tree both, since a staged change blocks the merge just as an
        // unstaged one does. Nothing outside this list is touched.
        restore_from_head(repo, &tracked)?;
        fast_forward_to_tracking(repo)?;
        return Ok(PullOutcome::FastForwarded {
            commits: incoming,
            discarded: tracked,
            restored: Vec::new(),
        });
    }

    Ok(PullOutcome::LocalChangesBlock {
        incoming,
        paths: tracked,
        untracked,
    })
}

/// Set the blocking changes aside, fast-forward, put them back.
///
/// The stash is limited to the blocking paths. Stashing the whole tree would
/// mean an unrelated edit elsewhere rode along, and any failure after that
/// point would be a failure holding work nobody asked it to hold.
fn autostash_then_take(
    repo: &gix::Repository,
    incoming: u32,
    paths: &[String],
) -> Result<PullOutcome> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for pull")?
        .to_path_buf();

    let mut stash_args: Vec<String> = vec![
        "stash".to_string(),
        "push".to_string(),
        "--message".to_string(),
        "wsb pull autostash".to_string(),
        "--".to_string(),
    ];
    stash_args.extend(paths.iter().cloned());
    let stashed = git_command()
        .args(&stash_args)
        .current_dir(&workdir)
        .output()
        .context("Failed to execute git stash push")?;
    if !stashed.status.success() {
        bail!(
            "git stash of {} failed: {}",
            paths.join(", "),
            String::from_utf8_lossy(&stashed.stderr).trim()
        );
    }

    // With the blockers set aside the merge has nothing to collide with. If it
    // still fails, the changes are put back before the failure is raised —
    // leaving them in a stash the caller never asked for would be work hidden
    // by an error message.
    if let Err(merge_error) = fast_forward_to_tracking(repo) {
        let restore = git_command()
            .args(["stash", "pop"])
            .current_dir(&workdir)
            .output()
            .context("Failed to execute git stash pop")?;
        if !restore.status.success() {
            bail!(
                "the merge failed ({merge_error}), and restoring your set-aside changes \
                 failed too ({}) — they are in `git stash list` as \"wsb pull autostash\"",
                String::from_utf8_lossy(&restore.stderr).trim()
            );
        }
        return Err(merge_error);
    }

    let popped = git_command()
        .args(["stash", "pop"])
        .current_dir(&workdir)
        .output()
        .context("Failed to execute git stash pop")?;
    if popped.status.success() {
        return Ok(PullOutcome::FastForwarded {
            commits: incoming,
            discarded: Vec::new(),
            restored: paths.to_vec(),
        });
    }

    // A conflicted pop keeps the stash entry, so nothing is lost. What it does
    // leave is conflict markers in the working tree; those paths are returned
    // to the merged content so the repository is in a state every other
    // command understands, and the operator is told where their work is.
    restore_from_head(repo, paths)?;
    Ok(PullOutcome::AutostashConflict {
        incoming,
        paths: paths.to_vec(),
        stash: "stash@{0}".to_string(),
    })
}

/// The files git named as standing in the way of a merge.
///
/// Git prints them one per line, indented, between a known first line and a
/// closing instruction. Returning `None` for any other message is what keeps
/// an unrelated failure from being reported as a working-tree collision.
fn overwritten_paths(message: &str) -> Option<Vec<String>> {
    let start = message.find("would be overwritten by merge:")?;
    let mut paths = Vec::new();
    for line in message[start..].lines().skip(1) {
        let trimmed = line.trim();
        if trimmed.is_empty() || !line.starts_with(char::is_whitespace) {
            break;
        }
        paths.push(trimmed.to_string());
    }
    (!paths.is_empty()).then_some(paths)
}

/// Which of these untracked paths already hold exactly what the incoming
/// commits would write there.
///
/// Compared byte for byte against the blob at the tracking commit. A path the
/// merge does not carry, or one whose bytes differ by so much as a newline, is
/// not in the result: this is "the file is already what it is about to
/// become", not "the file looks close enough".
fn identical_incoming(repo: &gix::Repository, paths: &[String]) -> Result<Vec<String>> {
    if paths.is_empty() {
        return Ok(Vec::new());
    }
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("bare repositories have no working tree"))?
        .to_path_buf();
    let tracking = tracking_ref(repo).map_err(|e| anyhow::anyhow!(e))?;
    let commit = repo
        .rev_parse_single(tracking.as_str())
        .context("cannot resolve the tracking branch")?
        .object()
        .context("cannot read the tracking branch")?
        .try_into_commit()
        .context("the tracking branch is not a commit")?;
    let tree = commit.tree().context("cannot read the incoming tree")?;

    let mut identical = Vec::new();
    for path in paths {
        let Ok(Some(entry)) = tree.clone().peel_to_entry_by_path(std::path::Path::new(path)) else {
            // Not a path the merge brings at all.
            continue;
        };
        let Ok(object) = entry.object() else {
            continue;
        };
        let Ok(on_disk) = std::fs::read(workdir.join(path)) else {
            continue;
        };
        if on_disk == object.data {
            identical.push(path.clone());
        }
    }
    Ok(identical)
}

/// Whether git tracks `file`, asked of the repository holding it.
pub fn is_tracked(file: &Path) -> Result<bool> {
    let dir = file.parent().context("a file has a directory")?;
    let name = file.file_name().context("a file has a name")?;
    let output = git_command()
        .arg("ls-files")
        .arg("--error-unmatch")
        .arg("--")
        .arg(name)
        .current_dir(dir)
        .output()
        .with_context(|| format!("Failed to ask git whether '{}' is tracked", file.display()))?;
    Ok(output.status.success())
}

/// Split blocking paths into the ones git tracks and the ones it does not.
fn split_tracked(
    repo: &gix::Repository,
    paths: &[String],
) -> Result<(Vec<String>, Vec<String>)> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for pull")?;
    let mut tracked = Vec::new();
    let mut untracked = Vec::new();
    for path in paths {
        let output = git_command()
            .args(["ls-files", "--error-unmatch", "--", path])
            .current_dir(workdir)
            .output()
            .with_context(|| format!("Failed to ask git whether '{path}' is tracked"))?;
        if output.status.success() {
            tracked.push(path.clone());
        } else {
            untracked.push(path.clone());
        }
    }
    Ok((tracked, untracked))
}

/// Restore the named paths from HEAD, in the index and the working tree.
fn restore_from_head(repo: &gix::Repository, paths: &[String]) -> Result<()> {
    if paths.is_empty() {
        return Ok(());
    }
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for pull")?;
    let mut args: Vec<String> = vec![
        "restore".to_string(),
        "--source=HEAD".to_string(),
        "--staged".to_string(),
        "--worktree".to_string(),
        "--".to_string(),
    ];
    args.extend(paths.iter().cloned());
    let output = git_command()
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git restore")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git restore of {} failed: {}",
            paths.join(", "),
            stderr.trim()
        );
    }
    Ok(())
}

/// The tracking ref of the current branch, as a full ref name.
fn tracking_ref(repo: &gix::Repository) -> Result<String> {
    let head = repo.head().context("Failed to read HEAD")?;
    let branch = head
        .referent_name()
        .context("Detached HEAD is not supported for pull")?;
    Ok(repo
        .branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)
        .transpose()
        .context("Failed to resolve tracking branch")?
        .context("No tracking branch configured for current branch")?
        .to_string())
}

fn fast_forward_to_tracking(repo: &gix::Repository) -> Result<()> {
    let tracking = tracking_ref(repo)?;
    merge_ff(repo, &tracking)
}

/// Replay this branch's commits on top of the remote's.
///
/// A rebase that hits a conflict is ABORTED rather than left half-applied: an
/// interrupted rebase leaves the repository in a state no other wsb command
/// understands, and a fleet command that did this to forty repositories would
/// leave the operator to unpick every one of them by hand.
fn rebase_onto_tracking(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for rebase")?;
    let tracking = tracking_ref(repo)?;

    let output = git_command()
        .args(["rebase", &tracking])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git rebase")?;
    if output.status.success() {
        return Ok(());
    }

    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    let abort = git_command()
        .args(["rebase", "--abort"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git rebase --abort")?;
    if !abort.status.success() {
        bail!(
            "git rebase onto {tracking} failed ({stderr}), AND the abort failed ({}) — \
             this repository is mid-rebase and needs `git rebase --abort` by hand",
            String::from_utf8_lossy(&abort.stderr).trim()
        );
    }
    bail!("git rebase onto {tracking} failed and was rolled back: {stderr}");
}

pub fn nearest_tag(repo: &gix::Repository, revspec: Option<&str>) -> Result<Option<String>> {
    let mut repo = repo.clone();
    repo.object_cache_size_if_unset(4 * 1024 * 1024);
    let commit = match revspec {
        Some(spec) => repo
            .rev_parse_single(spec)
            .with_context(|| format!("Failed to resolve revision '{spec}'"))?
            .object()
            .context("Failed to open revision object")?
            .try_into_commit()
            .context("Revision does not resolve to a commit")?,
        None => match repo.head_commit() {
            Ok(commit) => commit,
            Err(_) => return Ok(None),
        },
    };
    let resolution = match commit.describe().try_resolve() {
        Ok(Some(resolution)) => resolution,
        Ok(None) => return Ok(None),
        Err(_) => return Ok(None),
    };
    let describe = resolution.format()?.to_string();
    Ok(Some(
        describe
            .split_once('-')
            .map(|(tag, _)| tag.to_string())
            .unwrap_or(describe),
    ))
}

pub fn list_tags(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut tags: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .tags()
        .context("Failed to list tags")?
        .flatten()
        .map(|tag| tag.name().shorten().to_string())
        .collect();
    sort_tags_newest_first(&mut tags);
    Ok(tags)
}

/// Order tags newest-first by numeric version precedence, breaking ties by
/// reverse lexicographic order.
///
/// Tags carrying no digits sort last, so `tags[0]` is the highest version
/// whenever any version-like tag exists.
pub fn sort_tags_newest_first(tags: &mut [String]) {
    tags.sort_by(|a, b| {
        version_sort_key(b)
            .cmp(&version_sort_key(a))
            .then_with(|| b.cmp(a))
    });
}

/// List the tags that actually exist on `remote_name`, newest first.
///
/// This contacts the remote over the network. Unlike [`list_tags`] the result is
/// unaffected by which tags happen to have been fetched into this clone, which
/// is what makes it usable for stamping a dependency pin that an outside
/// consumer has to be able to resolve.
pub fn remote_tags(repo: &gix::Repository, remote_name: &str) -> Result<Vec<String>> {
    let mut tags: Vec<String> = remote_refs(repo, remote_name)?
        .into_iter()
        .filter_map(|(name, _)| name.strip_prefix("refs/tags/").map(str::to_string))
        .collect();
    sort_tags_newest_first(&mut tags);
    Ok(tags)
}

pub fn total_commit_count(repo: &gix::Repository, revspec: Option<&str>) -> Result<u32> {
    let commit = match revspec {
        Some(spec) => resolve_commit_id(repo, spec)?,
        None => match repo.head_id() {
            Ok(id) => id.detach(),
            Err(_) => return Ok(0),
        },
    };
    let commit = repo.find_commit(commit).context("Failed to open commit")?;
    let mut count = 0u32;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let _ = ancestor.context("Failed to inspect ancestor commit")?;
        count = count.saturating_add(1);
    }
    Ok(count)
}

pub fn commit_count_since(repo: &gix::Repository, revspec: &str) -> Result<u32> {
    if revspec == "v0" {
        return total_commit_count(repo, None);
    }
    let stop = resolve_commit_id(repo, revspec)?;
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    count_commits_until(repo, head, Some(stop))
}

pub fn change_count_since(repo: &gix::Repository, revspec: Option<&str>) -> Result<u32> {
    let stop = match revspec {
        Some(spec) => Some(resolve_commit_id(repo, spec)?),
        None => None,
    };
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    count_tree_changes_until(repo, head, stop)
}

/// A repository's part of a version, for the commit that holds its tree:
/// `(commits, file changes since the release tag)`.
///
/// A version is written into the commit it names, so it is computed while that
/// commit is being made, and must still be its version once the commit exists.
/// Counted from HEAD as it stands, it was not: the commit counted itself as one
/// more, and a release tag on it dropped its changes to none — lungo-rs at
/// exactly its `v1.86.160` release called itself `1.87.0`. So:
///
/// - `pending` (the tree holds changes a commit would record): the version of
///   the commit about to be made, whose parent is HEAD — every commit up to
///   HEAD, and the changes from HEAD back to the newest release tag;
/// - otherwise HEAD's own version: the commits before HEAD, and the changes
///   from HEAD's first parent back to the newest release tag that is not on
///   HEAD itself (a version does not move when its commit is tagged).
///
/// The second is what the first said when HEAD was being committed, so a
/// version survives its own commit and its own tag. `release_tags` is the
/// candidate tags, newest first.
pub fn version_counts(repo: &gix::Repository, release_tags: &[String], pending: bool) -> Result<(u32, u32)> {
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok((0, 0)),
    };
    let head_commit = repo.find_commit(head).context("Failed to open HEAD commit")?;
    let commits = total_commit_count(repo, None)?;
    let tag_commit = |tag: &str| resolve_commit_id(repo, tag);
    if pending {
        let stop = match release_tags.first() {
            Some(tag) => Some(tag_commit(tag)?),
            None => None,
        };
        return Ok((commits, count_tree_changes_until(repo, head, stop)?));
    }
    let mut stop = None;
    for tag in release_tags {
        let at = tag_commit(tag)?;
        if at != head {
            stop = Some(at);
            break;
        }
    }
    let changes = match head_commit.parent_ids().next() {
        Some(parent) => count_tree_changes_until(repo, parent.detach(), stop)?,
        None => 0,
    };
    Ok((commits.saturating_sub(1), changes))
}

pub fn count_commits_since_midnight(repo: &gix::Repository) -> Result<usize> {
    let now = chrono::Local::now();
    let midnight = now
        .date_naive()
        .and_hms_opt(0, 0, 0)
        .context("Failed to compute local midnight")?
        .and_local_timezone(*now.offset())
        .single()
        .context("Failed to resolve local midnight timezone")?
        .timestamp();
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    let commit = repo
        .find_commit(head)
        .context("Failed to open HEAD commit")?;
    let mut count = 0usize;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let ancestor = ancestor.context("Failed to inspect ancestor commit")?;
        if ancestor.commit_time.unwrap_or(i64::MIN) < midnight {
            break;
        }
        count += 1;
    }
    Ok(count)
}

pub fn has_changes(repo: &gix::Repository) -> Result<bool> {
    Ok(!status_entries(repo)?.is_empty())
}

/// The submodule of `repo` that contains `relative_path`, if any.
///
/// `relative_path` is repo-root-relative. A path equal to a submodule's own
/// path is NOT "inside" it — that is the gitlink entry itself, which this repo
/// does own and does stage.
///
/// Callers use this to keep a path out of the wrong index: `git add` on a path
/// inside a submodule fails hard ("Pathspec '...' is in submodule '...'"), and
/// a submodule's contents are only ever staged by the submodule.
pub fn submodule_containing(repo: &gix::Repository, relative_path: &str) -> Result<Option<String>> {
    let Some(submodules) = repo.submodules().context("Failed to read submodules")? else {
        return Ok(None);
    };
    for submodule in submodules {
        let sm_path = submodule.path().context("Failed to read submodule path")?;
        let sm_path = sm_path.to_string();
        // Compare on path SEGMENTS: a "floom-uikit" submodule must not swallow a
        // sibling "floom-uikit-extras/…" that merely shares a name prefix.
        let prefix = format!("{}/", sm_path.trim_end_matches('/'));
        if relative_path.starts_with(&prefix) {
            return Ok(Some(sm_path));
        }
    }
    Ok(None)
}

pub fn stage_paths(repo: &gix::Repository, paths: &[String]) -> Result<Vec<String>> {
    if paths.is_empty() {
        return Ok(Vec::new());
    }

    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    // `--` keeps a path that begins with a dash from being parsed as an option.
    let mut args = vec!["add".to_string(), "--".to_string()];
    for path in paths {
        args.push(path.clone());
    }

    let output = git_add_command(repo)?
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git add")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git add failed: {}", stderr.trim());
    }

    staged_objects_exist(repo, workdir, paths)?;
    Ok(paths.to_vec())
}

/// Every entry this just staged names an object the repository actually has.
///
/// `git add` writes the blob and then the index entry. When the write does not
/// survive — a full disk is the way this happens — the index can be left
/// naming a hash the object database does not hold, and `git add` has already
/// reported success. Nothing notices until the commit, which fails with
///
/// ```text
/// error: invalid object 100644 7e76d99… for 'mg-test/harness/guest-requirements.txt'
/// error: Error building trees
/// ```
///
/// — a message that names neither the cause nor the remedy, from a command the
/// operator ran rather than from the pre-commit hook that actually staged it.
/// Checked here because this is where it was staged: wsb must not leave an
/// index it can know is unbuildable.
fn staged_objects_exist(repo: &gix::Repository, workdir: &Path, paths: &[String]) -> Result<()> {
    let mut args = vec!["ls-files".to_string(), "-s".to_string(), "--".to_string()];
    args.extend(paths.iter().cloned());
    let listed = git_add_command(repo)?
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git ls-files")?;
    if !listed.status.success() {
        let stderr = String::from_utf8_lossy(&listed.stderr);
        bail!("git ls-files failed: {}", stderr.trim());
    }
    let listing = String::from_utf8_lossy(&listed.stdout);

    let mut absent: Vec<String> = Vec::new();
    for line in listing.lines() {
        // `<mode> <object> <stage>\t<path>`
        let Some((meta, path)) = line.split_once('\t') else {
            continue;
        };
        let mut fields = meta.split_whitespace();
        let (Some(mode), Some(object)) = (fields.next(), fields.next()) else {
            continue;
        };
        // A gitlink names a commit in the SUBMODULE's object database, which
        // this repository does not have and is not supposed to. Checking one
        // here reports every submodule in the fleet as corrupt, which is how
        // the first version of this read a healthy superproject.
        if mode == "160000" {
            continue;
        }
        let present = git_add_command(repo)?
            .args(["cat-file", "-e", object])
            .current_dir(workdir)
            .output()
            .context("Failed to execute git cat-file")?
            .status
            .success();
        if !present {
            absent.push(format!("{path} ({object})"));
        }
    }

    if absent.is_empty() {
        return Ok(());
    }
    bail!(
        "git add reported success, but the repository does not hold the object it staged \
         for: {}.\nThe index now names a blob that is not there, and a commit from it \
         fails with \"Error building trees\". The usual cause is a full disk — check \
         free space where {} lives, then stage again.",
        absent.join(", "),
        repo.git_dir().display()
    )
}

/// Throw away every change to tracked files: staged, unstaged, and deleted.
///
/// `git reset --hard HEAD`. What it restores is what HEAD holds, so a file
/// edited, staged, or deleted goes back to its committed content, and one that
/// was never committed is untouched — see [`remove_untracked_files`].
///
/// # What this does NOT undo
///
/// A submodule that has been moved to a different commit. The gitlink in the
/// index goes back to HEAD's, but the submodule's own working tree stays where
/// it was checked out, so the parent still reports it as modified. That is
/// git's behaviour and not a defect here: restoring the recorded commits is
/// `git submodule update`, and doing it silently would check out a different
/// revision of somebody's work in the middle of a command about local edits.
pub fn discard_tracked_changes(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        .args(["reset", "--hard", "HEAD"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git reset --hard")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git reset --hard failed: {}", stderr.trim());
    }

    Ok(())
}

/// Delete every untracked file, and the directories that held only those.
///
/// `git clean -fd`. IGNORED files are deliberately not touched: build output,
/// `node_modules` and `.wsb/` state are all ignored, and a command about local
/// changes that emptied them would be a different and much larger command.
///
/// Returns what it removed, as git reports it, so a caller can say what went
/// rather than how many.
pub fn remove_untracked_files(repo: &gix::Repository) -> Result<Vec<String>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        // `-d` for directories that contain only untracked files. No `-x`: see
        // above.
        .args(["clean", "-fd"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git clean")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git clean failed: {}", stderr.trim());
    }

    Ok(String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| line.strip_prefix("Removing "))
        .map(|path| path.trim().to_string())
        .collect())
}

pub fn checkout_branch(repo: &gix::Repository, branch_name: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        .args(["checkout", branch_name])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn create_branch(
    repo: &gix::Repository,
    branch_name: &str,
    from_ref: Option<&str>,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let mut args = vec![
        "checkout".to_string(),
        "-b".to_string(),
        branch_name.to_string(),
    ];
    if let Some(from) = from_ref {
        args.push(from.to_string());
    }

    let output = git_command()
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout -b")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout -b failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn delete_local_branch(repo: &gix::Repository, branch_name: &str, force: bool) -> Result<()> {
    let current = current_branch(repo).ok();
    if current.as_deref() == Some(branch_name) {
        bail!("Cannot delete the currently checked out branch '{branch_name}'");
    }

    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for branch deletion")?;

    let delete_flag = if force { "-D" } else { "-d" };
    let output = git_command()
        .args(["branch", delete_flag, branch_name])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git branch deletion")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git branch {delete_flag} failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn stage_all(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_add_command(repo)?
        .args(["add", "-A"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git add -A")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git add -A failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn commit_all(repo: &gix::Repository, message: &str) -> Result<Option<String>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        .args(["commit", "-m", message])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git commit")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let combined = format!("{} {}", stderr.trim(), stdout.trim());
        // Nothing staged is nothing to commit, in each of git's wordings: a
        // tree whose only changes are unstaged — a submodule's own content —
        // is "no changes added to commit".
        if combined.contains("nothing to commit")
            || combined.contains("nothing added to commit")
            || combined.contains("no changes added to commit")
        {
            return Ok(None);
        }
        // Both streams, always. Git states its reason on stdout and a hook
        // writes to stderr: taking stderr when it was not empty reported the
        // pre-commit hook's log line as the failure and dropped git's own,
        // and a checkpoint failed on capdag saying nothing about why.
        bail!(
            "git commit failed: {}",
            [stdout.trim(), stderr.trim()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n")
        );
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let commit_hash = stdout
        .lines()
        .find(|line| line.starts_with('['))
        .and_then(|line| line.split_whitespace().nth(1))
        .map(|s| s.to_string());

    Ok(commit_hash)
}

pub fn create_tag(repo: &gix::Repository, name: &str, message: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        .args(["tag", "-a", name, "-m", message])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git tag")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git tag failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn merge_ff(repo: &gix::Repository, branch: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let current_commit = repo
        .head_id()
        .context("Failed to resolve current HEAD")?
        .detach();
    let target_commit = resolve_commit_id(repo, branch)?;
    let merge_base = repo
        .merge_base(current_commit, target_commit)
        .context("Failed to compute merge base")?;
    if merge_base != current_commit {
        bail!("Fast-forward merge is not possible");
    }

    let output = git_command()
        .args(["merge", "--ff-only", branch])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git merge --ff-only")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git merge --ff-only failed: {}", stderr.trim());
    }

    Ok(())
}

/// What moving this repository to another commit would cost.
///
/// Computed before anything is touched, because the two outcomes are not the
/// same act and a person must not be asked to approve one and get the other.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MoveCost {
    /// Already there. Nothing to do.
    Already,
    /// The target is a descendant of this branch's tip: the branch moves
    /// forward and no commit stops being reachable.
    FastForward { commits: usize },
    /// The target is NOT a descendant. Moving there takes these commits off
    /// this branch — they survive in the reflog and nowhere a person looks.
    Discards { commits: usize },
}

/// Whether this repository already has the object, without fetching.
pub fn has_commit(repo: &gix::Repository, commit: &str) -> Result<bool> {
    let Ok(id) = gix::ObjectId::from_hex(commit.as_bytes()) else {
        bail!("'{commit}' is not a commit id");
    };
    Ok(repo.find_object(id).is_ok())
}

/// What it would cost to put this repository's current branch at `commit`.
pub fn move_cost(repo: &gix::Repository, commit: &str) -> Result<MoveCost> {
    let target = gix::ObjectId::from_hex(commit.as_bytes())
        .map_err(|_| anyhow::anyhow!("'{commit}' is not a commit id"))?;
    let head = repo.head_id().context("this repository has no HEAD")?.detach();
    if head == target {
        return Ok(MoveCost::Already);
    }
    let base = repo
        .merge_base(head, target)
        .context("the two commits share no history — this is not the same repository")?
        .detach();
    if base == head {
        // Everything here is reachable from the target: the branch moves
        // forward and nothing is left behind.
        return Ok(MoveCost::FastForward {
            commits: count_commits_until(repo, target, Some(head))? as usize,
        });
    }
    // Whatever is on this branch and not on the target's is what would stop
    // being reachable from the branch.
    Ok(MoveCost::Discards {
        commits: count_commits_until(repo, head, Some(base))? as usize,
    })
}

/// Put this repository's current branch at `commit`, worktree and all.
///
/// `git reset --hard`, which is the only operation that means "be at this
/// commit" for a branch. A detached checkout would leave HEAD on no branch —
/// which the peer machinery reports as blocked in its own right, so it would
/// trade one refusal for another rather than resolving anything.
///
/// Refuses outright on a detached HEAD: there is no branch to move, and
/// guessing which one was meant is how a commit made on nothing gets made.
pub fn move_branch_to(repo: &gix::Repository, commit: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("bare repositories have no working tree to move")?;
    if is_detached_head(repo)? {
        bail!(
            "HEAD is detached here, so there is no branch to move. Check out the branch \
             first — a reset would otherwise move nothing a later commit could follow."
        );
    }
    let output = git_command()
        .args(["reset", "--hard", commit])
        .current_dir(workdir)
        .output()
        .context("failed to execute git reset --hard")?;
    if !output.status.success() {
        bail!(
            "git reset --hard {commit} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

pub fn checkout_commit(repo: &gix::Repository, commit: gix::ObjectId) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = git_command()
        .args(["checkout", &commit.to_string()])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn clone_repository(url: &str, destination: &Path) -> Result<gix::Repository> {
    clone_repository_impl(url, destination, None)
}

/// Clone with the git process rooted at `working_dir`.
///
/// Submodule URLs are interpreted relative to the repository that declares them,
/// so cloning a submodule must not inherit the caller's arbitrary current directory.
pub fn clone_repository_in(
    url: &str,
    destination: &Path,
    working_dir: &Path,
) -> Result<gix::Repository> {
    clone_repository_impl(url, destination, Some(working_dir))
}

fn clone_repository_impl(
    url: &str,
    destination: &Path,
    working_dir: Option<&Path>,
) -> Result<gix::Repository> {
    let destination = if destination.is_absolute() {
        destination.to_path_buf()
    } else {
        match working_dir {
            Some(dir) => dir.join(destination),
            None => destination.to_path_buf(),
        }
    };

    let mut command = git_command();
    command.args(["clone", "--", url, destination.to_str().unwrap_or_default()]);
    if let Some(dir) = working_dir {
        command.current_dir(dir);
    }

    let output = command.output().context("Failed to execute git clone")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git clone failed: {}", stderr.trim());
    }

    open_repo(&destination)
}

pub fn push_current_branch(
    repo: &gix::Repository,
    remote_name: Option<&str>,
    set_upstream: bool,
    force_with_lease: bool,
) -> Result<PushOutcome> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for push")?;

    let remote = remote_name.unwrap_or("origin");

    let mut args: Vec<String> = vec!["push".to_string()];
    if set_upstream {
        args.push("--set-upstream".to_string());
    }
    if force_with_lease {
        args.push("--force-with-lease".to_string());
    }
    args.push(remote.to_string());

    // `--set-upstream` can only establish tracking if it is told which ref to
    // push. Without an explicit refspec git has no name to record and fails on
    // exactly the branches that need it — the ones with no upstream yet.
    if set_upstream {
        let branch = current_branch(repo)
            .context("Cannot set an upstream while HEAD is detached; check out a branch first")?;
        args.push(branch);
    }

    let output = git_command()
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git push — is git installed?")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // git push exits 0 when already up to date, so any failure is real
        bail!("git push failed: {}", stderr.trim());
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("Everything up-to-date") {
        Ok(PushOutcome::UpToDate)
    } else {
        Ok(PushOutcome::Updated)
    }
}

pub fn delete_remote_branch(
    repo: &gix::Repository,
    remote_name: Option<&str>,
    branch_name: &str,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote branch deletion")?;

    let remote = remote_name.unwrap_or("origin");
    let refspec = format!(":{branch_name}");

    let output = git_command()
        .args(["push", remote, &refspec])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git push — is git installed?")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git push --delete failed: {}", stderr.trim());
    }

    Ok(())
}

fn resolve_commit_id(repo: &gix::Repository, spec: &str) -> Result<gix::ObjectId> {
    repo.rev_parse_single(spec)
        .with_context(|| format!("Failed to resolve revision '{spec}'"))?
        .object()
        .context("Failed to open resolved revision")?
        .peel_to_commit()
        .context("Revision does not resolve to a commit")
        .map(|commit| commit.id)
}

fn count_commits_until(
    repo: &gix::Repository,
    from: gix::ObjectId,
    stop: Option<gix::ObjectId>,
) -> Result<u32> {
    let commit = repo.find_commit(from).context("Failed to open commit")?;
    let mut count = 0u32;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let ancestor = ancestor.context("Failed to inspect ancestor commit")?;
        if stop.is_some_and(|stop_id| ancestor.id == stop_id) {
            break;
        }
        count = count.saturating_add(1);
    }
    Ok(count)
}

fn count_tree_changes_until(
    repo: &gix::Repository,
    from: gix::ObjectId,
    stop: Option<gix::ObjectId>,
) -> Result<u32> {
    let commit = repo.find_commit(from).context("Failed to open commit")?;
    let mut total = 0u32;
    let mut current = Some(commit);
    while let Some(commit) = current {
        if stop.is_some_and(|stop_id| commit.id == stop_id) {
            break;
        }
        let tree_id = commit.tree_id().context("Failed to read commit tree id")?;
        let tree = repo.find_object(tree_id)?.peel_to_tree()?;
        let parent_tree = if let Some(parent_id) = commit.parent_ids().next() {
            let parent = repo
                .find_commit(parent_id)
                .context("Failed to open parent commit")?;
            Some(repo.find_object(parent.tree_id()?)?.peel_to_tree()?)
        } else {
            None
        };
        let changes = repo
            .diff_tree_to_tree(parent_tree.as_ref(), &tree, None)
            .context("Failed to diff commit trees")?;
        total = total.saturating_add(changes.len() as u32);

        let next_parent = commit.parent_ids().next();
        current = next_parent
            .map(|parent_id| {
                repo.find_commit(parent_id)
                    .context("Failed to open parent commit")
            })
            .transpose()?;
    }
    Ok(total)
}

fn version_sort_key(tag: &str) -> Vec<u64> {
    tag.trim_start_matches('v')
        .split(|ch: char| !ch.is_ascii_digit())
        .filter(|part| !part.is_empty())
        .map(|part| part.parse::<u64>().unwrap_or(0))
        .collect()
}

fn replace_or_append_config_section(config: &str, section: &str, replacement: &str) -> String {
    let mut output = String::new();
    let mut lines = config.lines().peekable();
    let header = format!("[{section}]");
    let mut replaced = false;

    while let Some(line) = lines.next() {
        let trimmed = line.trim();
        if trimmed == header {
            replaced = true;
            output.push_str(replacement);
            if !replacement.ends_with('\n') {
                output.push('\n');
            }
            while let Some(next) = lines.peek() {
                let next_trimmed = next.trim();
                if next_trimmed.starts_with('[') && next_trimmed.ends_with(']') {
                    break;
                }
                lines.next();
            }
            continue;
        }
        output.push_str(line);
        output.push('\n');
    }

    if !replaced {
        if !output.is_empty() && !output.ends_with("\n\n") {
            output.push('\n');
        }
        output.push_str(replacement);
        if !replacement.ends_with('\n') {
            output.push('\n');
        }
    }

    output
}

/// Every path git tracks in this repository, relative to its working
/// directory, with `/` separators.
///
/// Through `git ls-files -z`, which is the one answer that already accounts
/// for the index, sparse checkouts and the repository's own case rules. The
/// `-z` form is not an optimisation: a filename containing a newline is legal
/// on every filesystem this runs on, and the line-based form quotes it into
/// something that is no longer the name of a file.
pub fn tracked_paths(workdir: &Path) -> Result<Vec<String>, String> {
    let output = git_command()
        .args(["ls-files", "-z"])
        .current_dir(workdir)
        .output()
        .map_err(|e| format!("cannot list tracked files in {}: {e}", workdir.display()))?;
    if !output.status.success() {
        return Err(format!(
            "git ls-files failed in {}: {}",
            workdir.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    let text = String::from_utf8(output.stdout)
        .map_err(|_| format!("{} holds a path that is not UTF-8", workdir.display()))?;
    Ok(text
        .split('\0')
        .filter(|path| !path.is_empty())
        .map(|path| path.to_string())
        .collect())
}

#[cfg(test)]
mod staging_tests {
    use super::*;

    fn run(dir: &Path, args: &[&str]) {
        let output = git_command()
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap_or_else(|e| panic!("git {args:?}: {e}"));
        assert!(
            output.status.success(),
            "git {args:?} failed in {}: {}",
            dir.display(),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn repo(dir: &Path) {
        run(dir, &["init", "--initial-branch=main"]);
        run(dir, &["config", "user.name", "Test User"]);
        run(dir, &["config", "user.email", "test@example.invalid"]);
    }

    /// TEST12310: a lockfile is staged with its manifest only where the
    /// repository tracks it.
    ///
    /// A library ignores its `Cargo.lock`. Staging a rewritten lock
    /// unconditionally made `git add` refuse the ignored path, and every
    /// library's commit failed.
    #[test]
    fn test12310_only_a_tracked_file_is_tracked() {
        let temp = tempfile::tempdir().expect("a scratch directory");
        let root = temp.path();
        repo(root);
        std::fs::write(root.join(".gitignore"), "ignored.lock\n").unwrap();
        std::fs::write(root.join("tracked.lock"), "t").unwrap();
        std::fs::write(root.join("ignored.lock"), "i").unwrap();
        std::fs::write(root.join("new.lock"), "n").unwrap();
        run(root, &["add", ".gitignore", "tracked.lock"]);
        run(root, &["commit", "-m", "tracked"]);
        assert!(is_tracked(&root.join("tracked.lock")).unwrap());
        assert!(!is_tracked(&root.join("ignored.lock")).unwrap(), "an ignored file is not tracked");
        assert!(!is_tracked(&root.join("new.lock")).unwrap(), "nor is one never added");
    }

    /// TEST11203: staging refuses to leave an index naming an object the
    /// repository does not hold.
    ///
    /// `git add` writes the blob and then the index entry. Where the blob does
    /// not survive — a full disk is how this happens — the index is left
    /// naming a hash that is not there and `git add` has already reported
    /// success. Nothing notices until a commit, which fails with "invalid
    /// object … Error building trees": a message from a command the operator
    /// ran, naming neither the cause nor the hook that actually staged it.
    ///
    /// The check is exercised directly rather than through `stage_paths`,
    /// because there is no way in from outside: deleting the object and
    /// staging again simply writes it back, the file still being in the
    /// worktree. That is worth knowing on its own — re-staging is the remedy —
    /// and it is why the loss has to be arranged between the add and the
    /// check, which only the check itself sits after.
    #[test]
    fn test11203_staging_refuses_an_index_whose_object_is_missing() {
        let temp = tempfile::tempdir().expect("a scratch directory");
        let root = temp.path();
        repo(root);
        std::fs::write(root.join("rendered.txt"), "some rendered content\n").unwrap();

        let opened = open_repo(root).expect("the repository opens");
        stage_paths(&opened, &["rendered.txt".to_string()])
            .expect("a healthy add is accepted");
        staged_objects_exist(&opened, root, &["rendered.txt".to_string()])
            .expect("a healthy index passes the check");

        // The blob the index names.
        //
        // Through the scope-stripping command, like everything else this crate
        // runs. `GIT_DIR` and its relatives are exported into the PROCESS, and
        // tests share one — so a git here that inherited another test's scope
        // reads another repository, lists nothing, and this failed as
        // "an object id" with nothing about which repository it had looked in.
        let listed = git_command()
            .args(["ls-files", "-s", "--", "rendered.txt"])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(
            listed.status.success(),
            "git ls-files failed in {}: {}",
            root.display(),
            String::from_utf8_lossy(&listed.stderr)
        );
        let listing = String::from_utf8_lossy(&listed.stdout);
        let object = listing.split_whitespace().nth(1).unwrap_or_else(|| {
            panic!("git listed no object for rendered.txt in {}: {listing:?}", root.display())
        });
        let loose = root
            .join(".git/objects")
            .join(&object[..2])
            .join(&object[2..]);
        assert!(loose.is_file(), "the add wrote a loose object");

        // What a failed write leaves behind: the entry, without the object.
        std::fs::remove_file(&loose).expect("the object is removed");
        // Through the scope-stripping command, like the listing above and like
        // everything else this crate runs. A raw `git` inherits `GIT_INDEX_FILE`
        // from the PROCESS, and one test in this binary sets it — so this
        // sometimes wrote a tree from ANOTHER repository's index, which is
        // healthy, and the fixture then failed to be the broken state it exists
        // to arrange. It failed about once in every eight full runs, in the
        // assertion that says the fixture must be broken.
        let broken = git_command()
            .args(["write-tree"])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(
            !broken.status.success(),
            "the fixture must be the state git itself refuses, or this proves \
             nothing. git said: {}",
            String::from_utf8_lossy(&broken.stderr)
        );

        let refused = staged_objects_exist(&opened, root, &["rendered.txt".to_string()])
            .expect_err("the check must refuse an index whose object is gone");
        let said = refused.to_string();
        assert!(
            said.contains("rendered.txt"),
            "the refusal must name the file, said: {said}"
        );
        assert!(
            said.contains("full disk"),
            "the refusal must name the usual cause, said: {said}"
        );
    }

    /// TEST11205: staging into a repository never writes another repository's
    /// index, even when git hands one over.
    ///
    /// During a pre-commit hook git exports `GIT_INDEX_FILE`, and wsb honours
    /// it — a hook that staged into a fresh index would stage into an index
    /// nothing was about to commit. What it must not do is honour one
    /// belonging to a DIFFERENT repository.
    ///
    /// That is not hypothetical, because of where a submodule's git dir lives:
    /// `<root>/.git/modules/child`, which is INSIDE the superproject's. A test
    /// asking "is this index under my git dir" answers yes for the
    /// superproject when handed the submodule's — so a commit in the submodule
    /// would run the hook, wsb would resolve the workspace to the
    /// superproject, and the superproject's rendered files would be staged into
    /// the submodule's index. Those entries name blobs the submodule's object
    /// database does not have, and it can then build no trees at all.
    ///
    /// Both halves are asserted. Rejecting every handed-over index would also
    /// pass the first, and would break the hook this exists for.
    #[test]
    fn test11205_a_submodules_index_is_not_the_superprojects() {
        let temp = tempfile::tempdir().expect("a scratch directory");
        let root = temp.path().join("super");
        let inner = root.join("child");
        std::fs::create_dir_all(&inner).unwrap();
        repo(&root);

        // The ABSORBED layout, which is the whole point: a real submodule's
        // git dir lives at `<root>/.git/modules/<name>`, inside the
        // superproject's. A plain nested repository keeps its `.git` in its
        // own directory and never triggers this at all — which is how the
        // first version of this test passed against the very rule it was
        // written to catch.
        let separate = root.join(".git/modules/child");
        std::fs::create_dir_all(separate.parent().unwrap()).unwrap();
        run(
            &inner,
            &[
                "init",
                "--initial-branch=main",
                &format!("--separate-git-dir={}", separate.display()),
            ],
        );
        run(&inner, &["config", "user.name", "Test User"]);
        run(&inner, &["config", "user.email", "test@example.invalid"]);
        std::fs::write(inner.join("a.txt"), "in the child\n").unwrap();
        run(&inner, &["add", "-A"]);
        run(&inner, &["commit", "-m", "child"]);
        std::fs::write(root.join("rendered.txt"), "the superproject's own file\n").unwrap();

        let superproject = open_repo(&root).expect("the superproject opens");
        let child = open_repo(&inner).expect("the submodule opens");
        assert!(
            crate::platform::canonicalize(&separate)
                .unwrap()
                .starts_with(crate::platform::canonicalize(&root.join(".git")).unwrap()),
            "the fixture must put the submodule's git dir INSIDE the superproject's, \
             or it does not reproduce the condition"
        );

        // What git hands a hook running for a commit in the SUBMODULE.
        //
        // Under the crate's one environment turn: `GIT_INDEX_FILE` belongs to
        // the process, and every test that runs git in this binary is a test
        // this one can point at the wrong index.
        let handed = separate.join("index");
        let _env = crate::test_environment::Environment::set(&[(
            "GIT_INDEX_FILE",
            &handed.display().to_string(),
        )]);

        // Staging a superproject file must not touch it.
        stage_paths(&superproject, &["rendered.txt".to_string()])
            .expect("the superproject stages its own file");
        // Each check names the index it is asking about. Inheriting
        // `GIT_INDEX_FILE` from this process would make both of them read the
        // submodule's, and the second would then report the superproject as
        // having staged nothing — which is what it did.
        let child_holds = git_command()
            .args(["ls-files", "--", "rendered.txt"])
            .current_dir(&inner)
            .env("GIT_INDEX_FILE", &handed)
            .output()
            .unwrap();
        assert!(
            String::from_utf8_lossy(&child_holds.stdout).trim().is_empty(),
            "the superproject's file was staged into the submodule's index"
        );
        let root_holds = git_command()
            .args(["ls-files", "--", "rendered.txt"])
            .current_dir(&root)
            .env_remove("GIT_INDEX_FILE")
            .output()
            .unwrap();
        assert!(
            String::from_utf8_lossy(&root_holds.stdout).contains("rendered.txt"),
            "the superproject's file was not staged anywhere"
        );

        // And the index git handed over IS used by the repository it belongs
        // to, which is the whole reason this is honoured at all.
        std::fs::write(inner.join("b.txt"), "also in the child\n").unwrap();
        stage_paths(&child, &["b.txt".to_string()]).expect("the submodule stages its own file");
        let staged = git_command()
            .args(["ls-files", "--", "b.txt"])
            .current_dir(&inner)
            .env("GIT_INDEX_FILE", &handed)
            .output()
            .unwrap();
        assert!(
            String::from_utf8_lossy(&staged.stdout).contains("b.txt"),
            "the submodule's own staging did not reach the index git handed over"
        );
    }

    /// TEST11204: a submodule's gitlink is not mistaken for a missing object.
    ///
    /// A gitlink names a commit in the SUBMODULE's object database, which the
    /// superproject does not have and is not supposed to. The first version of
    /// the check above read every submodule in this workspace — fourteen of
    /// them — as a corrupt index.
    #[test]
    fn test11204_a_gitlink_is_not_a_missing_object() {
        let temp = tempfile::tempdir().expect("a scratch directory");
        let root = temp.path().join("super");
        let inner = root.join("child");
        std::fs::create_dir_all(&inner).unwrap();
        repo(&root);
        repo(&inner);
        std::fs::write(inner.join("a.txt"), "in the child\n").unwrap();
        run(&inner, &["add", "-A"]);
        run(&inner, &["commit", "-m", "child"]);

        // The gitlink, recorded the way a superproject records one.
        std::fs::write(root.join(".gitmodules"), "[submodule \"child\"]\n\tpath = child\n\turl = ./child\n").unwrap();
        run(&root, &["add", ".gitmodules", "child"]);
        std::fs::write(root.join("rendered.txt"), "some rendered content\n").unwrap();

        let opened = open_repo(&root).expect("the superproject opens");
        stage_paths(&opened, &["rendered.txt".to_string(), "child".to_string()])
            .expect("staging beside a gitlink must be accepted");
    }
}