mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
//! Environment variables mise reads, and the directories derived from them.

use crate::env_diff::{EnvDiff, EnvMap, env_value_matches};
use crate::env_value::EnvValue;
use crate::file::replace_path;
use indexmap::IndexMap;
use itertools::Itertools;
use log::LevelFilter;
use mise_settings::Settings;
use std::collections::{BTreeSet, HashMap, HashSet};
pub use std::env::*;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::LazyLock as Lazy;
use std::sync::atomic::AtomicBool;
use std::sync::{Mutex, RwLock};

pub static ARGS: RwLock<Vec<String>> = RwLock::new(vec![]);

pub const MISE_INSTALL_VERSION_ENV_VAR: &str = "MISE_INSTALL_VERSION";

pub const MISE_TOOL_VERSION_ENV_VAR: &str = "MISE_TOOL_VERSION";

pub const NON_TOOL_VERSION_ENV_VARS: &[&str] =
    &[MISE_INSTALL_VERSION_ENV_VAR, MISE_TOOL_VERSION_ENV_VAR];

#[cfg(unix)]
pub static SHELL: Lazy<String> = Lazy::new(|| var("SHELL").unwrap_or_else(|_| "sh".into()));

#[cfg(windows)]
pub static SHELL: Lazy<String> = Lazy::new(|| var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into()));

#[cfg(unix)]
pub static SHELL_COMMAND_FLAG: &str = "-c";

#[cfg(windows)]
pub static SHELL_COMMAND_FLAG: &str = "/c";

pub static HOME: Lazy<PathBuf> = Lazy::new(|| {
    if let Some(home) = crate::testing::home() {
        return home.to_path_buf();
    }
    homedir::my_home()
        .ok()
        .flatten()
        .unwrap_or_else(|| PathBuf::from("/"))
});

pub static EDITOR: Lazy<String> = Lazy::new(|| {
    var("VISUAL")
        .or_else(|_| var("EDITOR"))
        .unwrap_or_else(|_| DEFAULT_EDITOR.to_string())
});

/// The editor to fall back on when neither `VISUAL` nor `EDITOR` is set.
///
/// `nano` everywhere but Windows, which ships none of it — not `nano`, `vi`, `vim`, or anything
/// else POSIX — so the shared default left `mise tasks edit` there with nothing to run at all.
/// `notepad` is the one editor Windows can be relied on to have.
///
/// It also has to *wait*, because `mise dot edit --apply` converges the target as soon as the
/// editor returns. Measured on Windows 11 26200, where `System32\notepad.exe` no longer exists and
/// `notepad` resolves to a zero-byte app-execution alias under `WindowsApps`: spawned the way
/// `Command::status` does it, the parent was still waiting five seconds later, so the alias hands
/// back the real process rather than detaching from it.
#[cfg(windows)]
const DEFAULT_EDITOR: &str = "notepad";

#[cfg(not(windows))]
const DEFAULT_EDITOR: &str = "nano";

#[cfg(target_os = "macos")]
pub static XDG_CACHE_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CACHE_HOME").unwrap_or_else(|| HOME.join("Library/Caches")));

#[cfg(windows)]
pub static XDG_CACHE_HOME: Lazy<PathBuf> = Lazy::new(|| {
    var_path("XDG_CACHE_HOME")
        .or_else(|| var_path("TEMP"))
        .unwrap_or_else(temp_dir)
});

#[cfg(all(not(windows), not(target_os = "macos")))]
pub static XDG_CACHE_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CACHE_HOME").unwrap_or_else(|| HOME.join(".cache")));

pub static XDG_CONFIG_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CONFIG_HOME").unwrap_or_else(|| HOME.join(".config")));

#[cfg(unix)]
pub static XDG_DATA_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_DATA_HOME").unwrap_or_else(|| HOME.join(".local").join("share")));

#[cfg(windows)]
pub static XDG_DATA_HOME: Lazy<PathBuf> = Lazy::new(|| {
    var_path("XDG_DATA_HOME")
        .or(var_path("LOCALAPPDATA"))
        .unwrap_or_else(|| HOME.join("AppData").join("Local"))
});

pub static XDG_STATE_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_STATE_HOME").unwrap_or_else(|| HOME.join(".local").join("state")));

/// `%LOCALAPPDATA%`. What the `adrg/xdg` Go package resolves `XDG_CONFIG_HOME` to on Windows,
/// so it is where CLIs built on it — `glab` among them — keep their config.
///
/// Roaming `%APPDATA%` deliberately has no counterpart here. Its only consumer is the `gh`
/// lookup, which has to reproduce go-gh's literal `os.Getenv("AppData")` test — including
/// falling through to `~/.config/gh` when the variable is unset — so a synthesized default
/// would make mise look somewhere gh never would.
///
/// An empty `%LOCALAPPDATA%` falls back rather than resolving to an empty path — see
/// [`var_path`] — which is also what `adrg/xdg` does (`dir != "" && filepath.IsAbs(dir)`).
#[cfg(windows)]
pub static LOCAL_APPDATA: Lazy<PathBuf> =
    Lazy::new(|| var_path("LOCALAPPDATA").unwrap_or_else(|| HOME.join("AppData").join("Local")));

/// control display of "friendly" errors - defaults to release mode behavior unless overridden
pub static MISE_FRIENDLY_ERROR: Lazy<bool> = Lazy::new(|| {
    // default behavior: friendly in release mode unless debug logging
    var_bool("MISE_FRIENDLY_ERROR")
        .unwrap_or_else(|| !cfg!(debug_assertions) && log::max_level() < log::LevelFilter::Debug)
});

pub static MISE_TOOL_STUB: Lazy<bool> =
    Lazy::new(|| ARGS.read().unwrap().get(1).map(|s| s.as_str()) == Some("tool-stub"));

pub static MISE_NO_CONFIG: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_CONFIG"));
/// Whether mise is running in CI. Decided once per process: the answer comes
/// from about fifty variables, and several checks per command ask for it.
pub static IS_CI: Lazy<bool> = Lazy::new(ci_info::is_ci);

pub static MISE_NO_ENV: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_ENV"));

pub static MISE_NO_HOOKS: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_HOOKS"));

pub static MISE_PROGRESS_TRACE: Lazy<bool> = Lazy::new(|| var_is_true("MISE_PROGRESS_TRACE"));

pub static MISE_CACHE_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_CACHE_DIR").unwrap_or_else(|| XDG_CACHE_HOME.join("mise")));

pub static MISE_CONFIG_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_CONFIG_DIR").unwrap_or_else(|| XDG_CONFIG_HOME.join("mise")));

/// The default config directory location (XDG_CONFIG_HOME/mise), used to filter out
/// configs from this location when MISE_CONFIG_DIR is set to a different path
pub static MISE_DEFAULT_CONFIG_DIR: Lazy<PathBuf> = Lazy::new(|| XDG_CONFIG_HOME.join("mise"));

/// True if MISE_CONFIG_DIR was explicitly set to a non-default location
pub static MISE_CONFIG_DIR_OVERRIDDEN: Lazy<bool> = Lazy::new(|| {
    var_path("MISE_CONFIG_DIR").is_some() && *MISE_CONFIG_DIR != *MISE_DEFAULT_CONFIG_DIR
});

pub static MISE_DATA_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_DATA_DIR").unwrap_or_else(|| XDG_DATA_HOME.join("mise")));

pub static MISE_STATE_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_STATE_DIR").unwrap_or_else(|| XDG_STATE_HOME.join("mise")));

pub static MISE_TMP_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("MISE_TMP_DIR").unwrap_or_else(|| default_tmp_dir(&temp_dir(), &MISE_CACHE_DIR))
});

/// `<temp>/mise`, unless that is inside the cache directory, which `mise cache clear` deletes
/// wholesale. On Windows the default cache directory is `%TEMP%\mise`, the same path.
///
/// The check resolves both paths, so a cache directory spelled differently from the
/// temporary directory (through a symlink such as macOS `/private/var`, through `..`, or on
/// Windows in another case) is still seen to contain it.
fn default_tmp_dir(temp: &Path, cache: &Path) -> PathBuf {
    let tmp = temp.join("mise");
    if !is_within(&tmp, cache) {
        return tmp;
    }
    let tmp = temp.join("mise-tmp");
    if is_within(&tmp, cache) {
        // The cache directory is the temporary directory itself or one of its parents, so
        // nothing under it is outside the cache.
        debug!(
            "MISE_CACHE_DIR {} contains the temporary directory {}, so `mise cache clear` \
             deletes mise's temporary files; set MISE_TMP_DIR to a directory outside it",
            cache.display(),
            tmp.display()
        );
    }
    tmp
}

pub static MISE_SYSTEM_CONFIG_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("MISE_SYSTEM_CONFIG_DIR")
        .or_else(|| var_path("MISE_SYSTEM_DIR"))
        .unwrap_or_else(|| PathBuf::from("/etc/mise"))
});

pub static MISE_INSTALLS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_INSTALLS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("installs")));

/// Where the identity install layout keeps its installation directories. The
/// installs directory itself, except on Windows with the default installs
/// directory: there it is `<data>\i`, seven characters shorter than `installs`,
/// because the real installation path is what counts against `MAX_PATH`. Version
/// links and the catalog stay in the installs directory either way.
pub static MISE_INSTALL_STORE_DIR: Lazy<PathBuf> = Lazy::new(|| {
    let installs = &*MISE_INSTALLS_DIR;
    match var_path("MISE_INSTALL_STORE_DIR") {
        // Inside the installs directory the store would sit in a tool's
        // directory, where listing and prune take it for a version of that tool;
        // such a setting is ignored. The installs directory spelled another way
        // is the installs directory.
        Some(store) if is_within(&store, installs) => installs.clone(),
        Some(store) => store,
        None if cfg!(windows) && var_path("MISE_INSTALLS_DIR").is_none() => MISE_DATA_DIR.join("i"),
        None => installs.clone(),
    }
});

/// Whether `path` is `dir` or inside it, however either is spelled: relative,
/// through `..`, through a symlink, or (on Windows) in another case.
fn is_within(path: &Path, dir: &Path) -> bool {
    let comparable = |p: &Path| {
        let p = resolved_path(p);
        if cfg!(windows) {
            PathBuf::from(p.to_string_lossy().replace('/', "\\").to_lowercase())
        } else {
            p
        }
    };
    comparable(path).starts_with(comparable(dir))
}

/// `path` made absolute, with its longest existing ancestor resolved to the real
/// directory it names; what does not exist yet is kept as written.
fn resolved_path(path: &Path) -> PathBuf {
    let lexical = || {
        use path_absolutize::Absolutize;
        path.absolutize()
            .map_or_else(|_| path.to_path_buf(), |p| p.into_owned())
    };
    let Ok(absolute) = std::path::absolute(path) else {
        return lexical();
    };
    let mut existing = absolute.as_path();
    let mut missing = vec![];
    loop {
        if let Ok(real) = dunce::canonicalize(existing) {
            return missing.iter().rev().fold(real, |p, name| p.join(name));
        }
        // A missing `..` cannot be resolved against the real directory.
        match (existing.parent(), existing.file_name()) {
            (Some(parent), Some(name)) => {
                missing.push(name.to_os_string());
                existing = parent;
            }
            _ => return lexical(),
        }
    }
}

pub static MISE_DOWNLOADS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_DOWNLOADS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("downloads")));

pub static MISE_PLUGINS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_PLUGINS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("plugins")));

pub static MISE_SHIMS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_SHIMS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("shims")));

/// System-level data directory (like MISE_DATA_DIR but for system-wide tools).
pub static MISE_SYSTEM_DATA_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("MISE_SYSTEM_DATA_DIR").unwrap_or_else(|| PathBuf::from("/usr/local/share/mise"))
});

/// Directories of plugins installed for every user, searched in order after the user's own
/// plugins directory: `/usr/share/mise/plugins` for distro packages, then the `plugins`
/// directory under MISE_SYSTEM_DATA_DIR for the machine's admin.
pub static MISE_SYSTEM_PLUGINS_DIRS: Lazy<Vec<PathBuf>> =
    Lazy::new(|| match var_os("MISE_SYSTEM_PLUGINS_DIRS") {
        Some(v) => std::env::split_paths(&v)
            .filter(|p| !p.as_os_str().is_empty())
            .map(replace_path)
            .collect(),
        None => vec![
            PathBuf::from("/usr/share/mise/plugins"),
            MISE_SYSTEM_DATA_DIR.join("plugins"),
        ],
    });

/// System-level installs directory, derived from MISE_SYSTEM_DATA_DIR.
pub static MISE_SYSTEM_INSTALLS_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("MISE_SYSTEM_INSTALLS_DIR").unwrap_or_else(|| MISE_SYSTEM_DATA_DIR.join("installs"))
});

/// Extra shared install directories parsed from the environment variable.
/// This is the early/fallback source; prefer `shared_install_dirs()` which also
/// reads from Settings (config files) when available.
pub static MISE_SHARED_INSTALL_DIRS_ENV: Lazy<Vec<PathBuf>> = Lazy::new(|| {
    var_os("MISE_SHARED_INSTALL_DIRS")
        .map(|v| {
            std::env::split_paths(&v)
                .filter(|p| !p.as_os_str().is_empty())
                .map(replace_path)
                .collect()
        })
        .unwrap_or_default()
});

/// Early-boot variant used by install_state::init_tools() before Settings is loaded.
pub fn shared_install_dirs_early() -> Vec<PathBuf> {
    let system = &*MISE_SYSTEM_INSTALLS_DIR;
    let mut result = Vec::new();
    if system.is_dir() && *system != *MISE_INSTALLS_DIR {
        result.push(system.clone());
    }
    result.extend(MISE_SHARED_INSTALL_DIRS_ENV.iter().cloned());
    result
}

pub static MISE_GLOBAL_CONFIG_FILE: Lazy<Option<PathBuf>> =
    Lazy::new(|| var_path("MISE_GLOBAL_CONFIG_FILE").or_else(|| var_path("MISE_CONFIG_FILE")));

pub static MISE_GLOBAL_CONFIG_ROOT: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_GLOBAL_CONFIG_ROOT").unwrap_or_else(|| HOME.to_path_buf()));

pub static MISE_SYSTEM_CONFIG_FILE: Lazy<Option<PathBuf>> =
    Lazy::new(|| var_path("MISE_SYSTEM_CONFIG_FILE"));

pub static MISE_USE_TOML: Lazy<bool> = Lazy::new(|| !var_is_false("MISE_USE_TOML"));

pub static MISE_LIST_ALL_VERSIONS: Lazy<bool> = Lazy::new(|| var_is_true("MISE_LIST_ALL_VERSIONS"));

pub static ARGV0: Lazy<String> = Lazy::new(|| ARGS.read().unwrap()[0].to_string());

pub static MISE_BIN_NAME: Lazy<&str> = Lazy::new(|| filename(&ARGV0));

pub static MISE_LOG_FILE: Lazy<Option<PathBuf>> = Lazy::new(|| var_path("MISE_LOG_FILE"));

pub static MISE_LOG_FILE_LEVEL: Lazy<Option<LevelFilter>> = Lazy::new(log_file_level);

pub fn find_in_tree(base: &Path, rels: &[&[&str]]) -> Option<PathBuf> {
    for rel in rels {
        let mut p = base.to_path_buf();
        for part in *rel {
            p = p.join(part);
        }
        if p.exists() {
            return Some(p);
        }
    }
    None
}

pub fn mise_install_base() -> Option<PathBuf> {
    std::fs::canonicalize(&*MISE_BIN)
        .ok()
        .and_then(|p| p.parent().map(|p| p.to_path_buf()))
        .and_then(|p| p.parent().map(|p| p.to_path_buf()))
}

pub static MISE_SELF_UPDATE_INSTRUCTIONS: Lazy<Option<PathBuf>> = Lazy::new(|| {
    if let Some(p) = var_path("MISE_SELF_UPDATE_INSTRUCTIONS") {
        return Some(p);
    }
    let base = mise_install_base()?;
    // search lib/, lib/mise/, lib64/mise/
    find_in_tree(
        &base,
        &[
            &["lib", "mise-self-update-instructions.toml"],
            &["lib", "mise", "mise-self-update-instructions.toml"],
            &["lib64", "mise", "mise-self-update-instructions.toml"],
        ],
    )
});

pub static MISE_LOG_HTTP: Lazy<bool> = Lazy::new(|| var_is_true("MISE_LOG_HTTP"));

pub static MISE_LOG_VERBOSE_DEPS: Lazy<bool> = Lazy::new(|| var_is_true("MISE_LOG_VERBOSE_DEPS"));

pub static __USAGE: Lazy<Option<String>> = Lazy::new(|| var("__USAGE").ok());

pub static __MISE_SHIM: Lazy<bool> = Lazy::new(|| var_is_true("__MISE_SHIM"));

/// Absolute path of the shim that delegated to mise. Unlike `MISE_SHIMS_DIR`,
/// this remains reliable when a parent process preserves PATH but filters out
/// mise's directory configuration variables.
pub const MISE_SHIM_PATH_ENV: &str = "__MISE_SHIM_PATH";

pub static MISE_SHIM_PATH: Lazy<RwLock<Option<PathBuf>>> =
    Lazy::new(|| RwLock::new(var_path(MISE_SHIM_PATH_ENV)));

/// Set by `mise mcp` on the `mise run` it starts for a client: the run's arguments name tasks
/// only, never the path of a script to run. Read once, then kept out of the environment the run
/// gives its tasks (see `get_pristine_env`), so a `mise run ./script` that a task itself makes
/// keeps working.
pub const MISE_TASK_NAMES_ONLY_ENV: &str = "__MISE_TASK_NAMES_ONLY";

pub static MISE_TASK_NAMES_ONLY: Lazy<bool> = Lazy::new(|| {
    let set = var_os(MISE_TASK_NAMES_ONLY_ENV).is_some_and(|v| !v.is_empty());
    remove_var(MISE_TASK_NAMES_ONLY_ENV);
    set
});

/// What `mise x` resolved a shim's tool to. A native shim that finds its own path here was picked
/// instead of the tool, so it stops rather than dispatching back to `mise x`.
pub const MISE_SHIM_TARGET_ENV: &str = "__MISE_SHIM_TARGET";

pub static IS_RUNNING_AS_SHIM: Lazy<bool> = Lazy::new(|| {
    // When running tests, always treat as direct mise invocation
    // to avoid interfering with test expectations
    if crate::testing::active() {
        return false;
    }

    // Check if running as tool stub
    if *MISE_TOOL_STUB {
        return true;
    }

    let bin_name = *MISE_BIN_NAME;
    !is_mise_binary(bin_name)
});

/// Returns true if the given binary name refers to mise itself (not a shim).
/// Handles "mise", "mise.exe", "mise.bat", "mise.cmd", "mise-doctor", etc.
///
/// The comparison ignores case on Windows only. Its filesystem does too, so `MISE.EXE` starts the
/// same file as `mise.exe` and reaches `argv[0]` with whatever casing the caller wrote — and a
/// case-sensitive test then sent mise through `handle_shim` against itself. On unix
/// they are two different files, so a shim genuinely named `MISE` has to stay a shim.
pub fn is_mise_binary(bin_name: &str) -> bool {
    let is_mise = |s: &str| {
        if cfg!(windows) {
            s.eq_ignore_ascii_case("mise")
        } else {
            s == "mise"
        }
    };
    // Equivalent to matching "mise" plus the "mise." and "mise-" prefixes, with the case rule
    // applied in one place rather than three.
    is_mise(bin_name)
        || bin_name
            .split_once(['.', '-'])
            .is_some_and(|(stem, _)| is_mise(stem))
}

/// The suffixes `self-replace` gives the copies it makes of the running executable on Windows.
/// `get_temp_executable_name` builds `.{exe stem}.{32 random}{suffix}`.
///
/// This and the predicates below are compiled off Windows too, like
/// `unix_path_to_windows`, so they stay unit-tested everywhere rather than only
/// on the platform that runs them. Their callers are all `#[cfg(windows)]`, hence the allow.
pub const SELF_REPLACE_SUFFIXES: [&str; 2] = [".__selfdelete__.exe", ".__relocated__.exe"];

/// Whether `bin_name` is a copy of *this* executable that `self-replace` made while updating.
///
/// It is mise under a generated name, not a shim — but [`is_mise_binary`] cannot tell, because the
/// name **begins with a `.`**, so `split_once(['.', '-'])` hands back an empty stem and `is_mise("")`
/// is false. mise then walks into `handle_shim` and reports the name as a broken shim, advising the
/// user to reinstall a tool that was never uninstalled.
///
/// Takes the stem rather than reading `current_exe` so it stays pure, and requires it so that a
/// *different* application's orphan — `.othertool.….__selfdelete__.exe` — is not claimed as ours.
///
/// The random segment is checked too, because the caller that acts on this **deletes** the file:
/// anything short of the generated shape is somebody else's and stays where it is.
pub fn is_self_replace_helper(bin_name: &str, exe_stem: &str) -> bool {
    let prefix = format!(".{exe_stem}.");
    // Case-insensitively on Windows, and only for the stem. Measured: `current_exe()` hands back
    // whatever casing the caller used to start the process — `CASEPROBE.EXE` gives a stem of
    // `CASEPROBE` — so an update launched as `MISE.EXE` writes `.MISE.….__selfdelete__.exe`, and
    // the next one launched as `mise.exe` would fail to recognise its own orphan and leave it
    // there for good. The suffix and the random segment are generated by the crate and are always
    // lowercase, so only the stem can vary. Same rule, same reason, as [`is_mise_binary`].
    let matches = bin_name.get(..prefix.len()).is_some_and(|head| {
        if cfg!(windows) {
            head.eq_ignore_ascii_case(&prefix)
        } else {
            head == prefix
        }
    });
    if !matches {
        return false;
    }
    let rest = &bin_name[prefix.len()..];
    SELF_REPLACE_SUFFIXES.iter().any(|suffix| {
        rest.strip_suffix(suffix)
            .is_some_and(is_self_replace_random_segment)
    })
}

/// `self-replace` fills this many characters from `fastrand`'s `lowercase()`:
/// `for _ in 0..32 { file_name.push(rng.lowercase()) }` in `get_temp_executable_name`.
pub const SELF_REPLACE_RANDOM_LEN: usize = 32;

/// Exactly the segment that generator produces — nothing shorter, longer, or outside `a-z`.
///
/// Compares bytes rather than chars on purpose: ASCII bytes cannot appear inside a multi-byte
/// character, so this cannot mis-read a name that is not ASCII to begin with.
fn is_self_replace_random_segment(s: &str) -> bool {
    s.len() == SELF_REPLACE_RANDOM_LEN && s.bytes().all(|b| b.is_ascii_lowercase())
}

/// Whether *this* process is one of those copies, read straight from the OS.
///
/// Deliberately does not go through `ARGS`/`MISE_BIN_NAME`: this answers a question `main` asks
/// before the runtime, logging or config exist, in the same shape as
/// early executable-dispatch paths.
///
/// The stem is not checked, unlike [`is_self_replace_helper`], and it cannot be: the original stem
/// is *inside* the generated name, so a process running under one has nothing left to compare it
/// against. That costs nothing here — a running binary named `.x.….__selfdelete__.exe` was copied
/// from whatever spawned it, and the process asking is mise. Everything around the stem is still
/// required: a leading `.`, then some stem, then the generated random segment and the suffix.
#[cfg(windows)]
pub fn invoked_as_self_replace_helper() -> bool {
    let Some(invoked) = std::env::args_os().next() else {
        return false;
    };
    let Some(name) = Path::new(&invoked).file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    name.starts_with('.')
        && SELF_REPLACE_SUFFIXES.iter().any(|suffix| {
            name.strip_suffix(suffix).is_some_and(|head| {
                head.rsplit_once('.').is_some_and(|(stem, random)| {
                    !stem.is_empty() && is_self_replace_random_segment(random)
                })
            })
        })
}

/// Explicit terminal-width override: `MISE_TERM_WIDTH` takes precedence, then the
/// conventional `COLUMNS`. Lets tables/lists render sanely in CI where terminal
/// size detection returns 0. Honored exactly (no 80 floor) so a narrow width can
/// be forced on purpose. See discussion #4109.
///
/// `None` under mise's unit tests (like `TERM_WIDTH`) so tests that build a table don't pick up
/// a stray `COLUMNS`/`MISE_TERM_WIDTH` from the env.
pub static TERM_WIDTH_OVERRIDE: Lazy<Option<usize>> = Lazy::new(|| {
    if crate::testing::active() {
        return None;
    }
    for key in ["MISE_TERM_WIDTH", "COLUMNS"] {
        if let Some(w) = var(key)
            .ok()
            .and_then(|v| v.trim().parse::<usize>().ok())
            .filter(|w| *w > 0)
        {
            // COLUMNS is maintained by the shell and can leak in unintentionally,
            // so leave a breadcrumb when it (rather than MISE_TERM_WIDTH) is used.
            if key == "COLUMNS" {
                debug!(
                    "overriding terminal width with COLUMNS={w}; set MISE_TERM_WIDTH to control this explicitly"
                );
            }
            return Some(w);
        }
    }
    None
});

pub static TERM_WIDTH: Lazy<usize> = Lazy::new(|| {
    if crate::testing::active() {
        return 80;
    }
    if let Some(w) = *TERM_WIDTH_OVERRIDE {
        return w;
    }
    terminal_size::terminal_size()
        .map(|(w, _)| w.0 as usize)
        .unwrap_or(80)
        .max(80)
});

/// The mise executable, for re-running mise from a subprocess or pointing shims at it.
///
/// `__MISE_BIN` when a parent mise passed one, else the running executable, resolved by
/// [`mise_bin_behind`] so it never names a tool shim.
pub static MISE_BIN: Lazy<PathBuf> = Lazy::new(|| {
    var_path("__MISE_BIN")
        .or_else(|| current_exe().ok())
        .map(mise_bin_behind)
        .unwrap_or_else(|| "mise".into())
});

/// Whether running `path` runs mise rather than a tool: its file name is a mise name.
pub fn is_mise_path(path: &Path) -> bool {
    path.file_name()
        .is_some_and(|name| is_mise_binary(&name.to_string_lossy()))
}

/// The mise executable that `exe` runs.
///
/// mise chooses what to do from the name it was run as, so a path whose file name is not a mise
/// name runs a tool, never mise. macOS reports the path a process was launched through as
/// `current_exe()`, which for a shim launch is the shim (`shims/jq`). Re-running that runs `jq`,
/// and a reshim pointed at it makes every shim a link to itself (#15742).
///
/// Follow the shim link one step first: that is the mise the last reshim chose, usually a
/// launcher a package manager keeps across upgrades (`/opt/homebrew/bin/mise`), where the fully
/// resolved file is versioned (`…/Cellar/mise/<version>/bin/mise`) and goes away on cleanup.
/// Resolve fully only when that step does not end at mise. A path that is not a link to mise (a
/// Windows hardlink shim) is returned as given.
pub fn mise_bin_behind(exe: PathBuf) -> PathBuf {
    if is_mise_path(&exe) {
        return exe;
    }
    if let Ok(target) = std::fs::read_link(&exe) {
        // A relative link is relative to the directory the link really sits in. Resolve that
        // first: `..` after a symlinked shims directory names the real parent, and making the
        // joined path absolute later removes `..` without following links.
        let target = match exe.parent() {
            Some(dir) if target.is_relative() => {
                crate::file::canonicalize_or_self(dir).join(target)
            }
            _ => target,
        };
        if is_mise_path(&target) && target.exists() {
            return target;
        }
    }
    match crate::file::canonicalize_cached(&exe) {
        Some(resolved) if is_mise_path(&resolved) => resolved,
        _ => exe,
    }
}

pub static MISE_TIMINGS: Lazy<u8> = Lazy::new(|| var_u8("MISE_TIMINGS"));

pub static MISE_PID: Lazy<String> = Lazy::new(|| process::id().to_string());

pub static MISE_JOBS: Lazy<Option<usize>> =
    Lazy::new(|| var("MISE_JOBS").ok().and_then(|v| v.parse::<usize>().ok()));

pub static __MISE_SCRIPT: Lazy<bool> = Lazy::new(|| var_is_true("__MISE_SCRIPT"));

pub static __MISE_ORIG_PATH: Lazy<Option<String>> = Lazy::new(|| var("__MISE_ORIG_PATH").ok());

pub static __MISE_ZSH_PRECMD_RUN: Lazy<bool> = Lazy::new(|| !var_is_false("__MISE_ZSH_PRECMD_RUN"));

pub static OFFLINE: Lazy<bool> = Lazy::new(|| offline(&ARGS.read().unwrap()));

pub static WARN_ON_MISSING_REQUIRED_ENV: Lazy<bool> =
    Lazy::new(|| warn_on_missing_required_env(&ARGS.read().unwrap()));

pub static PATH_KEY: Lazy<String> =
    Lazy::new(|| path_key_from_env(vars_os().filter_map(|(k, _)| k.into_string().ok())));

#[cfg(unix)]
fn path_key_from_env(_keys: impl IntoIterator<Item = String>) -> String {
    "PATH".into()
}

#[cfg(windows)]
fn path_key_from_env(keys: impl IntoIterator<Item = String>) -> String {
    keys.into_iter()
        .find(|k| k.eq_ignore_ascii_case("PATH"))
        .unwrap_or("PATH".into())
}

/// Whether `key` names PATH.
///
/// Windows environment variable names are case-insensitive, so every spelling is the same
/// variable there — including `Path`, which is how Windows itself writes it. On unix only the
/// exact [`PATH_KEY`] is PATH, and a `Path` beside it is a variable of its own.
pub fn is_path_key(key: &str) -> bool {
    if cfg!(windows) {
        key.eq_ignore_ascii_case(&PATH_KEY)
    } else {
        key == *PATH_KEY
    }
}

/// Fold any spelling of PATH onto [`PATH_KEY`], leaving every other name alone.
///
/// mise owns PATH: it writes its own value under `PATH_KEY` after everything else has been
/// collected. A key that means PATH but is spelled differently would survive that write as a
/// second entry, and the two would then both be applied — so it has to be folded before it is
/// stored, not filtered afterwards. The identity on unix, where the only spelling that is PATH
/// is `PATH_KEY` already.
pub fn normalize_path_key(key: String) -> String {
    if is_path_key(&key) {
        PATH_KEY.to_string()
    } else {
        key
    }
}

pub static PATH_NON_PRISTINE: Lazy<Vec<PathBuf>> = Lazy::new(|| match var(&*PATH_KEY) {
    Ok(ref path) => split_paths(path).collect(),
    Err(_) => vec![],
});

pub static DIRENV_DIFF: Lazy<Option<String>> = Lazy::new(|| var("DIRENV_DIFF").ok());

/// GitHub token resolved from environment variables ONLY
/// (`MISE_GITHUB_TOKEN`, `GITHUB_API_TOKEN`, `GITHUB_TOKEN`).
///
/// Intended for subprocess env-var plumbing — passing a token to child processes such as
/// `cargo install` or `ruby-build` that read it themselves.
///
/// **Do not use for mise's own HTTP or sigstore calls.** Use
/// mise's `github::resolve_token_for_api_url` (which walks env vars,
/// `credential_command`, `github_tokens.toml`, gh CLI, and git credentials) or the
/// `github::sigstore` wrapper (which calls it internally). Passing this static
/// to attestation verification is the original cause of the lock-time rate-limit bug.
pub static GITHUB_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITHUB_TOKEN", "GITHUB_API_TOKEN", "GITHUB_TOKEN"]));

pub static MISE_GITHUB_ENTERPRISE_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITHUB_ENTERPRISE_TOKEN"]));

pub static GITLAB_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITLAB_TOKEN", "GITLAB_TOKEN"]));

pub static MISE_GITLAB_ENTERPRISE_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITLAB_ENTERPRISE_TOKEN"]));

pub static TEST_TRANCHE: Lazy<usize> = Lazy::new(|| var_u8("TEST_TRANCHE") as usize);

pub static TEST_TRANCHE_COUNT: Lazy<usize> = Lazy::new(|| var_u8("TEST_TRANCHE_COUNT") as usize);

pub static CLICOLOR_FORCE: Lazy<Option<bool>> =
    Lazy::new(|| var("CLICOLOR_FORCE").ok().map(|v| v != "0"));

pub static CLICOLOR: Lazy<Option<bool>> = Lazy::new(|| {
    if *CLICOLOR_FORCE == Some(true) {
        Some(true)
    } else if *NO_COLOR || var_is_false("MISE_COLOR") {
        Some(false)
    } else if let Ok(v) = var("CLICOLOR") {
        Some(v != "0")
    } else {
        None
    }
});

/// Disable color output - https://no-color.org/
pub static NO_COLOR: Lazy<bool> = Lazy::new(|| var("NO_COLOR").is_ok_and(|v| !v.is_empty()));

/// Force progress bars even in non-TTY (for debugging)
pub static MISE_FORCE_PROGRESS: Lazy<bool> = Lazy::new(|| var_is_true("MISE_FORCE_PROGRESS"));

/// Whether an AI coding agent is driving this process.
pub static AI_AGENT: Lazy<bool> = Lazy::new(mise_agent_env::is_agent);

pub static PYENV_ROOT: Lazy<PathBuf> =
    Lazy::new(|| var_path("PYENV_ROOT").unwrap_or_else(|| HOME.join(".pyenv")));

/// Where uv keeps the pythons it installs: `UV_PYTHON_INSTALL_DIR`, else `python` under uv's
/// data directory.
pub static UV_PYTHON_INSTALL_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("UV_PYTHON_INSTALL_DIR").unwrap_or_else(|| {
        uv_data_dir(cfg!(windows), &XDG_DATA_HOME, var_path("APPDATA"), &HOME).join("python")
    })
});

/// uv's data directory, resolved the way uv's `etcetera` strategy does. On Unix that is
/// `$XDG_DATA_HOME/uv`. On Windows `XDG_DATA_HOME` plays no part: it is the roaming
/// `%APPDATA%\uv`, not `%LOCALAPPDATA%` where mise keeps its own data.
fn uv_data_dir(
    windows: bool,
    xdg_data_home: &Path,
    appdata: Option<PathBuf>,
    home: &Path,
) -> PathBuf {
    if windows {
        appdata
            .unwrap_or_else(|| home.join("AppData").join("Roaming"))
            .join("uv")
    } else {
        xdg_data_home.join("uv")
    }
}

fn var_u8(key: &str) -> u8 {
    var(key)
        .ok()
        .and_then(|v| v.parse::<u8>().ok())
        .unwrap_or_default()
}

/// A variable read as a switch: `Some(true)` for `y`, `yes`, `true`, `1` or `on`, `Some(false)`
/// for `n`, `no`, `false`, `0` or `off` (in any case), and `None` when it is unset or anything
/// else.
pub fn var_bool(key: &str) -> Option<bool> {
    let v = var(key).ok()?.to_lowercase();
    match v.as_str() {
        "y" | "yes" | "true" | "1" | "on" => Some(true),
        "n" | "no" | "false" | "0" | "off" => Some(false),
        _ => None,
    }
}

pub fn var_is_true(key: &str) -> bool {
    var_bool(key) == Some(true)
}

pub fn var_is_false(key: &str) -> bool {
    var_bool(key) == Some(false)
}

pub fn in_home_dir() -> bool {
    current_dir().is_ok_and(|d| d == *HOME)
}

/// The value of `key` as a path, or `None` when it is unset **or empty**.
///
/// An empty value is not a directory. Without this it would yield an empty `PathBuf`, and every
/// caller joins onto the result — producing a *relative* path that gets resolved against the
/// current working directory. `XDG_CONFIG_HOME=` would make `MISE_CONFIG_DIR` the relative
/// `mise`, and a forge CLI lookup read `gh/hosts.yml` out of whatever directory mise happened to
/// be run from. Treating empty as unset is also what the tools mise mirrors here do: go-gh
/// (`os.Getenv(x) != ""`) and `adrg/xdg` (`dir != "" && filepath.IsAbs(dir)`) both fall through.
pub fn var_path(key: &str) -> Option<PathBuf> {
    var_os(key)
        .map(PathBuf::from)
        .map(replace_path)
        .filter(|p| !p.as_os_str().is_empty())
}

fn offline(args: &[String]) -> bool {
    if var_is_true("MISE_OFFLINE") {
        return true;
    }

    args.iter()
        .take_while(|a| *a != "--")
        .any(|a| a == "--offline")
}

/// returns true if missing required env vars should produce warnings instead of errors
fn warn_on_missing_required_env(args: &[String]) -> bool {
    // Check if we're running in a command that should warn instead of error
    args.iter()
        .take_while(|a| *a != "--")
        .filter(|a| !a.starts_with('-'))
        .nth(1)
        .map(|a| {
            [
                "hook-env", // Shell activation should not break the shell
            ]
            .contains(&a.as_str())
        })
        .unwrap_or_default()
}

fn log_file_level() -> Option<LevelFilter> {
    let log_level = var("MISE_LOG_FILE_LEVEL").unwrap_or_default();
    log_level.parse::<LevelFilter>().ok()
}

/// The basename of `path` by the host's path grammar, which on Windows means either separator.
///
/// `argv[0]` does not always arrive with `MAIN_SEPARATOR_STR`. libuv hands a Windows process a
/// forward-slash path, which is how Neovim's `jobstart` spawns mise, and splitting on the platform
/// separator left the whole path in [`MISE_BIN_NAME`]. [`is_mise_binary`] then said no and mise ran
/// itself as a shim named after its own path (discussion #11423).
///
/// Deferring to [`Path`] rather than splitting on both separators unconditionally is deliberate:
/// `\` is an ordinary filename character on unix, and splitting there would resolve a shim to a
/// different tool than the one invoked.
fn filename(path: &str) -> &str {
    Path::new(path)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(path)
}

fn get_token(keys: &[&str]) -> Option<String> {
    keys.iter()
        .find_map(|key| var(key).ok())
        .filter(|v| !v.trim().is_empty())
}

pub fn is_activated() -> bool {
    var("__MISE_DIFF").is_ok()
}

pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
    static MUTEX: Mutex<()> = Mutex::new(());
    let _mutex = MUTEX.lock().unwrap();
    let _overrides = BackendOverrideChange::of(key.as_ref());
    unsafe {
        std::env::set_var(key, value);
    }
}

pub fn remove_var<K: AsRef<OsStr>>(key: K) {
    static MUTEX: Mutex<()> = Mutex::new(());
    let _mutex = MUTEX.lock().unwrap();
    let _overrides = BackendOverrideChange::of(key.as_ref());
    unsafe {
        std::env::remove_var(key);
    }
}

/// Whether `key` names a `MISE_BACKENDS_*` override. Windows variable names
/// are case-insensitive, so `mise_backends_node` counts there as it does for
/// `env::var`.
pub fn is_backend_override_key(key: &str) -> bool {
    const PREFIX: &str = "MISE_BACKENDS_";
    if cfg!(windows) {
        key.get(..PREFIX.len())
            .is_some_and(|start| start.eq_ignore_ascii_case(PREFIX))
    } else {
        key.starts_with(PREFIX)
    }
}

const OVERRIDES_UNKNOWN: u8 = 0;
const OVERRIDES_NONE: u8 = 1;
const OVERRIDES_SOME: u8 = 2;
static BACKEND_OVERRIDES: std::sync::atomic::AtomicU8 =
    std::sync::atomic::AtomicU8::new(OVERRIDES_UNKNOWN);
static BACKEND_OVERRIDES_SCAN: Mutex<()> = Mutex::new(());

/// Whether the environment holds any `MISE_BACKENDS_*` variable.
///
/// Resolving a tool's backend asks for that tool's variable many times per
/// command, and each lookup walks the whole environment. Most environments
/// have none, so one walk answers every one of them. [`set_var`] and
/// [`remove_var`] forget the answer when they touch such a variable, so one
/// that mise sets on itself still takes effect.
pub fn backend_override_vars_set() -> bool {
    use std::sync::atomic::Ordering;
    match BACKEND_OVERRIDES.load(Ordering::Acquire) {
        OVERRIDES_NONE => return false,
        OVERRIDES_SOME => return true,
        _ => {}
    }
    let _scan = BACKEND_OVERRIDES_SCAN
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let any = vars_os().any(|(key, _)| key.to_str().is_some_and(is_backend_override_key));
    BACKEND_OVERRIDES.store(
        if any { OVERRIDES_SOME } else { OVERRIDES_NONE },
        Ordering::Release,
    );
    any
}

/// Held while a `MISE_BACKENDS_*` variable changes, so a scan cannot record
/// the environment as it was before the change.
struct BackendOverrideChange {
    _scan: std::sync::MutexGuard<'static, ()>,
}

impl BackendOverrideChange {
    fn of(key: &OsStr) -> Option<Self> {
        key.to_str()
            .is_some_and(is_backend_override_key)
            .then(|| Self {
                _scan: BACKEND_OVERRIDES_SCAN
                    .lock()
                    .unwrap_or_else(|e| e.into_inner()),
            })
    }
}

impl Drop for BackendOverrideChange {
    fn drop(&mut self) {
        BACKEND_OVERRIDES.store(OVERRIDES_UNKNOWN, std::sync::atomic::Ordering::Release);
    }
}

/// Remove the env cache encryption key to force fresh env computation
pub fn reset_env_cache_key() {
    remove_var("__MISE_ENV_CACHE_KEY");
}

/// Safe wrapper around std::env::vars() that handles invalid UTF-8 gracefully.
/// This function uses vars_os() and converts OsString to String, skipping any
/// environment variables that contain invalid UTF-8 sequences.
pub fn vars_safe() -> impl Iterator<Item = (String, String)> {
    vars_os().filter_map(|(k, v)| {
        let k_str = k.to_str()?;
        let v_str = v.to_str()?;
        Some((k_str.to_string(), v_str.to_string()))
    })
}

/// The raw `CMDCMDLINE` a generated Windows `.cmd` launcher was invoked through.
///
/// cmd.exe parses its whole command line before a batch file's `%*` expands, so an argument
/// containing `& ^ | " < >` or `%VAR%` never reaches `%*` intact. The original text does survive
/// in cmd's `CMDCMDLINE` pseudo-variable, but that is not part of the environment a child
/// inherits — measured — so the launcher copies it into this real variable.
pub const LAUNCHER_RAW_CMDLINE_ENV: &str = "__MISE_RAW_CMDLINE";

/// The launcher's own path, so [`recover_launcher_args`] can find where its arguments begin.
pub const LAUNCHER_PATH_ENV: &str = "__MISE_LAUNCHER";

/// Separates the launcher's own command from the caller's arguments.
///
/// The launcher always passes `%*` after this, so a run where the raw line cannot be trusted
/// still gets the arguments cmd managed to deliver rather than none at all.
pub const LAUNCHER_ARGS_SENTINEL: &str = "__MISE_LAUNCHER_ARGS__";

/// Arguments recovered from the launcher's raw command line, or `None` when there are none to
/// recover or the line cannot be shown to be this launcher's.
///
/// Read once and removed from the environment straight away: a task mise runs inherits this
/// process's environment, and a launcher or shim invoked *by* that task would otherwise recover
/// the outer invocation's arguments as its own.
static RECOVERED_LAUNCHER_ARGS: Lazy<Option<Vec<String>>> = Lazy::new(|| {
    let raw = var(LAUNCHER_RAW_CMDLINE_ENV).ok();
    let launcher = var(LAUNCHER_PATH_ENV).ok();
    remove_var(LAUNCHER_RAW_CMDLINE_ENV);
    remove_var(LAUNCHER_PATH_ENV);
    recover_launcher_args(&raw?, &launcher?)
});

/// The argument text `launcher` was called with, taken out of cmd's raw command line.
///
/// Deliberately strict about the shape. Only a line where cmd was spawned *for* this launcher is
/// accepted — `<cmd.exe> /c "" <launcher> " <args>"`, which is what a shell building a native
/// invocation produces. A line that merely mentions the launcher somewhere (a `call` from another
/// batch file, a `cmd /c "<launcher> a & b"` chain typed by hand, an interactive prompt) is
/// declined, because there the arguments were split by the shell before anything mise wrote ran
/// and `%*` is already as good as it gets.
pub fn recover_launcher_args(raw: &str, launcher: &str) -> Option<Vec<String>> {
    let (_, after) = raw.split_once(" /c ").or_else(|| raw.split_once(" /C "))?;
    // cmd's own `/c` argument, then the launcher path quoted inside it.
    let inner = after.strip_prefix('"')?.strip_suffix('"')?;
    let tail = inner
        .strip_prefix('"')?
        .strip_prefix(launcher)?
        .strip_prefix('"')?;
    Some(split_command_line(tail))
}

/// Split the argument section of a Windows command line the way a native program's runtime does.
///
/// The rules are the ones `CommandLineToArgvW` applies past the program name: arguments are
/// separated by whitespace, `"` toggles a quoted run in which whitespace is literal, `2n`
/// backslashes before a `"` are `n` backslashes and a toggle, and `2n+1` are `n` backslashes and
/// a literal `"`. Written out rather than calling the Win32 function so it is testable on every
/// platform — the end-to-end check that it agrees with a real Windows program lives in
/// `e2e-win/task_stub_native_launcher.Tests.ps1`.
pub fn split_command_line(line: &str) -> Vec<String> {
    let mut args = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    let mut started = false;
    let mut backslashes = 0usize;

    fn flush(current: &mut String, backslashes: &mut usize) {
        for _ in 0..*backslashes {
            current.push('\\');
        }
        *backslashes = 0;
    }

    for c in line.chars() {
        match c {
            '\\' => {
                backslashes += 1;
                started = true;
            }
            '"' => {
                for _ in 0..backslashes / 2 {
                    current.push('\\');
                }
                if backslashes % 2 == 1 {
                    current.push('"');
                } else {
                    in_quotes = !in_quotes;
                }
                backslashes = 0;
                // An empty quoted run is still an argument: `""` is one, not none.
                started = true;
            }
            ' ' | '\t' if !in_quotes => {
                flush(&mut current, &mut backslashes);
                if started {
                    args.push(std::mem::take(&mut current));
                    started = false;
                }
            }
            _ => {
                flush(&mut current, &mut backslashes);
                current.push(c);
                started = true;
            }
        }
    }
    flush(&mut current, &mut backslashes);
    if started {
        args.push(current);
    }
    args
}

/// Replace what a Windows launcher forwarded with what it was actually called with.
///
/// Everything up to [`LAUNCHER_ARGS_SENTINEL`] is the launcher's own command and is kept. What
/// follows is cmd's `%*`, used as-is unless the raw command line could be recovered, in which case
/// the recovered arguments take its place.
fn replace_after_sentinel(args: Vec<String>, recovered: Option<&Vec<String>>) -> Vec<String> {
    let Some(at) = args.iter().position(|a| a == LAUNCHER_ARGS_SENTINEL) else {
        return args;
    };
    let mut out = args[..at].to_vec();
    match recovered {
        Some(recovered) => out.extend(recovered.iter().cloned()),
        None => out.extend_from_slice(&args[at + 1..]),
    }
    out
}

fn apply_launcher_args(args: Vec<String>) -> Vec<String> {
    // Forced whatever argv looks like, so the environment variables never outlive this process
    // even when mise was not started by a launcher.
    let recovered = RECOVERED_LAUNCHER_ARGS.as_ref();
    replace_after_sentinel(args, recovered)
}

/// Safe wrapper around std::env::args() that handles invalid UTF-8 gracefully.
/// std::env::args() panics if any argument contains invalid UTF-8; this uses
/// args_os() and lossily converts each argument (invalid sequences become U+FFFD).
/// Unlike vars_safe() the conversion is lossy rather than skipping, so argument
/// positions are preserved and a malformed argv yields a normal "unknown command"
/// error instead of crashing.
pub fn args_safe() -> Vec<String> {
    apply_launcher_args(args_os().map(|a| a.to_string_lossy().to_string()).collect())
}

pub static __MISE_DIFF: Lazy<EnvDiff> = Lazy::new(get_env_diff);

/// essentially, this is whether we show spinners or build output on runtime install
pub static PRISTINE_ENV: Lazy<EnvMap> =
    Lazy::new(|| get_pristine_env(&__MISE_DIFF, vars_safe().collect()));

pub static PATH: Lazy<Vec<PathBuf>> = Lazy::new(|| match PRISTINE_ENV.get(&*PATH_KEY) {
    Some(path) => split_paths(path).collect(),
    None => vec![],
});

fn get_env_diff() -> EnvDiff {
    let env = vars_safe().collect::<HashMap<_, _>>();
    match env.get("__MISE_DIFF") {
        Some(raw) => EnvDiff::deserialize(raw).unwrap_or_else(|err| {
            warn!("Failed to deserialize __MISE_DIFF: {:#}", err);
            EnvDiff::default()
        }),
        None => EnvDiff::default(),
    }
}

/// this returns the environment as if __MISE_DIFF was reversed.
/// putting the shell back into a state before hook-env was run
fn get_pristine_env(mise_diff: &EnvDiff, orig_env: EnvMap) -> EnvMap {
    let orig_path: HashSet<PathBuf> = orig_env
        .get("__MISE_ORIG_PATH")
        .map(|p| split_paths(p).collect())
        .unwrap_or_default();
    let mut env = reverse_diff_preserving_overrides(mise_diff, orig_env);
    // meant for this process only, not for the commands it starts
    env.remove(MISE_TASK_NAMES_ONLY_ENV);

    // get the current path as a vector
    let path: Vec<PathBuf> = match env.get(&*PATH_KEY) {
        Some(path) => split_paths(path).collect(),
        None => vec![],
    };
    // get the paths that were removed by mise as a hashset
    let mut to_remove = mise_diff.path.iter().collect::<HashSet<_>>();

    // remove those paths that were added by mise, but only once (the first time).
    // A directory that was already on PATH before activation appears twice unless the
    // shell deduplicates PATH (e.g. zsh `typeset -U path`); with a single occurrence it
    // is the pre-activation entry, so keep it.
    let counts = path.iter().counts();
    let path = path
        .iter()
        .filter(|p| {
            let single_orig = orig_path.contains(*p) && counts.get(p) == Some(&1);
            single_orig || !to_remove.remove(p)
        })
        .cloned()
        .collect_vec();

    // put the pristine PATH back into the environment
    env.insert(
        PATH_KEY.to_string(),
        join_paths(path).unwrap().to_string_lossy().to_string(),
    );
    strip_inherited_secrets(&mut env, &INHERITED_SECRET_KEYS);
    env
}

/// Names-only marker a parent mise sets in the environment of a child that was
/// granted secrets: a comma-separated list of variable names, never values.
pub const SECRET_KEYS_MARKER: &str = "__MISE_SECRET_KEYS";

/// Whether two environment variable names are the same variable: exact on
/// Unix, case-insensitive on Windows.
#[cfg(not(windows))]
pub fn env_key_eq(a: &str, b: &str) -> bool {
    a == b
}

#[cfg(windows)]
pub fn env_key_eq(a: &str, b: &str) -> bool {
    windows_env_key_eq(a, b)
}

/// Names that are never treated as secrets, even when listed in the marker: the
/// always-kept sandbox keys and mise's own `__MISE_*` state.
pub fn is_reserved_secret_name(name: &str) -> bool {
    reserved_secret_name(name, env_key_eq)
}

fn reserved_secret_name(name: &str, eq: fn(&str, &str) -> bool) -> bool {
    const RESERVED: [&str; 7] = ["PATH", "HOME", "USER", "SHELL", "TERM", "COLORTERM", "LANG"];
    const PREFIX: &str = "__MISE_";
    RESERVED.iter().any(|r| eq(name, r))
        || name
            .get(..PREFIX.len())
            .is_some_and(|head| eq(head, PREFIX))
}

/// Whether `name` is a plain environment variable name: `[A-Za-z_][A-Za-z0-9_]*`.
pub fn is_valid_secret_name(name: &str) -> bool {
    let mut chars = name.chars();
    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn parse_secret_keys(marker: &str, eq: fn(&str, &str) -> bool) -> BTreeSet<String> {
    marker
        .split(',')
        .map(str::trim)
        .filter(|k| is_valid_secret_name(k) && !reserved_secret_name(k, eq))
        .map(String::from)
        .collect()
}

/// Variables a parent mise marked as secrets in this process's environment.
///
/// A forged marker can only add redaction, turn caches off, or hide those keys
/// from templates and nested tasks; it never grants anything.
pub static INHERITED_SECRET_KEYS: Lazy<BTreeSet<String>> = Lazy::new(|| {
    inherited_secret_keys(
        var(SECRET_KEYS_MARKER).ok().as_deref(),
        vars_safe().map(|(k, _)| k),
        env_key_eq,
    )
});

/// `mise x -- fish` hands fish its variables through temporary copies that fish only reads after
/// config.fish has run. The copies that hold a granted secret are named
/// `__MISE_FISH_SECRET_<n>`; a mise started from config.fish would otherwise see them as
/// ordinary, unmarked variables, so they are always treated as secrets. Copies of plain values
/// (`__MISE_FISH_ENV_<n>`) are not.
pub const FISH_SECRET_PREFIX: &str = "__MISE_FISH_SECRET_";
const FISH_TEMP_PREFIX: &str = FISH_SECRET_PREFIX;

fn is_fish_temp_name(name: &str, eq: fn(&str, &str) -> bool) -> bool {
    name.get(..FISH_TEMP_PREFIX.len())
        .is_some_and(|head| eq(head, FISH_TEMP_PREFIX))
}

fn inherited_secret_keys(
    marker: Option<&str>,
    names: impl Iterator<Item = String>,
    eq: fn(&str, &str) -> bool,
) -> BTreeSet<String> {
    let mut keys = marker.map(|v| parse_secret_keys(v, eq)).unwrap_or_default();
    keys.extend(names.filter(|k| is_fish_temp_name(k, eq)));
    keys
}

/// The live process environment minus inherited secrets and their marker, for
/// expanding `${VAR}` references in config-derived files: expanding against
/// the raw environment would copy a secret's value into a new, unmarked name.
pub fn vars_without_inherited_secrets() -> impl Iterator<Item = (String, String)> {
    vars_safe().filter(|(k, _)| !is_inherited_secret_key(k, &INHERITED_SECRET_KEYS))
}

fn is_inherited_secret_key(name: &str, keys: &BTreeSet<String>) -> bool {
    keys.iter().any(|m| env_key_eq(name, m)) || env_key_eq(name, SECRET_KEYS_MARKER)
}

/// Remove inherited secret keys and the marker from `env`, whatever spelling
/// the environment uses for them.
fn strip_inherited_secrets(env: &mut EnvMap, keys: &BTreeSet<String>) {
    strip_matching(env, keys, env_key_eq);
}

fn strip_matching(env: &mut EnvMap, keys: &BTreeSet<String>, eq: fn(&str, &str) -> bool) {
    env.retain(|k, _| !keys.iter().any(|m| eq(k, m)) && !eq(k, SECRET_KEYS_MARKER));
}

/// Keep inherited secrets out of a child mise starts. `CmdLineRunner` inherits
/// mise's process environment, so `env_remove` is what actually withholds them.
pub fn strip_inherited_secrets_for_child(env: &mut EnvMap, env_remove: &mut BTreeSet<String>) {
    strip_secrets_for_child(env, env_remove, &INHERITED_SECRET_KEYS, env_key_eq);
}

fn strip_secrets_for_child(
    env: &mut EnvMap,
    env_remove: &mut BTreeSet<String>,
    keys: &BTreeSet<String>,
    eq: fn(&str, &str) -> bool,
) {
    if keys.is_empty() {
        return;
    }
    // The marker's spelling may differ from the environment's, so withhold both.
    for k in keys.iter().map(String::as_str).chain([SECRET_KEYS_MARKER]) {
        env_remove.insert(k.to_string());
    }
    env_remove.extend(
        env.keys()
            .filter(|k| keys.iter().any(|m| eq(k, m)) || eq(k, SECRET_KEYS_MARKER))
            .cloned()
            .collect::<Vec<_>>(),
    );
    strip_matching(env, keys, eq);
}

/// Reverse values that are still in the state mise recorded, while preserving
/// values changed or removed by the caller after mise applied the environment.
fn reverse_diff_preserving_overrides(mise_diff: &EnvDiff, mut env: EnvMap) -> EnvMap {
    for (key, old_value) in &mise_diff.old {
        match env_diff_get(&mise_diff.new, key) {
            Some(new_value)
                if env_map_get(&env, key)
                    .is_some_and(|v| env_value_matches(mise_diff.v, new_value, v)) =>
            {
                let key = env_map_key(&env, key)
                    .cloned()
                    .unwrap_or_else(|| key.clone());
                env.insert(key, old_value.clone());
            }
            None if env_map_get(&env, key).is_none() => {
                env.insert(key.clone(), old_value.clone());
            }
            _ => {}
        }
    }

    for (key, new_value) in &mise_diff.new {
        if env_diff_get(&mise_diff.old, key).is_none()
            && env_map_get(&env, key).is_some_and(|v| env_value_matches(mise_diff.v, new_value, v))
            && let Some(key) = env_map_key(&env, key).cloned()
        {
            env.remove(&key);
        }
    }

    env
}

#[cfg(not(windows))]
fn env_map_key<'a>(env: &'a EnvMap, key: &str) -> Option<&'a String> {
    env.get_key_value(key).map(|(key, _)| key)
}

#[cfg(windows)]
fn env_map_key<'a>(env: &'a EnvMap, key: &str) -> Option<&'a String> {
    env.keys()
        .find(|candidate| windows_env_key_eq(candidate, key))
}

fn env_map_get<'a>(env: &'a EnvMap, key: &str) -> Option<&'a String> {
    env_map_key(env, key).and_then(|key| env.get(key))
}

#[cfg(not(windows))]
fn env_diff_get<'a>(env: &'a IndexMap<String, String>, key: &str) -> Option<&'a String> {
    env.get(key)
}

#[cfg(windows)]
fn env_diff_get<'a>(env: &'a IndexMap<String, String>, key: &str) -> Option<&'a String> {
    env.iter()
        .find(|(candidate, _)| windows_env_key_eq(candidate, key))
        .map(|(_, value)| value)
}

#[cfg(windows)]
fn windows_env_key_eq(left: &str, right: &str) -> bool {
    use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};

    let left = left.encode_utf16().collect::<Vec<_>>();
    let right = right.encode_utf16().collect::<Vec<_>>();
    let (Ok(left_len), Ok(right_len)) = (i32::try_from(left.len()), i32::try_from(right.len()))
    else {
        return false;
    };

    unsafe {
        CompareStringOrdinal(left.as_ptr(), left_len, right.as_ptr(), right_len, 1) == CSTR_EQUAL
    }
}

/// Returns the list of shared install directories to search.
/// Includes the system installs dir (`MISE_SYSTEM_DATA_DIR/installs`) plus any
/// user-configured dirs from Settings (config files) or the environment variable.
/// The user's primary install dir is NOT included here — it is checked separately.
pub fn shared_install_dirs() -> Vec<PathBuf> {
    let user_dirs = if let std::result::Result::Ok(settings) = Settings::try_get()
        && let Some(ref dirs) = settings.shared_install_dirs
        && !dirs.is_empty()
    {
        dirs.clone()
    } else {
        MISE_SHARED_INSTALL_DIRS_ENV.clone()
    };
    let system = Settings::try_get()
        .map(|settings| crate::dirs::system_installs_dir(&settings).to_path_buf())
        .unwrap_or_else(|_| MISE_SYSTEM_INSTALLS_DIR.clone());
    // System dir first (if it exists and isn't the user's own install dir),
    // then user-configured dirs.
    let mut result = Vec::new();
    if system.is_dir() && system != *MISE_INSTALLS_DIR {
        result.push(system);
    }
    result.extend(user_dirs);
    result
}

/// Categorize an install path as system, shared, or local.
pub fn install_path_category(path: &Path) -> InstallPathCategory {
    let system_installs = Settings::try_get()
        .map(|settings| crate::dirs::system_installs_dir(&settings).to_path_buf())
        .unwrap_or_else(|_| MISE_SYSTEM_INSTALLS_DIR.clone());
    if system_installs != *MISE_INSTALLS_DIR && path.starts_with(system_installs) {
        InstallPathCategory::System
    } else if shared_install_dirs().iter().any(|d| path.starts_with(d)) {
        InstallPathCategory::Shared
    } else {
        InstallPathCategory::Local
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstallPathCategory {
    /// Primary user install dir
    Local,
    /// System-level (/usr/local/share/mise/installs)
    System,
    /// User-configured shared dir
    Shared,
}

/// Look up a tool version in shared install directories.
/// `tool_dir_name` should be the kebab-cased directory name (e.g. from `ba.installs_path`).
/// Returns the first shared path where `<shared_dir>/<tool_dir_name>/<pathname>` exists,
/// or `primary_path` if not found in any shared directory.
pub fn find_in_shared_installs(
    primary_path: PathBuf,
    tool_dir_name: &str,
    pathname: &str,
) -> PathBuf {
    if !primary_path.exists() {
        for shared_dir in shared_install_dirs() {
            let shared_path = shared_dir.join(tool_dir_name).join(pathname);
            if shared_path.exists() {
                return shared_path;
            }
        }
    }
    primary_path
}

pub static PREFER_OFFLINE: Lazy<AtomicBool> =
    Lazy::new(|| prefer_offline(&ARGS.read().unwrap()).into());

/// Commands whose explicit purpose is to enumerate remote versions/tags. Under
/// `prefer_offline`, remote-version lookups are otherwise capped to a single
/// ~3s attempt with no retries so fast/interactive commands (shims, activation)
/// never stall. These commands opt out of that cap so they honor the full
/// configured `fetch_remote_versions_timeout` even when `prefer_offline` is set
/// (https://github.com/jdx/mise/discussions/11185).
pub static REMOTE_FETCH_COMMAND: Lazy<AtomicBool> =
    Lazy::new(|| remote_fetch_command(&ARGS.read().unwrap()).into());

/// returns true if new runtime versions should not be fetched
fn prefer_offline(args: &[String]) -> bool {
    // First check if MISE_PREFER_OFFLINE is set
    if var_is_true("MISE_PREFER_OFFLINE") {
        return true;
    }

    let settings_args_end = first_non_global_arg_idx(args).unwrap_or(args.len());
    if args[..settings_args_end]
        .iter()
        .any(|arg| arg == "--prefer-offline")
    {
        return true;
    }

    prefer_offline_command(args)
}

/// Commands that should not fetch remote versions.
const PREFER_OFFLINE_COMMANDS: &[&str] = &[
    "activate", "current", "direnv", "env", "exec", "hook-env", "ls", "where", "which", "x",
];

/// Commands whose whole purpose is to enumerate remote versions, or to report
/// the newest one. See [`REMOTE_FETCH_COMMAND`]. They also keep a cached version
/// list for only `fetch_remote_versions_cache`, never for a tool's release-age
/// window (`crate::network::release_age_list_window_applies`).
const REMOTE_FETCH_COMMANDS: &[&str] = &[
    "latest",
    "lock",
    "ls-remote",
    "list-all",
    "list-remote",
    "outdated",
    "upgrade",
    "up",
];

fn first_non_global_arg_idx(args: &[String]) -> Option<usize> {
    // Uses the cached global-flag list rather than building a fresh clap tree.
    // This runs from `Lazy` statics during startup, so on essentially every
    // invocation; building the tree here cost ~6.3M instructions per run.
    crate::args::first_non_global_arg_idx_cached(args)
}

/// Whether the subcommand at `command_idx` is one of `names`.
fn is_command(args: &[String], command_idx: Option<usize>, names: &[&str]) -> bool {
    command_idx
        .and_then(|idx| args.get(idx))
        .map(|a| names.contains(&a.as_str()))
        .unwrap_or_default()
}

fn prefer_offline_command(args: &[String]) -> bool {
    is_command(
        args,
        first_non_global_arg_idx(args),
        PREFER_OFFLINE_COMMANDS,
    )
}

/// See [`REMOTE_FETCH_COMMAND`].
fn remote_fetch_command(args: &[String]) -> bool {
    is_command(args, first_non_global_arg_idx(args), REMOTE_FETCH_COMMANDS)
}

tokio::task_local! {
    static INSTALL_ENV: IndexMap<String, EnvValue>;
}

/// Overlays a tool's `install_env` on the process env for the duration of `future`,
/// so anything it does reads that tool's values through [`scoped_var`].
pub async fn with_install_env<T>(
    env: IndexMap<String, EnvValue>,
    future: impl std::future::Future<Output = T>,
) -> T {
    INSTALL_ENV.scope(env, future).await
}

/// Reads an env var through the active [`with_install_env`] overlay, falling back to the
/// process env. Blank reads as unset, as does an `install_env` entry set to `false`.
pub fn scoped_var(key: &str) -> Option<String> {
    match INSTALL_ENV.try_with(|env| env.get(key).cloned()) {
        Ok(Some(value)) => value.into_string(),
        _ => std::env::var(key).ok(),
    }
    .map(|value| value.trim().to_string())
    .filter(|value| !value.is_empty())
}

static MISE_ENV: std::sync::OnceLock<fn() -> &'static [String]> = std::sync::OnceLock::new();

/// Register how to read the active `MISE_ENV` environments. They come from
/// command-line flags, the environment and `.miserc.toml`, which mise resolves.
pub fn set_mise_env(f: fn() -> &'static [String]) {
    let _ = MISE_ENV.set(f);
}

/// The prefix mise's built-in Homebrew support installs into: the platform
/// default, unless the undocumented `MISE_SYSTEM_BREW_PREFIX` override (used
/// to test the pour pipeline without touching the real prefix) is set.
pub fn system_brew_prefix() -> PathBuf {
    match var("MISE_SYSTEM_BREW_PREFIX") {
        Ok(p) if !p.is_empty() => PathBuf::from(p),
        _ if cfg!(target_os = "macos") => PathBuf::from("/opt/homebrew"),
        _ => PathBuf::from("/home/linuxbrew/.linuxbrew"),
    }
}

/// The active `MISE_ENV` environments. See [`set_mise_env`].
pub fn mise_env() -> &'static [String] {
    let f = MISE_ENV
        .get()
        .expect("mise_util::env::set_mise_env must be called first");
    f()
}

/// Deliberately not `#[cfg(windows)]`: the code under test is pure string handling, and the whole
/// point of writing the splitter out rather than calling `CommandLineToArgvW` was that it can be
/// checked on every platform CI runs.
#[cfg(test)]
mod launcher_args_tests {
    use super::*;

    /// A command line shaped the way a shell builds one when it spawns cmd to run `launcher`.
    fn cmd_line(launcher: &str, tail: &str) -> String {
        format!("C:\\WINDOWS\\system32\\cmd.exe /c \"\"{launcher}\"{tail}\"")
    }

    const LAUNCHER: &str = "C:\\proj\\bin\\hello.cmd";

    #[test]
    fn splits_the_way_a_native_program_would() {
        assert_eq!(split_command_line(" a b c"), ["a", "b", "c"]);
        assert_eq!(split_command_line("  a   b  "), ["a", "b"]);
        assert_eq!(split_command_line(""), Vec::<String>::new());
        assert_eq!(split_command_line("   "), Vec::<String>::new());
        // Whitespace is literal inside quotes, and the quotes themselves are not part of it.
        assert_eq!(split_command_line(" \"m n\""), ["m n"]);
        assert_eq!(split_command_line(" a\"b c\"d"), ["ab cd"]);
        // An empty quoted run is an argument, not nothing.
        assert_eq!(split_command_line(" \"\""), [""]);
        // A tab separates like a space.
        assert_eq!(split_command_line(" a\tb"), ["a", "b"]);
    }

    #[test]
    fn applies_the_backslash_rules() {
        // Backslashes are only special immediately before a quote, which is why a Windows path
        // full of them survives untouched.
        assert_eq!(split_command_line(" C:\\a\\b"), ["C:\\a\\b"]);
        assert_eq!(split_command_line(" trail\\"), ["trail\\"]);
        // `2n` backslashes then `"`: n backslashes, and the quote toggles.
        assert_eq!(split_command_line(" \"a\\\\\"b"), ["a\\b"]);
        // `2n+1`: n backslashes and a literal quote.
        assert_eq!(split_command_line(" q\\\"r"), ["q\"r"]);
        assert_eq!(split_command_line(" q\\\\\\\"r"), ["q\\\"r"]);
    }

    #[test]
    fn recovers_the_arguments_cmd_destroyed() {
        // Every shape measured to reach the task differently through a `%*` launcher.
        for (tail, expected) in [
            (" c&d", vec!["c&d"]),
            (" i^j", vec!["i^j"]),
            (" e%OS%f", vec!["e%OS%f"]),
            (" a>b", vec!["a>b"]),
            (" a<b", vec!["a<b"]),
            (" ^caret", vec!["^caret"]),
            (" a!b", vec!["a!b"]),
            (" \"x y&z\"", vec!["x y&z"]),
            (" a \"b c\" d", vec!["a", "b c", "d"]),
            ("", Vec::<&str>::new()),
        ] {
            let raw = cmd_line(LAUNCHER, tail);
            assert_eq!(
                recover_launcher_args(&raw, LAUNCHER).unwrap(),
                expected,
                "{raw:?}"
            );
        }
    }

    #[test]
    fn declines_a_line_that_is_not_this_launchers_own() {
        // The controls. Accepting any of these would either take arguments that were never meant
        // as one -- the shell had already split them, exactly as it would for a native program --
        // or, worse, let the `exit` in the launcher close a shell mise was not spawned by.
        for raw in [
            // An interactive prompt: no `/c` at all.
            "\"C:\\WINDOWS\\system32\\cmd.exe\"".to_string(),
            // `call` from another batch file: the line is the outer script's.
            "\"cmd.exe\" /c \"C:\\proj\\outer.cmd\"".to_string(),
            // Typed by hand to run the launcher and then something else: the launcher path is not
            // quoted, so it is not the sole thing cmd was given.
            format!("\"cmd.exe\" /c \"{LAUNCHER} foo & echo done\""),
            // A different launcher's line.
            cmd_line("C:\\proj\\bin\\other.cmd", " a"),
            // Truncated or malformed.
            format!("\"cmd.exe\" /c \"\"{LAUNCHER}\" a"),
            format!("\"cmd.exe\" /c {LAUNCHER} a"),
            String::new(),
        ] {
            assert!(recover_launcher_args(&raw, LAUNCHER).is_none(), "{raw:?}");
        }
    }

    #[test]
    fn the_sentinel_marks_where_the_callers_arguments_begin() {
        let argv = |extra: &[&str]| {
            let mut v = vec!["mise".to_string(), "run".to_string(), "hello".to_string()];
            v.push(LAUNCHER_ARGS_SENTINEL.to_string());
            v.extend(extra.iter().map(|s| s.to_string()));
            v
        };
        // Nothing recovered: what cmd delivered is used, and the sentinel is not passed on.
        assert_eq!(
            replace_after_sentinel(argv(&["c"]), None),
            ["mise", "run", "hello", "c"]
        );
        // Recovered: it replaces what cmd delivered rather than adding to it.
        assert_eq!(
            replace_after_sentinel(argv(&["c"]), Some(&vec!["c&d".to_string()])),
            ["mise", "run", "hello", "c&d"]
        );
        // No sentinel at all -- an ordinary mise invocation -- is left exactly as it is.
        let plain = vec!["mise".to_string(), "run".to_string(), "hello".to_string()];
        assert_eq!(
            replace_after_sentinel(plain.clone(), Some(&vec!["nope".to_string()])),
            plain
        );
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn fish_secret_copies_are_always_inherited_secrets_but_plain_copies_are_not() {
        let names = [
            "PATH",
            "__MISE_FISH_SECRET_0",
            "__MISE_FISH_SECRET_12",
            "__MISE_FISH_ENV_1",
            "__MISE_DIFF",
        ]
        .iter()
        .map(|s| s.to_string());
        let keys = inherited_secret_keys(Some("DEPLOY_KEY,__MISE_FISH_SECRET_9"), names, |a, b| {
            a == b
        });
        // the marker parser still ignores mise's own names; the live secret copies are added
        assert_eq!(
            keys,
            BTreeSet::from(
                [
                    "DEPLOY_KEY",
                    "__MISE_FISH_SECRET_0",
                    "__MISE_FISH_SECRET_12"
                ]
                .map(String::from)
            )
        );
        // so a child mise strips them, and a plain copy passes through
        let mut env = EnvMap::from([
            ("__MISE_FISH_SECRET_0".into(), "s3cr3t".into()),
            ("__MISE_FISH_ENV_1".into(), "1".into()),
            ("KEEP".into(), "1".into()),
        ]);
        let mut remove = BTreeSet::new();
        strip_secrets_for_child(&mut env, &mut remove, &keys, |a, b| a == b);
        assert_eq!(
            env.keys().collect::<Vec<_>>(),
            ["KEEP", "__MISE_FISH_ENV_1"]
        );
        assert!(remove.contains("__MISE_FISH_SECRET_0"));
        assert!(!remove.contains("__MISE_FISH_ENV_1"));
    }

    use super::*;

    #[test]
    fn backend_override_vars_follow_set_var_and_remove_var() {
        let key = "MISE_BACKENDS___MISE_TEST_OVERRIDE_VARS";
        let others = || {
            vars_os().any(|(k, _)| {
                k.to_str()
                    .is_some_and(|k| k != key && is_backend_override_key(k))
            })
        };
        if others() {
            // Another test holds an override; this one cannot see "none".
            return;
        }
        assert!(!backend_override_vars_set());
        set_var(key, "core:node");
        assert!(backend_override_vars_set());
        remove_var(key);
        assert_eq!(backend_override_vars_set(), others());
    }

    #[test]
    fn var_bool_reads_the_switch_spellings_and_nothing_else() {
        let key = "__MISE_TEST_VAR_BOOL";
        for (value, expected) in [
            ("1", Some(true)),
            ("Yes", Some(true)),
            ("ON", Some(true)),
            ("y", Some(true)),
            ("0", Some(false)),
            ("No", Some(false)),
            ("OFF", Some(false)),
            ("n", Some(false)),
            ("", None),
            ("maybe", None),
        ] {
            set_var(key, value);
            assert_eq!(var_bool(key), expected, "{value:?}");
            assert_eq!(var_is_true(key), expected == Some(true), "{value:?}");
            assert_eq!(var_is_false(key), expected == Some(false), "{value:?}");
        }
        remove_var(key);
        assert_eq!(var_bool(key), None);
    }

    /// A Homebrew-like layout: `bin/mise` is the stable launcher, a link to the versioned file.
    #[cfg(unix)]
    fn brew_layout(root: &Path) -> (PathBuf, PathBuf) {
        let cellar = root.join("Cellar/mise/1.0/bin");
        std::fs::create_dir_all(&cellar).unwrap();
        let real = cellar.join("mise");
        std::fs::write(&real, "").unwrap();
        std::fs::create_dir_all(root.join("bin")).unwrap();
        let launcher = root.join("bin/mise");
        std::os::unix::fs::symlink(&real, &launcher).unwrap();
        std::fs::create_dir_all(root.join("shims")).unwrap();
        (launcher, real)
    }

    #[cfg(unix)]
    #[test]
    fn a_tool_shim_resolves_to_the_launcher_it_links_to() {
        let tmp = tempfile::tempdir().unwrap();
        let (launcher, _real) = brew_layout(tmp.path());
        let shim = tmp.path().join("shims/jq");
        std::os::unix::fs::symlink(&launcher, &shim).unwrap();
        // One step, not the versioned file behind it: that goes away on `brew cleanup`.
        assert_eq!(mise_bin_behind(shim), launcher);
    }

    #[cfg(unix)]
    #[test]
    fn a_relative_shim_link_resolves_against_the_shim_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let (launcher, _real) = brew_layout(tmp.path());
        let shim = tmp.path().join("shims/jq");
        std::os::unix::fs::symlink("../bin/mise", &shim).unwrap();
        let resolved = mise_bin_behind(shim);
        assert_eq!(
            std::fs::canonicalize(&resolved).unwrap(),
            std::fs::canonicalize(&launcher).unwrap()
        );
        assert!(is_mise_path(&resolved));
    }

    #[cfg(unix)]
    #[test]
    fn a_relative_shim_link_follows_a_symlinked_shims_directory() {
        let tmp = tempfile::tempdir().unwrap();
        // The real shims live in `farm`; `data/shims` is a link to them.
        let (launcher, _real) = brew_layout(&tmp.path().join("farm"));
        std::fs::create_dir_all(tmp.path().join("data")).unwrap();
        std::os::unix::fs::symlink(tmp.path().join("farm/shims"), tmp.path().join("data/shims"))
            .unwrap();
        std::os::unix::fs::symlink("../bin/mise", tmp.path().join("farm/shims/jq")).unwrap();
        let resolved = mise_bin_behind(tmp.path().join("data/shims/jq"));
        // Made absolute the way shims are written, lexically: still the launcher in `farm`.
        let written = std::path::absolute(&resolved).unwrap();
        let written: PathBuf = written.components().fold(PathBuf::new(), |mut p, c| {
            match c {
                std::path::Component::ParentDir => {
                    p.pop();
                }
                c => p.push(c),
            }
            p
        });
        assert_eq!(
            written,
            std::fs::canonicalize(tmp.path().join("farm/bin"))
                .unwrap()
                .join("mise")
        );
        assert_eq!(
            std::fs::canonicalize(&resolved).unwrap(),
            std::fs::canonicalize(&launcher).unwrap()
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_shim_through_a_link_not_named_mise_resolves_fully() {
        let tmp = tempfile::tempdir().unwrap();
        let (_launcher, real) = brew_layout(tmp.path());
        let hop = tmp.path().join("bin/hop");
        std::os::unix::fs::symlink(&real, &hop).unwrap();
        let shim = tmp.path().join("shims/jq");
        std::os::unix::fs::symlink(&hop, &shim).unwrap();
        assert_eq!(mise_bin_behind(shim), std::fs::canonicalize(&real).unwrap());
    }

    #[cfg(unix)]
    #[test]
    fn mise_and_paths_that_do_not_lead_to_mise_are_kept() {
        let tmp = tempfile::tempdir().unwrap();
        let (launcher, _real) = brew_layout(tmp.path());
        // Already mise: not resolved, so the launcher is kept rather than the versioned file.
        assert_eq!(mise_bin_behind(launcher.clone()), launcher);
        // A plain file under a tool's name, like a Windows hardlink shim.
        let tool = tmp.path().join("bin/jq");
        std::fs::write(&tool, "").unwrap();
        assert_eq!(mise_bin_behind(tool.clone()), tool);
        // A bare name is left for PATH lookup.
        assert_eq!(mise_bin_behind("mise".into()), PathBuf::from("mise"));
    }

    #[test]
    fn default_tmp_dir_stays_out_of_the_cache_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let temp = dunce::canonicalize(tmp.path()).unwrap();
        // The Windows default: `%TEMP%\mise` for both.
        assert_eq!(
            default_tmp_dir(&temp, &temp.join("mise")),
            temp.join("mise-tmp")
        );
        // The same cache directory with a trailing separator, or spelled through `..`.
        assert_eq!(
            default_tmp_dir(&temp, &temp.join("mise").join("")),
            temp.join("mise-tmp")
        );
        assert_eq!(
            default_tmp_dir(&temp, &temp.join("x").join("..").join("mise")),
            temp.join("mise-tmp")
        );
        // Unix and macOS defaults keep the cache elsewhere, so the path is unchanged.
        let home_cache = temp.join("home").join(".cache").join("mise");
        assert_eq!(default_tmp_dir(&temp, &home_cache), temp.join("mise"));
        // A cache inside the temporary directory does not contain it.
        assert_eq!(
            default_tmp_dir(&temp, &temp.join("mise").join("cache")),
            temp.join("mise")
        );
        assert_eq!(
            default_tmp_dir(&temp, &temp.join("mise-cache")),
            temp.join("mise")
        );
        // A cache directory that is the temporary directory itself has no default outside it.
        assert_eq!(default_tmp_dir(&temp, &temp), temp.join("mise-tmp"));
        if cfg!(windows) {
            // `TEMP` and `TMP` differing only in case.
            let upper = PathBuf::from(temp.to_string_lossy().to_uppercase());
            assert_eq!(
                default_tmp_dir(&temp, &upper.join("mise")),
                temp.join("mise-tmp")
            );
        }
        #[cfg(unix)]
        {
            // The cache directory written through a symlink to the temporary directory, as
            // macOS `/private/var/folders/...` is to `/var/folders/...`.
            let link = temp.join("link");
            std::os::unix::fs::symlink(&temp, &link).unwrap();
            assert_eq!(
                default_tmp_dir(&temp, &link.join("mise")),
                temp.join("mise-tmp")
            );
        }
    }

    fn keys(names: &[&str]) -> BTreeSet<String> {
        names.iter().map(|k| k.to_string()).collect()
    }

    #[test]
    fn test_secret_marker_parsing_ignores_invalid_and_reserved_names() {
        assert_eq!(
            parse_secret_keys("A, B,bad name,PATH,__MISE_X,HOME", str::eq),
            keys(&["A", "B"])
        );
        assert!(parse_secret_keys("", str::eq).is_empty());
        assert!(parse_secret_keys("1A,a-b", str::eq).is_empty());
        // case-insensitive platforms: `Path` and `__mise_x` are still reserved
        let ci = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
        assert_eq!(parse_secret_keys("Path,__mise_x,Foo", ci), keys(&["Foo"]));
        assert_eq!(parse_secret_keys("Path", str::eq), keys(&["Path"]));
    }

    #[test]
    fn test_inherited_secret_key_matching() {
        let k = keys(&["FOO"]);
        assert!(is_inherited_secret_key("FOO", &k));
        assert!(is_inherited_secret_key(SECRET_KEYS_MARKER, &k));
        assert!(!is_inherited_secret_key("BAR", &k));
        assert!(!is_inherited_secret_key("X", &BTreeSet::new()));
    }

    #[test]
    fn test_strip_inherited_secrets_removes_keys_and_marker() {
        let mut env: EnvMap = [
            ("FOO", "secret"),
            ("KEEP", "x"),
            (SECRET_KEYS_MARKER, "FOO"),
        ]
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .into();
        strip_inherited_secrets(&mut env, &keys(&["FOO"]));
        assert_eq!(env.keys().collect::<Vec<_>>(), vec!["KEEP"]);
        let mut mixed: EnvMap = [("Foo", "s"), ("KEEP", "x"), ("__mise_secret_keys", "FOO")]
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .into();
        strip_matching(&mut mixed, &keys(&["FOO"]), str::eq);
        assert_eq!(mixed.len(), 3);
        strip_matching(&mut mixed, &keys(&["FOO"]), |a, b| {
            a.eq_ignore_ascii_case(b)
        });
        assert_eq!(mixed.keys().collect::<Vec<_>>(), vec!["KEEP"]);
    }

    #[test]
    fn test_strip_secrets_for_child_fills_env_remove() {
        let mut env: EnvMap = [("FOO", "secret"), ("KEEP", "x")]
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .into();
        let mut env_remove = BTreeSet::new();
        strip_secrets_for_child(&mut env, &mut env_remove, &BTreeSet::new(), str::eq);
        assert!(env_remove.is_empty() && env.contains_key("FOO"));
        strip_secrets_for_child(&mut env, &mut env_remove, &keys(&["FOO"]), str::eq);
        assert_eq!(env_remove, keys(&["FOO", SECRET_KEYS_MARKER]));
        assert_eq!(env.keys().collect::<Vec<_>>(), vec!["KEEP"]);
        // the env's own spelling is withheld too
        let mut env: EnvMap = [("Foo", "s"), ("KEEP", "x")]
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .into();
        let mut env_remove = BTreeSet::new();
        strip_secrets_for_child(&mut env, &mut env_remove, &keys(&["FOO"]), |a, b| {
            a.eq_ignore_ascii_case(b)
        });
        assert!(env_remove.contains("Foo") && env_remove.contains("FOO"));
        assert_eq!(env.keys().collect::<Vec<_>>(), vec!["KEEP"]);
    }

    #[cfg(windows)]
    #[test]
    fn test_secret_keys_are_case_insensitive_on_windows() {
        assert!(is_reserved_secret_name("Path"));
        assert!(is_reserved_secret_name("__mise_x"));
        assert!(!is_reserved_secret_name("Foo"));
        let mut env: EnvMap = [("Foo", "s"), ("KEEP", "x")]
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .into();
        let mut env_remove = BTreeSet::new();
        strip_secrets_for_child(&mut env, &mut env_remove, &keys(&["FOO"]), env_key_eq);
        assert!(env_remove.contains("Foo"));
        assert_eq!(env.keys().collect::<Vec<_>>(), vec!["KEEP"]);
    }

    #[test]
    fn test_is_within_sees_through_spellings() {
        let tmp = tempfile::tempdir().unwrap();
        let data = dunce::canonicalize(tmp.path()).unwrap();
        let installs = data.join("installs");
        std::fs::create_dir_all(&installs).unwrap();
        // inside, written plainly or through `..`
        assert!(is_within(&installs.join("store"), &installs));
        assert!(is_within(
            &installs.join("x").join("..").join("store"),
            &installs
        ));
        assert!(is_within(&installs, &installs));
        // a sibling written through the installs directory is not inside it
        assert!(!is_within(&installs.join("..").join("store"), &installs));
        assert!(!is_within(&data.join("installs-store"), &installs));
        if cfg!(windows) {
            let upper = PathBuf::from(installs.to_string_lossy().to_uppercase());
            assert!(is_within(&upper.join("store"), &installs));
        }
        #[cfg(unix)]
        {
            // through a symlink to the installs directory
            let link = data.join("link");
            std::os::unix::fs::symlink(&installs, &link).unwrap();
            assert!(is_within(&link.join("store"), &installs));
            assert!(!is_within(&link.join("..").join("store"), &installs));
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_path_key_from_env_uses_uppercase_path_on_unix() {
        assert_eq!(
            path_key_from_env(vec!["path".into(), "HOME".into()]),
            "PATH"
        );
        assert_eq!(
            path_key_from_env(vec!["Path".into(), "HOME".into()]),
            "PATH"
        );
    }
    #[cfg(windows)]
    #[test]
    fn test_path_key_from_env_preserves_windows_path_casing() {
        assert_eq!(
            path_key_from_env(vec!["Path".into(), "TEMP".into()]),
            "Path"
        );
        assert_eq!(
            path_key_from_env(vec!["TEMP".into(), "PATH".into()]),
            "PATH"
        );
        assert_eq!(path_key_from_env(vec!["TEMP".into()]), "PATH");
    }
    #[test]
    fn test_token_overwrite() {
        // Clean up any existing environment variables that might interfere
        remove_var("MISE_GITHUB_TOKEN");
        remove_var("GITHUB_TOKEN");
        remove_var("GITHUB_API_TOKEN");

        set_var("MISE_GITHUB_TOKEN", "");
        set_var("GITHUB_TOKEN", "invalid_token");
        assert_eq!(
            get_token(&["MISE_GITHUB_TOKEN", "GITHUB_TOKEN"]),
            None,
            "Empty token should overwrite other tokens"
        );
        assert_eq!(
            get_token(&["GITHUB_API_TOKEN", "GITHUB_TOKEN"]),
            Some("invalid_token".into()),
            "Unset token should not overwrite other tokens"
        );
        remove_var("MISE_GITHUB_TOKEN");
        remove_var("GITHUB_TOKEN");
        remove_var("GITHUB_API_TOKEN");
    }
    #[test]
    fn test_filename_takes_the_basename() {
        // The reported case: libuv gives a Windows process a forward-slash argv[0], and splitting
        // on MAIN_SEPARATOR_STR left the whole path behind. `/` separates on every platform, so
        // the case the fix is for is pinned everywhere.
        assert_eq!(filename("C:/Users/alice/.cargo/bin/mise.EXE"), "mise.EXE");
        // A unix path was equally unhandled on Windows, since the separator there is `\`.
        assert_eq!(filename("/usr/local/bin/mise"), "mise");
        // A trailing separator used to yield an empty name.
        assert_eq!(filename("/usr/local/bin/mise/"), "mise");
        // Bare names pass through, which is the common case.
        assert_eq!(filename("mise"), "mise");
        assert_eq!(filename("mise.exe"), "mise.exe");
    }
    /// `\` separates path components only on Windows, so the two tests below are a deliberate
    /// platform split rather than duplicated coverage.
    ///
    /// This half is the regression guard: the spelling that always worked has to keep working.
    #[cfg(windows)]
    #[test]
    fn test_filename_splits_on_backslash_on_windows() {
        assert_eq!(filename(r"C:\Users\alice\.cargo\bin\mise.EXE"), "mise.EXE");
        assert_eq!(filename(r"C:\tools\mise\"), "mise");
    }
    /// The other half. On unix `\` is an ordinary filename character, so splitting on it would
    /// resolve a shim to a different tool than the one invoked. `filename` defers to the host
    /// path grammar to avoid that, and this pins the choice.
    #[cfg(unix)]
    #[test]
    fn test_filename_keeps_backslashes_on_unix() {
        assert_eq!(
            filename(r"C:\Users\alice\.cargo\bin\mise.EXE"),
            r"C:\Users\alice\.cargo\bin\mise.EXE"
        );
        assert_eq!(filename(r"/opt/odd/weird\name"), r"weird\name");
    }
    #[test]
    fn test_a_full_path_argv0_is_recognised_as_mise_itself() {
        // What the fix is actually for: `filename` is only interesting because its result feeds
        // `is_mise_binary`, and a false there sends mise into shim mode against its own path.
        for argv0 in [
            "C:/Users/alice/.cargo/bin/mise.EXE",
            "/usr/local/bin/mise",
            "mise",
        ] {
            assert!(
                is_mise_binary(filename(argv0)),
                "argv[0] {argv0:?} should be recognised as mise, not a shim"
            );
        }
        // The backslash spelling only resolves where `\` is a separator; see the pair of
        // `filename` tests above.
        #[cfg(windows)]
        assert!(
            is_mise_binary(filename(r"C:\Users\alice\.cargo\bin\mise.exe")),
            "a backslash argv[0] should be recognised as mise on Windows"
        );
        // The control: a real shim invocation must still be treated as one, or this "fix" would
        // be mise refusing to act as a shim at all.
        for argv0 in ["/home/alice/.local/share/mise/shims/node", "node.exe"] {
            assert!(
                !is_mise_binary(filename(argv0)),
                "argv[0] {argv0:?} should still be a shim"
            );
        }
    }

    #[test]
    fn test_reverse_diff_preserves_runtime_overrides() {
        let diff = EnvDiff {
            v: crate::env_diff::ENV_STATE_VERSION,
            old: [
                ("CHANGED".into(), "before".into()),
                ("REMOVED".into(), "before".into()),
            ]
            .into(),
            new: [
                ("ADDED".into(), crate::env_diff::hash_env_value("managed")),
                ("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
            ]
            .into(),
            ..Default::default()
        };
        let current = [
            ("ADDED".into(), "override".into()),
            ("CHANGED".into(), "override".into()),
            ("REMOVED".into(), "override".into()),
        ]
        .into();

        assert_eq!(
            reverse_diff_preserving_overrides(&diff, current),
            [
                ("ADDED".into(), "override".into()),
                ("CHANGED".into(), "override".into()),
                ("REMOVED".into(), "override".into()),
            ]
            .into()
        );
    }
    #[test]
    fn test_reverse_diff_with_hashed_new_values() {
        let diff = EnvDiff {
            v: crate::env_diff::ENV_STATE_VERSION,
            old: [("CHANGED".into(), "before".into())].into(),
            new: [
                ("ADDED".into(), crate::env_diff::hash_env_value("managed")),
                ("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
            ]
            .into(),
            ..Default::default()
        };
        let current = [
            ("ADDED".into(), "managed".into()),
            ("CHANGED".into(), "override".into()),
        ]
        .into();
        // CHANGED was overridden after mise applied it, so it is left alone;
        // ADDED is still the managed value and is removed.
        assert_eq!(
            reverse_diff_preserving_overrides(&diff, current),
            [("CHANGED".into(), "override".into())].into()
        );
    }

    /// A shell that keeps running across a mise upgrade still holds a `__MISE_DIFF` the
    /// previous version wrote with plaintext `new` values. It must reverse cleanly, or the
    /// managed variables would be treated as part of the pristine environment.
    #[test]
    fn test_reverse_diff_with_plaintext_new_values_from_older_mise() {
        let diff = EnvDiff {
            old: [("CHANGED".into(), "before".into())].into(),
            new: [
                ("ADDED".into(), "managed".into()),
                ("CHANGED".into(), "managed".into()),
            ]
            .into(),
            ..Default::default()
        };
        let current = [
            ("ADDED".into(), "managed".into()),
            ("CHANGED".into(), "managed".into()),
        ]
        .into();
        assert_eq!(
            reverse_diff_preserving_overrides(&diff, current),
            [("CHANGED".into(), "before".into())].into()
        );
    }

    /// A directory on PATH before activation that mise also added stays in the pristine PATH
    /// when the shell deduplicated PATH, and loses only mise's copy when it did not.
    #[test]
    fn test_pristine_path_keeps_deduplicated_orig_entry() {
        let diff = EnvDiff {
            path: vec![PathBuf::from("/x/bin")],
            ..Default::default()
        };
        let join = |dirs: &[&str]| {
            join_paths(dirs.iter().map(PathBuf::from))
                .unwrap()
                .to_string_lossy()
                .to_string()
        };
        let pristine_path = |dirs: &[&str]| {
            let orig = [
                (PATH_KEY.to_string(), join(dirs)),
                ("__MISE_ORIG_PATH".into(), join(&["/usr/bin", "/x/bin"])),
            ]
            .into();
            get_pristine_env(&diff, orig)[&*PATH_KEY].clone()
        };
        assert_eq!(
            pristine_path(&["/x/bin", "/usr/bin"]),
            join(&["/x/bin", "/usr/bin"])
        );
        assert_eq!(
            pristine_path(&["/x/bin", "/usr/bin", "/x/bin"]),
            join(&["/usr/bin", "/x/bin"])
        );
    }

    /// The pristine env derived from a version 1 diff must not keep managed values: a changed
    /// variable's previous value would otherwise be recorded as `old` in the next diff.
    #[test]
    fn test_pristine_env_from_plaintext_v1_diff() {
        let diff = EnvDiff {
            v: 1,
            old: [("CHANGED".into(), "before".into())].into(),
            new: [
                ("ADDED".into(), "managed".into()),
                ("CHANGED".into(), "managed".into()),
            ]
            .into(),
            ..Default::default()
        };
        let orig = [
            ("ADDED".into(), "managed".into()),
            ("CHANGED".into(), "managed".into()),
            ("OTHER".into(), "kept".into()),
        ]
        .into();
        let pristine = get_pristine_env(&diff, orig);
        assert_eq!(pristine.get("CHANGED").map(String::as_str), Some("before"));
        assert!(!pristine.contains_key("ADDED"));
        assert_eq!(pristine.get("OTHER").map(String::as_str), Some("kept"));
    }

    #[test]
    fn test_reverse_diff_restores_unchanged_managed_values() {
        let diff = EnvDiff {
            v: crate::env_diff::ENV_STATE_VERSION,
            old: [
                ("CHANGED".into(), "before".into()),
                ("REMOVED".into(), "before".into()),
            ]
            .into(),
            new: [
                ("ADDED".into(), crate::env_diff::hash_env_value("managed")),
                ("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
            ]
            .into(),
            ..Default::default()
        };
        let current = [
            ("ADDED".into(), "managed".into()),
            ("CHANGED".into(), "managed".into()),
        ]
        .into();

        assert_eq!(
            reverse_diff_preserving_overrides(&diff, current),
            [
                ("CHANGED".into(), "before".into()),
                ("REMOVED".into(), "before".into()),
            ]
            .into()
        );
    }
    #[test]
    fn test_reverse_diff_preserves_runtime_removals() {
        let diff = EnvDiff {
            v: crate::env_diff::ENV_STATE_VERSION,
            old: [("CHANGED".into(), "before".into())].into(),
            new: [
                ("ADDED".into(), crate::env_diff::hash_env_value("managed")),
                ("CHANGED".into(), crate::env_diff::hash_env_value("managed")),
            ]
            .into(),
            ..Default::default()
        };

        assert_eq!(
            reverse_diff_preserving_overrides(&diff, EnvMap::new()),
            EnvMap::new()
        );
    }
    #[cfg(windows)]
    #[test]
    fn test_reverse_diff_matches_environment_keys_case_insensitively_on_windows() {
        let diff = EnvDiff {
            v: crate::env_diff::ENV_STATE_VERSION,
            old: [
                ("Changed".into(), "before".into()),
                ("MÎSE_FOO".into(), "before-unicode".into()),
            ]
            .into(),
            new: [
                ("Added".into(), crate::env_diff::hash_env_value("managed")),
                ("Changed".into(), crate::env_diff::hash_env_value("managed")),
                (
                    "MÎSE_FOO".into(),
                    crate::env_diff::hash_env_value("managed-unicode"),
                ),
            ]
            .into(),
            ..Default::default()
        };
        let current = [
            ("ADDED".into(), "managed".into()),
            ("CHANGED".into(), "managed".into()),
            ("mîse_foo".into(), "managed-unicode".into()),
        ]
        .into();

        assert_eq!(
            reverse_diff_preserving_overrides(&diff, current),
            [
                ("CHANGED".into(), "before".into()),
                ("mîse_foo".into(), "before-unicode".into()),
            ]
            .into()
        );
    }

    #[test]
    fn test_remote_fetch_command_skips_global_option_values() {
        let args = |args: &[&str]| {
            args.iter()
                .map(|arg| (*arg).to_string())
                .collect::<Vec<_>>()
        };

        assert!(remote_fetch_command(&args(&[
            "mise", "--cd", "/tmp", "lock"
        ])));
        assert!(remote_fetch_command(&args(&[
            "mise",
            "--profile",
            "development",
            "ls-remote",
        ])));
        assert!(remote_fetch_command(&args(&[
            "mise",
            "--cd=/tmp",
            "--profile=development",
            "outdated",
        ])));
        assert!(remote_fetch_command(&args(&["mise", "latest", "node"])));
        assert!(!remote_fetch_command(&args(&["mise", "install", "node"])));
    }
    #[test]
    fn test_prefer_offline_command_skips_global_option_values() {
        let args = |args: &[&str]| {
            args.iter()
                .map(|arg| (*arg).to_string())
                .collect::<Vec<_>>()
        };

        assert!(prefer_offline_command(&args(&[
            "mise", "--cd", "/tmp", "activate"
        ])));
        assert!(prefer_offline_command(&args(&[
            "mise",
            "--profile",
            "development",
            "hook-env",
        ])));
        assert!(prefer_offline_command(&args(&["mise", "-C/tmp", "env",])));
        assert!(!prefer_offline_command(&args(&[
            "mise", "--cd", "/tmp", "lock"
        ])));
        assert!(prefer_offline(&args(&[
            "mise",
            "--cd",
            "/tmp",
            "--prefer-offline",
            "lock",
        ])));
    }

    #[test]
    fn uv_data_dir_follows_uv_not_mise_on_each_platform() {
        let xdg = Path::new("/xdg");
        let home = Path::new("/home/u");
        let appdata = || Some(PathBuf::from("/roaming"));
        // Unix: uv honors XDG_DATA_HOME.
        assert_eq!(
            uv_data_dir(false, xdg, appdata(), home),
            PathBuf::from("/xdg/uv")
        );
        // Windows: roaming %APPDATA%, never XDG_DATA_HOME (which mise points at LocalAppData).
        assert_eq!(
            uv_data_dir(true, xdg, appdata(), home),
            PathBuf::from("/roaming/uv")
        );
        // Windows with no %APPDATA%: the same fallback etcetera uses.
        assert_eq!(
            uv_data_dir(true, xdg, None, home),
            home.join("AppData").join("Roaming").join("uv")
        );
    }
}