mise 2026.7.18

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
use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::config::Settings;
use crate::http::HTTP;
use crate::toolset::{RawBackendOptions, ToolVersionOptions};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{dirs, file};
use eyre::{Context, Result, bail, ensure};
use heck::ToShoutySnakeCase;
use indexmap::IndexMap;
use serde::Serialize as _;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::env;
use std::env::consts::OS;
use std::fmt::Display;
use std::fs::File;
use std::io::Read;
use std::iter::Iterator;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock as Lazy, Mutex};
use std::time::Duration;
use strum::IntoEnumIterator;
use url::Url;

// the registry is generated from registry/ in the project root
static BAKED_REGISTRY: Registry = include!(concat!(env!("OUT_DIR"), "/registry.rs"));

pub(crate) fn baked_registry() -> &'static Registry {
    &BAKED_REGISTRY
}

pub static REGISTRY: Lazy<&'static Registry> = Lazy::new(|| {
    if !Settings::get().registry_floating {
        return &BAKED_REGISTRY;
    }

    if !registry_cache_path().exists() {
        return &BAKED_REGISTRY;
    }

    match load_cached_floating_registry() {
        Ok(registry) => Box::leak(Box::new(registry)),
        Err(err) => {
            warn!("failed to load floating mise registry, using baked-in registry: {err:#}");
            &BAKED_REGISTRY
        }
    }
});

const MISE_REGISTRY_ARCHIVE_URL: &str = "https://mise.jdx.dev/registry/latest.tar.zst";
const MAX_REGISTRY_ARCHIVE_ENTRIES: usize = 4096;
const MAX_REGISTRY_ARCHIVE_ENTRY_SIZE: u64 = 1024 * 1024;
const MAX_REGISTRY_ARCHIVE_SIZE: u64 = 16 * 1024 * 1024;

pub struct Registry {
    entries: &'static [(&'static str, RegistryTool)],
    lookup: RegistryLookup,
}

enum RegistryLookup {
    Static(phf::Map<&'static str, usize>),
    Dynamic(HashMap<&'static str, usize>),
}

impl Registry {
    pub fn get(&self, name: &str) -> Option<&'static RegistryTool> {
        self.lookup.get(name).map(|index| &self.entries[*index].1)
    }

    pub fn contains_key(&self, name: &str) -> bool {
        self.lookup.get(name).is_some()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&'static str, &'static RegistryTool)> {
        self.entries.iter().map(|(name, tool)| (*name, tool))
    }

    pub fn keys(&self) -> impl Iterator<Item = &'static str> {
        self.entries.iter().map(|(name, _)| *name)
    }

    pub fn values(&self) -> impl Iterator<Item = &'static RegistryTool> {
        self.entries.iter().map(|(_, tool)| tool)
    }

    fn dynamic(entries: BTreeMap<String, RegistryTool>) -> Self {
        let entries = entries
            .into_iter()
            .map(|(name, tool)| (leak_string(name), tool))
            .collect::<Vec<_>>();
        let entries = leak_vec(entries);
        let lookup = entries
            .iter()
            .enumerate()
            .map(|(index, (name, _))| (*name, index))
            .collect();
        Self {
            entries,
            lookup: RegistryLookup::Dynamic(lookup),
        }
    }
}

impl RegistryLookup {
    fn get(&self, name: &str) -> Option<&usize> {
        match self {
            Self::Static(lookup) => lookup.get(name),
            Self::Dynamic(lookup) => lookup.get(name),
        }
    }
}

#[derive(Debug, Clone)]
pub struct RegistryTool {
    pub short: &'static str,
    pub description: Option<&'static str>,
    pub backends: &'static [RegistryBackend],
    #[allow(unused)]
    pub aliases: &'static [&'static str],
    pub overrides: &'static [&'static str],
    pub test: &'static Option<RegistryToolTest>,
    pub os: &'static [&'static str],
    pub idiomatic_files: &'static [RegistryIdiomaticFile],
    pub detect: &'static [&'static str],
}

#[derive(Debug, Clone)]
pub struct RegistryIdiomaticFile {
    pub path: &'static str,
    pub version_regex: Option<&'static str>,
    pub version_json_path: Option<&'static str>,
    pub version_expr: Option<&'static str>,
}

impl RegistryIdiomaticFile {
    pub fn has_parser(&self) -> bool {
        self.version_regex.is_some()
            || self.version_json_path.is_some()
            || self.version_expr.is_some()
    }
}

#[derive(Debug, Clone)]
pub struct RegistryToolTest {
    pub cmd: &'static str,
    pub expected: &'static str,
    pub tools: &'static [&'static str],
}

#[derive(Debug, Clone)]
pub struct RegistryBackend {
    pub full: &'static str,
    pub platforms: &'static [&'static str],
    pub options: &'static [(&'static str, &'static str)],
}

fn registry_cache_path() -> PathBuf {
    dirs::CACHE.join("mise-registry").join("registry.tar.zst")
}

fn load_cached_floating_registry() -> Result<Registry> {
    parse_registry_archive(&registry_cache_path())
        .wrap_err("failed to load cached floating mise registry")
}

fn cache_is_fresh(path: &Path, ttl: Duration) -> bool {
    path.metadata()
        .and_then(|metadata| metadata.modified())
        .and_then(|modified| modified.elapsed().map_err(std::io::Error::other))
        .is_ok_and(|age| age < ttl)
}

/// Refresh the floating mise registry before anything initializes [`REGISTRY`].
/// Fast and offline commands use the cached archive (or the baked registry) without networking.
pub async fn refresh() {
    let settings = Settings::get();
    if !settings.registry_floating || settings.prefer_offline() {
        return;
    }

    let cache_path = registry_cache_path();
    if cache_is_fresh(&cache_path, settings.registry_cache_ttl()) {
        if parse_registry_archive(&cache_path).is_ok() {
            return;
        }
        warn!("cached floating mise registry is invalid; refreshing it");
    }

    if let Err(err) = download_registry_archive(&cache_path).await {
        warn!("failed to refresh floating mise registry: {err:#}");
    }
}

async fn download_registry_archive(cache_path: &Path) -> Result<()> {
    let download_path = cache_path.with_extension(format!("download-{}", std::process::id()));
    let pr = MultiProgressReport::get().add_pre_backend("mise registry");
    if let Err(err) = HTTP
        .download_file(MISE_REGISTRY_ARCHIVE_URL, &download_path, Some(pr.as_ref()))
        .await
    {
        let _ = file::remove_file(&download_path);
        pr.abandon();
        return Err(err);
    }

    let result = (|| {
        parse_registry_archive(&download_path)
            .wrap_err("downloaded mise registry archive is invalid")?;
        replace_registry_cache(&download_path, cache_path)?;
        Ok(())
    })();
    match result {
        Ok(()) => {
            pr.finish();
            Ok(())
        }
        Err(err) => {
            let _ = file::remove_file(&download_path);
            pr.abandon();
            Err(err)
        }
    }
}

#[cfg(not(windows))]
fn replace_registry_cache(download_path: &Path, cache_path: &Path) -> Result<()> {
    file::rename(download_path, cache_path)
}

#[cfg(windows)]
fn replace_registry_cache(download_path: &Path, cache_path: &Path) -> Result<()> {
    let backup_path = cache_path.with_extension(format!("backup-{}", std::process::id()));
    let had_cache = cache_path.exists();
    if backup_path.exists() {
        file::remove_file(&backup_path)?;
    }
    if had_cache {
        file::rename(cache_path, &backup_path)?;
    }
    if let Err(install_err) = file::rename(download_path, cache_path) {
        if had_cache && let Err(restore_err) = file::rename(&backup_path, cache_path) {
            return Err(install_err).wrap_err(format!(
                "failed to install downloaded registry and restore cached registry: {restore_err:#}"
            ));
        }
        return Err(install_err).wrap_err("failed to install downloaded registry");
    }
    if had_cache {
        file::remove_file(&backup_path)?;
    }
    Ok(())
}

fn parse_registry_archive(path: &Path) -> Result<Registry> {
    let file = File::open(path)?;
    let decoder = zstd::Decoder::new(file)?;
    let mut archive = jdx_tar::Archive::new(decoder);
    let mut sources = BTreeMap::new();
    let mut archive_size = 0_u64;

    for (index, entry) in archive.entries()?.enumerate() {
        let mut entry = entry?;
        track_registry_archive_entry(index, entry.size(), &mut archive_size)?;
        if entry.entry_type() != jdx_tar::EntryType::File {
            continue;
        }
        let path = entry.path()?;
        let components = path
            .components()
            .map(|component| component.as_os_str())
            .collect::<Vec<_>>();
        if components.len() != 2 || components[0] != "registry" {
            continue;
        }
        let file_path = PathBuf::from(components[1]);
        if file_path
            .extension()
            .is_none_or(|extension| extension != "toml")
        {
            continue;
        }
        let short = file_path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .ok_or_else(|| eyre::eyre!("invalid registry filename: {}", path.display()))?
            .to_string();
        let mut source = String::new();
        entry.read_to_string(&mut source)?;
        sources.insert(short, source);
    }

    ensure!(
        !sources.is_empty(),
        "archive does not contain registry entries"
    );
    registry_from_sources(sources)
}

fn track_registry_archive_entry(
    index: usize,
    entry_size: u64,
    archive_size: &mut u64,
) -> Result<()> {
    ensure!(
        index < MAX_REGISTRY_ARCHIVE_ENTRIES,
        "registry archive contains too many entries"
    );
    ensure!(
        entry_size <= MAX_REGISTRY_ARCHIVE_ENTRY_SIZE,
        "registry archive entry is too large"
    );
    *archive_size = archive_size
        .checked_add(entry_size)
        .ok_or_else(|| eyre::eyre!("registry archive size overflow"))?;
    ensure!(
        *archive_size <= MAX_REGISTRY_ARCHIVE_SIZE,
        "registry archive is too large"
    );
    Ok(())
}

fn registry_from_sources(sources: BTreeMap<String, String>) -> Result<Registry> {
    let mut entries = BTreeMap::new();
    for (short, source) in sources {
        let value: toml::Value = toml::from_str(&source)
            .wrap_err_with(|| format!("failed to parse registry/{short}.toml"))?;
        let tool = parse_registry_tool(&short, &value)
            .wrap_err_with(|| format!("invalid registry/{short}.toml"))?;
        entries.insert(short, tool.clone());
        for alias in tool.aliases {
            entries.insert((*alias).to_string(), tool.clone());
        }
    }
    Ok(Registry::dynamic(entries))
}

fn parse_registry_tool(short: &str, value: &toml::Value) -> Result<RegistryTool> {
    let table = value
        .as_table()
        .ok_or_else(|| eyre::eyre!("registry tool must be a TOML table"))?;
    let backends = table
        .get("backends")
        .and_then(toml::Value::as_array)
        .ok_or_else(|| eyre::eyre!("backends must be an array"))?
        .iter()
        .map(parse_registry_backend)
        .collect::<Result<Vec<_>>>()?;
    ensure!(!backends.is_empty(), "backends must not be empty");

    let aliases = string_array(table.get("aliases"), "aliases")?;
    let overrides = string_array(table.get("overrides"), "overrides")?;
    let os = string_array(table.get("os"), "os")?;
    let idiomatic_files = parse_registry_idiomatic_files(table.get("idiomatic_files"))?;
    let detect = string_array(table.get("detect"), "detect")?;
    let description = table
        .get("description")
        .map(|value| {
            value
                .as_str()
                .map(|value| leak_string(value.to_string()))
                .ok_or_else(|| eyre::eyre!("description must be a string"))
        })
        .transpose()?;
    let test = table.get("test").map(parse_registry_test).transpose()?;

    Ok(RegistryTool {
        short: leak_string(short.to_string()),
        description,
        backends: leak_vec(backends),
        aliases: leak_vec(aliases),
        overrides: leak_vec(overrides),
        test: Box::leak(Box::new(test)),
        os: leak_vec(os),
        idiomatic_files: leak_vec(idiomatic_files),
        detect: leak_vec(detect),
    })
}

fn parse_registry_idiomatic_files(
    value: Option<&toml::Value>,
) -> Result<Vec<RegistryIdiomaticFile>> {
    value
        .map(|value| {
            value
                .as_array()
                .ok_or_else(|| eyre::eyre!("idiomatic_files must be an array"))?
                .iter()
                .map(parse_registry_idiomatic_file)
                .collect()
        })
        .transpose()
        .map(Option::unwrap_or_default)
}

fn parse_registry_idiomatic_file(value: &toml::Value) -> Result<RegistryIdiomaticFile> {
    match value {
        toml::Value::String(path) => Ok(RegistryIdiomaticFile {
            path: leak_string(path.clone()),
            version_regex: None,
            version_json_path: None,
            version_expr: None,
        }),
        toml::Value::Table(table) => {
            for key in table.keys() {
                ensure!(
                    matches!(
                        key.as_str(),
                        "path" | "version_regex" | "version_json_path" | "version_expr"
                    ),
                    "unknown idiomatic file field: {key}"
                );
            }
            let string = |key: &str| -> Result<Option<&'static str>> {
                table
                    .get(key)
                    .map(|value| {
                        value
                            .as_str()
                            .map(|value| leak_string(value.to_string()))
                            .ok_or_else(|| eyre::eyre!("idiomatic_files.{key} must be a string"))
                    })
                    .transpose()
            };
            let path = string("path")?
                .ok_or_else(|| eyre::eyre!("idiomatic_files.path must be a string"))?;
            Ok(RegistryIdiomaticFile {
                path,
                version_regex: string("version_regex")?,
                version_json_path: string("version_json_path")?,
                version_expr: string("version_expr")?,
            })
        }
        _ => Err(eyre::eyre!(
            "idiomatic_files entries must be strings or tables"
        )),
    }
}

fn parse_registry_backend(value: &toml::Value) -> Result<RegistryBackend> {
    match value {
        toml::Value::String(full) => Ok(RegistryBackend {
            full: leak_string(full.clone()),
            platforms: &[],
            options: &[],
        }),
        toml::Value::Table(table) => {
            let full = table
                .get("full")
                .and_then(toml::Value::as_str)
                .ok_or_else(|| eyre::eyre!("backend full must be a string"))?;
            let platforms = string_array(table.get("platforms"), "backend platforms")?;
            let options = table
                .get("options")
                .and_then(toml::Value::as_table)
                .map(|options| {
                    options
                        .iter()
                        .map(|(key, value)| {
                            let mut serialized = String::new();
                            value.serialize(toml::ser::ValueSerializer::new(&mut serialized))?;
                            Ok((leak_string(key.clone()), leak_string(serialized)))
                        })
                        .collect::<Result<Vec<_>>>()
                })
                .transpose()?
                .unwrap_or_default();
            Ok(RegistryBackend {
                full: leak_string(full.to_string()),
                platforms: leak_vec(platforms),
                options: leak_vec(options),
            })
        }
        _ => bail!("backend must be a string or table"),
    }
}

fn parse_registry_test(value: &toml::Value) -> Result<RegistryToolTest> {
    let table = value
        .as_table()
        .ok_or_else(|| eyre::eyre!("test must be a table"))?;
    let cmd = table
        .get("cmd")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| eyre::eyre!("test.cmd must be a string"))?;
    let expected = table
        .get("expected")
        .and_then(toml::Value::as_str)
        .ok_or_else(|| eyre::eyre!("test.expected must be a string"))?;
    let tools = string_array(table.get("tools"), "test.tools")?;
    Ok(RegistryToolTest {
        cmd: leak_string(cmd.to_string()),
        expected: leak_string(expected.to_string()),
        tools: leak_vec(tools),
    })
}

fn string_array(value: Option<&toml::Value>, name: &str) -> Result<Vec<&'static str>> {
    value
        .map(|value| {
            value
                .as_array()
                .ok_or_else(|| eyre::eyre!("{name} must be an array"))?
                .iter()
                .map(|value| {
                    value
                        .as_str()
                        .map(|value| leak_string(value.to_string()))
                        .ok_or_else(|| eyre::eyre!("{name} must contain only strings"))
                })
                .collect()
        })
        .transpose()
        .map(Option::unwrap_or_default)
}

fn leak_string(value: String) -> &'static str {
    Box::leak(value.into_boxed_str())
}

fn leak_vec<T>(value: Vec<T>) -> &'static [T] {
    Box::leak(value.into_boxed_slice())
}

// Cache for environment variable overrides
static ENV_BACKENDS: Lazy<Mutex<HashMap<String, &'static str>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

impl RegistryTool {
    pub fn backends(&self) -> Vec<&'static str> {
        // Check for environment variable override first
        // e.g., MISE_BACKENDS_GRAPHITE='github:withgraphite/homebrew-tap[exe=gt]'
        let env_key = format!("MISE_BACKENDS_{}", self.short.to_shouty_snake_case());

        // Check cache first
        {
            let cache = ENV_BACKENDS.lock().unwrap();
            if let Some(&backend) = cache.get(&env_key) {
                return vec![backend];
            }
        }

        // Check environment variable
        if let Ok(env_value) = env::var(&env_key) {
            // Store in cache with 'static lifetime
            let leaked = Box::leak(env_value.into_boxed_str());
            let mut cache = ENV_BACKENDS.lock().unwrap();
            cache.insert(env_key.clone(), leaked);
            return vec![leaked];
        }

        static BACKEND_TYPES: Lazy<HashSet<String>> = Lazy::new(|| {
            let mut backend_types = BackendType::iter()
                .map(|b| b.to_string())
                .collect::<HashSet<_>>();
            time!("disable_backends");
            for backend in &Settings::get().disable_backends {
                backend_types.remove(backend);
            }
            time!("disable_backends");
            if cfg!(windows) {
                backend_types.remove("asdf");
            }
            backend_types
        });
        let settings = Settings::get();
        let experimental = settings.experimental;
        self.backends
            .iter()
            .filter(|rb| backend_matches_platform(rb.platforms, &settings))
            .map(|rb| rb.full)
            .filter(|full| {
                full.split(':')
                    .next()
                    .is_some_and(|b| BACKEND_TYPES.contains(b))
            })
            // Filter out experimental backends if experimental mode is disabled
            .filter(|full| {
                if experimental {
                    return true;
                }
                let backend_type = BackendType::guess(full);
                !backend_type.is_experimental()
            })
            .collect()
    }

    pub fn is_supported_os(&self) -> bool {
        self.os.is_empty() || self.os.contains(&OS)
    }

    pub fn ba(&self) -> Option<BackendArg> {
        self.backends()
            .first()
            .map(|f| BackendArg::new(self.short.to_string(), Some(f.to_string())))
    }

    /// Get RegistryBackend for a specific full backend string
    pub fn get_backend(&self, full: &str) -> Option<&RegistryBackend> {
        self.backends.iter().find(|rb| rb.full == full)
    }

    /// Get options for a specific backend
    pub fn backend_options(&self, full: &str) -> ToolVersionOptions {
        let mut opts = IndexMap::new();

        if let Some(backend) = self.get_backend(full) {
            for (k, v) in backend.options {
                let value = v.parse::<toml::Value>().unwrap_or_else(|e| {
                    panic!("failed to parse registry option {k} as a TOML value: {e}")
                });
                opts.insert(k.to_string(), value);
            }
        }

        ToolVersionOptions {
            opts: RawBackendOptions::from(opts),
            ..Default::default()
        }
    }
}

/// Matches registry backend selectors using the schema's normalized platform names.
///
/// Unlike `backends.options.platforms.*` lookup, this is deliberately not
/// alias-tolerant: registry selectors use canonical names such as `macos-x64`,
/// while option lookup accepts release asset aliases such as `darwin-amd64`.
fn backend_matches_platform(platforms: &[&str], settings: &Settings) -> bool {
    let os = settings.os();
    let arch = settings.arch();
    let platform = format!("{os}-{arch}");

    platforms.is_empty()
        || platforms.contains(&os)
        || platforms.contains(&arch)
        || platforms.contains(&platform.as_str())
}

pub fn shorts_for_full(full: &str) -> &'static Vec<&'static str> {
    static EMPTY: Vec<&'static str> = vec![];
    static FULL_TO_SHORT: Lazy<HashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| {
        let mut map: HashMap<&'static str, Vec<&'static str>> = HashMap::new();
        for (short, rt) in REGISTRY.iter() {
            for full in rt.backends() {
                map.entry(full).or_default().push(short);
            }
        }
        map
    });
    FULL_TO_SHORT.get(full).unwrap_or(&EMPTY)
}

pub fn is_trusted_plugin(name: &str, remote: &str) -> bool {
    let Ok(normalized_url) = normalize_remote(remote) else {
        return false;
    };
    if normalized_url.starts_with("github.com/mise-plugins/") {
        return true;
    }

    let official_registry_plugin_remotes = || {
        static REMOTES: Lazy<HashSet<String>> = Lazy::new(|| {
            REGISTRY
                .values()
                .flat_map(|tool| tool.backends.iter().map(|backend| backend.full))
                .filter(|full| full.starts_with("asdf:") || full.starts_with("vfox:"))
                .filter_map(|full| normalize_remote(&full_to_url(full)).ok())
                .collect()
        });
        &*REMOTES
    };

    let name_matches_official_remote = REGISTRY.get(name).is_some_and(|tool| {
        tool.backends
            .iter()
            .map(|backend| backend.full)
            .filter(|full| full.starts_with("asdf:") || full.starts_with("vfox:"))
            .filter_map(|full| normalize_remote(&full_to_url(full)).ok())
            .any(|official_remote| official_remote == normalized_url)
    });

    name_matches_official_remote || official_registry_plugin_remotes().contains(&normalized_url)
}

pub fn normalize_remote(remote: &str) -> eyre::Result<String> {
    let url = Url::parse(remote)?;
    let host = url
        .host_str()
        .ok_or_else(|| eyre::eyre!("URL has no host: {remote}"))?;
    let path = url.path().trim_end_matches(".git");
    Ok(format!("{host}{path}"))
}

pub fn full_to_url(full: &str) -> String {
    if url_like(full) {
        return full.to_string();
    }
    let (_backend, url) = full.split_once(':').unwrap_or(("", full));
    if url_like(url) {
        url.to_string()
    } else {
        format!("https://github.com/{url}.git")
    }
}

pub(crate) fn url_like(s: &str) -> bool {
    s.starts_with("https://")
        || s.starts_with("http://")
        || s.starts_with("git@")
        || s.starts_with("ssh://")
        || s.starts_with("git://")
}

impl Display for RegistryTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.short)
    }
}

/// Returns true when `name` passes the configured tool filter.
///
/// `None` means no allowlist is configured, so `disable_tools` excludes
/// individual tools. `Some(empty)` is an explicit empty allowlist and disables
/// every tool. When an allowlist is configured, it is authoritative and
/// `disable_tools` is not applied.
pub fn tool_enabled<T: Ord>(
    enable_tools: Option<&BTreeSet<T>>,
    disable_tools: &BTreeSet<T>,
    name: &T,
) -> bool {
    match enable_tools {
        Some(enable_tools) => enable_tools.contains(name),
        None => !disable_tools.contains(name),
    }
}

#[cfg(test)]
mod tests {
    use crate::config::Config;

    fn registry_archive(entries: &[(&str, &str)]) -> tempfile::NamedTempFile {
        use std::io::Cursor;

        let file = tempfile::NamedTempFile::new().unwrap();
        let encoder = zstd::Encoder::new(file.reopen().unwrap(), 0).unwrap();
        let mut archive = jdx_tar::Builder::new(encoder);
        for (path, contents) in entries {
            let mut header = jdx_tar::Header::new_gnu(jdx_tar::EntryType::File);
            header.set_size(contents.len() as u64);
            header.set_mode(0o644);
            archive
                .append_data(&mut header, path, Cursor::new(contents.as_bytes()))
                .unwrap();
        }
        archive.into_inner().unwrap().finish().unwrap();
        file
    }

    #[test]
    fn test_dynamic_registry_parses_tools_aliases_and_options() {
        use super::*;

        let registry = registry_from_sources(BTreeMap::from([(
            "example".to_string(),
            r#"
aliases = ["example-alias"]
description = "Example tool"
backends = [
  "aqua:example/tool",
  { full = "github:example/tool", platforms = ["linux-x64"], options = { bin = "example" } },
]
idiomatic_files = [
  ".example-version",
  { path = "example.json", version_json_path = ".tool.version" },
  { path = "example.txt", version_regex = 'version=(\S+)', version_expr = "versions[0]" },
]
test = { cmd = "example --version", expected = "{{version}}", tools = ["node"] }
"#
            .to_string(),
        )]))
        .unwrap();

        let tool = registry.get("example-alias").unwrap();
        assert_eq!(tool.short, "example");
        assert_eq!(tool.description, Some("Example tool"));
        assert_eq!(tool.backends[0].full, "aqua:example/tool");
        assert_eq!(tool.backends[1].platforms, &["linux-x64"]);
        assert_eq!(
            tool.backend_options("github:example/tool").get("bin"),
            Some("example")
        );
        assert_eq!(tool.idiomatic_files[0].path, ".example-version");
        assert!(!tool.idiomatic_files[0].has_parser());
        assert_eq!(tool.idiomatic_files[1].path, "example.json");
        assert_eq!(
            tool.idiomatic_files[1].version_json_path,
            Some(".tool.version")
        );
        assert_eq!(
            tool.idiomatic_files[2].version_regex,
            Some(r"version=(\S+)")
        );
        assert_eq!(tool.idiomatic_files[2].version_expr, Some("versions[0]"));
        assert_eq!(tool.test.as_ref().unwrap().tools, &["node"]);
    }

    #[test]
    fn test_dynamic_registry_rejects_unknown_idiomatic_file_fields() {
        use super::*;

        let err = registry_from_sources(BTreeMap::from([(
            "example".to_string(),
            r#"
backends = ["aqua:example/tool"]
idiomatic_files = [{ path = ".example-version", parser = "shell" }]
"#
            .to_string(),
        )]))
        .err()
        .unwrap();

        assert!(
            format!("{err:#}").contains("unknown idiomatic file field: parser"),
            "{err:#}"
        );
    }

    #[test]
    fn test_registry_archive_only_reads_top_level_registry_directory() {
        use super::*;

        let archive = registry_archive(&[
            ("registry/example.toml", "backends = [\"aqua:good/tool\"]"),
            (
                "e2e/registry/example.toml",
                "backends = [\"aqua:wrong/tool\"]",
            ),
        ]);
        let registry = parse_registry_archive(archive.path()).unwrap();

        assert_eq!(
            registry.get("example").unwrap().backends[0].full,
            "aqua:good/tool"
        );
    }

    #[test]
    fn test_registry_archive_rejects_nested_registry_directory() {
        use super::*;

        let archive = registry_archive(&[(
            "e2e/registry/example.toml",
            "backends = [\"aqua:wrong/tool\"]",
        )]);

        assert!(parse_registry_archive(archive.path()).is_err());
    }

    #[test]
    fn test_registry_archive_limits() {
        use super::*;

        let mut size = 0;
        assert!(
            track_registry_archive_entry(MAX_REGISTRY_ARCHIVE_ENTRIES, 0, &mut size)
                .unwrap_err()
                .to_string()
                .contains("too many entries")
        );
        assert!(
            track_registry_archive_entry(0, MAX_REGISTRY_ARCHIVE_ENTRY_SIZE + 1, &mut size)
                .unwrap_err()
                .to_string()
                .contains("entry is too large")
        );
        size = MAX_REGISTRY_ARCHIVE_SIZE;
        assert!(
            track_registry_archive_entry(0, 1, &mut size)
                .unwrap_err()
                .to_string()
                .contains("archive is too large")
        );
    }

    #[test]
    fn test_tool_disabled() {
        use super::*;
        let name = "cargo";

        assert!(tool_enabled(None, &BTreeSet::new(), &name));
        assert!(!tool_enabled(
            Some(&BTreeSet::new()),
            &BTreeSet::new(),
            &name
        ));
        assert!(tool_enabled(
            Some(&BTreeSet::from(["cargo"])),
            &BTreeSet::new(),
            &name
        ));
        assert!(!tool_enabled(None, &BTreeSet::from(["cargo"]), &name));
        assert!(tool_enabled(
            Some(&BTreeSet::from(["cargo"])),
            &BTreeSet::from(["cargo"]),
            &name
        ));
    }

    #[test]
    fn test_registry_iteration_is_sorted() {
        use super::*;

        // The interactive tool selector and --all test-tool path consume registry
        // iteration order directly, so keep PHF lookup separate from sorted output.
        let keys = REGISTRY.keys().collect::<Vec<_>>();
        let mut sorted = keys.clone();
        sorted.sort_unstable();

        assert!(!keys.is_empty());
        assert_eq!(keys, sorted);
    }

    #[test]
    fn test_backend_platform_matching_normalizes_settings() {
        use super::*;

        for (raw_os, raw_arch, selector) in [
            ("windows", "x86_64", "windows-x64"),
            ("windows", "amd64", "x64"),
            ("linux", "aarch64", "linux-arm64"),
            ("darwin", "x86_64", "macos-x64"),
        ] {
            let settings = Settings {
                os: Some(raw_os.to_string()),
                arch: Some(raw_arch.to_string()),
                ..Default::default()
            };

            assert!(
                backend_matches_platform(&[selector], &settings),
                "{raw_os}-{raw_arch} should match normalized selector {selector}"
            );
        }
    }

    #[test]
    fn test_backend_platform_matching_preserves_os_only_and_order() {
        use super::*;

        let settings = Settings {
            os: Some("darwin".to_string()),
            arch: Some("amd64".to_string()),
            ..Default::default()
        };
        let backends = [
            RegistryBackend {
                full: "aqua:first/tool",
                platforms: &["macos"],
                options: &[],
            },
            RegistryBackend {
                full: "github:second/tool",
                platforms: &["macos-x64"],
                options: &[],
            },
            RegistryBackend {
                full: "cargo:third-tool",
                platforms: &[],
                options: &[],
            },
            RegistryBackend {
                full: "npm:excluded-tool",
                platforms: &["linux"],
                options: &[],
            },
        ];

        let matching = backends
            .iter()
            .filter(|backend| backend_matches_platform(backend.platforms, &settings))
            .map(|backend| backend.full)
            .collect::<Vec<_>>();

        assert_eq!(
            matching,
            ["aqua:first/tool", "github:second/tool", "cargo:third-tool"]
        );

        let alias_selector = RegistryBackend {
            full: "github:owner/repo",
            platforms: &["darwin-amd64"],
            options: &[],
        };
        assert!(!backend_matches_platform(
            alias_selector.platforms,
            &settings
        ));
    }

    #[test]
    fn test_backend_options_parse_toml_values() {
        use super::*;

        static OPTIONS: &[(&str, &str)] = &[
            ("bin", r#""rg""#),
            ("prerelease", "true"),
            ("strip_components", "1"),
            (
                "targets",
                r#"["x86_64-unknown-linux-gnu", "aarch64-apple-darwin"]"#,
            ),
            (
                "platforms",
                r#"{ linux-x64 = { asset_pattern = "tool-linux.tar.gz" } }"#,
            ),
        ];
        static BACKENDS: &[RegistryBackend] = &[RegistryBackend {
            full: "github:owner/repo",
            platforms: &[],
            options: OPTIONS,
        }];
        let tool = RegistryTool {
            short: "test",
            description: None,
            backends: BACKENDS,
            aliases: &[],
            overrides: &[],
            test: &None,
            os: &[],
            idiomatic_files: &[],
            detect: &[],
        };

        let opts = tool.backend_options("github:owner/repo");

        assert_eq!(opts.get("bin"), Some("rg"));
        assert_eq!(
            opts.opts.get("prerelease"),
            Some(&toml::Value::Boolean(true))
        );
        assert_eq!(
            opts.opts.get("strip_components"),
            Some(&toml::Value::Integer(1))
        );
        assert!(opts.opts.get("targets").is_some_and(toml::Value::is_array));
        assert_eq!(
            opts.get_nested_string("platforms.linux-x64.asset_pattern"),
            Some("tool-linux.tar.gz".to_string())
        );
    }

    #[tokio::test]
    async fn test_backend_env_override() {
        let _config = Config::get().await.unwrap();
        use super::*;

        // Clear the cache first
        ENV_BACKENDS.lock().unwrap().clear();

        // Test with a known tool from the registry
        if let Some(tool) = REGISTRY.get("node") {
            // First test without env var - should return default backends
            let default_backends = tool.backends();
            assert!(!default_backends.is_empty());

            // Test with env var override
            // SAFETY: This is safe in a test environment
            unsafe {
                env::set_var("MISE_BACKENDS_NODE", "test:backend");
            }
            let overridden_backends = tool.backends();
            assert_eq!(overridden_backends.len(), 1);
            assert_eq!(overridden_backends[0], "test:backend");

            // Clean up
            // SAFETY: This is safe in a test environment
            unsafe {
                env::remove_var("MISE_BACKENDS_NODE");
            }
            ENV_BACKENDS.lock().unwrap().clear();
        }
    }

    #[test]
    fn test_normalize_remote() {
        use super::*;

        // Standard HTTPS URLs should work
        let result = normalize_remote("https://github.com/mise-plugins/vfox-node.git");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "github.com/mise-plugins/vfox-node");

        // file:// URLs should return an error (no host)
        let result = normalize_remote("file:///path/to/repo");
        assert!(result.is_err());

        // Invalid URLs should return an error
        let result = normalize_remote("not-a-url");
        assert!(result.is_err());
    }

    #[test]
    fn test_is_trusted_plugin_rejects_non_normalizable_remote() {
        use super::*;

        assert!(!is_trusted_plugin("cmake", "not-a-url"));
    }

    #[test]
    fn test_is_trusted_plugin_rejects_non_registry_plugin_url() {
        use super::*;

        assert!(!is_trusted_plugin(
            "vfox-attacker-evil",
            "https://github.com/attacker/evil.git"
        ));
    }

    #[test]
    fn test_is_trusted_plugin_accepts_official_registry_plugin_url() {
        use super::*;

        assert!(is_trusted_plugin(
            "cmake",
            "https://github.com/mise-plugins/vfox-cmake.git"
        ));
        assert!(is_trusted_plugin(
            "vfox-jdx-vfox-mongod",
            "https://github.com/jdx/vfox-mongod.git"
        ));
    }

    #[test]
    fn test_is_trusted_plugin_rejects_shorthand_mismatch() {
        use super::*;

        assert!(!is_trusted_plugin(
            "cmake",
            "https://github.com/attacker/vfox-cmake.git"
        ));
    }
}