rsconstruct 0.9.184

Rust based fast build system
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
//! External tool registry and installation engine.
//!
//! Lives at the crate root because nothing here depends on the `Processor`
//! trait, and every file under `src/processor/` must be a real processor.
//! This is the data and the mechanics of "what tools exist and how do we
//! install them", which `builder/tools.rs` orchestrates on top of.

/// A single way to install a tool.
pub struct InstallMethod {
    /// Package manager or method name (e.g., "pip", "apt", "npm", "snap", "cargo", "binary")
    pub method: &'static str,
    /// Package name for the package manager (e.g., "taplo-cli" for cargo, "texlive-latex-base" for apt)
    pub package: &'static str,
}

/// Where an install puts a tool.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstallTarget {
    /// Inside the project: its tool directory (`.rsconstruct/tools`), or
    /// the venv inside the repo.
    Project,
    /// Onto the machine: a system package manager, a user-wide prefix
    /// (`~/.cargo/bin`, `npm -g`, `gem --user-install`), or a venv outside
    /// the repo.
    Machine,
}

impl InstallTarget {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Project => "project",
            Self::Machine => "machine",
        }
    }
}

/// Context for executing an install: verbosity and eatmydata preference.
///
/// `sudo` is decided at execution time via `crate::platform::needs_sudo()`;
/// callers don't need to pass it in.
pub struct InstallCtx {
    /// When true, print each subprocess argv before running it.
    pub verbose: bool,
    /// When true, prepend `eatmydata` to system-package-manager calls
    /// (apt/dnf/pacman) for faster installs. No-op when eatmydata isn't
    /// on PATH.
    pub use_eatmydata: bool,
    /// The project's rsconstruct.lock entries for `binary` installs, by
    /// recipe name: a pinned recipe downloads the locked URL and must match
    /// the locked SHA-256. Empty outside a project.
    pub binary_pins: std::collections::BTreeMap<String, crate::tool_lock::BinaryPin>,
    /// Install a `binary` recipe that has no entry in `binary_pins`. Off
    /// unless the user asked for it (`tool install machine
    /// --allow-unpinned`): an unpinned install is whatever the URL serves.
    pub allow_unpinned: bool,
}

/// What to do about a release binary the lock does not pin.
pub const UNPINNED_HELP: &str = "An unpinned binary is whatever its URL serves today, installed with no checksum to hold it to. \
     In a project, run `rsconstruct tool lock` to pin it; \
     to install it unpinned anyway, pass --allow-unpinned to `tool install machine`.";

impl InstallMethod {
    pub const fn new(method: &'static str, package: &'static str) -> Self {
        Self { method, package }
    }

    /// The targets this method can install to. A system package manager
    /// only reaches the machine; a language package manager or a release
    /// binary reaches either, depending on the prefix (or venv) it is
    /// pointed at. A `.deb` binary is installed by apt, so it is machine
    /// only; a binary kept as a whole release tree needs a prefix of its
    /// own, so it is project only. Empty for `manual`, which installs
    /// nothing, and for anything unknown.
    pub fn targets(&self) -> &'static [InstallTarget] {
        const MACHINE: &[InstallTarget] = &[InstallTarget::Machine];
        const BOTH: &[InstallTarget] = &[InstallTarget::Project, InstallTarget::Machine];
        match self.method {
            "apt" | "dnf" | "pacman" | "brew" | "snap" => MACHINE,
            "pip" | "npm" | "cargo" | "gem" => BOTH,
            "uv-sync" | "npm-ci" | "npm-install" => &[InstallTarget::Project],
            "binary" => match binary_recipe(self.package) {
                Some(BinaryRecipe {
                    archive: ArchiveKind::Deb { .. },
                    ..
                }) => MACHINE,
                Some(BinaryRecipe {
                    archive: ArchiveKind::Tree { .. },
                    ..
                }) => &[InstallTarget::Project],
                Some(_) => BOTH,
                None => &[],
            },
            _ => &[],
        }
    }

    /// Human-readable preview of what installing this entry's package
    /// would do — first line of the first describe step. Lossy for
    /// multi-step installs (binary fetches), but adequate for `tool list`,
    /// which is registry-wide and so has no project lock to pin against.
    pub fn command(&self) -> String {
        let steps = describe(
            self.method,
            &[self.package],
            &std::collections::BTreeMap::new(),
        );
        steps.first().map_or_else(
            || format!("({}) {}", self.method, self.package),
            |argv| join_argv(argv),
        )
    }
}

impl ToolInfo {
    /// The tool's preferred target: `prefer` when it is set, otherwise the
    /// project when the tool has a project install, since a project runs
    /// its own tools and the machine is the last resort. None only for a
    /// tool with neither slot, which `every_slot_holds_a_method_for_its_target`
    /// rules out.
    pub fn preferred_target(&self) -> Option<InstallTarget> {
        self.prefer.or_else(|| {
            if self.project.is_some() {
                Some(InstallTarget::Project)
            } else if self.machine.is_some() {
                Some(InstallTarget::Machine)
            } else {
                None
            }
        })
    }

    /// The tool's install method for `target`, if it has one.
    pub const fn slot(&self, target: InstallTarget) -> Option<&InstallMethod> {
        match target {
            InstallTarget::Project => self.project.as_ref(),
            InstallTarget::Machine => self.machine.as_ref(),
        }
    }

    /// The method `tool install` uses for this tool: the one in the slot of
    /// its preferred target.
    pub fn preferred_method(&self) -> Option<&InstallMethod> {
        self.slot(self.preferred_target()?)
    }

    /// Every method the tool lists, each once, in the order project,
    /// machine, alternatives, with the targets it is listed for: a method
    /// that fills both slots appears once, for both.
    pub fn methods(&self) -> Vec<(&InstallMethod, Vec<InstallTarget>)> {
        let mut out: Vec<(&InstallMethod, Vec<InstallTarget>)> = Vec::new();
        for target in [InstallTarget::Project, InstallTarget::Machine] {
            if let Some(m) = self.slot(target) {
                match out
                    .iter_mut()
                    .find(|(seen, _)| seen.method == m.method && seen.package == m.package)
                {
                    Some((_, targets)) => targets.push(target),
                    None => out.push((m, vec![target])),
                }
            }
        }
        out.extend(self.alternatives.iter().map(|m| (m, Vec::new())));
        out
    }
}

/// Display the steps that `run(method, packages, ctx)` would execute,
/// without executing them. Used for logs and previews. `binary_pins` is
/// the lock's `[binary]` table (see [`InstallCtx::binary_pins`]): a pinned
/// recipe is described at its locked URL, exactly as `run` installs it.
pub fn describe(
    method: &str,
    packages: &[&str],
    binary_pins: &std::collections::BTreeMap<String, crate::tool_lock::BinaryPin>,
) -> Vec<Vec<String>> {
    let sudo = sudo_argv();
    let strs = |parts: &[&str]| -> Vec<String> { parts.iter().map(|s| (*s).to_string()).collect() };
    let prefix = |head: &[&str], tail: &[&str]| -> Vec<String> {
        sudo.iter()
            .chain(head.iter())
            .chain(tail.iter())
            .map(|s| (*s).to_string())
            .collect()
    };
    match method {
        "apt" => {
            // Run `apt-get update` first so the package index isn't stale.
            // CI runners ship with indexes a few days old; without this, an
            // `install` for a security-updated package 404s on the mirror.
            let update = prefix(&["apt-get", "update"], &[]);
            let mut install = prefix(&["apt-get", "install", "-y"], &[]);
            install.extend(packages.iter().map(|s| (*s).to_string()));
            vec![update, install]
        }
        "dnf" => {
            let mut argv = prefix(&["dnf", "install", "-y"], &[]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            vec![argv]
        }
        "pacman" => {
            let mut argv = prefix(&["pacman", "-S", "--noconfirm"], &[]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            vec![argv]
        }
        "brew" => {
            let mut argv = strs(&["brew", "install"]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            vec![argv]
        }
        "snap" => {
            let mut argv = prefix(&["snap", "install"], &[]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            vec![argv]
        }
        "pip" => vec![{
            let mut a = strs(&["pip", "install"]);
            a.extend(packages.iter().map(|s| (*s).to_string()));
            a
        }],
        "npm" => vec![{
            let mut a = strs(&["npm", "install", "-g"]);
            a.extend(packages.iter().map(|s| (*s).to_string()));
            a
        }],
        // The project's own package sets: these commands take no package
        // names, they read the manifest (and lockfile) in the working
        // directory. `packages` is the declared list, kept for the
        // skip/preview display only.
        "uv-sync" => vec![uv_sync_argv()],
        "npm-ci" => vec![strs(&["npm", "ci"])],
        "npm-install" => vec![strs(&["npm", "install"])],
        "cargo" => vec![{
            let mut a = cargo_install_argv();
            a.extend(packages.iter().map(|s| (*s).to_string()));
            a
        }],
        "gem" => vec![{
            let mut a = gem_install_argv();
            a.extend(packages.iter().map(|s| (*s).to_string()));
            a
        }],
        "binary" => packages
            .iter()
            .flat_map(|p| describe_binary(p, binary_pins))
            .collect(),
        "manual" => packages
            .iter()
            .map(|p| vec!["# manual:".to_string(), (*p).to_string()])
            .collect(),
        _ => packages
            .iter()
            .map(|p| vec![format!("# unknown method '{}':", method), (*p).to_string()])
            .collect(),
    }
}

/// Execute the install for `method` over `packages` (batched when the
/// method supports it). Each subprocess runs argv-style — never via a
/// shell. Returns Err on the first failure.
pub fn run(method: &str, packages: &[&str], ctx: &InstallCtx) -> anyhow::Result<()> {
    use anyhow::Context as _;
    use std::process::Command;
    if packages.is_empty() {
        return Ok(());
    }
    let exec = |argv: &[String]| -> anyhow::Result<()> {
        if ctx.verbose {
            println!("Running: {}", join_argv(argv));
        }
        // Deliberately NOT routed through run_command: installers must
        // inherit the terminal, both so `sudo` can prompt for a password and
        // so apt/dnf can render progress. Capturing would hang on the
        // password prompt. This is one of the two documented exceptions to
        // the "everything goes through the central runner" rule (see
        // docs/src/internal/architecture.md).
        let status = Command::new(&argv[0])
            .args(&argv[1..])
            .status()
            .with_context(|| format!("failed to spawn: {}", join_argv(argv)))?;
        if !status.success() {
            anyhow::bail!(
                "{} exited with code {}",
                join_argv(argv),
                status
                    .code()
                    .map_or_else(|| "unknown".to_string(), |c| c.to_string())
            );
        }
        Ok(())
    };
    let sudo = sudo_argv();
    let eatmydata: &[&str] = if ctx.use_eatmydata && which::which("eatmydata").is_ok() {
        &["eatmydata"]
    } else {
        &[]
    };
    let pkgmgr_argv = |head: &[&str]| -> Vec<String> {
        sudo.iter()
            .chain(eatmydata.iter())
            .chain(head.iter())
            .map(|s| (*s).to_string())
            .collect()
    };
    match method {
        "apt" => {
            // Refresh the package index before installing — CI runners ship
            // with stale indexes that 404 on security-updated packages.
            let update = pkgmgr_argv(&["apt-get", "update"]);
            exec(&update)?;
            let mut argv = pkgmgr_argv(&["apt-get", "install", "-y"]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "dnf" => {
            let mut argv = pkgmgr_argv(&["dnf", "install", "-y"]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "pacman" => {
            let mut argv = pkgmgr_argv(&["pacman", "-S", "--noconfirm"]);
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "brew" => {
            // brew is macOS-only; no sudo, no eatmydata.
            let mut argv = vec!["brew".to_string(), "install".to_string()];
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "snap" => {
            // snap doesn't need eatmydata.
            let mut argv: Vec<String> = sudo
                .iter()
                .chain(["snap", "install"].iter())
                .map(|s| (*s).to_string())
                .collect();
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "pip" => {
            let mut argv = vec!["pip".to_string(), "install".to_string()];
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "npm" => {
            let mut argv = vec!["npm".to_string(), "install".to_string(), "-g".to_string()];
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        // See `describe`: these read the project's manifest and lock, so
        // the declared names are not passed (to `npm install` they would
        // mean "add these to package.json").
        "uv-sync" => exec(&uv_sync_argv()),
        "npm-ci" => exec(&["npm".to_string(), "ci".to_string()]),
        "npm-install" => exec(&["npm".to_string(), "install".to_string()]),
        "cargo" => {
            let mut argv = cargo_install_argv();
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
        }
        "gem" => {
            let mut argv = gem_install_argv();
            argv.extend(packages.iter().map(|s| (*s).to_string()));
            exec(&argv)
            // The bin dir a `--user-install` just created becomes visible to
            // the NEXT rsconstruct invocation, via the PATH augmentation at
            // startup. Nothing in this process probes for the tool after
            // installing it, and re-augmenting here would mutate the
            // environment with tokio threads alive (see platform::set_env).
        }
        "binary" => {
            for pkg in packages {
                run_binary(pkg, ctx)?;
            }
            Ok(())
        }
        "manual" => anyhow::bail!(
            "method '{}' is manual-only — install these packages by hand: {}",
            method,
            packages.join(", ")
        ),
        other => anyhow::bail!("unknown install method '{other}'"),
    }
}

/// Install `pkg` into the empty directory `prefix`, the way a project's
/// tool directory holds it (see `tool_store`): its executables end up in
/// `prefix/bin`, and nothing outside `prefix` is written — so no sudo, and
/// no global state for another project to disagree with.
pub fn install_into_prefix(
    pkg: &crate::tool_store::Package,
    prefix: &std::path::Path,
    ctx: &InstallCtx,
) -> anyhow::Result<()> {
    let root = prefix.to_string_lossy();
    let (name, version) = (pkg.name.as_str(), pkg.version.as_str());
    let request = format!("{name}@{version}");
    match pkg.method.as_str() {
        // --locked for the reason given at `cargo_install_argv`; no --force,
        // the root is empty.
        "cargo" => exec_inherited_env(
            &["cargo", "install", "--locked", "--root", &root, &request],
            &[],
            ctx.verbose,
        ),
        // --global with --prefix: the global layout (lib/node_modules plus
        // bin/ shims) under a prefix of our choosing.
        "npm" => exec_inherited_env(
            &["npm", "install", "--global", "--prefix", &root, &request],
            &[],
            ctx.verbose,
        ),
        // GEM_HOME/GEM_PATH name only the prefix, so every dependency is
        // installed into it rather than satisfied by whatever gems this
        // machine happens to have; the result runs anywhere GEM_PATH
        // includes it (see `tool_store::augment_env`).
        "gem" => {
            let bin = prefix.join("bin");
            exec_inherited_env(
                &[
                    "gem",
                    "install",
                    "--install-dir",
                    &root,
                    "--bindir",
                    &bin.to_string_lossy(),
                    "--no-document",
                    "--version",
                    version,
                    name,
                ],
                &[("GEM_HOME", &root), ("GEM_PATH", &root)],
                ctx.verbose,
            )?;
            keep_own_gem_executables(name, version, &root, &bin)
        }
        "binary" => install_binary_into_prefix(name, version, prefix, ctx),
        other => anyhow::bail!("install method '{other}' does not install into a project"),
    }
}

/// The `binary` case of [`install_into_prefix`]: download the locked asset,
/// check both hashes the lock records, and put the executable in
/// `prefix/bin`. `version` is `sha256-<executable hash>`, as
/// `tool_store::Package` records a binary.
fn install_binary_into_prefix(
    name: &str,
    version: &str,
    prefix: &std::path::Path,
    ctx: &InstallCtx,
) -> anyhow::Result<()> {
    use anyhow::Context as _;
    let recipe = binary_recipe(name)
        .ok_or_else(|| anyhow::anyhow!("no binary install recipe for '{name}'"))?;
    let pin = ctx
        .binary_pins
        .get(name)
        .with_context(|| format!("binary {name} has no rsconstruct.lock entry"))?;
    let work = prefix.join(".work");
    std::fs::create_dir_all(&work)
        .with_context(|| format!("Failed to create {}", work.display()))?;
    let fetched = fetch_binary(
        &recipe,
        &pin.url,
        Some(&pin.sha256),
        &work.to_string_lossy(),
        ctx.verbose,
    )?;
    let payload = std::path::Path::new(&fetched.payload);
    let sha = file_sha256(payload)?;
    if version != format!("sha256-{sha}") {
        anyhow::bail!(
            "the executable unpacked from {} has sha256 {sha}, but rsconstruct.lock wants {version}",
            pin.url
        );
    }
    if let ArchiveKind::Tree { exe, .. } = recipe.archive {
        // The unpacked prefix is the package's: its top-level entries move up.
        let tree = std::path::PathBuf::from(tree_dir(&work.to_string_lossy(), recipe.dest))
            .join(tree_prefix(exe));
        let entries = std::fs::read_dir(&tree)
            .with_context(|| format!("Failed to read directory {}", tree.display()))?;
        for entry in entries {
            let entry =
                entry.with_context(|| format!("Failed to read directory {}", tree.display()))?;
            let dest = prefix.join(entry.file_name());
            std::fs::rename(entry.path(), &dest).with_context(|| {
                format!(
                    "Failed to move {} into place as {}",
                    entry.path().display(),
                    dest.display()
                )
            })?;
        }
    } else {
        let bin = prefix.join("bin");
        std::fs::create_dir_all(&bin)
            .with_context(|| format!("Failed to create {}", bin.display()))?;
        let dest = bin.join(recipe.dest);
        std::fs::rename(payload, &dest).with_context(|| {
            format!(
                "Failed to move {} into place as {}",
                payload.display(),
                dest.display()
            )
        })?;
    }
    std::fs::remove_dir_all(&work).with_context(|| format!("Failed to remove {}", work.display()))
}

fn sudo_argv() -> &'static [&'static str] {
    if crate::platform::needs_sudo() {
        &["sudo"]
    } else {
        &[]
    }
}

/// The argv prefix for installing crates. `--locked` builds each crate with
/// the Cargo.lock it was published with instead of re-resolving its
/// dependencies on the installing machine, so the same crate version yields
/// the same binary everywhere. `--force` makes cargo replace a binary of the
/// same name that it did not install itself — without it cargo refuses with
/// "binary `x` already exists in destination", which is exactly what a CI
/// cache holding a prebuilt nextest tarball produced once the crate list
/// took over. It never causes extra work: only tools absent from PATH reach
/// this command, so the build was going to happen anyway. This is the
/// machine install of `tool install machine`; a project's crates
/// go into its tool directory instead (see [`install_into_prefix`]). Used by
/// both `describe` and `run` so the printed plan matches what executes.
fn cargo_install_argv() -> Vec<String> {
    vec![
        "cargo".to_string(),
        "install".to_string(),
        "--locked".to_string(),
        "--force".to_string(),
    ]
}

/// The argv prefix for installing gems. Appends `--user-install` when a
/// plain `gem install` would die on an unwritable default gem dir — the
/// apt-ruby case, where gems go to root-owned `/var/lib/gems` and rsconstruct
/// deliberately doesn't sudo-wrap language package managers. Used by both
/// `describe` and `run` so the printed plan matches what executes.
fn gem_install_argv() -> Vec<String> {
    let mut argv = vec!["gem".to_string(), "install".to_string()];
    if gem_needs_user_install() {
        argv.push("--user-install".to_string());
    }
    argv
}

/// The project install of the repo's Python packages: `uv sync` builds the
/// repo's `.venv` from uv.lock, the code's dependencies and the Python
/// tools its processors run together. `--locked` fails when uv.lock is out
/// of date with pyproject.toml instead of quietly re-resolving it.
/// `--no-install-project` leaves the project itself out: building it is
/// the build's job, not the install's, and a package whose build needs
/// something CI does not have (a build hook demanding an uncommitted
/// `client_secret.json`) failed the install outright when it was in. Used
/// by both `describe` and `run` so the printed plan matches what executes.
fn uv_sync_argv() -> Vec<String> {
    ["uv", "sync", "--locked", "--no-install-project"]
        .iter()
        .map(|s| (*s).to_string())
        .collect()
}

/// Whether the default gem dir is unwritable for the current user (never
/// true for root). Asks `gem env gemdir` once per process; a missing or
/// broken `gem` reports false and lets the install fail with gem's own
/// message.
fn gem_needs_user_install() -> bool {
    static NEEDS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *NEEDS.get_or_init(|| {
        if crate::platform::is_root() {
            return false;
        }
        let Ok(out) = std::process::Command::new("gem")
            .args(["env", "gemdir"])
            .output()
        else {
            return false;
        };
        if !out.status.success() {
            return false;
        }
        let stdout = String::from_utf8_lossy(&out.stdout);
        let gemdir = std::path::Path::new(stdout.trim());
        if gemdir.as_os_str().is_empty() {
            return false;
        }
        !nearest_existing_ancestor_is_writable(gemdir)
    })
}

/// `access(W_OK)` on the path, or — when it doesn't exist yet — on its
/// nearest existing ancestor, which is what decides whether the path could
/// be created.
fn nearest_existing_ancestor_is_writable(path: &std::path::Path) -> bool {
    let mut p = path;
    loop {
        if p.exists() {
            return crate::platform::path_is_writable(p);
        }
        match p.parent() {
            Some(parent) => p = parent,
            None => return false,
        }
    }
}

/// Make the project's own Node.js executables resolvable: prepend
/// `./node_modules/.bin`, when it exists, to this process's PATH, so
/// `which`-based tool probes and every spawned child (tools, processor
/// scripts) see the packages `tool install project` put there from
/// package.json.
/// Prepended, not appended: the version the project's lock pins must win
/// over a global install of the same tool, which is the whole point of
/// installing from the lock. This is what `npm run` does for scripts.
///
/// Called once at the top of `main()`, before any thread exists — the
/// safety condition of `platform::set_env`.
pub fn augment_path_with_node_modules_bin() {
    let Ok(cwd) = std::env::current_dir() else {
        return;
    };
    let bin = cwd.join("node_modules").join(".bin");
    if !bin.is_dir() {
        return;
    }
    let path = std::env::var_os("PATH").unwrap_or_default();
    if let Some(new_path) = path_with_prepended_dir(&path, &bin) {
        crate::platform::set_env("PATH", &new_path);
    }
}

/// Make the repo's Python environment the one everything runs in: prepend
/// `./.venv/bin` to this process's PATH. That is where `tool install
/// project` (`uv sync`) puts the code's dependencies and the Python tools
/// its processors run, and with it first, `python`, `ruff` and `pytest`
/// resolve to the locked copies with no venv activated, in a shell or on a
/// CI runner alike.
///
/// Only in a project directory (one with rsconstruct.toml), and like the
/// tool directory's `bin/`, even before `.venv` exists, so the environment
/// `uv sync` creates in this very invocation is found by what it runs next.
///
/// Called once at the top of `main()`, before any thread exists — the
/// safety condition of `platform::set_env`.
pub fn augment_path_with_repo_venv() {
    let Ok(cwd) = std::env::current_dir() else {
        return;
    };
    if !cwd.join(crate::config::CONFIG_FILE).exists() {
        return;
    }
    let bin = cwd.join(".venv").join("bin");
    let path = std::env::var_os("PATH").unwrap_or_default();
    if let Some(new_path) = path_with_prepended_dir(&path, &bin) {
        crate::platform::set_env("PATH", &new_path);
    }
}

/// `path` with `dir` moved to the front, or `None` when it is already
/// first. An occurrence further back is dropped rather than duplicated.
pub fn path_with_prepended_dir(
    path: &std::ffi::OsStr,
    dir: &std::path::Path,
) -> Option<std::ffi::OsString> {
    let existing: Vec<std::path::PathBuf> = std::env::split_paths(path).collect();
    if existing.first().is_some_and(|first| first == dir) {
        return None;
    }
    let rest = existing.into_iter().filter(|p| p != dir);
    // join_paths only errors on an entry containing the separator, which
    // can't happen: every entry came from split_paths or is a real dir.
    std::env::join_paths(std::iter::once(dir.to_path_buf()).chain(rest)).ok()
}

/// Make user-installed gem executables resolvable: append the user gem bin
/// dirs that exist to this process's PATH, so `which`-based tool probes and
/// every spawned child (tools, processor scripts) see them. `gem install
/// --user-install` puts binaries in a dir that is on nobody's PATH by
/// default, which would otherwise leave a just-installed tool reported as
/// missing.
///
/// Called once at the top of `main()`, before any thread exists — the
/// safety condition of `platform::set_env`.
pub fn augment_path_with_user_gem_bins() {
    let Some(home) = std::env::var_os("HOME") else {
        return;
    };
    let gem_home = std::env::var_os("GEM_HOME");
    let dirs = user_gem_bin_dirs(std::path::Path::new(&home), gem_home.as_deref());
    if dirs.is_empty() {
        return;
    }
    let path = std::env::var_os("PATH").unwrap_or_default();
    if let Some(new_path) = path_with_appended_dirs(&path, &dirs) {
        crate::platform::set_env("PATH", &new_path);
    }
}

/// Existing user-level gem executable dirs: `$GEM_HOME/bin` plus the
/// per-ruby-version `bin` dirs of both user-install layouts —
/// `~/.gem/ruby/<version>/bin` (upstream rubygems) and
/// `~/.local/share/gem/ruby/<version>/bin` (the Debian/Ubuntu XDG patch).
/// Only dirs that exist are returned; globbing the layouts costs two
/// readdirs and avoids spawning ruby at every startup.
fn user_gem_bin_dirs(
    home: &std::path::Path,
    gem_home: Option<&std::ffi::OsStr>,
) -> Vec<std::path::PathBuf> {
    let mut dirs = Vec::new();
    if let Some(gem_home) = gem_home {
        let bin = std::path::Path::new(gem_home).join("bin");
        if bin.is_dir() {
            dirs.push(bin);
        }
    }
    for base in [home.join(".gem/ruby"), home.join(".local/share/gem/ruby")] {
        let Ok(entries) = std::fs::read_dir(&base) else {
            continue;
        };
        let mut versions: Vec<std::path::PathBuf> = entries
            .flatten()
            .map(|e| e.path().join("bin"))
            .filter(|p| p.is_dir())
            .collect();
        versions.sort();
        dirs.append(&mut versions);
    }
    dirs
}

/// `path` with the dirs not already on it appended, or None when every dir
/// is already present. Append rather than prepend: a system-installed tool
/// keeps winning over a user gem of the same name.
fn path_with_appended_dirs(
    path: &std::ffi::OsStr,
    dirs: &[std::path::PathBuf],
) -> Option<std::ffi::OsString> {
    let existing: Vec<std::path::PathBuf> = std::env::split_paths(path).collect();
    let missing: Vec<std::path::PathBuf> = dirs
        .iter()
        .filter(|d| !existing.contains(d))
        .cloned()
        .collect();
    if missing.is_empty() {
        return None;
    }
    // join_paths only errors on an entry containing the separator, which
    // can't happen: every entry came from split_paths or is a real dir.
    std::env::join_paths(existing.into_iter().chain(missing)).ok()
}

fn join_argv(argv: &[String]) -> String {
    argv.join(" ")
}

/// The directory `run_binary` downloads and unpacks into: this process's
/// own, under the system temp directory, created private (see
/// `platform::create_private_dir`) for one install and removed after it.
///
/// It used to be `/tmp` itself, with file names made from the tool's name
/// alone. Two installs of one tool on the same host then shared every
/// path, one removing or renaming the file the other was about to hash or
/// `sudo mv`; and a name anyone can predict in a directory anyone can
/// write to is a name another user can occupy first.
fn install_work_dir() -> String {
    std::env::temp_dir()
        .join(format!("rsconstruct-install-{}", std::process::id()))
        .to_string_lossy()
        .into_owned()
}

/// Description of the steps that `run_binary` would execute, for the
/// install plan `tool install` prints and the `-i` prompt shows. Built
/// from the same [`FetchPlan`] `fetch_binary` executes, at the same URL
/// `run_binary` downloads (the locked one when `binary_pins` has an entry),
/// so the preview cannot drift from the install. The one thing it cannot
/// show is a GitHub-release `.deb`'s asset URL, which is resolved from the
/// releases API at install time: a preview must not make that call.
fn describe_binary(
    pkg: &str,
    binary_pins: &std::collections::BTreeMap<String, crate::tool_lock::BinaryPin>,
) -> Vec<Vec<String>> {
    let Some(recipe) = binary_recipe(pkg) else {
        return vec![vec![format!("# unknown binary recipe '{pkg}'")]];
    };
    let mut steps: Vec<Vec<String>> = Vec::new();
    let pin = binary_pins.get(pkg);
    let url = match (pin, &recipe.archive) {
        (Some(pin), _) => pin.url.clone(),
        (
            None,
            ArchiveKind::Deb {
                source:
                    DebSource::GithubRelease {
                        repo,
                        asset_pattern,
                    },
            },
        ) => {
            steps.push(vec![format!(
                "# resolve latest '{asset_pattern}' .deb asset from {repo}"
            )]);
            "<resolved-asset-url>".to_string()
        }
        (
            None,
            ArchiveKind::Deb {
                source: DebSource::Url(url),
            },
        ) => (*url).to_string(),
        (None, _) => recipe.url.to_string(),
    };
    let work_dir = install_work_dir();
    let plan = fetch_plan(&recipe, &url, &work_dir);
    steps.push(plan.curl);
    if let Some(pin) = pin {
        steps.push(vec![format!(
            "# sha256 of {} must be {} (rsconstruct.lock)",
            plan.download, pin.sha256
        )]);
    }
    steps.extend(plan.unpack.iter().map(Step::argv));
    if let ArchiveKind::Tree { exe, .. } = recipe.archive {
        let prefix = std::path::Path::new(&tree_dir(&work_dir, recipe.dest)).join(tree_prefix(exe));
        steps.push(vec![format!(
            "# {} becomes the package's prefix in {}",
            prefix.display(),
            crate::tool_store::REPO_TOOLS_DIR
        )]);
    } else {
        steps.push(install_argv(&recipe, &plan.payload));
    }
    steps
}

/// One step of turning a downloaded file into an installable one.
/// `fetch_binary` runs these and `describe_binary` prints them, from the
/// same [`FetchPlan`], so what is shown is what happens.
enum Step {
    /// Spawn argv with the terminal inherited.
    Exec(Vec<String>),
    Rename {
        from: String,
        to: String,
    },
    Remove(String),
    /// `chmod 0755`.
    MakeExecutable(String),
}

impl Step {
    /// The step as the command it amounts to, for previews.
    fn argv(&self) -> Vec<String> {
        match self {
            Self::Exec(argv) => argv.clone(),
            Self::Rename { from, to } => vec!["mv".to_string(), from.clone(), to.clone()],
            Self::Remove(path) => vec!["rm".to_string(), path.clone()],
            Self::MakeExecutable(path) => {
                vec!["chmod".to_string(), "+x".to_string(), path.clone()]
            }
        }
    }

    fn run(&self, verbose: bool) -> anyhow::Result<()> {
        use anyhow::Context as _;
        match self {
            Self::Exec(argv) => exec_inherited(
                &argv.iter().map(String::as_str).collect::<Vec<_>>(),
                verbose,
            ),
            Self::Rename { from, to } => {
                std::fs::rename(from, to).with_context(|| format!("rename {from} -> {to}"))
            }
            Self::Remove(path) => {
                std::fs::remove_file(path).with_context(|| format!("remove {path}"))
            }
            Self::MakeExecutable(path) => {
                crate::platform::set_permissions_mode(std::path::Path::new(path), 0o755)
                    .with_context(|| format!("chmod +x {path}"))
            }
        }
    }
}

/// How a recipe's payload gets from its URL to an installable file under
/// a work directory.
struct FetchPlan {
    /// Where curl puts the download: the archive, the binary itself, or
    /// the `.deb`.
    download: String,
    /// The curl argv that fetches `download`.
    curl: Vec<String>,
    /// What turns `download` into `payload`, in order, after the download's
    /// hash has been checked. Empty for a `.deb`, which apt installs as is.
    unpack: Vec<Step>,
    /// The executable ready to move into place, or the `.deb` for apt.
    payload: String,
}

/// The plan for `recipe`, downloading `url` into `base`.
fn fetch_plan(recipe: &BinaryRecipe, url: &str, base: &str) -> FetchPlan {
    let dest = recipe.dest;
    let final_tmp = format!("{base}/{dest}");
    let exec = |parts: &[&str]| Step::Exec(parts.iter().map(|s| (*s).to_string()).collect());
    let (download, unpack) = match recipe.archive {
        // A .deb is installed by apt as is: apt pulls the dependency tree
        // a bare binary would be missing, and the payload is not a single
        // executable.
        ArchiveKind::Deb { .. } => {
            let download = format!("{base}/{dest}.deb");
            return FetchPlan {
                curl: crate::download::curl_argv(url, &download),
                payload: download.clone(),
                download,
                unpack: Vec::new(),
            };
        }
        ArchiveKind::TarGz { inner } | ArchiveKind::Zip { inner } => {
            let download = format!("{base}/{dest}.dl");
            let extract = match recipe.archive {
                ArchiveKind::TarGz { .. } => exec(&["tar", "-xzf", &download, "-C", base, inner]),
                _ => exec(&["unzip", "-o", &download, inner, "-d", base]),
            };
            let mut unpack = vec![extract];
            // The member lands at <base>/<inner>, which need not be <dest>
            // (oxlint's is named after the target triple).
            let inner_path = format!("{base}/{inner}");
            if inner_path != final_tmp {
                unpack.push(Step::Rename {
                    from: inner_path,
                    to: final_tmp.clone(),
                });
            }
            unpack.push(Step::Remove(download.clone()));
            (download, unpack)
        }
        ArchiveKind::Gunzip => {
            // gunzip insists on a .gz name and strips it: the download is
            // renamed to <dest>.dl.gz, so gunzip leaves <dest>.dl, which
            // then moves to <dest>.
            let download = format!("{base}/{dest}.dl");
            let gz = format!("{download}.gz");
            let unpack = vec![
                Step::Rename {
                    from: download.clone(),
                    to: gz.clone(),
                },
                exec(&["gunzip", "-f", &gz]),
                Step::Rename {
                    from: download.clone(),
                    to: final_tmp.clone(),
                },
            ];
            (download, unpack)
        }
        ArchiveKind::Raw => {
            let download = format!("{base}/{dest}.dl");
            let unpack = vec![Step::Rename {
                from: download.clone(),
                to: final_tmp.clone(),
            }];
            (download, unpack)
        }
        // The whole archive is unpacked; the executable stays in its tree.
        ArchiveKind::Tree { packing, exe } => {
            let download = format!("{base}/{dest}.dl");
            let tree = tree_dir(base, dest);
            let payload = format!("{tree}/{exe}");
            let mut unpack = match packing {
                Packing::Zip => vec![exec(&["unzip", "-q", "-o", &download, "-d", &tree])],
                // tar finds the compression (gzip, xz) from the file itself.
                Packing::Tar => vec![
                    exec(&["mkdir", "-p", &tree]),
                    exec(&["tar", "-xf", &download, "-C", &tree]),
                ],
            };
            unpack.push(Step::Remove(download.clone()));
            unpack.push(Step::MakeExecutable(payload.clone()));
            return FetchPlan {
                curl: crate::download::curl_argv(url, &download),
                unpack,
                download,
                payload,
            };
        }
    };
    let mut unpack = unpack;
    unpack.push(Step::MakeExecutable(final_tmp.clone()));
    FetchPlan {
        curl: crate::download::curl_argv(url, &download),
        download,
        unpack,
        payload: final_tmp,
    }
}

/// Where a [`ArchiveKind::Tree`] recipe unpacks its archive under `base`.
fn tree_dir(base: &str, dest: &str) -> String {
    format!("{base}/{dest}.tree")
}

/// The install prefix inside a [`ArchiveKind::Tree`] archive: its `exe`
/// member (`<prefix>/bin/<name>`) without the `bin/<name>`. Empty when the
/// archive's root is the prefix.
fn tree_prefix(exe: &str) -> &std::path::Path {
    std::path::Path::new(exe)
        .parent()
        .and_then(std::path::Path::parent)
        .unwrap_or_else(|| std::path::Path::new(""))
}

/// The command that installs a fetched payload: apt for a `.deb`, a move
/// into `/usr/local/bin` for an executable. Shared by `run_binary` and
/// `describe_binary`. Not for a [`ArchiveKind::Tree`], which only a
/// project's tool directory installs.
fn install_argv(recipe: &BinaryRecipe, payload: &str) -> Vec<String> {
    let mut argv: Vec<String> = sudo_argv().iter().map(|s| (*s).to_string()).collect();
    if matches!(recipe.archive, ArchiveKind::Deb { .. }) {
        argv.extend(["apt-get", "install", "-y", payload].map(str::to_string));
    } else {
        argv.extend([
            "mv".to_string(),
            payload.to_string(),
            format!("/usr/local/bin/{}", recipe.dest),
        ]);
    }
    argv
}

/// The GitHub API's description of `repo`'s latest release.
fn latest_github_release(repo: &str) -> anyhow::Result<serde_json::Value> {
    crate::download::get_json(&format!(
        "https://api.github.com/repos/{repo}/releases/latest"
    ))
}

/// The `releases/latest/download/` infix of a GitHub URL that always serves
/// the newest release's asset of that name.
const GITHUB_LATEST_DOWNLOAD: &str = "/releases/latest/download/";

/// Rewrite a `https://github.com/<owner>/<repo>/releases/latest/download/<asset>`
/// URL to the same asset of release `tag`, or None when `url` is not one.
fn pin_github_latest_url(url: &str, tag: &str) -> Option<String> {
    let rest = url.strip_prefix("https://github.com/")?;
    let at = rest.find(GITHUB_LATEST_DOWNLOAD)?;
    let repo = &rest[..at];
    let asset = &rest[at + GITHUB_LATEST_DOWNLOAD.len()..];
    Some(format!(
        "https://github.com/{repo}/releases/download/{tag}/{asset}"
    ))
}

/// The `<owner>/<repo>` of a `https://github.com/<owner>/<repo>/...` URL.
fn github_repo_of(url: &str) -> Option<&str> {
    let rest = url.strip_prefix("https://github.com/")?;
    let owner_end = rest.find('/')?;
    let repo_end = rest[owner_end + 1..]
        .find('/')
        .map_or(rest.len(), |i| owner_end + 1 + i);
    Some(&rest[..repo_end])
}

/// Resolve the browser-download URL of the newest release asset in `repo`
/// whose name contains `asset_pattern` and ends in `.deb`. Resolving at
/// install time (instead of pinning a URL in the recipe) is what keeps the
/// recipe from breaking every time upstream cuts a release.
fn resolve_latest_deb_asset(repo: &str, asset_pattern: &str) -> anyhow::Result<String> {
    use anyhow::Context as _;
    // Authenticated and retried by download::get_json; see there for why.
    let release = latest_github_release(repo)?;
    release["assets"]
        .as_array()
        .with_context(|| format!("GitHub release for {repo} has no 'assets' array"))?
        .iter()
        .find_map(|a| {
            let name = a["name"].as_str()?;
            let is_deb = std::path::Path::new(name)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("deb"));
            (name.contains(asset_pattern) && is_deb)
                .then(|| a["browser_download_url"].as_str())?
                .map(std::string::ToString::to_string)
        })
        .with_context(|| {
            format!("No .deb asset matching '{asset_pattern}' in the latest {repo} release")
        })
}

/// Run `argv` with the terminal inherited, failing on a non-zero exit.
///
/// Same exception as `run()` above: the binary installer shells out to
/// `sudo mv` / `sudo apt-get`, which need the terminal for a password
/// prompt, so these steps cannot go through the capturing central runner.
fn exec_inherited(argv: &[&str], verbose: bool) -> anyhow::Result<()> {
    exec_inherited_env(argv, &[], verbose)
}

/// [`exec_inherited`] with extra environment variables for the child.
fn exec_inherited_env(argv: &[&str], env: &[(&str, &str)], verbose: bool) -> anyhow::Result<()> {
    use anyhow::Context as _;
    if verbose {
        println!("Running: {}", argv.join(" "));
    }
    let status = std::process::Command::new(argv[0])
        .args(&argv[1..])
        .envs(env.iter().copied())
        .status()
        .with_context(|| format!("failed to spawn: {}", argv.join(" ")))?;
    if !status.success() {
        anyhow::bail!(
            "{} exited with code {}",
            argv.join(" "),
            status
                .code()
                .map_or_else(|| "unknown".to_string(), |c| c.to_string())
        );
    }
    Ok(())
}

/// Remove from `bin` every executable that is not gem `name`'s own.
///
/// `gem install --bindir` writes a binstub for every gem it installs, the
/// dependencies included, so the package of `jekyll` came with `kramdown`,
/// `rougify`, `rake` and more. A package's executables are what a project's
/// `bin/` exposes, and two packages may not expose the same one: `jekyll`
/// and `mdl` both depend on kramdown, so a project that locked both could
/// not install its tools. The dependencies stay installed as libraries;
/// only their binstubs go, and the gem's own never needed them.
fn keep_own_gem_executables(
    name: &str,
    version: &str,
    gem_home: &str,
    bin: &std::path::Path,
) -> anyhow::Result<()> {
    use anyhow::Context as _;
    let argv = [
        "gem",
        "specification",
        name,
        "--version",
        version,
        "executables",
    ];
    let out = std::process::Command::new(argv[0])
        .args(&argv[1..])
        .envs([("GEM_HOME", gem_home), ("GEM_PATH", gem_home)])
        .output()
        .with_context(|| format!("failed to spawn: {}", argv.join(" ")))?;
    if !out.status.success() {
        anyhow::bail!(
            "{} failed: {}",
            argv.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let own = gem_executables(&String::from_utf8_lossy(&out.stdout));
    let entries = match std::fs::read_dir(bin) {
        Ok(entries) => entries,
        // A gem with no executable of its own or of any dependency.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e).with_context(|| format!("Failed to read {}", bin.display())),
    };
    for entry in entries {
        let entry = entry.with_context(|| format!("Failed to read {}", bin.display()))?;
        if !own.contains(&entry.file_name().to_string_lossy().into_owned()) {
            std::fs::remove_file(entry.path())
                .with_context(|| format!("Failed to remove {}", entry.path().display()))?;
        }
    }
    Ok(())
}

/// The executable names in the output of `gem specification <gem>
/// executables`: a YAML document that is a list of plain names, one `- name`
/// line each (`--- []` for a gem with none).
fn gem_executables(yaml: &str) -> Vec<String> {
    yaml.lines()
        .filter_map(|line| line.strip_prefix("- "))
        .map(|name| name.trim().trim_matches(['"', '\'']).to_string())
        .collect()
}

/// SHA-256 of a file's bytes, hex-encoded, streamed rather than read whole
/// (a `.deb` payload runs to hundreds of megabytes).
pub fn file_sha256(path: &std::path::Path) -> anyhow::Result<String> {
    use anyhow::Context as _;
    use sha2::Digest as _;
    let mut file = std::fs::File::open(path)
        .with_context(|| format!("Failed to open {} for hashing", path.display()))?;
    let mut hasher = sha2::Sha256::new();
    std::io::copy(&mut file, &mut hasher)
        .with_context(|| format!("Failed to read {} for hashing", path.display()))?;
    Ok(hex::encode(hasher.finalize()))
}

/// A binary recipe's payload, downloaded and unpacked into a work directory
/// but not yet installed.
#[derive(Debug)]
struct FetchedBinary {
    /// SHA-256 of the file as downloaded (the archive, for an archive).
    download_sha256: String,
    /// The executable ready to move into place, or the `.deb` for apt.
    payload: String,
}

/// Download `url` into `base` and unpack `recipe`'s executable from it,
/// following [`fetch_plan`]. With `expected_sha256`, a download whose hash
/// differs is an error: the lock said which bytes to install, and these
/// are not they.
///
/// Shared by `run_binary` (base [`install_work_dir`], the paths
/// `describe_binary` shows) and `tool lock` (a private directory), so a
/// locked hash is always the hash of exactly what an install downloads.
fn fetch_binary(
    recipe: &BinaryRecipe,
    url: &str,
    expected_sha256: Option<&str>,
    base: &str,
    verbose: bool,
) -> anyhow::Result<FetchedBinary> {
    let plan = fetch_plan(recipe, url, base);
    exec_inherited(
        &plan.curl.iter().map(String::as_str).collect::<Vec<_>>(),
        verbose,
    )?;
    let download_sha256 = file_sha256(std::path::Path::new(&plan.download))?;
    if let Some(expected) = expected_sha256
        && expected != download_sha256
    {
        std::fs::remove_file(&plan.download).ok();
        anyhow::bail!(
            "{url} does not match rsconstruct.lock: sha256 {download_sha256}, locked {expected}"
        );
    }
    for step in &plan.unpack {
        step.run(verbose)?;
    }
    Ok(FetchedBinary {
        download_sha256,
        payload: plan.payload,
    })
}

/// The URL `pkg`'s recipe downloads when no lock entry says otherwise: a
/// GitHub-release `.deb` resolved to today's latest asset, a vendor URL as
/// is, and anything else straight from the recipe.
fn unpinned_binary_url(recipe: &BinaryRecipe) -> anyhow::Result<String> {
    match recipe.archive {
        ArchiveKind::Deb {
            source:
                DebSource::GithubRelease {
                    repo,
                    asset_pattern,
                },
        } => resolve_latest_deb_asset(repo, asset_pattern),
        ArchiveKind::Deb {
            source: DebSource::Url(url),
        } => Ok(url.to_string()),
        _ => Ok(recipe.url.to_string()),
    }
}

fn run_binary(pkg: &str, ctx: &InstallCtx) -> anyhow::Result<()> {
    let recipe = binary_recipe(pkg)
        .ok_or_else(|| anyhow::anyhow!("no binary install recipe for '{pkg}'"))?;
    if matches!(recipe.archive, ArchiveKind::Tree { .. }) {
        anyhow::bail!(
            "the '{pkg}' binary is a whole release tree, installed only into a project \
             (`rsconstruct tool install project {pkg}`)"
        );
    }
    // A lock entry decides the exact asset and its bytes. Without one (no
    // project, or a recipe that cannot be pinned) the recipe would decide,
    // and nothing would vouch for the bytes: that takes an explicit yes.
    let pin = ctx.binary_pins.get(pkg);
    if pin.is_none() && !ctx.allow_unpinned {
        anyhow::bail!(
            "Refusing to install the release binary '{pkg}': rsconstruct.lock does not pin it\n{UNPINNED_HELP}"
        );
    }
    let url = match pin {
        Some(pin) => pin.url.clone(),
        None => unpinned_binary_url(&recipe)?,
    };
    use anyhow::Context as _;
    let work_dir = install_work_dir();
    crate::platform::create_private_dir(std::path::Path::new(&work_dir)).with_context(|| {
        format!("Failed to create the install work directory {work_dir} (remove it if a crashed install left it)")
    })?;
    let result = fetch_binary(
        &recipe,
        &url,
        pin.map(|p| p.sha256.as_str()),
        &work_dir,
        ctx.verbose,
    )
    .and_then(|fetched| {
        // Nothing vouches for these bytes but the server they came from;
        // say which they were, so the install can be told from another.
        if pin.is_none() {
            crate::output::info(&format!(
                "{pkg}: not pinned in rsconstruct.lock; installing {url} (sha256 {})",
                fetched.download_sha256
            ));
        }
        let argv = install_argv(&recipe, &fetched.payload);
        exec_inherited(
            &argv.iter().map(String::as_str).collect::<Vec<_>>(),
            ctx.verbose,
        )
    });
    // The download, and whatever unpacking left beside the executable
    // that `mv` consumed or the `.deb` apt copied into its cache.
    let removed = std::fs::remove_dir_all(&work_dir)
        .with_context(|| format!("Failed to remove the install work directory {work_dir}"));
    result.and(removed)
}

/// Whether `pkg`'s binary recipe can be recorded in rsconstruct.lock. A
/// vendor `.deb` URL that always serves the current build (Chrome's) names
/// no release that could be installed again later, so it cannot.
pub fn binary_is_pinnable(pkg: &str) -> bool {
    binary_recipe(pkg).is_some_and(|r| {
        !matches!(
            r.archive,
            ArchiveKind::Deb {
                source: DebSource::Url(_)
            }
        )
    })
}

/// Whether `pkg`'s binary installs into a project's tool directory: every
/// recipe but a `.deb`, which apt installs onto the machine.
pub fn binary_is_repo_local(pkg: &str) -> bool {
    binary_recipe(pkg).is_some_and(|r| !matches!(r.archive, ArchiveKind::Deb { .. }))
}

/// Resolve `pkg`'s binary to the exact asset of today's latest release and
/// record what installing it puts on disk: the download's SHA-256, plus the
/// executable's SHA-256 (or, for a `.deb`, its package name and version) so
/// an installed copy can later be checked against the lock.
pub fn lock_binary(
    ctx: &crate::build_context::BuildContext,
    pkg: &str,
    verbose: bool,
) -> anyhow::Result<crate::tool_lock::BinaryPin> {
    use anyhow::Context as _;
    let recipe = binary_recipe(pkg)
        .ok_or_else(|| anyhow::anyhow!("no binary install recipe for '{pkg}'"))?;
    if !binary_is_pinnable(pkg) {
        anyhow::bail!("the '{pkg}' binary is a vendor URL with no versioned release to lock");
    }
    let url = if recipe.url.contains(GITHUB_LATEST_DOWNLOAD) {
        let repo = github_repo_of(recipe.url)
            .with_context(|| format!("cannot tell the GitHub repo of {}", recipe.url))?;
        let release = latest_github_release(repo)?;
        let tag = release["tag_name"]
            .as_str()
            .with_context(|| format!("the latest {repo} release has no tag_name"))?;
        pin_github_latest_url(recipe.url, tag)
            .with_context(|| format!("cannot pin {} to release {tag}", recipe.url))?
    } else {
        unpinned_binary_url(&recipe)?
    };
    let base = std::env::temp_dir().join(format!("rsconstruct-lock-{}-{pkg}", std::process::id()));
    std::fs::create_dir_all(&base)
        .with_context(|| format!("Failed to create {}", base.display()))?;
    let result = (|| {
        let fetched = fetch_binary(&recipe, &url, None, &base.to_string_lossy(), verbose)?;
        let mut pin = crate::tool_lock::BinaryPin {
            url: url.clone(),
            sha256: fetched.download_sha256,
            executable_sha256: None,
            deb_package: None,
            deb_version: None,
        };
        if matches!(recipe.archive, ArchiveKind::Deb { .. }) {
            let mut cmd = std::process::Command::new("dpkg-deb");
            cmd.args(["-f", &fetched.payload, "Package", "Version"]);
            let out = crate::processor::run_command_capture(ctx, &cmd)
                .with_context(|| format!("failed to run `dpkg-deb -f {}`", fetched.payload))?;
            if !out.status.success() {
                anyhow::bail!(
                    "`dpkg-deb -f {}` failed: {}",
                    fetched.payload,
                    String::from_utf8_lossy(&out.stderr).trim()
                );
            }
            let fields = String::from_utf8_lossy(&out.stdout).into_owned();
            let field = |name: &str| {
                fields.lines().find_map(|l| {
                    l.strip_prefix(name)
                        .and_then(|v| v.strip_prefix(':'))
                        .map(|v| v.trim().to_string())
                })
            };
            pin.deb_package = field("Package");
            pin.deb_version = field("Version");
            if pin.deb_package.is_none() || pin.deb_version.is_none() {
                anyhow::bail!("{url}: the .deb names no Package/Version");
            }
        } else {
            pin.executable_sha256 = Some(file_sha256(std::path::Path::new(&fetched.payload))?);
        }
        Ok(pin)
    })();
    std::fs::remove_dir_all(&base).ok();
    result
}

struct BinaryRecipe {
    url: &'static str,
    archive: ArchiveKind,
    dest: &'static str,
}

enum ArchiveKind {
    TarGz {
        inner: &'static str,
    },
    /// A `.zip` holding the binary as the member `inner`.
    Zip {
        inner: &'static str,
    },
    Gunzip,
    /// The download is the binary itself, no extraction needed.
    Raw,
    /// An archive holding an install prefix (`bin/` beside the `include/`,
    /// `lib/` or `share/` the executables find relative to their own path),
    /// kept whole. Installed only into a project's tool directory, where a
    /// package has a prefix of its own, and every executable in the
    /// prefix's `bin/` goes on PATH. `exe` is the member the lock hashes,
    /// `<prefix>/bin/<name>`: the prefix is the archive's root
    /// (`bin/protoc`) or its top directory (`node-v26.13.0-linux-x64/bin/node`).
    Tree {
        packing: Packing,
        exe: &'static str,
    },
    /// The download is a `.deb` installed with apt, not a bare binary dropped
    /// into /usr/local/bin: apt pulls the dependency tree a raw binary would
    /// be missing.
    ///
    /// `source` says where the `.deb` comes from — a GitHub release whose
    /// asset is resolved at install time (so the recipe doesn't pin a version
    /// that goes stale the moment upstream cuts a release), or a vendor URL
    /// that is already stable.
    Deb {
        source: DebSource,
    },
}

/// How a [`ArchiveKind::Tree`] archive is packed.
#[derive(Clone, Copy)]
enum Packing {
    Zip,
    /// A tarball, compressed with whatever `tar -xf` recognizes.
    Tar,
}

/// Where a [`ArchiveKind::Deb`] payload is fetched from.
enum DebSource {
    /// Newest asset in `repo`'s latest release whose name contains
    /// `asset_pattern` and ends in `.deb`.
    GithubRelease {
        repo: &'static str,
        asset_pattern: &'static str,
    },
    /// A vendor URL that always points at the current build.
    Url(&'static str),
}

fn binary_recipe(pkg: &str) -> Option<BinaryRecipe> {
    match pkg {
        // Pinned like actionlint: oxlint lives in the oxc monorepo, whose
        // "latest" release is whichever crate was tagged most recently, so
        // there is no `releases/latest/download/...` URL that reliably names
        // an oxlint asset. Bump this deliberately. The tarball holds one
        // file named after the target triple, not `oxlint`.
        "oxlint" => Some(BinaryRecipe {
            url: "https://github.com/oxc-project/oxc/releases/download/oxlint_v1.86.0/oxlint-x86_64-unknown-linux-gnu.tar.gz",
            archive: ArchiveKind::TarGz {
                inner: "oxlint-x86_64-unknown-linux-gnu",
            },
            dest: "oxlint",
        }),
        "rumdl" => Some(BinaryRecipe {
            url: "https://github.com/rvben/rumdl/releases/download/v0.2.66/rumdl-v0.2.66-x86_64-unknown-linux-gnu.tar.gz",
            archive: ArchiveKind::TarGz { inner: "rumdl" },
            dest: "rumdl",
        }),
        // Pinned rather than tracking latest, unlike taplo/hadolint below.
        // zola 0.23 renamed config keys (highlight_code -> [markdown.highlighting])
        // and swapped the syntax highlighter, so an unpinned upgrade can fail a
        // site build on config alone -- a breakage that lands in the consuming
        // project's CI, not here. Bump this deliberately.
        "zola" => Some(BinaryRecipe {
            url: "https://github.com/getzola/zola/releases/download/v0.23.3/zola-v0.23.3-x86_64-unknown-linux-gnu.tar.gz",
            archive: ArchiveKind::TarGz { inner: "zola" },
            dest: "zola",
        }),
        "taplo" => Some(BinaryRecipe {
            url: "https://github.com/tamasfe/taplo/releases/latest/download/taplo-linux-x86_64.gz",
            archive: ArchiveKind::Gunzip,
            dest: "taplo",
        }),
        // Pinned like zola: actionlint's release assets embed the version in
        // the filename (actionlint_1.7.12_linux_amd64.tar.gz), so there is no
        // stable `releases/latest/download/...` URL to track the way taplo
        // and hadolint do. Bump this deliberately.
        "actionlint" => Some(BinaryRecipe {
            url: "https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz",
            archive: ArchiveKind::TarGz {
                inner: "actionlint",
            },
            dest: "actionlint",
        }),
        // Pinned like actionlint: selene's release assets embed the version
        // in the filename (selene-0.32.0-linux.zip). Bump this deliberately.
        // The full build, not selene-light: only the full one carries the
        // Roblox standard library, and the size difference is irrelevant.
        "selene" => Some(BinaryRecipe {
            url: "https://github.com/Kampfkarren/selene/releases/download/0.32.0/selene-0.32.0-linux.zip",
            archive: ArchiveKind::Zip { inner: "selene" },
            dest: "selene",
        }),
        "hadolint" => Some(BinaryRecipe {
            url: "https://github.com/hadolint/hadolint/releases/latest/download/hadolint-Linux-x86_64",
            archive: ArchiveKind::Raw,
            dest: "hadolint",
        }),
        // Tracks latest like hadolint: every release in the biome repo is a
        // CLI release, so `releases/latest` always carries the raw
        // `biome-linux-x64` asset. The glibc build, not the musl one, to match
        // the rest of the registry.
        "biome" => Some(BinaryRecipe {
            url: "https://github.com/biomejs/biome/releases/latest/download/biome-linux-x64",
            archive: ArchiveKind::Raw,
            dest: "biome",
        }),
        // Pinned like actionlint: shellcheck's release assets embed the
        // version in the filename and in the tarball's top directory. The
        // binary is statically linked. Bump this deliberately.
        "shellcheck" => Some(BinaryRecipe {
            url: "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.x86_64.tar.gz",
            archive: ArchiveKind::TarGz {
                inner: "shellcheck-v0.11.0/shellcheck",
            },
            dest: "shellcheck",
        }),
        // Tracks latest like hadolint: every jq release carries the raw,
        // statically linked `jq-linux-amd64` asset under that same name.
        "jq" => Some(BinaryRecipe {
            url: "https://github.com/jqlang/jq/releases/latest/download/jq-linux-amd64",
            archive: ArchiveKind::Raw,
            dest: "jq",
        }),
        // Pinned like actionlint: pandoc's release assets embed the version
        // in the filename and in the tarball's top directory. The binary is
        // statically linked; pandoc-server and pandoc-lua beside it are not
        // needed. A new pandoc can change generated documents, so bump this
        // deliberately.
        "pandoc" => Some(BinaryRecipe {
            url: "https://github.com/jgm/pandoc/releases/download/3.13/pandoc-3.13-linux-amd64.tar.gz",
            archive: ArchiveKind::TarGz {
                inner: "pandoc-3.13/bin/pandoc",
            },
            dest: "pandoc",
        }),
        // Pinned like actionlint: protoc's release assets embed the version
        // in the filename. Kept whole: protoc finds the well-known types
        // (google/protobuf/*.proto) in the include/ beside its bin/. Code it
        // generates checks the protobuf runtime it is compiled or imported
        // against, so bump this deliberately.
        "protoc" => Some(BinaryRecipe {
            url: "https://github.com/protocolbuffers/protobuf/releases/download/v36.2/protoc-36.2-linux-x86_64.zip",
            archive: ArchiveKind::Tree {
                packing: Packing::Zip,
                exe: "bin/protoc",
            },
            dest: "protoc",
        }),
        // Pinned like actionlint: qpdf's release assets embed the version in
        // the filename. Kept whole: qpdf loads libqpdf and the libraries
        // bundled with it from the lib/ beside its bin/ (RUNPATH
        // $ORIGIN/../lib).
        "qpdf" => Some(BinaryRecipe {
            url: "https://github.com/qpdf/qpdf/releases/download/v12.4.2/qpdf-12.4.2-bin-linux-x86_64.zip",
            archive: ArchiveKind::Tree {
                packing: Packing::Zip,
                exe: "bin/qpdf",
            },
            dest: "qpdf",
        }),
        // Pinned to one release: nodejs.org keeps every version under a
        // permanent URL, but has no GitHub-style "latest" redirect that
        // `tool lock --upgrade` could follow. The current LTS. Kept whole:
        // npm and npx in its bin/ link into the lib/node_modules beside it.
        // Bump this deliberately.
        "node" => Some(BinaryRecipe {
            url: "https://nodejs.org/dist/v26.13.0/node-v26.13.0-linux-x64.tar.xz",
            archive: ArchiveKind::Tree {
                packing: Packing::Tar,
                exe: "node-v26.13.0-linux-x64/bin/node",
            },
            dest: "node",
        }),
        // Pinned like node: LilyPond publishes its binaries on GitLab, one
        // permanent URL per version. 2.24.4 is the stable release the
        // fleet's scores were engraved with; a new LilyPond changes the
        // engraving, so bump this deliberately. Kept whole: lilypond runs
        // its bundled Guile, Ghostscript and Python from the tree.
        "lilypond" => Some(BinaryRecipe {
            url: "https://gitlab.com/api/v4/projects/lilypond%2Flilypond/packages/generic/lilypond/2.24.4/lilypond-2.24.4-linux-x86_64.tar.gz",
            archive: ArchiveKind::Tree {
                packing: Packing::Tar,
                exe: "lilypond-2.24.4/bin/lilypond",
            },
            dest: "lilypond",
        }),
        // FFmpeg publishes no binaries; BtbN's static GPL builds are the
        // usual source. Pinned to a month-end autobuild: BtbN prunes the
        // daily builds after about two weeks but keeps each month's last
        // one for about two years, while its "latest" assets are replaced
        // in place and would break a locked hash. The build is static;
        // ffprobe and ffplay come with it. Bump this deliberately, to a
        // newer month-end build.
        "ffmpeg" => Some(BinaryRecipe {
            url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-09-30-13-08/ffmpeg-n8.1.3-9-g29e619e767-linux64-gpl-8.1.tar.xz",
            archive: ArchiveKind::Tree {
                packing: Packing::Tar,
                exe: "ffmpeg-n8.1.3-9-g29e619e767-linux64-gpl-8.1/bin/ffmpeg",
            },
            dest: "ffmpeg",
        }),
        // Tracks latest like hadolint: every uv release carries this asset
        // under the same name. The glibc build, like the rest of the registry.
        "uv" => Some(BinaryRecipe {
            url: "https://github.com/astral-sh/uv/releases/latest/download/uv-x86_64-unknown-linux-gnu.tar.gz",
            archive: ArchiveKind::TarGz {
                inner: "uv-x86_64-unknown-linux-gnu/uv",
            },
            dest: "uv",
        }),
        // Tracks latest like hadolint: every zizmor release carries this
        // asset under the same name, the binary at the tarball's root.
        "zizmor" => Some(BinaryRecipe {
            url: "https://github.com/zizmorcore/zizmor/releases/latest/download/zizmor-x86_64-unknown-linux-gnu.tar.gz",
            archive: ArchiveKind::TarGz { inner: "zizmor" },
            dest: "zizmor",
        }),
        // Pinned like actionlint: tectonic's release assets embed the
        // version in the filename, and its tags are `tectonic@<version>`
        // (the `%40` below). The musl build: it is statically linked, where
        // the glibc one loads the machine's fontconfig, harfbuzz and ICU. A
        // new tectonic can change typeset documents, so bump this
        // deliberately.
        "tectonic" => Some(BinaryRecipe {
            url: "https://github.com/tectonic-typesetting/tectonic/releases/download/tectonic%400.17.0/tectonic-0.17.0-x86_64-unknown-linux-musl.tar.gz",
            archive: ArchiveKind::TarGz { inner: "tectonic" },
            dest: "tectonic",
        }),
        // checkpatch.pl ships only inside the kernel tree — there is no release
        // artifact and no distro package. Fetching the single script from
        // torvalds/linux master is the automatable equivalent of "copy it out
        // of a kernel checkout", and keeps the tool out of the manual-only
        // bucket that `tool install machine --all` rejects.
        //
        // Pinned to one kernel commit, not master: icheckpatch is a port of
        // this exact script and its tests compare the two line for line, so
        // a checkpatch.pl that moved on would fail them for changes the port
        // has not followed yet. Moving the pin means porting the diff
        // between the two commits into src/engines/checkpatch/ - do both in
        // the same change.
        "checkpatch.pl" => Some(BinaryRecipe {
            url: "https://raw.githubusercontent.com/torvalds/linux/e5f92606156a6a823992294d214c285b49cd72e9/scripts/checkpatch.pl",
            archive: ArchiveKind::Raw,
            dest: "checkpatch.pl",
        }),
        // The Nu Html Checker's jar, from the npm registry: the checker's
        // GitHub releases are one tag, `latest`, whose assets are replaced
        // in place on every upstream commit, so a locked hash of them
        // (the self-contained vnu.linux.zip included) would break within
        // days. The registry keeps every version of the `vnu-jar` package
        // under a permanent URL; the package is the jar plus a launcher
        // script that is not used. Run with `java -jar`. New versions
        // follow the HTML standard and can report new errors, so bump this
        // deliberately.
        "vnu.jar" => Some(BinaryRecipe {
            url: "https://registry.npmjs.org/vnu-jar/-/vnu-jar-26.11.14.tgz",
            archive: ArchiveKind::TarGz {
                inner: "package/build/dist/vnu.jar",
            },
            dest: "vnu.jar",
        }),
        // drawio ships an official .deb but has no apt repo, and its snap
        // needs a running snapd — unavailable in containers and flaky on CI
        // runners, which made this the one tool `--all` could not provision.
        "drawio" => Some(BinaryRecipe {
            url: "https://github.com/jgraph/drawio-desktop/releases/latest",
            archive: ArchiveKind::Deb {
                source: DebSource::GithubRelease {
                    repo: "jgraph/drawio-desktop",
                    asset_pattern: "amd64",
                },
            },
            dest: "drawio",
        }),
        // Chrome is not in the Ubuntu archive — `apt install
        // google-chrome-stable` only works after adding Google's repo. The
        // vendor .deb is the official route and is not version-pinned.
        "google-chrome-stable" => Some(BinaryRecipe {
            url: "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb",
            archive: ArchiveKind::Deb {
                source: DebSource::Url(
                    "https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb",
                ),
            },
            dest: "google-chrome",
        }),
        _ => None,
    }
}

/// Information about an external tool: its name, runtime category, and install methods.
pub struct ToolInfo {
    /// Bare binary name, as found on `$PATH` — never a path.
    ///
    /// This is the detection key: it goes straight to `which::which` (see
    /// `builder/tools.rs` and `tool_lock.rs`), so it decides whether a tool
    /// reports `installed` or `missing`, and which binary gets version-locked.
    ///
    /// `which` switches behaviour on the presence of a separator, so a name
    /// containing `/` is NOT looked up on `$PATH` — it is resolved relative to
    /// the *current working directory*. A vendored-looking entry such as
    /// `gems/bin/mdl` therefore only resolves when rsconstruct happens to be
    /// invoked from the one directory with that subtree beneath it, and reports
    /// `missing` everywhere else — including for a user who has the tool
    /// installed and on `$PATH` at, say, `~/install/gems/bin/mdl`. Two such
    /// entries were removed for exactly this reason; keep names bare.
    ///
    /// In both modes `which` also requires the executable bit, so a present but
    /// non-executable file reads as `missing`.
    ///
    /// To pin a project-local binary, set the per-processor `command` config
    /// field (`config/processor_configs.rs`) instead — that is the value that
    /// actually gets executed. This field stays a bare name so detection works
    /// from any cwd.
    pub name: &'static str,
    /// Runtime category ("python", "node", "ruby", "rust", "perl", "jvm", "system")
    pub runtime: &'static str,
    /// The preferred way to install the tool into the project. None when
    /// there is no project route (a system package, a `.deb`).
    pub project: Option<InstallMethod>,
    /// The preferred way to install the tool onto the machine.
    pub machine: Option<InstallMethod>,
    /// Other known ways to install it (brew for macOS, a crate where a
    /// release binary is preferred, ...). Listed by `tool list -M`, never
    /// chosen by an install.
    pub alternatives: &'static [InstallMethod],
    /// The preferred target overall, when it is not the default (the
    /// project if the tool has a project install, else the machine; see
    /// [`ToolInfo::preferred_target`]). Set only to override that default.
    pub prefer: Option<InstallTarget>,
    /// Where the tool writes its own state inside the project when it runs:
    /// caches, bytecode, build directories — files that are not a product's
    /// outputs but that the tool writes every time. Under `execution_model =
    /// "sandbox"` a processor may write the folders of every tool it runs
    /// (its `required_tools`) plus its own `sandbox_writable` config, and
    /// nothing else besides its declared outputs; see `src/sandbox.rs`.
    ///
    /// Each entry is a path relative to the project root (`target`,
    /// `.ruff_cache`), or `**/NAME` for a directory called NAME anywhere in
    /// the tree (`**/__pycache__`, which Python writes beside every module
    /// it imports, the project's `.venv` included). Empty for a tool that
    /// writes nothing but its outputs.
    pub sandbox_writable: &'static [&'static str],
    /// Whether the tool reaches the network as part of its ordinary work
    /// (a package manager installing, a checker fetching an advisory
    /// database or a schema). Under `execution_model = "sandbox"` a
    /// processor gets the network when any tool it runs (its
    /// `required_tools`) needs it, or when its config sets
    /// `sandbox_network = true`; otherwise the network is cut off, and a
    /// tool that reaches for it fails. `false` for a tool that only needs
    /// what is already on the machine, even if it can download (cargo
    /// builds from its registry cache; fetching is the install step's job).
    pub needs_network: bool,
}

/// The tools no single processor owns: language runtimes and compilers that
/// several processors run, and tools a project selects through config
/// (`required_tools`, a cc profile's cross toolchain) or that rsconstruct
/// runs itself. A tool exactly one processor runs is declared in that
/// processor's file instead (see `inventory::collect!(ToolInfo)` below);
/// `central_registry_holds_only_unowned_tools` keeps the split honest.
pub static TOOLS: &[ToolInfo] = &[
    // Python. uv, which `tool install project` runs to build the .venv, is
    // declared in `processor/mass_generator/uv.rs`: one processor runs it.
    ToolInfo {
        name: "python",
        runtime: "python",
        project: None,
        // `python-is-python3` provides `/usr/bin/python` and pulls in `python3`.
        machine: Some(InstallMethod::new("apt", "python-is-python3")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &["**/__pycache__"],
        needs_network: false,
    },
    // The interpreter under the name `[build] python = "python3"` requires.
    ToolInfo {
        name: "python3",
        runtime: "python",
        project: None,
        machine: Some(InstallMethod::new("apt", "python3")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &["**/__pycache__"],
        needs_network: false,
    },
    // Node
    // The project's own Node.js, npm included: its release tree goes into
    // the project's tool directory, installed ahead of `npm ci` and the
    // npm packages, which run on it.
    ToolInfo {
        name: "node",
        runtime: "node",
        project: Some(InstallMethod::new("binary", "node")),
        machine: Some(InstallMethod::new("apt", "nodejs")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // Ruby
    ToolInfo {
        name: "ruby",
        runtime: "ruby",
        project: None,
        machine: Some(InstallMethod::new("apt", "ruby")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // Rust
    // The machine gets rustup, never a distro cargo: Ubuntu's rustup package
    // installs cargo, rustc, rustfmt and cargo-clippy as rustup proxies,
    // which run the toolchain the project's rust-toolchain.toml pins and
    // install it on first use. A plain `apt install cargo` would ignore that
    // file. A host that already has rustup never reaches the install path:
    // `which` finds cargo first.
    ToolInfo {
        name: "cargo",
        runtime: "rust",
        project: None,
        machine: Some(InstallMethod::new("apt", "rustup")),
        alternatives: &[],
        prefer: None,
        // Cargo's build directory at its default place (bound straight to the
        // real tree), the one of a crate in a subdirectory, and the lockfile
        // cargo writes when there is none or updates when the manifest moved.
        sandbox_writable: &["target", "**/target", "**/Cargo.lock"],
        // cargo downloads the crates a build needs that are not in
        // ~/.cargo yet, as npm and pip do; cut off, a cold build fails
        // ("Could not resolve host: index.crates.io", seen on four rs*
        // repos in the 2026-11-09 fleet run).
        needs_network: true,
    },
    // Perl
    ToolInfo {
        name: "perl",
        runtime: "perl",
        project: None,
        machine: Some(InstallMethod::new("apt", "perl")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "perltidy",
        runtime: "perl",
        project: None,
        machine: Some(InstallMethod::new("apt", "perltidy")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // System
    // Run by rsconstruct itself under `execution_model = "sandbox"`
    // (src/sandbox.rs), around every sandboxed processor's tools.
    ToolInfo {
        name: "bwrap",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "bubblewrap")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // Run by rsconstruct itself under `undeclared_reads = "report"`
    // (src/read_trace.rs), around every external tool a product runs.
    ToolInfo {
        name: "strace",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "strace")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // Run by a project's own scripts (a generic processor's
    // `required_tools`), not by any one processor.
    ToolInfo {
        name: "ffmpeg",
        runtime: "system",
        project: Some(InstallMethod::new("binary", "ffmpeg")),
        machine: Some(InstallMethod::new("apt", "ffmpeg")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "lilypond",
        runtime: "system",
        project: Some(InstallMethod::new("binary", "lilypond")),
        machine: Some(InstallMethod::new("apt", "lilypond")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // ARM bare-metal cross toolchain. Debian splits it the same way as the
    // native one: the compiler driver comes from gcc-arm-none-eabi, while ar
    // and objcopy come from binutils-arm-none-eabi.
    ToolInfo {
        name: "arm-none-eabi-gcc",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "gcc-arm-none-eabi")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "arm-none-eabi-ar",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "binutils-arm-none-eabi")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "arm-none-eabi-objcopy",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "binutils-arm-none-eabi")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "gcc",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "gcc")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "g++",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "g++")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "clang",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "clang")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "clang++",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "clang")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "make",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "make")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "pdflatex",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "texlive-latex-base")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    ToolInfo {
        name: "dot",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "graphviz")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
    // Debian/Ubuntu package the Clojure CLI, which is what makes this
    // installable without the official shell installer; brew is the macOS
    // route. See https://clojure.org/guides/install_clojure
    ToolInfo {
        name: "clojure",
        runtime: "jvm",
        project: None,
        machine: Some(InstallMethod::new("apt", "clojure")),
        alternatives: &[InstallMethod::new("brew", "clojure/tools/clojure")],
        prefer: None,
        // The CLI caches the resolved classpath in the project.
        sandbox_writable: &[".cpcache"],
        needs_network: false,
    },
    // Built-in / coreutils
    ToolInfo {
        name: "true",
        runtime: "system",
        project: None,
        machine: Some(InstallMethod::new("apt", "coreutils")),
        alternatives: &[],
        prefer: None,
        sandbox_writable: &[],
        needs_network: false,
    },
];

// A processor owns its tools: each tool only it runs is declared in its own
// file with `inventory::submit!`, next to its plugin entry, so the install
// methods sit beside the code that runs the tool. Consumers must iterate
// `all_tools()`, never TOOLS directly.
inventory::collect!(ToolInfo);

/// Every known tool: the central table plus processor-file submissions.
pub fn all_tools() -> impl Iterator<Item = &'static ToolInfo> {
    TOOLS.iter().chain(inventory::iter::<ToolInfo>)
}

/// Look up a tool by name.
pub fn tool_info(tool: &str) -> Option<&'static ToolInfo> {
    all_tools().find(|t| t.name == tool)
}

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

    /// A tool name must have exactly one registry entry — a processor
    /// submitting a name the central table already carries (or two
    /// processors submitting the same name) would make `tool_info`'s answer
    /// depend on iteration order.
    #[test]
    fn tool_names_are_unique_across_central_and_submitted() {
        let mut seen = std::collections::HashSet::new();
        let mut dups: Vec<&str> = Vec::new();
        for t in all_tools() {
            if !seen.insert(t.name) {
                dups.push(t.name);
            }
        }
        dups.sort_unstable();
        assert!(dups.is_empty(), "duplicate tool registry entries: {dups:?}");
    }

    /// A slot names a method that can install to the slot's target (no apt
    /// in `project`, no `manual` anywhere), every tool fills at least one
    /// slot, and `prefer` only overrides: it names a filled slot other than
    /// the one the default would pick.
    #[test]
    fn every_slot_holds_a_method_for_its_target() {
        let mut bad: Vec<String> = Vec::new();
        for t in all_tools() {
            for target in [InstallTarget::Project, InstallTarget::Machine] {
                if let Some(m) = t.slot(target)
                    && !m.targets().contains(&target)
                {
                    bad.push(format!(
                        "{}: {} slot holds {} {}, which cannot install to the {}",
                        t.name,
                        target.as_str(),
                        m.method,
                        m.package,
                        target.as_str(),
                    ));
                }
            }
            if t.project.is_none() && t.machine.is_none() {
                bad.push(format!(
                    "{}: neither a project nor a machine install",
                    t.name
                ));
            }
            if let Some(prefer) = t.prefer {
                let default = if t.project.is_some() {
                    InstallTarget::Project
                } else {
                    InstallTarget::Machine
                };
                if t.slot(prefer).is_none() {
                    bad.push(format!(
                        "{}: prefers the {}, but has no {} install",
                        t.name,
                        prefer.as_str(),
                        prefer.as_str(),
                    ));
                } else if prefer == default {
                    bad.push(format!(
                        "{}: `prefer` repeats the default ({}); leave it None",
                        t.name,
                        prefer.as_str(),
                    ));
                }
            }
        }
        assert!(bad.is_empty(), "install slots: {bad:#?}");
    }

    /// An alternative is never installed, so it must still be a method
    /// `run` knows, and must not repeat a slot.
    #[test]
    fn alternatives_are_known_and_distinct_from_the_slots() {
        let mut bad: Vec<String> = Vec::new();
        for t in all_tools() {
            for alt in t.alternatives {
                if alt.targets().is_empty() {
                    bad.push(format!(
                        "{}: alternative {} {} installs nowhere",
                        t.name, alt.method, alt.package
                    ));
                }
                let repeats = [t.project.as_ref(), t.machine.as_ref()]
                    .into_iter()
                    .flatten()
                    .any(|m| m.method == alt.method && m.package == alt.package);
                if repeats {
                    bad.push(format!(
                        "{}: alternative {} {} repeats a slot",
                        t.name, alt.method, alt.package
                    ));
                }
            }
        }
        assert!(bad.is_empty(), "install alternatives: {bad:#?}");
    }

    /// The names of the `ToolInfo` entries a processor file submits.
    fn submitted_tool_names(source: &str) -> Vec<&str> {
        source
            .split("crate::tools::ToolInfo {")
            .skip(1)
            .filter_map(|rest| rest.split_once("name: \"")?.1.split_once('"'))
            .map(|(name, _)| name)
            .collect()
    }

    /// Processors own their tools. Every processor is built with its default
    /// config and asked which tools it runs. A tool exactly one processor
    /// runs must be declared in that processor's file, not in the central
    /// table; a tool a processor file declares must be run by no other
    /// processor, or it is shared and belongs in the central table.
    #[test]
    fn central_registry_holds_only_unowned_tools() {
        let processors = crate::builder::create_all_default_processors().unwrap();
        let mut runners: std::collections::BTreeMap<String, Vec<String>> =
            std::collections::BTreeMap::new();
        for (pname, processor) in &processors {
            for tool in processor.required_tools() {
                runners.entry(tool).or_default().push(pname.clone());
            }
        }
        let mut bad: Vec<String> = Vec::new();
        for tool in TOOLS {
            if let Some([only]) = runners.get(tool.name).map(Vec::as_slice) {
                bad.push(format!(
                    "{}: only {only} runs it, so it belongs in that processor's file",
                    tool.name
                ));
            }
        }
        for plugin in crate::registries::all_plugins() {
            let pname = plugin.pname();
            let file = format!("src/{}.rs", pname.replace('.', "/"));
            let source = std::fs::read_to_string(&file)
                .unwrap_or_else(|e| panic!("{pname}: cannot read {file}: {e}"));
            for name in submitted_tool_names(&source) {
                let others: Vec<&String> = runners
                    .get(name)
                    .into_iter()
                    .flatten()
                    .filter(|p| **p != pname)
                    .collect();
                if !others.is_empty() {
                    bad.push(format!(
                        "{name}: declared in {file} but also run by {others:?}, so it is \
                         shared and belongs in the central table"
                    ));
                }
            }
        }
        bad.sort();
        assert!(bad.is_empty(), "tool registry ownership: {bad:#?}");
    }
}

/// Return the default install command for a tool, if known.
pub fn tool_install_command(tool: &str) -> Option<String> {
    tool_info(tool)
        .and_then(ToolInfo::preferred_method)
        .map(InstallMethod::command)
}

/// Return the runtime category for a tool, if known.
pub fn tool_runtime(tool: &str) -> Option<&'static str> {
    tool_info(tool).map(|t| t.runtime)
}

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

    /// `sudo_argv()` returns either `["sudo"]` or `[]` based on runtime
    /// state. Empty when running as root or when `sudo` isn't on PATH.
    #[test]
    fn sudo_argv_matches_runtime() {
        let prefix = sudo_argv();
        if crate::platform::needs_sudo() {
            assert_eq!(prefix, &["sudo"]);
        } else {
            assert!(prefix.is_empty(), "{prefix:?}");
        }
    }

    /// Only bin dirs that actually exist are collected, from all three
    /// layouts: `$GEM_HOME/bin`, `~/.gem/ruby/<v>/bin` (upstream) and
    /// `~/.local/share/gem/ruby/<v>/bin` (Debian/Ubuntu).
    #[test]
    fn user_gem_bin_dirs_collects_existing_layouts() {
        let home = tempfile::TempDir::new().unwrap();
        let none_yet = user_gem_bin_dirs(home.path(), None);
        assert!(none_yet.is_empty(), "{none_yet:?}");

        let upstream = home.path().join(".gem/ruby/3.2.0/bin");
        let debian = home.path().join(".local/share/gem/ruby/3.3.0/bin");
        let gem_home = home.path().join("mygems");
        std::fs::create_dir_all(&upstream).unwrap();
        std::fs::create_dir_all(&debian).unwrap();
        std::fs::create_dir_all(gem_home.join("bin")).unwrap();
        // A version dir without bin/ must not be collected.
        std::fs::create_dir_all(home.path().join(".gem/ruby/2.7.0")).unwrap();

        let dirs = user_gem_bin_dirs(home.path(), Some(gem_home.as_os_str()));
        assert_eq!(dirs, vec![gem_home.join("bin"), upstream, debian]);
    }

    /// Appending keeps the original PATH order, adds only what's missing,
    /// and reports None when there is nothing to add.
    #[test]
    fn path_with_appended_dirs_appends_only_missing() {
        use std::path::PathBuf;
        let path = std::ffi::OsString::from("/usr/bin:/home/u/.gem/ruby/3.2.0/bin");
        let dirs = vec![
            PathBuf::from("/home/u/.gem/ruby/3.2.0/bin"),
            PathBuf::from("/home/u/mygems/bin"),
        ];
        let new_path = path_with_appended_dirs(&path, &dirs).unwrap();
        assert_eq!(
            new_path,
            "/usr/bin:/home/u/.gem/ruby/3.2.0/bin:/home/u/mygems/bin"
        );

        assert!(path_with_appended_dirs(&new_path, &dirs).is_none());
        assert!(path_with_appended_dirs(&path, &[]).is_none());
    }

    /// `node_modules/.bin` goes first so the locked version shadows a global
    /// install; an occurrence further back is moved, not duplicated; and a
    /// PATH that already leads with it is left alone.
    #[test]
    fn path_with_prepended_dir_puts_dir_first_once() {
        use std::path::Path;
        let bin = Path::new("/proj/node_modules/.bin");
        let path = std::ffi::OsString::from("/usr/bin:/proj/node_modules/.bin:/bin");
        let new_path = path_with_prepended_dir(&path, bin).unwrap();
        assert_eq!(new_path, "/proj/node_modules/.bin:/usr/bin:/bin");

        assert!(path_with_prepended_dir(&new_path, bin).is_none());

        let without = std::ffi::OsString::from("/usr/bin:/bin");
        assert_eq!(
            path_with_prepended_dir(&without, bin).unwrap(),
            "/proj/node_modules/.bin:/usr/bin:/bin"
        );
    }

    /// A missing path is judged by its nearest existing ancestor — that is
    /// what decides whether the path could be created.
    #[test]
    fn ancestor_writability_walks_to_existing_dir() {
        let dir = tempfile::TempDir::new().unwrap();
        assert!(nearest_existing_ancestor_is_writable(
            &dir.path().join("a/b/c")
        ));
        if !crate::platform::is_root() {
            crate::platform::set_permissions_mode(dir.path(), 0o555).unwrap();
            assert!(!nearest_existing_ancestor_is_writable(
                &dir.path().join("a/b/c")
            ));
            crate::platform::set_permissions_mode(dir.path(), 0o755).unwrap();
        }
    }

    /// `apt` describe must run `apt-get update` first, then call
    /// `apt-get install -y <pkg>` exactly once with the package name
    /// after the flags. Whether `sudo` is prepended depends on runtime
    /// state.
    #[test]
    fn apt_describe_shape_is_correct() {
        let steps = describe("apt", &["cowsay"], &no_pins());
        assert_eq!(steps.len(), 2);

        let update = &steps[0];
        let upd_idx = update
            .iter()
            .position(|s| s == "apt-get")
            .expect("apt-get in update argv");
        assert_eq!(update[upd_idx + 1], "update");
        assert_eq!(update.len(), upd_idx + 2);

        let install = &steps[1];
        let pkgmgr_idx = install
            .iter()
            .position(|s| s == "apt-get")
            .expect("apt-get in install argv");
        assert_eq!(install[pkgmgr_idx + 1], "install");
        assert_eq!(install[pkgmgr_idx + 2], "-y");
        assert_eq!(install[pkgmgr_idx + 3], "cowsay");
        if install[0] == "sudo" {
            assert_eq!(pkgmgr_idx, 1);
        } else {
            assert_eq!(pkgmgr_idx, 0);
        }
    }

    /// `apt` batch describe collapses many packages into one apt-get
    /// install call (still preceded by a single `apt-get update`).
    #[test]
    fn apt_batch_describe_collapses() {
        let steps = describe("apt", &["foo", "bar", "baz"], &no_pins());
        assert_eq!(steps.len(), 2);
        let install = &steps[1];
        let pkgmgr_idx = install
            .iter()
            .position(|s| s == "apt-get")
            .expect("apt-get in argv");
        assert_eq!(&install[pkgmgr_idx + 3..], &["foo", "bar", "baz"]);
    }

    /// `cargo` describe is `cargo install --locked --force <crates>`: no
    /// sudo, `--locked` so the crate builds with its published Cargo.lock,
    /// and `--force` so a same-named binary cargo did not install (a
    /// prebuilt tarball in a CI cache) is replaced instead of refused.
    #[test]
    fn cargo_describe_is_locked_and_forced_without_sudo() {
        let steps = describe("cargo", &["cargo-deny", "mdbook"], &no_pins());
        assert_eq!(steps.len(), 1);
        assert_eq!(
            steps[0],
            vec![
                "cargo",
                "install",
                "--locked",
                "--force",
                "cargo-deny",
                "mdbook"
            ]
        );
    }

    #[test]
    fn github_latest_urls_pin_to_a_tag() {
        assert_eq!(
            pin_github_latest_url(
                "https://github.com/tamasfe/taplo/releases/latest/download/taplo-linux-x86_64.gz",
                "0.10.0"
            )
            .as_deref(),
            Some("https://github.com/tamasfe/taplo/releases/download/0.10.0/taplo-linux-x86_64.gz")
        );
        assert_eq!(
            pin_github_latest_url("https://dl.google.com/x.deb", "1"),
            None
        );
        assert_eq!(
            github_repo_of("https://github.com/hadolint/hadolint/releases/latest/download/h"),
            Some("hadolint/hadolint")
        );
    }

    #[test]
    fn gem_executables_reads_the_yaml_list() {
        assert_eq!(gem_executables("---\n- jekyll\n"), ["jekyll"]);
        assert_eq!(
            gem_executables("---\n- mdl\n- \"odd name\"\n"),
            ["mdl", "odd name"]
        );
        assert_eq!(gem_executables("--- []\n"), Vec::<String>::new());
    }

    /// A gem package keeps its own executables and loses its dependencies'
    /// binstubs: `jekyll` and `mdl` both came with `kramdown`, and a
    /// project's `bin/` cannot hold two of one name. Runs the real `gem`
    /// against a hand-written installed spec, so nothing is downloaded.
    #[test]
    fn a_gem_package_keeps_only_its_own_executables() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let specs = home.join("specifications");
        std::fs::create_dir_all(&specs).unwrap();
        std::fs::write(
            specs.join("mytool-1.2.3.gemspec"),
            "Gem::Specification.new do |s|\n  s.name = \"mytool\"\n  s.version = \"1.2.3\"\n  \
             s.summary = \"x\"\n  s.authors = [\"x\"]\n  s.files = []\n  \
             s.executables = [\"mytool\", \"mytool-admin\"]\nend\n",
        )
        .unwrap();
        let bin = home.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        for exe in ["mytool", "mytool-admin", "kramdown", "rake"] {
            std::fs::write(bin.join(exe), "#!/bin/sh\n").unwrap();
        }

        keep_own_gem_executables("mytool", "1.2.3", &home.to_string_lossy(), &bin).unwrap();

        let mut left: Vec<String> = std::fs::read_dir(&bin)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        left.sort();
        assert_eq!(left, ["mytool", "mytool-admin"]);
    }

    /// Chrome's vendor URL always serves the current build, so it is the
    /// one recipe the lock cannot record; GitHub-release recipes can be.
    #[test]
    fn only_versioned_binary_recipes_are_pinnable() {
        assert!(!binary_is_pinnable("google-chrome-stable"));
        for pkg in ["rumdl", "taplo", "hadolint", "drawio", "checkpatch.pl"] {
            assert!(binary_is_pinnable(pkg), "{pkg}");
        }
        assert!(!binary_is_pinnable("no-such-recipe"));
    }

    /// `pip` describe never uses sudo, regardless of runtime state.
    #[test]
    fn pip_describe_never_has_sudo() {
        let steps = describe("pip", &["ruff"], &no_pins());
        assert_eq!(steps.len(), 1);
        let argv = &steps[0];
        assert_eq!(argv[0], "pip");
        assert!(!argv.contains(&"sudo".to_string()));
    }

    /// `uv-sync` is one `uv sync --locked --no-install-project`, whatever
    /// names it is handed: it reads pyproject.toml and uv.lock, leaves the
    /// project itself to the build, and never uses sudo.
    #[test]
    fn uv_sync_describe_is_a_locked_sync() {
        let steps = describe("uv-sync", &["ruff", "pytest"], &no_pins());
        assert_eq!(
            steps,
            vec![
                ["uv", "sync", "--locked", "--no-install-project"]
                    .map(String::from)
                    .to_vec()
            ]
        );
    }

    /// `binary` describe yields a multi-step plan (download, extract,
    /// chmod, mv) with no shell metacharacters anywhere.
    #[test]
    fn binary_describe_has_no_shell_metachars() {
        for pkg in &[
            "taplo",
            "rumdl",
            "zola",
            "oxlint",
            "selene",
            "shellcheck",
            "jq",
            "pandoc",
            "protoc",
            "qpdf",
            "uv",
            "node",
            "lilypond",
            "ffmpeg",
        ] {
            let steps = describe("binary", &[pkg], &no_pins());
            assert!(steps.len() >= 3, "binary {pkg} should have >=3 steps");
            for step in &steps {
                for arg in step {
                    for forbidden in &['|', '>', '<', ';', '&'] {
                        assert!(
                            !arg.contains(*forbidden),
                            "binary {pkg} step contains shell metachar '{forbidden}': {arg:?}"
                        );
                    }
                }
            }
        }
    }

    /// An empty `[binary]` lock table, for describing outside a project.
    fn no_pins() -> std::collections::BTreeMap<String, crate::tool_lock::BinaryPin> {
        std::collections::BTreeMap::new()
    }

    fn argv(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| (*s).to_string()).collect()
    }

    /// The install plan `tool install` prints must name the URL the install
    /// downloads: the locked one when rsconstruct.lock has an entry. It used
    /// to show the recipe's `releases/latest` URL regardless.
    #[test]
    fn binary_describe_names_the_pinned_url() {
        let latest =
            "https://github.com/tamasfe/taplo/releases/latest/download/taplo-linux-x86_64.gz";
        let pinned =
            "https://github.com/tamasfe/taplo/releases/download/0.10.0/taplo-linux-x86_64.gz";
        let mut pins = no_pins();
        pins.insert(
            "taplo".to_string(),
            crate::tool_lock::BinaryPin {
                url: pinned.to_string(),
                sha256: "ab12".to_string(),
                executable_sha256: None,
                deb_package: None,
                deb_version: None,
            },
        );

        let steps = describe("binary", &["taplo"], &pins);
        assert_eq!(
            steps[0].last().map(String::as_str),
            Some(pinned),
            "{steps:?}"
        );
        assert!(
            steps[1][0].starts_with('#') && steps[1][0].contains("ab12"),
            "the locked hash is part of the plan: {steps:?}"
        );

        let steps = describe("binary", &["taplo"], &no_pins());
        assert_eq!(
            steps[0].last().map(String::as_str),
            Some(latest),
            "{steps:?}"
        );
    }

    /// The described steps are the fetch's steps. Before they were derived
    /// from one plan, the preview showed `gunzip -f /tmp/taplo.dl` (gunzip
    /// rejects a name without `.gz`) and left out the rename of a tar
    /// member that is not named after the tool.
    #[test]
    fn binary_describe_shows_the_steps_fetch_takes() {
        // Every path is in this process's own work directory, not `/tmp`
        // itself under a name another install or another user shares.
        let dir = install_work_dir();
        assert!(dir.ends_with(&format!("rsconstruct-install-{}", std::process::id())));
        let at = |name: &str| format!("{dir}/{name}");

        let steps = describe("binary", &["taplo"], &no_pins());
        assert_eq!(steps.len(), 6, "{steps:?}");
        assert_eq!(steps[0][0], "curl");
        assert_eq!(
            &steps[1..5],
            &[
                argv(&["mv", &at("taplo.dl"), &at("taplo.dl.gz")]),
                argv(&["gunzip", "-f", &at("taplo.dl.gz")]),
                argv(&["mv", &at("taplo.dl"), &at("taplo")]),
                argv(&["chmod", "+x", &at("taplo")]),
            ]
        );
        assert!(
            steps[5].ends_with(&argv(&["mv", &at("taplo"), "/usr/local/bin/taplo"])),
            "{steps:?}"
        );

        let steps = describe("binary", &["oxlint"], &no_pins());
        assert!(
            steps.contains(&argv(&[
                "mv",
                &at("oxlint-x86_64-unknown-linux-gnu"),
                &at("oxlint")
            ])),
            "{steps:?}"
        );
        assert!(
            steps.contains(&argv(&["rm", &at("oxlint.dl")])),
            "{steps:?}"
        );

        // A member already named after the tool is not renamed onto itself.
        let steps = describe("binary", &["rumdl"], &no_pins());
        assert!(
            !steps.contains(&argv(&["mv", &at("rumdl"), &at("rumdl")])),
            "{steps:?}"
        );
    }

    /// The work directory is made new and private; one already there is
    /// refused rather than adopted.
    #[test]
    fn the_install_work_directory_is_private_and_never_adopted() {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("work");
        crate::platform::create_private_dir(&dir).unwrap();
        let mode = crate::platform::get_mode(&std::fs::metadata(&dir).unwrap());
        assert_eq!(mode & 0o777, 0o700);
        assert!(crate::platform::create_private_dir(&dir).is_err());
    }

    /// Run the plan for real against local files: a gzip asset comes out as
    /// `<base>/<dest>`, a tarball member not named `dest` is renamed to it,
    /// nothing is left behind, and a locked hash that differs is refused.
    #[test]
    fn fetch_binary_unpacks_gzip_and_renamed_tar_members() {
        let tmp = tempfile::TempDir::new().unwrap();
        let base = tmp.path().to_string_lossy().into_owned();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        let is_executable = |path: &str| {
            let meta = std::fs::metadata(path).unwrap();
            crate::platform::get_mode(&meta) & 0o111 != 0
        };

        std::fs::write(src.join("payload"), b"#!/bin/sh\necho gz\n").unwrap();
        let status = std::process::Command::new("gzip")
            .arg("-k")
            .arg(src.join("payload"))
            .status()
            .unwrap();
        assert!(status.success());
        let recipe = BinaryRecipe {
            url: "",
            archive: ArchiveKind::Gunzip,
            dest: "fake-gz-tool",
        };
        let url = format!("file://{}", src.join("payload.gz").display());
        let fetched = fetch_binary(&recipe, &url, None, &base, false).unwrap();
        assert_eq!(fetched.payload, format!("{base}/fake-gz-tool"));
        assert_eq!(
            std::fs::read(&fetched.payload).unwrap(),
            b"#!/bin/sh\necho gz\n"
        );
        assert!(is_executable(&fetched.payload));
        assert!(!tmp.path().join("fake-gz-tool.dl").exists());
        assert!(!tmp.path().join("fake-gz-tool.dl.gz").exists());
        assert_eq!(
            fetched.download_sha256,
            file_sha256(&src.join("payload.gz")).unwrap()
        );

        std::fs::write(src.join("tool-x86_64-unknown-linux-gnu"), b"tar member").unwrap();
        let status = std::process::Command::new("tar")
            .arg("-czf")
            .arg(src.join("tool.tar.gz"))
            .arg("-C")
            .arg(&src)
            .arg("tool-x86_64-unknown-linux-gnu")
            .status()
            .unwrap();
        assert!(status.success());
        let recipe = BinaryRecipe {
            url: "",
            archive: ArchiveKind::TarGz {
                inner: "tool-x86_64-unknown-linux-gnu",
            },
            dest: "fake-tar-tool",
        };
        let url = format!("file://{}", src.join("tool.tar.gz").display());
        let fetched = fetch_binary(&recipe, &url, None, &base, false).unwrap();
        assert_eq!(fetched.payload, format!("{base}/fake-tar-tool"));
        assert_eq!(std::fs::read(&fetched.payload).unwrap(), b"tar member");
        assert!(is_executable(&fetched.payload));
        assert!(!tmp.path().join("tool-x86_64-unknown-linux-gnu").exists());
        assert!(!tmp.path().join("fake-tar-tool.dl").exists());

        let err = fetch_binary(&recipe, &url, Some("0000"), &base, false).unwrap_err();
        assert!(
            err.to_string().contains("does not match rsconstruct.lock"),
            "{err}"
        );
        assert!(!tmp.path().join("fake-tar-tool.dl").exists());
    }

    /// A release kept whole unpacks to a tree beside the work files: the
    /// executable stays at its member path, next to the directories it
    /// reads at run time, and the download is gone.
    #[test]
    fn fetch_binary_keeps_a_release_tree_whole() {
        let tmp = tempfile::TempDir::new().unwrap();
        let base = tmp.path().to_string_lossy().into_owned();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(src.join("bin")).unwrap();
        std::fs::create_dir_all(src.join("include/google")).unwrap();
        std::fs::write(src.join("bin/tool"), b"#!/bin/sh\necho tree\n").unwrap();
        std::fs::write(src.join("include/google/a.proto"), b"syntax").unwrap();
        let status = std::process::Command::new("zip")
            .args(["-q", "-r", "../tool.zip", "bin", "include"])
            .current_dir(&src)
            .status()
            .unwrap();
        assert!(status.success());
        let recipe = BinaryRecipe {
            url: "",
            archive: ArchiveKind::Tree {
                packing: Packing::Zip,
                exe: "bin/tool",
            },
            dest: "fake-tree-tool",
        };
        let url = format!("file://{}", tmp.path().join("tool.zip").display());
        let fetched = fetch_binary(&recipe, &url, None, &base, false).unwrap();
        let tree = tree_dir(&base, "fake-tree-tool");
        assert_eq!(fetched.payload, format!("{tree}/bin/tool"));
        let meta = std::fs::metadata(&fetched.payload).unwrap();
        assert!(crate::platform::get_mode(&meta) & 0o111 != 0);
        assert_eq!(
            std::fs::read(format!("{tree}/include/google/a.proto")).unwrap(),
            b"syntax"
        );
        assert!(!tmp.path().join("fake-tree-tool.dl").exists());

        // A tarball whose prefix is its top directory, xz-compressed.
        let status = std::process::Command::new("tar")
            .arg("-cJf")
            .arg(tmp.path().join("tool.tar.xz"))
            .arg("--transform=s,^,tool-1.0/,")
            .args(["bin", "include"])
            .current_dir(&src)
            .status()
            .unwrap();
        assert!(status.success());
        let recipe = BinaryRecipe {
            url: "",
            archive: ArchiveKind::Tree {
                packing: Packing::Tar,
                exe: "tool-1.0/bin/tool",
            },
            dest: "fake-tar-tree-tool",
        };
        let url = format!("file://{}", tmp.path().join("tool.tar.xz").display());
        let fetched = fetch_binary(&recipe, &url, None, &base, false).unwrap();
        let tree = tree_dir(&base, "fake-tar-tree-tool");
        assert_eq!(fetched.payload, format!("{tree}/tool-1.0/bin/tool"));
        let meta = std::fs::metadata(&fetched.payload).unwrap();
        assert!(crate::platform::get_mode(&meta) & 0o111 != 0);
        assert_eq!(
            std::fs::read(format!("{tree}/tool-1.0/include/google/a.proto")).unwrap(),
            b"syntax"
        );
        assert!(!tmp.path().join("fake-tar-tree-tool.dl").exists());
    }

    /// A tree recipe's `exe` is `<prefix>/bin/<name>`: the prefix becomes
    /// the package's, and its bin/ is what goes on PATH.
    #[test]
    fn tree_recipes_name_an_executable_in_the_prefix_bin() {
        assert_eq!(tree_prefix("bin/protoc"), std::path::Path::new(""));
        assert_eq!(
            tree_prefix("node-v1/bin/node"),
            std::path::Path::new("node-v1")
        );
        for info in all_tools() {
            for method in [&info.project, &info.machine].into_iter().flatten() {
                if method.method != "binary" {
                    continue;
                }
                let Some(BinaryRecipe {
                    archive: ArchiveKind::Tree { exe, .. },
                    ..
                }) = binary_recipe(method.package)
                else {
                    continue;
                };
                let parent = std::path::Path::new(exe).parent().unwrap();
                assert!(parent.ends_with("bin"), "{}: {exe}", method.package);
            }
        }
    }

    /// node, lilypond, ffmpeg, protoc and qpdf need the directories beside
    /// their executable, so their release is kept whole and installs only
    /// into a project; a machine install of it is refused rather than half
    /// done.
    #[test]
    fn tree_binaries_install_only_into_a_project() {
        for pkg in ["protoc", "qpdf", "node", "lilypond", "ffmpeg"] {
            assert_eq!(
                InstallMethod::new("binary", pkg).targets(),
                &[InstallTarget::Project],
                "{pkg}"
            );
            let ctx = InstallCtx {
                verbose: false,
                use_eatmydata: false,
                binary_pins: no_pins(),
                allow_unpinned: false,
            };
            let err = run_binary(pkg, &ctx).unwrap_err();
            assert!(err.to_string().contains("only into a project"), "{err}");
        }
    }

    /// A release binary with no lock entry is not installed unless the
    /// caller said so: the refusal comes before anything is downloaded.
    #[test]
    fn an_unpinned_binary_is_refused() {
        let ctx = InstallCtx {
            verbose: false,
            use_eatmydata: false,
            binary_pins: no_pins(),
            allow_unpinned: false,
        };
        for pkg in ["taplo", "google-chrome-stable"] {
            let err = run_binary(pkg, &ctx).unwrap_err().to_string();
            assert!(
                err.contains("does not pin it") && err.contains("--allow-unpinned"),
                "{pkg}: {err}"
            );
        }
    }
}