mise 2026.8.16

Dev tools, env vars, and tasks in one CLI
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
use crate::Result;
use crate::config::miserc;
use crate::env_diff::{EnvDiff, EnvMap};
use crate::file::replace_path;
use crate::shell::ShellType;
use crate::{cli::args::ToolArg, file::display_path};
use eyre::Context;
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use log::LevelFilter;
pub(crate) use std::env::*;
use std::process;
use std::sync::LazyLock as Lazy;
use std::sync::RwLock;
use std::{
    collections::{HashMap, HashSet},
    ffi::OsStr,
    sync::Mutex,
};
use std::{path::Path, string::ToString};
use std::{path::PathBuf, sync::atomic::AtomicBool};

pub(crate) static ARGS: RwLock<Vec<String>> = RwLock::new(vec![]);
pub(crate) static TOOL_ARGS: RwLock<Vec<ToolArg>> = RwLock::new(vec![]);
pub(crate) const MISE_INSTALL_VERSION_ENV_VAR: &str = "MISE_INSTALL_VERSION";
pub(crate) const MISE_TOOL_VERSION_ENV_VAR: &str = "MISE_TOOL_VERSION";
pub(crate) const NON_TOOL_VERSION_ENV_VARS: &[&str] =
    &[MISE_INSTALL_VERSION_ENV_VAR, MISE_TOOL_VERSION_ENV_VAR];
#[cfg(unix)]
pub(crate) static SHELL: Lazy<String> = Lazy::new(|| var("SHELL").unwrap_or_else(|_| "sh".into()));
#[cfg(windows)]
pub(crate) static SHELL: Lazy<String> =
    Lazy::new(|| var("COMSPEC").unwrap_or_else(|_| "cmd.exe".into()));
pub(crate) static MISE_SHELL: Lazy<Option<ShellType>> =
    Lazy::new(|| detect_shell(var("MISE_SHELL").ok(), var("SHELL").ok(), &SHELL));

/// Which shell mise should speak, from the environment.
///
/// `SHELL` is consulted here but deliberately *not* through [`SHELL`], which on Windows reads
/// `COMSPEC`. Git Bash, MSYS2 and Cygwin all set `SHELL` to a real shell there, and
/// [`ShellType::from_str`] already understands the form they use, but nothing ever looked. Reading
/// it through [`SHELL`] instead would be wrong: [`SHELL_COMMAND_FLAG`] is `/c` on Windows and
/// `mise exec -c` and `mise en` pair the two, so `bash.exe /c …` is what that would run.
///
/// Split out from the `Lazy` because that is process-wide and reads the real environment, so the
/// precedence below cannot be exercised from a test any other way.
fn detect_shell(
    mise_shell: Option<String>,
    shell_var: Option<String>,
    fallback: &str,
) -> Option<ShellType> {
    // What `mise activate` exports, so it decides on its own. Set but unparseable is an answer,
    // not a reason to start guessing.
    if let Some(s) = mise_shell {
        return s.parse().ok();
    }
    // On unix `SHELL` *is* the fallback, so consulting it separately would be the same lookup
    // twice. On Windows it is the one the fallback cannot reach.
    if cfg!(windows)
        && let Some(st) = shell_var.and_then(|s| s.parse().ok())
    {
        return Some(st);
    }
    fallback.parse().ok()
}
#[cfg(unix)]
pub(crate) static SHELL_COMMAND_FLAG: &str = "-c";
#[cfg(windows)]
pub(crate) static SHELL_COMMAND_FLAG: &str = "/c";

// paths and directories
#[cfg(test)]
pub(crate) static HOME: Lazy<PathBuf> =
    Lazy::new(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test"));
#[cfg(not(test))]
pub(crate) static HOME: Lazy<PathBuf> = Lazy::new(|| {
    homedir::my_home()
        .ok()
        .flatten()
        .unwrap_or_else(|| PathBuf::from("/"))
});

pub(crate) 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 dotfiles 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(macos)]
pub(crate) static XDG_CACHE_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CACHE_HOME").unwrap_or_else(|| HOME.join("Library/Caches")));
#[cfg(windows)]
pub(crate) 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(macos)))]
pub(crate) static XDG_CACHE_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CACHE_HOME").unwrap_or_else(|| HOME.join(".cache")));
pub(crate) static XDG_CONFIG_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_CONFIG_HOME").unwrap_or_else(|| HOME.join(".config")));
#[cfg(unix)]
pub(crate) static XDG_DATA_HOME: Lazy<PathBuf> =
    Lazy::new(|| var_path("XDG_DATA_HOME").unwrap_or_else(|| HOME.join(".local").join("share")));
#[cfg(windows)]
pub(crate) 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(crate) 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(crate) 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(crate) static MISE_FRIENDLY_ERROR: Lazy<bool> = Lazy::new(|| {
    if var_is_true("MISE_FRIENDLY_ERROR") {
        true
    } else if var_is_false("MISE_FRIENDLY_ERROR") {
        false
    } else {
        // default behavior: friendly in release mode unless debug logging
        !cfg!(debug_assertions) && log::max_level() < log::LevelFilter::Debug
    }
});
pub(crate) static MISE_TOOL_STUB: Lazy<bool> =
    Lazy::new(|| ARGS.read().unwrap().get(1).map(|s| s.as_str()) == Some("tool-stub"));
pub(crate) static MISE_NO_CONFIG: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_CONFIG"));
pub(crate) static MISE_NO_ENV: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_ENV"));
pub(crate) static MISE_NO_HOOKS: Lazy<bool> = Lazy::new(|| var_is_true("MISE_NO_HOOKS"));
pub(crate) static MISE_PROGRESS_TRACE: Lazy<bool> =
    Lazy::new(|| var_is_true("MISE_PROGRESS_TRACE"));
pub(crate) static MISE_CACHE_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_CACHE_DIR").unwrap_or_else(|| XDG_CACHE_HOME.join("mise")));
pub(crate) 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(crate) 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(crate) static MISE_CONFIG_DIR_OVERRIDDEN: Lazy<bool> = Lazy::new(|| {
    var_path("MISE_CONFIG_DIR").is_some() && *MISE_CONFIG_DIR != *MISE_DEFAULT_CONFIG_DIR
});
pub(crate) static MISE_DATA_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_DATA_DIR").unwrap_or_else(|| XDG_DATA_HOME.join("mise")));
pub(crate) static MISE_STATE_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_STATE_DIR").unwrap_or_else(|| XDG_STATE_HOME.join("mise")));
pub(crate) static MISE_TMP_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_TMP_DIR").unwrap_or_else(|| temp_dir().join("mise")));
pub(crate) 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"))
});

// data subdirs
pub(crate) static MISE_INSTALLS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_INSTALLS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("installs")));
pub(crate) static MISE_DOWNLOADS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_DOWNLOADS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("downloads")));
pub(crate) static MISE_PLUGINS_DIR: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_PLUGINS_DIR").unwrap_or_else(|| MISE_DATA_DIR.join("plugins")));
pub(crate) 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(crate) static MISE_SYSTEM_DATA_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("MISE_SYSTEM_DATA_DIR").unwrap_or_else(|| PathBuf::from("/usr/local/share/mise"))
});
/// System-level installs directory, derived from MISE_SYSTEM_DATA_DIR.
pub(crate) static MISE_SYSTEM_INSTALLS_DIR: Lazy<PathBuf> =
    Lazy::new(|| 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.
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()
});

/// 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(crate) fn shared_install_dirs() -> Vec<PathBuf> {
    use crate::config::Settings;
    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 = &*MISE_SYSTEM_INSTALLS_DIR;
    // 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.clone());
    }
    result.extend(user_dirs);
    result
}

/// Early-boot variant used by install_state::init_tools() before Settings is loaded.
pub(crate) 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
}

/// Categorize an install path as system, shared, or local.
pub(crate) fn install_path_category(path: &Path) -> InstallPathCategory {
    if path.starts_with(&*MISE_SYSTEM_INSTALLS_DIR) {
        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(crate) 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(crate) 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(crate) static MISE_DEFAULT_TOOL_VERSIONS_FILENAME: Lazy<String> = Lazy::new(|| {
    var("MISE_DEFAULT_TOOL_VERSIONS_FILENAME")
        .ok()
        .or(MISE_OVERRIDE_TOOL_VERSIONS_FILENAMES
            .as_ref()
            .and_then(|v| v.first().cloned()))
        .or(var("MISE_DEFAULT_TOOL_VERSIONS_FILENAME").ok())
        .unwrap_or_else(|| ".tool-versions".into())
});
pub(crate) static MISE_DEFAULT_CONFIG_FILENAME: Lazy<String> = Lazy::new(|| {
    var("MISE_DEFAULT_CONFIG_FILENAME")
        .ok()
        .or(MISE_OVERRIDE_CONFIG_FILENAMES.first().cloned())
        .unwrap_or_else(|| "mise.toml".into())
});
pub(crate) static MISE_OVERRIDE_TOOL_VERSIONS_FILENAMES: Lazy<Option<IndexSet<String>>> =
    Lazy::new(|| match var("MISE_OVERRIDE_TOOL_VERSIONS_FILENAMES") {
        Ok(v) if v == "none" => Some([].into()),
        Ok(v) => Some(split_colon_list(&v)),
        Err(_) => {
            miserc::get_override_tool_versions_filenames().map(|v| v.iter().cloned().collect())
        }
    });
pub(crate) static MISE_OVERRIDE_CONFIG_FILENAMES: Lazy<IndexSet<String>> =
    Lazy::new(|| match var("MISE_OVERRIDE_CONFIG_FILENAMES") {
        Ok(v) => split_colon_list(&v),
        Err(_) => miserc::get_override_config_filenames()
            .map(|v| v.iter().cloned().collect())
            .unwrap_or_default(),
    });
pub(crate) static MISE_ENV: Lazy<Vec<String>> = Lazy::new(|| environment(&ARGS.read().unwrap()));

/// The tri-state auto_env setting: MISE_AUTO_ENV env var > .miserc.toml > unset
pub(crate) fn auto_env_setting() -> Option<bool> {
    if var_is_true("MISE_AUTO_ENV") {
        Some(true)
    } else if var_is_false("MISE_AUTO_ENV") {
        Some(false)
    } else {
        miserc::get_auto_env()
    }
}

/// The tri-state env_conf_d setting: MISE_ENV_CONF_D env var > .miserc.toml > unset.
pub(crate) fn env_conf_d_setting() -> Option<bool> {
    if var_is_true("MISE_ENV_CONF_D") {
        Some(true)
    } else if var_is_false("MISE_ENV_CONF_D") {
        Some(false)
    } else {
        miserc::get_env_conf_d()
    }
}

/// Keep dotted conf.d fragments unconditional through the deprecation window.
pub(crate) fn env_conf_d_default_for_version(v: &versions::Versioning) -> bool {
    *v >= versions::Versioning::new("2027.8.10").unwrap()
}

/// Whether `conf.d` filenames carry environment suffixes, resolving the
/// setting against the version-gated default.
pub(crate) fn env_conf_d() -> bool {
    env_conf_d_setting().unwrap_or_else(|| env_conf_d_default_for_version(&crate::cli::version::V))
}

/// Default for auto_env when the setting is unset: off until mise 2027.6.0
pub(crate) fn auto_env_default_for_version(v: &versions::Versioning) -> bool {
    *v >= versions::Versioning::new("2027.6.0").unwrap()
}

/// Platform-derived environment names, regardless of whether auto_env is enabled.
/// Ordered least to most specific: os family ("unix"), os, "{os}-{arch}".
/// On Windows the family equals the os so it dedupes to ["windows", "windows-{arch}"].
pub(crate) fn platform_env_names() -> Vec<String> {
    let mut names: Vec<String> = vec![];
    for name in [
        consts::FAMILY.to_string(),
        crate::cli::version::OS.to_string(),
        format!(
            "{}-{}",
            *crate::cli::version::OS,
            *crate::cli::version::ARCH
        ),
    ] {
        if !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// Platform environments active for config file discovery and lockfile selection.
/// Empty unless auto_env is enabled. Names already in MISE_ENV are excluded so
/// explicit environments keep their user-specified (higher) precedence.
/// These are deliberately not part of MISE_ENV: they do not affect the
/// `{{ mise_env }}` template variable or MISE_ENV propagation to subprocesses.
pub(crate) static AUTO_ENV_NAMES: Lazy<Vec<String>> = Lazy::new(|| {
    let enabled =
        auto_env_setting().unwrap_or_else(|| auto_env_default_for_version(&crate::cli::version::V));
    if !enabled {
        return vec![];
    }
    platform_env_names()
        .into_iter()
        .filter(|name| !MISE_ENV.contains(name))
        .collect()
});

/// Auto platform envs followed by explicit MISE_ENV entries, for "later wins"
/// consumers like config filename enumeration.
pub(crate) static MISE_ENV_WITH_AUTO: Lazy<Vec<String>> = Lazy::new(|| {
    AUTO_ENV_NAMES
        .iter()
        .chain(MISE_ENV.iter())
        .cloned()
        .collect()
});

pub(crate) static MISE_GLOBAL_CONFIG_FILE: Lazy<Option<PathBuf>> =
    Lazy::new(|| var_path("MISE_GLOBAL_CONFIG_FILE").or_else(|| var_path("MISE_CONFIG_FILE")));
pub(crate) static MISE_GLOBAL_CONFIG_ROOT: Lazy<PathBuf> =
    Lazy::new(|| var_path("MISE_GLOBAL_CONFIG_ROOT").unwrap_or_else(|| HOME.to_path_buf()));
pub(crate) static MISE_SYSTEM_CONFIG_FILE: Lazy<Option<PathBuf>> =
    Lazy::new(|| var_path("MISE_SYSTEM_CONFIG_FILE"));
pub(crate) static MISE_IGNORED_CONFIG_PATHS: Lazy<Vec<PathBuf>> = Lazy::new(|| {
    let invocation_cwd = miserc::invocation_cwd()
        .map(Path::to_path_buf)
        .or_else(|| current_dir().ok())
        .unwrap_or_default();
    var_os("MISE_IGNORED_CONFIG_PATHS")
        .map(|v| {
            split_paths(&v)
                .filter(|p| !p.as_os_str().is_empty())
                .map(|p| miserc::resolve_ignored_config_path(p, &invocation_cwd))
                .collect()
        })
        .or_else(|| miserc::get_ignored_config_paths().map(|paths| paths.iter().cloned().collect()))
        .unwrap_or_default()
});
pub(crate) static MISE_CEILING_PATHS: Lazy<HashSet<PathBuf>> = Lazy::new(|| {
    var_os("MISE_CEILING_PATHS")
        .map(|v| {
            split_paths(&v)
                .filter(|p| !p.as_os_str().is_empty())
                .map(replace_path)
                .collect()
        })
        .or_else(|| {
            miserc::get_ceiling_paths()
                .map(|paths| paths.iter().cloned().map(replace_path).collect())
        })
        .unwrap_or_default()
});
pub(crate) static MISE_USE_TOML: Lazy<bool> = Lazy::new(|| !var_is_false("MISE_USE_TOML"));
pub(crate) static MISE_LIST_ALL_VERSIONS: Lazy<bool> =
    Lazy::new(|| var_is_true("MISE_LIST_ALL_VERSIONS"));
pub(crate) static ARGV0: Lazy<String> = Lazy::new(|| ARGS.read().unwrap()[0].to_string());
pub(crate) static MISE_BIN_NAME: Lazy<&str> = Lazy::new(|| filename(&ARGV0));
pub(crate) static MISE_LOG_FILE: Lazy<Option<PathBuf>> = Lazy::new(|| var_path("MISE_LOG_FILE"));
pub(crate) static MISE_LOG_FILE_LEVEL: Lazy<Option<LevelFilter>> = Lazy::new(log_file_level);
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
}

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(crate) 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"],
        ],
    )
});
#[cfg(feature = "self_update")]
pub(crate) static MISE_SELF_UPDATE_AVAILABLE: Lazy<Option<bool>> = Lazy::new(|| {
    if var_is_true("MISE_SELF_UPDATE_AVAILABLE") {
        Some(true)
    } else if var_is_false("MISE_SELF_UPDATE_AVAILABLE") {
        Some(false)
    } else {
        None
    }
});
#[cfg(feature = "self_update")]
pub(crate) static MISE_SELF_UPDATE_DISABLED_PATH: Lazy<Option<PathBuf>> = Lazy::new(|| {
    let base = mise_install_base()?;
    find_in_tree(
        &base,
        &[
            &["lib", ".disable-self-update"],
            &["lib", "mise", ".disable-self-update"],
            &["lib64", "mise", ".disable-self-update"],
        ],
    )
});
pub(crate) static MISE_LOG_HTTP: Lazy<bool> = Lazy::new(|| var_is_true("MISE_LOG_HTTP"));
pub(crate) static MISE_LOG_VERBOSE_DEPS: Lazy<bool> =
    Lazy::new(|| var_is_true("MISE_LOG_VERBOSE_DEPS"));

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

// true if running inside a shim
pub(crate) 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(crate) const MISE_SHIM_PATH_ENV: &str = "__MISE_SHIM_PATH";
pub(crate) static MISE_SHIM_PATH: Lazy<RwLock<Option<PathBuf>>> =
    Lazy::new(|| RwLock::new(var_path(MISE_SHIM_PATH_ENV)));

// true if the current process is running as a shim (not direct mise invocation)
pub(crate) 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 cfg!(test) {
        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 [`crate::shims::handle_shim`] against itself. On unix
/// they are two different files, so a shim genuinely named `MISE` has to stay a shim.
pub(crate) 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
/// [`crate::path::windows_path_list_to_unix`], so they stay unit-tested everywhere rather than only
/// on the platform that runs them. Their callers are all `#[cfg(windows)]`, hence the allow.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) 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.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) 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`.
#[cfg_attr(not(windows), allow(dead_code))]
pub(crate) 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.
#[cfg_attr(not(windows), allow(dead_code))]
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(crate) 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.
///
/// Gated to `None` under `#[cfg(test)]` (like `TERM_WIDTH`) so unit tests that
/// build a table don't pick up a stray `COLUMNS`/`MISE_TERM_WIDTH` from the env.
#[cfg(test)]
pub(crate) static TERM_WIDTH_OVERRIDE: Lazy<Option<usize>> = Lazy::new(|| None);

#[cfg(not(test))]
pub(crate) static TERM_WIDTH_OVERRIDE: Lazy<Option<usize>> = Lazy::new(|| {
    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
});

#[cfg(test)]
pub(crate) static TERM_WIDTH: Lazy<usize> = Lazy::new(|| 80);

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

/// true if inside a script like bin/exec-env or bin/install
/// used to prevent infinite loops
pub(crate) static MISE_BIN: Lazy<PathBuf> = Lazy::new(|| {
    var_path("__MISE_BIN")
        .or_else(|| current_exe().ok())
        .unwrap_or_else(|| "mise".into())
});
pub(crate) static MISE_TIMINGS: Lazy<u8> = Lazy::new(|| var_u8("MISE_TIMINGS"));
pub(crate) static MISE_PID: Lazy<String> = Lazy::new(|| process::id().to_string());
pub(crate) static MISE_JOBS: Lazy<Option<usize>> =
    Lazy::new(|| var("MISE_JOBS").ok().and_then(|v| v.parse::<usize>().ok()));
pub(crate) static __MISE_SCRIPT: Lazy<bool> = Lazy::new(|| var_is_true("__MISE_SCRIPT"));
pub(crate) static __MISE_DIFF: Lazy<EnvDiff> = Lazy::new(get_env_diff);
pub(crate) static __MISE_ORIG_PATH: Lazy<Option<String>> =
    Lazy::new(|| var("__MISE_ORIG_PATH").ok());
pub(crate) static __MISE_ZSH_PRECMD_RUN: Lazy<bool> =
    Lazy::new(|| !var_is_false("__MISE_ZSH_PRECMD_RUN"));
pub(crate) static LINUX_DISTRO: Lazy<Option<String>> = Lazy::new(linux_distro);
pub(crate) 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(crate) static REMOTE_FETCH_COMMAND: Lazy<AtomicBool> =
    Lazy::new(|| remote_fetch_command(&ARGS.read().unwrap()).into());
pub(crate) static OFFLINE: Lazy<bool> = Lazy::new(|| offline(&ARGS.read().unwrap()));
pub(crate) static WARN_ON_MISSING_REQUIRED_ENV: Lazy<bool> =
    Lazy::new(|| warn_on_missing_required_env(&ARGS.read().unwrap()));
/// essentially, this is whether we show spinners or build output on runtime install
pub(crate) static PRISTINE_ENV: Lazy<EnvMap> =
    Lazy::new(|| get_pristine_env(&__MISE_DIFF, vars_safe().collect()));
pub(crate) 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(crate) 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(crate) fn normalize_path_key(key: String) -> String {
    if is_path_key(&key) {
        PATH_KEY.to_string()
    } else {
        key
    }
}
pub(crate) static PATH: Lazy<Vec<PathBuf>> = Lazy::new(|| match PRISTINE_ENV.get(&*PATH_KEY) {
    Some(path) => split_paths(path).collect(),
    None => vec![],
});
pub(crate) static PATH_NON_PRISTINE: Lazy<Vec<PathBuf>> = Lazy::new(|| match var(&*PATH_KEY) {
    Ok(ref path) => split_paths(path).collect(),
    Err(_) => vec![],
});
pub(crate) 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
/// [`crate::github::resolve_token_for_api_url`] (which walks env vars,
/// `credential_command`, `github_tokens.toml`, gh CLI, and git credentials) or the
/// [`crate::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(crate) static GITHUB_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITHUB_TOKEN", "GITHUB_API_TOKEN", "GITHUB_TOKEN"]));
pub(crate) static MISE_GITHUB_ENTERPRISE_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITHUB_ENTERPRISE_TOKEN"]));
pub(crate) static GITLAB_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITLAB_TOKEN", "GITLAB_TOKEN"]));
pub(crate) static MISE_GITLAB_ENTERPRISE_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_GITLAB_ENTERPRISE_TOKEN"]));
pub(crate) static MISE_FORGEJO_ENTERPRISE_TOKEN: Lazy<Option<String>> =
    Lazy::new(|| get_token(&["MISE_FORGEJO_ENTERPRISE_TOKEN"]));

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

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

pub(crate) 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(crate) 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(crate) static MISE_FORCE_PROGRESS: Lazy<bool> =
    Lazy::new(|| var_is_true("MISE_FORCE_PROGRESS"));

// python
pub(crate) static PYENV_ROOT: Lazy<PathBuf> =
    Lazy::new(|| var_path("PYENV_ROOT").unwrap_or_else(|| HOME.join(".pyenv")));
pub(crate) static UV_PYTHON_INSTALL_DIR: Lazy<PathBuf> = Lazy::new(|| {
    var_path("UV_PYTHON_INSTALL_DIR").unwrap_or_else(|| XDG_DATA_HOME.join("uv").join("python"))
});

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(),
    }
}

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

pub(crate) fn var_is_true(key: &str) -> bool {
    match var(key) {
        Ok(v) => {
            let v = v.to_lowercase();
            v == "y" || v == "yes" || v == "true" || v == "1" || v == "on"
        }
        Err(_) => false,
    }
}

fn var_is_false(key: &str) -> bool {
    match var(key) {
        Ok(v) => {
            let v = v.to_lowercase();
            v == "n" || v == "no" || v == "false" || v == "0" || v == "off"
        }
        Err(_) => false,
    }
}

pub(crate) 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(crate) fn var_path(key: &str) -> Option<PathBuf> {
    var_os(key)
        .map(PathBuf::from)
        .map(replace_path)
        .filter(|p| !p.as_os_str().is_empty())
}

/// 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 mut env = reverse_diff_preserving_overrides(mise_diff, orig_env);

    // get the current path as a vector
    let path = 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)
    let path = path
        .into_iter()
        .filter(|p| !to_remove.remove(p))
        .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(),
    );
    env
}

/// 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) == Some(new_value) => {
                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) == Some(new_value)
            && 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
    }
}

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 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. See
/// [`REMOTE_FETCH_COMMAND`].
const REMOTE_FETCH_COMMANDS: &[&str] = &[
    "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::cli::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)
}

/// 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 environment(args: &[String]) -> Vec<String> {
    let arg_defs = HashSet::from(["--profile", "-P", "--env", "-E"]);

    // Get environment value from args or env vars
    // Precedence: CLI args > env vars > .miserc.toml
    let from_args = if *IS_RUNNING_AS_SHIM {
        // When running as shim, ignore command line args and use env vars only
        vec![]
    } else {
        // Subcommands where positional args accept hyphen values, so -E after the
        // first positional would be a task arg, not a global flag.
        let run_subcommands: HashSet<&str> = HashSet::from(["run", "r"]);
        // Try to get from command line args first
        // Handles `--env production`, `--env=production`, `-E production`, `-E=production`,
        // and `-Eproduction`.
        let mut values = Vec::new();
        let mut it = args.iter().take_while(|a| a.as_str() != "--");
        let mut in_run_subcommand = false;
        while let Some(arg) = it.next() {
            if arg.starts_with('-') {
                if arg_defs.contains(arg.as_str()) {
                    // Case: `-E production` or `--env production`
                    if let Some(next) = it.next() {
                        values.push(next.to_string());
                    }
                } else if let Some((prefix, rest)) = arg.split_at_checked(2)
                    && !rest.starts_with('=')
                    && arg_defs.contains(prefix)
                {
                    // Case: `-Eproduction`
                    values.push(rest.to_string());
                } else if let Some((flag, value)) = arg.split_once('=') {
                    // Case: `-E=production` or `--env=production`
                    if arg_defs.contains(flag) {
                        values.push(value.to_string());
                    }
                }
            } else {
                // After `run`/`r`, the first positional is the task name — everything
                // after that belongs to the task, so stop scanning for env flags.
                if in_run_subcommand {
                    break;
                }
                if run_subcommands.contains(arg.as_str()) {
                    in_run_subcommand = true;
                }
            }
        }
        values
            .into_iter()
            .flat_map(|s| {
                s.split(',')
                    .filter(|s| !s.is_empty())
                    .map(String::from)
                    .collect::<Vec<_>>()
            })
            .collect()
    };
    if !from_args.is_empty() {
        return from_args;
    }
    var("MISE_ENV")
        .ok()
        .or_else(|| var("MISE_PROFILE").ok())
        .or_else(|| var("MISE_ENVIRONMENT").ok())
        .map(|s| {
            s.split(',')
                .filter(|s| !s.is_empty())
                .map(String::from)
                .collect()
        })
        .or_else(|| miserc::get_env().cloned())
        .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()
}

fn linux_distro() -> Option<String> {
    crate::platform::linux_os_release().map(|release| release.id.clone())
}

/// Split a colon-separated string into a set, filtering empty segments.
/// Empty segments arise from empty strings, leading/trailing colons, or
/// consecutive colons — all of which should be ignored rather than
/// injected as empty paths into config discovery.
fn split_colon_list(value: &str) -> IndexSet<String> {
    value
        .split(':')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}

/// 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(crate) fn is_activated() -> bool {
    var("__MISE_DIFF").is_ok()
}

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

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

/// Remove the env cache encryption key to force fresh env computation
pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn args_safe() -> Vec<String> {
    apply_launcher_args(args_os().map(|a| a.to_string_lossy().to_string()).collect())
}

pub(crate) fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<()> {
    let path = path.as_ref();
    trace!("cd {}", display_path(path));
    std::env::set_current_dir(path)
        .wrap_err_with(|| format!("failed to set current directory to {}", display_path(path)))?;
    Ok(())
}

/// 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 {
    use pretty_assertions::assert_eq;

    use crate::config::Config;

    use super::*;

    #[test]
    fn test_reverse_diff_preserves_runtime_overrides() {
        let diff = EnvDiff {
            old: [
                ("CHANGED".into(), "before".into()),
                ("REMOVED".into(), "before".into()),
            ]
            .into(),
            new: [
                ("ADDED".into(), "managed".into()),
                ("CHANGED".into(), "managed".into()),
            ]
            .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_restores_unchanged_managed_values() {
        let diff = EnvDiff {
            old: [
                ("CHANGED".into(), "before".into()),
                ("REMOVED".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()),
                ("REMOVED".into(), "before".into()),
            ]
            .into()
        );
    }

    #[test]
    fn test_reverse_diff_preserves_runtime_removals() {
        let diff = EnvDiff {
            old: [("CHANGED".into(), "before".into())].into(),
            new: [
                ("ADDED".into(), "managed".into()),
                ("CHANGED".into(), "managed".into()),
            ]
            .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 {
            old: [
                ("Changed".into(), "before".into()),
                ("MÎSE_FOO".into(), "before-unicode".into()),
            ]
            .into(),
            new: [
                ("Added".into(), "managed".into()),
                ("Changed".into(), "managed".into()),
                ("MÎSE_FOO".into(), "managed-unicode".into()),
            ]
            .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()
        );
    }

    #[tokio::test]
    async fn test_var_path() {
        let _config = Config::get().await.unwrap();
        set_var("MISE_TEST_PATH", "/foo/bar");
        assert_eq!(
            var_path("MISE_TEST_PATH").unwrap(),
            PathBuf::from("/foo/bar")
        );
        remove_var("MISE_TEST_PATH");
    }

    /// An empty value is not a directory. Callers all join onto the result, so returning
    /// `Some("")` would hand them a relative path resolved against the cwd — e.g. an empty
    /// `XDG_CONFIG_HOME` turning `MISE_CONFIG_DIR` into the relative `mise`.
    #[tokio::test]
    async fn test_var_path_treats_empty_as_unset() {
        let _config = Config::get().await.unwrap();
        set_var("MISE_TEST_EMPTY_PATH", "");
        assert_eq!(var_path("MISE_TEST_EMPTY_PATH"), None);
        remove_var("MISE_TEST_EMPTY_PATH");
    }

    /// vars_safe() must skip pairs whose key or value is not valid UTF-8 rather
    /// than panicking the way std::env::vars() does (#5370).
    #[cfg(unix)]
    #[test]
    fn test_vars_safe_skips_invalid_utf8() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        // 0xff can never appear in valid UTF-8.
        let bad_value_key = "MISE_TEST_VARS_SAFE_BAD_VALUE";
        let bad_key = OsString::from_vec(b"MISE_TEST_VARS_SAFE_BAD_KEY_\xff".to_vec());
        let good_key = "MISE_TEST_VARS_SAFE_GOOD";

        // the guard restores the previous environment on drop, so even a failing
        // assertion below cannot leak a non-UTF-8 var into the test process
        let mut guard = crate::test::EnvVarGuard::new();
        guard
            .set(bad_value_key, OsString::from_vec(vec![0xff]))
            .set(&bad_key, "ok")
            .set(good_key, "1");

        // Both malformed vars really are in the process environment...
        assert!(vars_os().any(|(k, _)| k == bad_value_key));
        assert!(vars_os().any(|(k, _)| k == bad_key));
        // ...and vars_safe() returns without panicking.
        let safe: Vec<(String, String)> = vars_safe().collect();

        assert!(!safe.iter().any(|(k, _)| k == bad_value_key));
        assert!(
            !safe
                .iter()
                .any(|(k, _)| k.starts_with("MISE_TEST_VARS_SAFE_BAD_KEY_"))
        );
        // Valid neighbours are still returned.
        assert!(safe.iter().any(|(k, v)| k == good_key && v == "1"));
    }

    #[test]
    fn test_auto_env_default_for_version() {
        let v = |s: &str| versions::Versioning::new(s).unwrap();
        assert!(!auto_env_default_for_version(&v("2026.6.2")));
        assert!(!auto_env_default_for_version(&v("2026.12.0")));
        assert!(!auto_env_default_for_version(&v("2027.5.9")));
        assert!(auto_env_default_for_version(&v("2027.6.0")));
        assert!(auto_env_default_for_version(&v("2028.1.0")));
    }

    #[test]
    fn test_env_conf_d_default_for_version() {
        let v = |s: &str| versions::Versioning::new(s).unwrap();
        assert!(!env_conf_d_default_for_version(&v("2026.8.10")));
        assert!(!env_conf_d_default_for_version(&v("2027.8.9")));
        assert!(env_conf_d_default_for_version(&v("2027.8.10")));
    }

    #[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",
        ])));
    }

    #[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",
        ])));
    }

    #[cfg(unix)]
    #[test]
    fn test_platform_env_names_unix() {
        let names = platform_env_names();
        assert_eq!(names.len(), 3);
        assert_eq!(names[0], "unix");
        assert_eq!(names[1], *crate::cli::version::OS);
        assert_eq!(
            names[2],
            format!(
                "{}-{}",
                *crate::cli::version::OS,
                *crate::cli::version::ARCH
            )
        );
    }

    #[cfg(windows)]
    #[test]
    fn test_platform_env_names_windows() {
        // os family == os on windows, so the list dedupes to two entries
        let names = platform_env_names();
        assert_eq!(
            names,
            vec![
                "windows".to_string(),
                format!("windows-{}", *crate::cli::version::ARCH)
            ]
        );
    }

    #[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");
    }

    #[cfg(windows)]
    #[test]
    fn test_is_path_key_accepts_any_casing_on_windows() {
        for spelling in ["PATH", "Path", "path", "pAtH"] {
            assert!(is_path_key(spelling), "{spelling}");
            assert_eq!(normalize_path_key(spelling.to_string()), *PATH_KEY);
        }

        assert!(!is_path_key("PATHEXT"));
        assert!(!is_path_key("TEMP"));
        assert!(!is_path_key(""));
        // A name that is not PATH keeps the spelling the config gave it.
        assert_eq!(normalize_path_key("Temp".to_string()), "Temp");
    }

    #[cfg(unix)]
    #[test]
    fn test_is_path_key_is_exact_on_unix() {
        assert!(is_path_key("PATH"));
        assert_eq!(normalize_path_key("PATH".to_string()), "PATH");

        // `Path` is a variable of its own here, so folding it would drop what was asked for.
        assert!(!is_path_key("Path"));
        assert!(!is_path_key("path"));
        assert_eq!(normalize_path_key("Path".to_string()), "Path");

        assert!(!is_path_key("PATHEXT"));
        assert!(!is_path_key(""));
    }

    #[test]
    fn test_split_colon_list() {
        let cases: Vec<(&str, Vec<&str>)> = vec![
            ("", vec![]),    // empty string — was causing panic
            (":", vec![]),   // colon only
            (":::", vec![]), // multiple colons
            ("mise.toml", vec!["mise.toml"]),
            ("a:b", vec!["a", "b"]),
            (":a:b:", vec!["a", "b"]), // leading/trailing colons
            ("a::b", vec!["a", "b"]),  // consecutive colons
        ];
        for (input, expected) in cases {
            let result = split_colon_list(input);
            let expected: IndexSet<String> = expected.into_iter().map(|s| s.to_string()).collect();
            assert_eq!(result, expected, "input: {input:?}");
        }
    }

    #[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_is_mise_binary() {
        // The spellings mise is actually invoked under, on every platform.
        assert!(is_mise_binary("mise"));
        assert!(is_mise_binary("mise.exe"));
        assert!(is_mise_binary("mise.cmd"));
        assert!(is_mise_binary("mise-doctor"));
        // The controls. Real shim names must stay shims, or this stops being a test of anything:
        // a version that always returned true would pass every assertion above.
        assert!(!is_mise_binary("node"));
        assert!(!is_mise_binary("node.exe"));
        assert!(!is_mise_binary("misex"));
        assert!(!is_mise_binary("misex.exe"));
    }

    /// Windows resolves `MISE.EXE` to the same file as `mise.exe` and hands the process `argv[0]`
    /// with the casing the caller wrote, so the test has to ignore case there. See the pair below.
    #[cfg(windows)]
    #[test]
    fn test_is_mise_binary_ignores_case_on_windows() {
        assert!(is_mise_binary("MISE.EXE"));
        assert!(is_mise_binary("Mise.exe"));
        assert!(is_mise_binary("MISE"));
        assert!(is_mise_binary("MISE-DOCTOR"));
        // Case-insensitivity must not widen what counts as mise.
        assert!(!is_mise_binary("NODE.EXE"));
        assert!(!is_mise_binary("MISEX.EXE"));
    }

    /// The other half. On unix `MISE` is a different file from `mise`, so a shim by that name has
    /// to keep being treated as a shim; ignoring case here would make mise run itself instead.
    #[cfg(unix)]
    #[test]
    fn test_is_mise_binary_is_case_sensitive_on_unix() {
        assert!(!is_mise_binary("MISE"));
        assert!(!is_mise_binary("Mise"));
        assert!(!is_mise_binary("MISE-DOCTOR"));
    }

    fn detect(mise_shell: Option<&str>, shell_var: Option<&str>, fallback: &str) -> String {
        detect_shell(
            mise_shell.map(str::to_string),
            shell_var.map(str::to_string),
            fallback,
        )
        .map(|st| st.to_string())
        .unwrap_or_else(|| "(none)".to_string())
    }

    /// `mise activate` exports `MISE_SHELL`, so it decides on its own — including deciding that
    /// the answer is nothing. Falling back after an unparseable value would start guessing at a
    /// shell the session has already named.
    #[test]
    fn mise_shell_wins_and_an_unparseable_one_is_still_the_answer() {
        assert_eq!(detect(Some("zsh"), Some("/bin/bash"), "/bin/bash"), "zsh");
        assert_eq!(
            detect(Some("nonsense"), Some("/bin/bash"), "/bin/bash"),
            "(none)"
        );
    }

    /// The fix: Git Bash, MSYS2 and Cygwin set `SHELL` on Windows, where the fallback reads
    /// `COMSPEC` and so can never see it.
    #[cfg(windows)]
    #[test]
    fn shell_is_consulted_on_windows() {
        for shell_var in [
            r"C:\Program Files\Git\bin\bash.exe",
            "/bin/bash.exe",
            r"C:\msys64\usr\bin\zsh.exe",
        ] {
            let expected = match shell_var.contains("zsh") {
                true => "zsh",
                false => "bash",
            };
            assert_eq!(
                detect(None, Some(shell_var), r"C:\WINDOWS\system32\cmd.exe"),
                expected,
                "{shell_var}"
            );
        }
        // Unchanged where there is nothing to find: cmd.exe is not a shell mise generates for.
        assert_eq!(detect(None, None, r"C:\WINDOWS\system32\cmd.exe"), "(none)");
    }

    /// The control. On unix `SHELL` *is* the fallback, so the extra lookup must not exist —
    /// otherwise this test would pass for the wrong reason on every platform.
    #[cfg(unix)]
    #[test]
    fn the_fallback_is_the_only_second_source_on_unix() {
        // A `SHELL` that disagrees with the fallback is ignored: unix passes the same value as
        // both, so anything else would mean the Windows branch had leaked.
        assert_eq!(detect(None, Some("/bin/zsh"), "/bin/bash"), "bash");
        assert_eq!(detect(None, None, "/bin/zsh"), "zsh");
        assert_eq!(detect(None, None, "sh"), "bash");
    }

    /// The names `self-replace` generates, which mise used to report as broken shims. Measured with
    /// `TEMP` at 199 and 201 characters, where the copy's own init hook stops recognising itself.
    #[test]
    fn a_self_replace_copy_of_this_binary_is_recognised() {
        let rand = "qzcdgqhxhqwhzdwyqchsmdxcqouxxche";
        assert!(is_self_replace_helper(
            &format!(".mise.{rand}.__selfdelete__.exe"),
            "mise"
        ));
        assert!(is_self_replace_helper(
            &format!(".mise.{rand}.__relocated__.exe"),
            "mise"
        ));
        // The stem follows the binary, so a renamed mise is still recognised.
        assert!(is_self_replace_helper(
            &format!(".mise-dev.{rand}.__selfdelete__.exe"),
            "mise-dev"
        ));
    }

    /// The controls. Two of them are the reason the stem is a parameter at all.
    #[test]
    fn ordinary_names_and_other_applications_are_not() {
        let rand = "qzcdgqhxhqwhzdwyqchsmdxcqouxxche";
        // mise itself, and a genuine shim.
        assert!(!is_self_replace_helper("mise.exe", "mise"));
        assert!(!is_self_replace_helper("node.exe", "mise"));
        // Another application's orphan, sitting in the same TEMP. Matching the suffix alone would
        // claim it — and the sweep would delete it.
        assert!(!is_self_replace_helper(
            &format!(".node.{rand}.__selfdelete__.exe"),
            "mise"
        ));
        // Ours by name, but not one of these copies.
        assert!(!is_self_replace_helper(".mise.something.exe", "mise"));
    }

    /// The segment between the stem and the suffix has to be the one `self-replace` generates —
    /// 32 characters from `fastrand`'s `lowercase()`. The caller acting on a `true` here **deletes
    /// the file**, so a name that merely looks similar must not qualify.
    #[test]
    fn a_name_that_only_resembles_a_generated_one_is_left_alone() {
        let ok = "qzcdgqhxhqwhzdwyqchsmdxcqouxxche";
        assert_eq!(ok.len(), SELF_REPLACE_RANDOM_LEN, "premise");
        assert!(is_self_replace_helper(
            &format!(".mise.{ok}.__selfdelete__.exe"),
            "mise"
        ));

        // No segment at all.
        assert!(!is_self_replace_helper(".mise..__selfdelete__.exe", "mise"));
        assert!(!is_self_replace_helper(".mise.__selfdelete__.exe", "mise"));
        // Too short, and too long.
        assert!(!is_self_replace_helper(
            ".mise.abc.__selfdelete__.exe",
            "mise"
        ));
        assert!(!is_self_replace_helper(
            &format!(".mise.{ok}x.__selfdelete__.exe"),
            "mise"
        ));
        // Right length, wrong alphabet — a digit and an uppercase letter.
        let digits = format!("{}1", &ok[..SELF_REPLACE_RANDOM_LEN - 1]);
        assert!(!is_self_replace_helper(
            &format!(".mise.{digits}.__selfdelete__.exe"),
            "mise"
        ));
        let upper = format!("{}A", &ok[..SELF_REPLACE_RANDOM_LEN - 1]);
        assert!(!is_self_replace_helper(
            &format!(".mise.{upper}.__selfdelete__.exe"),
            "mise"
        ));
    }

    /// The stem carries whatever casing the caller used to start mise — measured: `current_exe()`
    /// returns `CASEPROBE` for a `caseprobe.exe` started as `CASEPROBE.EXE`. So an update launched
    /// one way writes an orphan the next one, launched the other way, has to still recognise.
    #[cfg(windows)]
    #[test]
    fn an_orphan_from_a_differently_cased_launch_is_still_ours() {
        let rand = "qzcdgqhxhqwhzdwyqchsmdxcqouxxche";
        for stem in ["mise", "MISE", "Mise"] {
            for written in ["mise", "MISE", "Mise"] {
                assert!(
                    is_self_replace_helper(&format!(".{written}.{rand}.__selfdelete__.exe"), stem),
                    "stem {stem} should claim an orphan written as {written}"
                );
            }
        }
        // Still not another application's, however it is cased.
        assert!(!is_self_replace_helper(
            &format!(".NODE.{rand}.__selfdelete__.exe"),
            "mise"
        ));
    }

    /// The control for the rule above: unix filesystems are case-sensitive, so `MISE` and `mise`
    /// are different files and an orphan of one is not an orphan of the other.
    #[cfg(unix)]
    #[test]
    fn casing_still_separates_names_on_unix() {
        let rand = "qzcdgqhxhqwhzdwyqchsmdxcqouxxche";
        assert!(is_self_replace_helper(
            &format!(".mise.{rand}.__selfdelete__.exe"),
            "mise"
        ));
        assert!(!is_self_replace_helper(
            &format!(".MISE.{rand}.__selfdelete__.exe"),
            "mise"
        ));
    }
}