use crate::duration; use crate::file::FindUp; use crate::platform::Platform; use crate::{dirs, env, file}; use confique::{Config, Layer}; use eyre::{Result, WrapErr, bail, eyre}; use itertools::Itertools; use mise_util::network; use path_absolutize::Absolutize; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::fmt::Debug; use std::path::{Path, PathBuf}; use std::sync::LazyLock as Lazy; use std::sync::{Arc, Mutex, RwLock}; use std::time::Duration; use std::{ collections::{BTreeMap, BTreeSet}, sync::atomic::{AtomicBool, Ordering}, }; use super::{TOML_CONFIG_FILENAMES, load_config_paths, load_config_paths_from}; use url::Url; #[derive(Clone, Copy)] pub enum CompilePurpose { Install, Inspect, } pub use mise_settings::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum SettingsSourcePolicy { EnvironmentOnly, Hierarchy, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum SettingsTrustPolicy { AsDiscovered, TrustedOnly, /// Global and system config only: no project file is consulted, trusted or not. GlobalOnly, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) struct SettingsLoadPolicy { source: SettingsSourcePolicy, trust: SettingsTrustPolicy, } impl SettingsLoadPolicy { const ENVIRONMENT_ONLY: Self = Self { source: SettingsSourcePolicy::EnvironmentOnly, trust: SettingsTrustPolicy::AsDiscovered, }; pub(crate) const TRUSTED_HIERARCHY: Self = Self { source: SettingsSourcePolicy::Hierarchy, trust: SettingsTrustPolicy::TrustedOnly, }; /// Settings no project file can influence. The trust check reads a few of them /// (`paranoid`, `trusted_config_paths`, ...), so they must exist before any project /// file can be classified as trusted. const GLOBAL_HIERARCHY: Self = Self { source: SettingsSourcePolicy::Hierarchy, trust: SettingsTrustPolicy::GlobalOnly, }; } /// Settings that control idiomatic version-file discovery for one config root. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct IdiomaticVersionFileSettings { pub(crate) enable_tools: BTreeSet, pub(crate) disable_files: BTreeSet, } impl IdiomaticVersionFileSettings { fn from_settings(settings: &Settings) -> Self { Self { enable_tools: settings.idiomatic_version_file_enable_tools.clone(), disable_files: settings.idiomatic_version_file_disable_files.clone(), } } pub(crate) fn current() -> Self { Settings::try_get() .map(|settings| Self::from_settings(&settings)) .unwrap_or_default() } /// Resolve through the canonical settings loader, then retain only the fields needed for /// idiomatic discovery. Parsing a reduced schema here would create a second validation path. pub(crate) fn resolve_from(root: &Path, policy: SettingsLoadPolicy) -> Result { Settings::load_sources_from(Some(root), policy) .map(|settings| Self::from_settings(&settings)) } /// Like [`Self::resolve_from`] for the root of a tracked config, which belongs to another /// folder. Its settings never apply to this run, so a setting mise drops from one of its /// files (a global-only key in a project config) asks the user for nothing and stays silent. pub(crate) fn resolve_from_foreign_root( root: &Path, policy: SettingsLoadPolicy, ) -> Result { let _quiet = QuietIgnoredSettings::new(); Self::resolve_from(root, policy) } } thread_local! { /// Depth of [`QuietIgnoredSettings`] guards on this thread. static QUIET_IGNORED_SETTINGS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// While alive, the warnings about settings mise ignores in a config file are not printed. struct QuietIgnoredSettings; impl QuietIgnoredSettings { fn new() -> Self { QUIET_IGNORED_SETTINGS.with(|depth| depth.set(depth.get() + 1)); Self } fn active() -> bool { QUIET_IGNORED_SETTINGS.with(|depth| depth.get() > 0) } } impl Drop for QuietIgnoredSettings { fn drop(&mut self) { QUIET_IGNORED_SETTINGS.with(|depth| depth.set(depth.get() - 1)); } } static PACKAGE_QUERY_SETTINGS: AtomicBool = AtomicBool::new(false); type ParseCache = std::collections::HashMap>; thread_local! { /// Settings files parsed during the current [`load`], so the global-only pass that /// bootstraps trust and the trusted pass that follows it read each file once. `None` /// outside a load. `load` runs on one thread, so this never mixes concurrent loads. static LOAD_PARSE_CACHE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// The settings layer read from the environment during the current [`load`], which builds /// settings three times. Reading it asks the environment for every setting's variable, so /// the three passes share one read. `None` outside a load, where each read is fresh; /// `Some(None)` until the load's first pass reads it. static LOAD_ENV_LAYER: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; /// How many times the environment's settings layer was read on this thread. #[cfg(test)] static ENV_LAYER_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many times each settings file was actually parsed on this thread. #[cfg(test)] static PARSE_COUNTS: std::cell::RefCell> = std::cell::RefCell::new(std::collections::HashMap::new()); } /// Shares one read of the environment's settings layer for as long as it lives. struct SharedEnvLayer; impl SharedEnvLayer { fn start() -> Self { LOAD_ENV_LAYER.set(Some(None)); Self } } impl Drop for SharedEnvLayer { fn drop(&mut self) { LOAD_ENV_LAYER.set(None); } } /// The settings the environment sets, as the layer `builder().env()` would read. fn env_settings_layer() -> Result { if let Some(Some(shared)) = LOAD_ENV_LAYER.with_borrow(Clone::clone) { return Ok(shared); } #[cfg(test)] ENV_LAYER_READS.set(ENV_LAYER_READS.get() + 1); let layer = SettingsPartial::from_env()?; LOAD_ENV_LAYER.with_borrow_mut(|shared| { if let Some(shared) = shared { *shared = Some(layer.clone()); } }); Ok(layer) } fn parse_settings_file_once(path: &Path) -> Result { let cached = LOAD_PARSE_CACHE .with_borrow(|cache| cache.as_ref().and_then(|cache| cache.get(path).cloned())); if let Some(cached) = cached { return cached.map_err(|err| eyre::eyre!(err)); } #[cfg(test)] PARSE_COUNTS.with_borrow_mut(|counts| *counts.entry(path.to_path_buf()).or_default() += 1); let parsed = Settings::parse_settings_file(path); LOAD_PARSE_CACHE.with_borrow_mut(|cache| { if let Some(cache) = cache { cache.insert( path.to_path_buf(), parsed .as_ref() .map(Clone::clone) .map_err(|err| err.to_string()), ); } }); parsed } /// Set while [`load`] has published its global-only bootstrap snapshot, so the cache reads as /// loaded although the real settings are still being built. static BOOTSTRAPPING: AtomicBool = AtomicBool::new(false); /// Whether the settings cache holds only the snapshot used to decide trust. Warnings that depend /// on the final settings must wait for them. pub(crate) fn is_bootstrapping() -> bool { BOOTSTRAPPING.load(Ordering::Relaxed) } /// Caches the resolved `safe` value from the most recent settings load so static CLI_SETTINGS: Mutex> = Mutex::new(None); static EXPLICIT_INLINE_SHELL: RwLock> = RwLock::new(None); /// Resolved `trusted_config_paths` entries. Unlike `canonicalize_cached` this remembers entries /// that don't exist: each lookup can be a slow autofs/network call, and every config checked in /// the process would repeat it. Cleared whenever settings change, so a path created since is seen. static TRUSTED_PATHS_RESOLVED: Lazy>>> = Lazy::new(Default::default); /// Queue key for the `lockfile_mode = "merge"` deprecation, which warns about a value rather than /// a whole setting, so it has no `SETTINGS_META` entry. [`warn_deprecated_now`] special-cases it. const LOCKFILE_MODE_MERGE: &str = "lockfile_mode.merge"; static PENDING_DEPRECATED_SETTINGS: Lazy>> = Lazy::new(Default::default); /// `write_targets.*` keys a non-global config set, with the first file that set each one. /// /// A write target only matters to a command that writes global config, so instead of warning /// whenever such a file loads, the write path asks [`ignored_write_target`] and warns there. static IGNORED_WRITE_TARGETS: Lazy>> = Lazy::new(Default::default); /// Warnings found while building the settings, such as a file that failed to parse or a key it may /// not set, held until warnings can be printed. /// /// A set rather than a list because settings can be built more than once per run — `add_cli_matches` /// rebuilds them when CLI flags set something — and each build re-reports the same problem. The /// messages name their file, which is what keeps two files failing the same way from collapsing /// into one. static PENDING_SETTINGS_WARNINGS: Lazy>> = Lazy::new(Default::default); /// Whether warnings found while loading settings can be printed yet. /// /// `logger::init()` calls `Settings::try_get()` before installing the logger, so the first build /// happens with nothing to print to. Anything found there is queued above and flushed once the /// logger exists. static WARNINGS_READY: AtomicBool = AtomicBool::new(false); // TODO(2027.8.0): Remove the per-tool warning accessors once the NixOS // and Alpine `all_compile` deprecation process is complete. fn default_all_compile(linux_distro: Option<&str>) -> bool { matches!(linux_distro, Some("alpine" | "nixos")) } fn compile_inherits_distro_all_compile_default( linux_distro: Option<&str>, distro: &str, explicit_all_compile: Option, compile: Option, ) -> bool { linux_distro == Some(distro) && explicit_all_compile.is_none() && compile.is_none() } /// Like [`effective_compile_setting`], but only an explicit `all_compile` counts, never the /// distro default. fn explicit_compile_setting(all_compile: Option, compile: Option) -> Option { effective_compile_setting(all_compile == Some(true), compile) } fn effective_compile_setting(all_compile: bool, compile: Option) -> Option { compile.or_else(|| all_compile.then_some(true)) } fn distro_all_compile_deprecation_id(distro: &str, tool: &str) -> Option<&'static str> { match (distro, tool) { ("nixos", "node") => Some("nixos.node_all_compile_default"), ("nixos", "python") => Some("nixos.python_all_compile_default"), ("nixos", "erlang") => Some("nixos.erlang_all_compile_default"), ("nixos", "ruby") => Some("nixos.ruby_all_compile_default"), ("alpine", "node") => Some("alpine.node_all_compile_default"), ("alpine", "python") => Some("alpine.python_all_compile_default"), ("alpine", "erlang") => Some("alpine.erlang_all_compile_default"), ("alpine", "ruby") => Some("alpine.ruby_all_compile_default"), _ => None, } } fn warn_implicit_all_compile_default_deprecated( tool: &str, all_compile: Option, compile: Option, ) { if mise_util::testing::in_tests() { return; } let distro = env::LINUX_DISTRO.as_deref(); if compile_inherits_distro_all_compile_default(distro, "nixos", all_compile, compile) && let Some(id) = distro_all_compile_deprecation_id("nixos", tool) { deprecated_at!( "2026.8.0", "2027.8.0", id, "The automatic all_compile=true default on NixOS caused {tool} to compile from source. Enable nix-ld to use precompiled binaries, or configure all_compile=true explicitly to keep compiling tools from source." ); } if compile_inherits_distro_all_compile_default(distro, "alpine", all_compile, compile) && let Some(id) = distro_all_compile_deprecation_id("alpine", tool) { deprecated_at!( "2026.8.0", "2027.8.0", id, "The automatic all_compile=true default on Alpine caused {tool} to compile from source. Set all_compile=false to use precompiled musl binaries when available, or configure all_compile=true explicitly to keep compiling tools from source." ); } } static DEFAULT_SETTINGS: Lazy = Lazy::new(|| { let mut s = SettingsPartial::empty(); s.python.default_packages_file = Some(env::HOME.join(".default-python-packages")); s }); #[derive(Serialize, Deserialize)] pub struct SettingsFile { #[serde(default)] pub settings: SettingsPartial, } fn parse_boolish_toml_value(value: &toml::Value) -> Option { match value { toml::Value::Boolean(value) => Some(*value), toml::Value::Integer(0) => Some(false), toml::Value::Integer(1) => Some(true), toml::Value::String(value) => match value.trim().to_ascii_lowercase().as_str() { "y" | "yes" | "true" | "1" | "on" => Some(true), "n" | "no" | "false" | "0" | "off" => Some(false), _ => None, }, toml::Value::Table(table) => table.get("value").and_then(parse_boolish_toml_value), _ => None, } } fn tera_v1_from_env_config(raw: &toml::Value) -> Option { raw.get("env") .and_then(toml::Value::as_table) .and_then(|env| env.get("MISE_TERA_V1")) .and_then(parse_boolish_toml_value) } fn deprecated_settings_in_toml_table(settings: &toml::Table) -> Vec<&'static str> { SETTINGS_META .iter() .filter_map(|(key, meta)| { meta.deprecated?; let value = nested_toml_value(settings, key)?; should_warn_deprecated_value(value).then_some(*key) }) .collect() } fn deprecated_settings_in_env_directives(raw: &toml::Value) -> Vec<&'static str> { tera_v1_from_env_config(raw) .is_some() .then_some("tera_v1") .into_iter() .collect() } fn deprecated_settings_in_toml_config(raw: &toml::Value) -> Vec<&'static str> { let mut deprecated = Vec::new(); if let Some(settings) = raw.get("settings").and_then(toml::Value::as_table) { deprecated.extend(deprecated_settings_in_toml_table(settings)); } deprecated.extend(deprecated_settings_in_env_directives(raw)); deprecated } fn warn_deprecated_env_settings() { for (key, meta) in SETTINGS_META.iter() { let Some(env_key) = meta.env else { continue; }; if meta.deprecated.is_some() && env::var_os(env_key).is_some_and(|value| !value.as_os_str().is_empty()) { warn_deprecated(key); } } } /// Report a problem found while building the settings, such as a file that could not be parsed. /// /// Queued rather than printed when the logger is not up yet. Every warning from the build goes /// through here: when the CLI flags set nothing, the pre-logger build is the only one, so a `warn!` /// there would never be seen. `warn_once!` cannot stand in for the /// queue: it records the message as seen even when nothing was printed, so the pre-logger build /// would silence the one that comes after it. /// /// Readiness is read while the queue is held, and the flush sets it while holding the same lock, so /// a warning cannot be queued into a set that has just been drained. pub(crate) fn warn_while_loading_settings(msg: String) { { let mut pending = PENDING_SETTINGS_WARNINGS.lock().unwrap(); if !WARNINGS_READY.load(Ordering::SeqCst) { pending.insert(msg); return; } } warn_once!("{msg}"); } fn queue_deprecated_settings(keys: impl IntoIterator) { for key in keys { warn_deprecated(key); } } fn nested_toml_value<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> { let mut parts = key.split('.').collect_vec(); let last = parts.pop()?; let mut current = table; for part in parts { current = current.get(part)?.as_table()?; } current.get(last) } fn should_warn_deprecated_value(value: &toml::Value) -> bool { match value { toml::Value::String(value) => !value.is_empty(), toml::Value::Array(value) => !value.is_empty(), toml::Value::Table(value) => { if value.get("unset").and_then(toml::Value::as_bool) == Some(true) { return false; } match value.get("value") { Some(value) => should_warn_deprecated_value(value), None => !value.is_empty(), } } _ => true, } } fn warn_deprecated(key: &'static str) { // Same lock discipline as `warn_while_loading_settings`: the readiness read and the insert have to // be one step against the flush, or a key queued just after the drain is never printed. { let mut pending = PENDING_DEPRECATED_SETTINGS.lock().unwrap(); if !WARNINGS_READY.load(Ordering::SeqCst) { pending.insert(key); return; } } warn_deprecated_now(key); } fn warn_deprecated_now(key: &'static str) { if key == LOCKFILE_MODE_MERGE { deprecated_at!( "2027.4.0", "2027.10.0", LOCKFILE_MODE_MERGE, "lockfile_mode=\"merge\" is deprecated. Remove the setting to use the default \"generate\" mode." ); return; } if let Some(meta) = SETTINGS_META.get(key) && let (Some(msg), Some(warn_at), Some(remove_at)) = ( meta.deprecated, meta.deprecated_warn_at, meta.deprecated_remove_at, ) { use versions::Versioning; let warn_version = Versioning::new(warn_at).unwrap(); let remove_version = Versioning::new(remove_at).unwrap(); debug_assert!( *crate::version::V < remove_version, "Deprecated setting [{key}] should have been removed in {remove_at}. Please remove this deprecated setting.", ); if *crate::version::V >= warn_version { let id = Box::leak(format!("setting.{key}").into_boxed_str()); if crate::output::DEPRECATED.lock().unwrap().insert(id) { warn!( "deprecated [setting.{key}]: {msg} This will be removed in mise {remove_at}." ); } } } } /// Settle the verbosity settings against each other, so `log_level` is the single answer. /// /// `debug`, `trace`, `quiet` and `verbose` each say something about `log_level`, and they overlap: /// the order below is the precedence. Kept apart from the rest of the load so it can also be /// applied to a partial view of the settings — see [`Settings::cli_log_level`]. fn normalize_verbosity(settings: &mut Settings) { if settings.debug { settings.log_level = "debug".to_string(); } if settings.trace { settings.log_level = "trace".to_string(); } if settings.quiet { settings.log_level = "error".to_string(); } if settings.log_level == "trace" || settings.log_level == "debug" { settings.verbose = true; settings.debug = true; if settings.log_level == "trace" { settings.trace = true; } } // handle the special case of `mise -v` which should show version, not set verbose. // Use the args mise was invoked with (already captured safely in Cli::run and kept // in sync with internal re-dispatch like `mise asdf ...`) rather than re-reading the // process argv. See also Settings::no_config(). let is_version_flag = { let args = env::ARGS.read().unwrap(); args.len() == 2 && args[1] == "-v" }; if settings.verbose && !is_version_flag { settings.quiet = false; if settings.log_level != "trace" { settings.log_level = "debug".to_string(); } } } /// Move the deprecated top-level `auto_update` and `auto_update_check_duration` onto /// `self_update.*` within a single layer. /// /// Done per layer rather than on the merged settings so that a source's own `self_update.*` value /// wins over its deprecated spelling while precedence between sources stays as it was: a deprecated /// key in the global config still beats the new key's default, and loses to the new key set in a /// higher-priority source. fn normalize_self_update_aliases(partial: &mut SettingsPartial) { if let Some(v) = partial.auto_update.take() { warn_deprecated("auto_update"); partial.self_update.auto.get_or_insert(v.into()); } if let Some(v) = partial.auto_update_check_duration.take() { warn_deprecated("auto_update_check_duration"); partial.self_update.check_duration.get_or_insert(v); } } /// Environment variables of the deprecated settings that [`normalize_self_update_aliases`] /// migrates. const DEPRECATED_SELF_UPDATE_ENV: [&str; 2] = ["MISE_AUTO_UPDATE", "MISE_AUTO_UPDATE_CHECK_DURATION"]; /// The environment's deprecated self-update settings, moved to `self_update.*`, as a layer to sit /// at the environment's own precedence. `None` when none of their variables is set, so the common /// case does not read the environment a second time. fn self_update_env_alias_layer() -> Result> { if !DEPRECATED_SELF_UPDATE_ENV .iter() .any(|name| std::env::var_os(name).is_some()) { return Ok(None); } let mut env_layer = env_settings_layer()?; normalize_self_update_aliases(&mut env_layer); let mut alias_layer = SettingsPartial::empty(); alias_layer.self_update.auto = env_layer.self_update.auto; alias_layer.self_update.check_duration = env_layer.self_update.check_duration; Ok(Some(alias_layer)) } /// An interval that isn't a duration would leave the setting on while every /// check failed quietly, so turn it off and say why. fn validate_auto_update(key: &str, value: &mut AutoUpdate) { if let Some(interval) = value.interval() && let Err(err) = duration::parse_duration(interval) { warn_while_loading_settings(format!( "{key} must be true, false, or a duration such as \"6h\", got {interval:?}: {err}" )); *value = AutoUpdate::Off; } } fn normalize_hidden_config_aliases(mut partial: SettingsPartial) -> SettingsPartial { normalize_self_update_aliases(&mut partial); if let Some(v) = partial.install_before.take() { warn_deprecated("install_before"); if partial.minimum_release_age.is_none() { partial.minimum_release_age = Some(v); } } if let Some(v) = partial.task.cache_remote_mode.take() { warn_deprecated("task.cache_remote_mode"); if partial.task.cache.remote_mode.is_none() { partial.task.cache.remote_mode = Some(v); } } if let Some(v) = partial.task.cache_remote_namespace.take() { warn_deprecated("task.cache_remote_namespace"); if partial.task.cache.remote_namespace.is_none() { partial.task.cache.remote_namespace = Some(v); } } if let Some(v) = partial.task.cache_remote_oidc_audience.take() { warn_deprecated("task.cache_remote_oidc_audience"); if partial.task.cache.remote_oidc_audience.is_none() { partial.task.cache.remote_oidc_audience = Some(v); } } if let Some(v) = partial.task.cache_remote_token.take() { warn_deprecated("task.cache_remote_token"); if partial.task.cache.remote_token.is_none() { partial.task.cache.remote_token = Some(v); } } if let Some(v) = partial.task.cache_remote_token_file.take() { warn_deprecated("task.cache_remote_token_file"); if partial.task.cache.remote_token_file.is_none() { partial.task.cache.remote_token_file = Some(v); } } if let Some(v) = partial.task.cache_remote_url.take() { warn_deprecated("task.cache_remote_url"); if partial.task.cache.remote_url.is_none() { partial.task.cache.remote_url = Some(v); } } partial } fn normalize_storage_dirs(settings: &mut Settings) -> Result<()> { for (name, path) in [ ("shims_dir", &mut settings.shims_dir), ("system_installs_dir", &mut settings.system_installs_dir), ("system_shims_dir", &mut settings.system_shims_dir), ] { let Some(configured) = path.take() else { continue; }; let configured = file::replace_path(&configured); if !configured.is_absolute() { bail!("settings.{name} must resolve to an absolute path"); } *path = Some(configured); } Ok(()) } fn strip_local_only_settings(settings: &mut toml::Table, path: &Path, is_global: bool) { if is_global { return; } for key in SETTINGS_META .iter() .filter_map(|(key, meta)| meta.global_only.then_some(*key)) { if let Some(value) = remove_nested_toml_value(settings, key) && should_warn_ignored_global_only_value(&value) { if key.starts_with("write_targets.") { IGNORED_WRITE_TARGETS .lock() .unwrap() .entry(key) .or_insert_with(|| path.to_path_buf()); } else if !QuietIgnoredSettings::active() { warn_while_loading_settings(format!( "{key} in non-global config {} is ignored for security reasons", path.display() )); } } } } /// The non-global config file that set `key` (such as `write_targets.dotfiles`), which mise /// ignored because write targets apply only from global config. pub(crate) fn ignored_write_target(key: &str) -> Option { IGNORED_WRITE_TARGETS.lock().unwrap().get(key).cloned() } /// Drop settings the config loader consumes *before* any config file is read — the config /// filenames and paths. A value written here can never take effect, and leaving it in the /// partial makes `mise settings get` report it as if it were live, which is what /// ran into. Unlike the global-only strip this /// applies to every config, global included: the ordering problem is the same either way. fn strip_env_only_settings(settings: &mut toml::Table, path: &Path) { for (key, meta) in SETTINGS_META.iter().filter(|(_, meta)| meta.env_only) { if remove_nested_toml_value(settings, key).is_some() && !QuietIgnoredSettings::active() { warn_while_loading_settings(format!( "{key} in {} is ignored: mise reads it before config files load. Set {} instead.", file::display_path(path), meta.env.unwrap_or("the matching MISE_* variable") )); } } } fn remove_nested_toml_value(table: &mut toml::Table, key: &str) -> Option { let mut parts = key.split('.').collect_vec(); let last = parts.pop()?; let mut current = table; for part in parts { current = current.get_mut(part)?.as_table_mut()?; } current.remove(last) } fn should_warn_ignored_global_only_value(value: &toml::Value) -> bool { !matches!(value, toml::Value::String(s) if s.is_empty()) } /// `aqua.registries` entries must be URLs — `github_repo_slug` requires a /// parseable `https` URL, and anything else fails later with `relative URL /// without a base`. A value that is not a URL is therefore dead today, so /// reading it as a path relative to the config file that declared it is a pure /// widening: it lets a registry committed alongside the project be referenced /// portably, without changing any config that works now. See discussion #4306. /// /// Returns `None` when the value should be left as written. fn resolve_registry_source(value: &str, config_root: &Path) -> Option { let looks_like_path = match Url::parse(value) { Err(_) => true, // A Windows path such as `C:\registry.yaml` parses as a URL whose scheme // is the drive letter. No real URL scheme is a single character. Ok(url) => url.scheme().len() == 1, }; if !looks_like_path { return None; } // Joining an absolute path returns it unchanged, so absolute entries are // normalized rather than rebased onto the config root. let joined = config_root.join(value); let absolute = joined .absolutize() .map(|p| p.into_owned()) .unwrap_or(joined); // Leave the value alone if it cannot be expressed as a file URL rather than // substituting something the user did not write. Url::from_file_path(&absolute).ok().map(String::from) } /// Rewrite relative `aqua.registries` entries so they resolve against the config /// root of the file that declared them. Both `aqua.registries = [..]` under /// `[settings]` and `[settings.aqua]` + `registries = [..]` parse to the same /// nested table, so navigating the table covers either spelling. fn resolve_aqua_registry_paths(settings: &mut toml::Table, path: &Path) { let Some(registries) = settings .get_mut("aqua") .and_then(toml::Value::as_table_mut) .and_then(|aqua| aqua.get_mut("registries")) .and_then(toml::Value::as_array_mut) else { return; }; let config_root = crate::config::config_file::config_root::config_root(path); let declared_by_global = crate::config::is_global_config(path); for entry in registries.iter_mut() { if let Some(value) = entry.as_str() && let Some(resolved) = resolve_registry_source(value, &config_root) { *entry = toml::Value::String(resolved); } if let Some(file) = entry .as_str() .and_then(|value| Url::parse(value).ok()) .filter(|url| url.scheme() == "file") .and_then(|url| url.to_file_path().ok()) { record_local_aqua_registry(file, declared_by_global); } } } /// Local `aqua.registries` files, by whether a project config names them /// (`true`) or only global or system config does (`false`). static LOCAL_AQUA_REGISTRIES: Lazy>> = Lazy::new(Default::default); fn record_local_aqua_registry(file: PathBuf, declared_by_global: bool) { let mut registries = LOCAL_AQUA_REGISTRIES.lock().unwrap(); let by_project = registries.entry(file).or_insert(!declared_by_global); // Global config trusts what it names by path, as it is itself. if declared_by_global { *by_project = false; } } /// Whether a local aqua registry file was named by a project config rather /// than by global or system config. Paranoid mode binds a project config's /// trust to its own content, which does not cover a registry file that can /// change without it, so such a file needs trust of its own there. /// /// An entry may name a directory, which the reader looks up `registry.yaml` or /// `registry.yml` in, so the nearest recorded ancestor of `file` decides. pub(crate) fn local_aqua_registry_needs_trust(file: &Path) -> bool { let registries = LOCAL_AQUA_REGISTRIES.lock().unwrap(); file.ancestors() .find_map(|path| registries.get(path).copied()) .unwrap_or(false) } /// Resolve task discovery exclusions while the settings file that declared them is still known. /// Once settings layers are merged, a relative `PathBuf` no longer carries enough information to /// distinguish two config roots. fn resolve_task_disable_paths(settings: &mut toml::Table, path: &Path) { let config_root = crate::config::config_file::config_root::config_root(path); let resolve = |paths: &mut Vec| { for entry in paths { let Some(value) = entry.as_str() else { continue; }; let value = Path::new(value); if value.is_absolute() || value == Path::new("~") || value.starts_with("~/") { continue; } let joined = config_root.join(value); let resolved = joined .absolutize() .map(|path| path.into_owned()) .unwrap_or(joined); *entry = toml::Value::String(resolved.to_string_lossy().into_owned()); } }; if let Some(paths) = settings .get_mut("task") .and_then(toml::Value::as_table_mut) .and_then(|task| task.get_mut("disable_paths")) .and_then(toml::Value::as_array_mut) { resolve(paths); } if let Some(paths) = settings .get_mut("task_disable_paths") .and_then(toml::Value::as_array_mut) { resolve(paths); } } /// Build a resolver for path settings declared in the settings file at `path`. /// /// The returned closure takes a `label` (e.g. `settings.age.key_file`) and a TOML value. It /// renders the value as a tera template (`config_root`, `xdg_config_home`, ...), then joins a /// relative result to `base`. Absolute and `~/` paths are kept as written. Render errors name /// `label` and the file. fn settings_path_resolver<'a>( path: &'a Path, base: PathBuf, ) -> impl FnMut(&str, &mut toml::Value) -> Result<()> + 'a { let config_root = crate::config::config_file::config_root::config_root(path); let mut tera = crate::tera::get_miserc_tera(); let mut context = tera::Context::new(); context.insert("env", &*env::PRISTINE_ENV); context.insert("config_root", &config_root.to_string_lossy()); context.insert( "config_source", &crate::config::config_file::config_root::config_source(path), ); if let Ok(cwd) = std::env::current_dir() { context.insert("cwd", &cwd.to_string_lossy()); } context.insert("xdg_cache_home", &env::XDG_CACHE_HOME.to_string_lossy()); context.insert("xdg_config_home", &env::XDG_CONFIG_HOME.to_string_lossy()); context.insert("xdg_data_home", &env::XDG_DATA_HOME.to_string_lossy()); context.insert("xdg_state_home", &env::XDG_STATE_HOME.to_string_lossy()); context.insert("mise_config_dir", &env::MISE_CONFIG_DIR.to_string_lossy()); context.insert("system_brew_prefix", &env::system_brew_prefix()); move |label: &str, target: &mut toml::Value| -> Result<()> { let Some(value) = target.as_str() else { return Ok(()); }; let rendered = if crate::tera::contains_template_syntax(value) { // Safe mode never applies a project's [settings]; commands such as // `mise settings` that parse every discovered file do not render // its templates either. The template stays as written, so only // this setting goes unresolved and the file's others still show. if Settings::safe_mode() && !crate::config::is_global_config(path) { warn_while_loading_settings(format!( "not rendering {label} in {}: safe mode does not render templates from project config; run without MISE_SAFE to show it", file::display_path(path) )); return Ok(()); } crate::tera::render_config_str(&mut tera, value, &context, path).map_err(|err| { eyre!( "failed to render {label} in {}: {err}", file::display_path(path) ) })? } else { value.to_string() }; let rendered_path = Path::new(&rendered); let resolved = if rendered_path.is_absolute() || rendered_path == Path::new("~") || rendered_path.starts_with("~/") { rendered_path.to_path_buf() } else { let joined = base.join(rendered_path); joined .absolutize() .map(|p| p.into_owned()) .unwrap_or(joined) }; *target = toml::Value::String(resolved.to_string_lossy().into_owned()); Ok(()) } } /// Resolve age identity paths while the settings file that declared them is /// still known. Once settings layers are merged, a relative `PathBuf` no /// longer carries enough information to distinguish two config roots. fn resolve_age_paths(settings: &mut toml::Table, path: &Path) -> Result<()> { let Some(age) = settings.get_mut("age").and_then(toml::Value::as_table_mut) else { return Ok(()); }; let config_root = crate::config::config_file::config_root::config_root(path); let mut resolve = settings_path_resolver(path, config_root); if let Some(key_file) = age.get_mut("key_file") { resolve("settings.age.key_file", key_file)?; } for setting in ["identity_files", "ssh_identity_files"] { if let Some(values) = age.get_mut(setting).and_then(toml::Value::as_array_mut) { for value in values { resolve(&format!("settings.age.{setting}"), value)?; } } } Ok(()) } /// Render templates in `dotfiles.root`, such as `{{ mise_config_dir }}/home`, so a dotfiles /// repository adopted as the global config can keep its sources beside it. A plain path is left /// as written, keeping the process-relative behavior of a root without a template. fn resolve_dotfiles_root_path(settings: &mut toml::Table, path: &Path) { let Some(root) = settings .get_mut("dotfiles") .and_then(toml::Value::as_table_mut) .and_then(|dotfiles| dotfiles.get_mut("root")) else { return; }; if !root .as_str() .is_some_and(crate::tera::contains_template_syntax) { return; } let config_root = crate::config::config_file::config_root::config_root(path); // A render error must not drop the file's other settings. The unrendered template is left in // place, so the dotfiles sources fail to resolve and name it. if let Err(err) = settings_path_resolver(path, config_root)("settings.dotfiles.root", root) { warn_while_loading_settings(format!("{err}")); } } /// Resolve `write_targets` paths against the config root of the declaring settings file, for the /// same reason as [`resolve_age_paths`]. Templates such as `{{ xdg_config_home }}` let dotfiles /// shared between machines name a global fragment without hardcoding the config directory. fn resolve_write_target_paths(settings: &mut toml::Table, path: &Path) { let Some(targets) = settings .get_mut("write_targets") .and_then(toml::Value::as_table_mut) else { return; }; let config_root = crate::config::config_file::config_root::config_root(path); let mut resolve = settings_path_resolver(path, config_root); for section in ["tools", "packages", "dotfiles"] { if let Some(target) = targets.get_mut(section) && let Err(err) = resolve(&format!("settings.write_targets.{section}"), target) { // Dropping the whole settings layer would silently send global writes to the // default file. The unrendered template is not an absolute path, so the write // fails in `configured_global_write_path` instead. warn_while_loading_settings(format!("{err}")); } } } /// mise behavior layered on the generated [`Settings`] type, which lives in the /// `mise-settings` crate. pub trait SettingsExt: Sized { /// Returns true only when `--yes` was explicitly supplied on this command /// line, excluding implicit confirmation from CI mode or configuration. fn cli_yes() -> bool; fn warn_default_package_file_deprecated(id: &'static str, package_type: &str); fn all_compile(&self) -> bool; fn node_compile(&self, purpose: CompilePurpose) -> Option; /// The `compile` setting for a lock target that is not the current platform. The distro /// default of `all_compile` describes the host generating the lock, not the target, so only /// explicit settings apply. fn explicit_compile(&self, compile: Option) -> Option; fn python_compile(&self, purpose: CompilePurpose) -> Option; fn erlang_compile(&self, purpose: CompilePurpose) -> Option; fn ruby_compile(&self, purpose: CompilePurpose) -> Option; /// The log level the parsed CLI flags ask for, without a full settings build. /// /// [`Self::try_get`] can keep failing once the CLI flags are part of it — `--cd` naming a /// directory that `validate_cd_path` accepts but the `chdir` refuses is the case `Cli::run` /// propagates — and from then on no build succeeds. A caller that only knows how to give up /// would be left holding the level from before the flags were parsed, and anything printed /// from there on ignores `--quiet`. /// /// `None` when the flags said nothing about verbosity: the level already in force came from a /// build that worked, and that build could see the config files this cannot. Only when the CLI /// does speak is it worth answering, and then it outranks them anyway. fn cli_log_level() -> Option; /// Initialize a Git credential subprocess without reading project settings. fn init_git_credential() -> Result<()>; /// Select process-wide query isolation before parsing can trigger lazy settings or miserc reads. fn select_package_query_sources(); /// Report whether this invocation requires environment-only settings and local diagnostics. fn is_package_query() -> bool; /// Apply CLI overrides and validate environment settings after query isolation is selected. fn init_package_query(cli: SettingsPartial) -> Result<()>; fn flush_pending_warnings(); /// Flush without waiting for CLI settings, for a path that is about to leave. /// /// Startup queues warnings before the logger exists and only flushes them once CLI flags are /// known — but several steps in between can fail first, and a diagnostic that was queued and /// never flushed is worse than one printed a moment early. fn flush_pending_warnings_before_exit(); /// Install the settings layer the command-line flags set (see `Cli::settings_layer`). fn add_cli_matches(cli: SettingsPartial); fn parse_settings_file(path: &Path) -> Result; fn reset(cli_settings: Option); /// Rebuild settings from config files without discarding CLI overrides. /// /// Builds the new settings before swapping them in, so readers on other threads never /// find the cache empty, and a build that fails leaves the previous settings in place and /// reports why. Emptying the cache instead would only defer the failure to the next /// `Settings::get()`, which can do nothing but unwrap it — and release builds abort on a /// panic, so a bad setting would end a `mise install` with a SIGABRT and a core dump /// rather than an error message. fn reload() -> Result<()>; /// Merge an override into the CLI-level settings partial. /// /// `reset` replaces CLI_SETTINGS wholesale, which would clobber overrides /// installed earlier in startup (`--offline`, `--quiet`, etc.). This /// helper merges in-place so a subcommand flag (e.g. `mise ls-remote /// --prerelease`) can layer on top of those without losing them, then /// rebuilds the settings with the override applied, like [`Self::reload`]. /// A rebuild that fails puts the CLI layer back as it was, so the override /// it could not apply is not waiting for the next reload to pick up. fn override_with(updater: impl FnOnce(&mut SettingsPartial)) -> Result<()>; /// Returns configured lockfile platforms parsed into Platform structs, or None for defaults. /// Errors on invalid platform strings (same validation as `mise lock --platform`). fn lockfile_platforms(&self) -> Result>>; /// The `trusted_config_paths` entries as written (with `~` expanded), without touching the /// filesystem. Entries that are not absolute are left out with a warning: they trust nothing. fn trusted_config_paths_as_written(&self) -> impl Iterator + '_; /// The `trusted_config_paths` entries that exist, canonicalized. fn trusted_config_paths(&self) -> impl Iterator + '_; fn global_tools_file(&self) -> PathBuf; fn system_installs_dir(&self) -> &Path; fn env_files(&self) -> Vec; fn as_dict(&self) -> eyre::Result; fn cache_prune_age_duration(&self) -> Option; /// How long a tracked config or tool stub may go unused before mise /// forgets it, or `None` to keep it until the file is deleted. fn prune_forget_unused_after_duration(&self) -> eyre::Result>; fn upgrade_prune_after_duration(&self) -> eyre::Result; fn tool_update_check_duration(&self) -> eyre::Result; #[cfg(feature = "self_update")] fn self_update_check_duration(&self) -> eyre::Result; fn fetch_remote_versions_timeout(&self) -> Duration; /// duration that remote version cache is kept for /// for "fast" commands (represented by PREFER_OFFLINE), these are always /// cached. For "slow" commands like `mise ls-remote` or `mise install`: /// - if MISE_FETCH_REMOTE_VERSIONS_CACHE is set, use that /// - if MISE_FETCH_REMOTE_VERSIONS_CACHE is not set, use HOURLY fn fetch_remote_versions_cache(&self) -> Option; fn http_timeout(&self) -> Duration; fn http_download_timeout(&self) -> Duration; /// Fast-path commands should make at most one network attempt before falling /// back to cached/local behavior. In particular, shims must not multiply a /// stalled resolver timeout by the configured retry count. fn http_retries(&self) -> i64; /// Returns true if offline mode is enabled via setting or CLI flag/env var. fn offline(&self) -> bool; /// Returns true if prefer-offline mode is enabled via setting, env var, or /// because the current command is a "fast" command (hook-env, activate, etc.). /// Also returns true if offline mode is enabled (offline implies prefer-offline). fn prefer_offline(&self) -> bool; fn env_cache_ttl(&self) -> Duration; fn aqua_registry_cache_ttl(&self) -> Duration; fn registry_cache_ttl(&self) -> Duration; fn task_timeout_duration(&self) -> Option; fn task_lock_timeout_duration(&self) -> Option; fn default_inline_shell(&self) -> Result>; /// Explicitly selecting even the default value expresses intent to run a /// shell. Cache provenance separately from the resolved string value. fn implicit_inline_shell(&self) -> bool; fn default_file_shell(&self) -> Result>; /// Inject `-NoProfile` into a PowerShell shell command when /// `windows_powershell_no_profile` is enabled. No-op for other shells. fn maybe_no_profile(&self, shell: &mut Vec); fn no_config() -> bool; fn no_env() -> bool; fn no_hooks() -> bool; /// Whether safe mode (`MISE_SAFE=1` or the `safe` setting) is active. /// /// Safe to call during the config parse pass: it reads the loaded setting /// when settings are available, otherwise falls back to the `MISE_SAFE` /// environment variable. This avoids triggering a recursive settings load /// from `trust_check` (which runs while config files are being parsed, /// before settings are loaded, e.g. after `Config::reset`). `safe` is /// global-only, so it can only come from the environment or global config; /// the env fallback covers the common `MISE_SAFE=1` case in that window. fn safe_mode() -> bool; /// Errors when safe mode (`MISE_SAFE=1`) is enabled. Call this before any /// operation that would execute code controlled by project configuration. /// Safe mode is a security boundary: blocked operations must fail loudly, /// never silently fall back to something that executes. fn ensure_not_safe(operation: &str) -> Result<()>; } impl SettingsExt for Settings { fn cli_yes() -> bool { Self::cli_yes_from(CLI_SETTINGS.lock().unwrap().as_ref()) } fn warn_default_package_file_deprecated(id: &'static str, package_type: &str) { if SETTINGS_META .get(id) .is_some_and(|m| m.deprecated.is_some()) { warn_deprecated(id); return; } deprecated_at!( "2026.11.0", "2027.11.0", id, "Default {package_type} files are deprecated. Use tool-level postinstall hooks for packages that should be installed into every runtime version, or use package manager backends such as npm:, pypi:, gem:, or go: for CLI tools." ); } fn all_compile(&self) -> bool { self.all_compile.unwrap_or_else(|| { !mise_util::testing::in_tests() && default_all_compile(env::LINUX_DISTRO.as_ref().map(|distro| distro.as_str())) }) } fn node_compile(&self, purpose: CompilePurpose) -> Option { self.compile_setting(purpose, "node", self.node.compile) } fn explicit_compile(&self, compile: Option) -> Option { explicit_compile_setting(self.all_compile, compile) } fn python_compile(&self, purpose: CompilePurpose) -> Option { self.compile_setting(purpose, "python", self.python.compile) } fn erlang_compile(&self, purpose: CompilePurpose) -> Option { self.compile_setting(purpose, "erlang", self.erlang.compile) } fn ruby_compile(&self, purpose: CompilePurpose) -> Option { self.compile_setting(purpose, "ruby", self.ruby.compile) } fn cli_log_level() -> Option { let cli = CLI_SETTINGS.lock().unwrap().clone()?; // `add_cli_matches` folds `--trace`/`--debug`/`-vv` into `log_level`, and `--silent` into // `quiet`, so these four cover every flag that moves the level. if cli.quiet.is_none() && cli.silent.is_none() && cli.log_level.is_none() && cli.verbose.is_none() { return None; } // Environment-only: the CLI layer plus `MISE_*`. It skips config discovery, which is both // what makes it survive the failure that sent us here and why its answer is a fallback // rather than the real one. let mut settings = Self::load_sources_from(None, SettingsLoadPolicy::ENVIRONMENT_ONLY).ok()?; normalize_verbosity(&mut settings); Some(settings.log_level()) } fn init_git_credential() -> Result<()> { super::miserc::init_global_only(); let mut builder = Self::builder().env(); // Reuse operator-owned authentication settings, including the OAuth // client ID needed to locate cached tokens. Never discover project files. let paths = super::override_config_files() .into_iter() .rev() .chain(super::global_config_files().into_iter().rev()) .chain(super::system_config_files().into_iter().rev()); for path in paths { if let Ok(settings) = Self::parse_settings_file(&path) { let mut layer = SettingsPartial::empty(); layer.github = settings.github; builder = builder.preloaded(layer); } } let settings = builder.load()?; mise_settings::store(Arc::new(settings)); Ok(()) } fn select_package_query_sources() { PACKAGE_QUERY_SETTINGS.store(true, Ordering::Relaxed); } fn is_package_query() -> bool { PACKAGE_QUERY_SETTINGS.load(Ordering::Relaxed) } fn init_package_query(cli: SettingsPartial) -> Result<()> { Self::add_cli_matches(cli); Self::try_get()?; Ok(()) } fn flush_pending_warnings() { if CLI_SETTINGS.lock().unwrap().is_none() { return; } Self::flush_pending_warnings_now(); } fn flush_pending_warnings_before_exit() { Self::flush_pending_warnings_now(); } fn add_cli_matches(cli: SettingsPartial) { // Don't process mise-specific flags when running as a shim let cli = if *crate::env::IS_RUNNING_AS_SHIM { SettingsPartial::empty() } else { cli }; // Startup builds the settings once before it parses the flags, with no CLI layer. Flags // that set nothing leave that build as it is: rebuilding would read the same files and // environment for the same result, and drop the installed-tool state read since. let mut current = CLI_SETTINGS.lock().unwrap(); if cli.is_empty() && current.is_none() && mise_settings::is_loaded() { *current = Some(cli); return; } drop(current); Self::reset(Some(cli)); } fn parse_settings_file(path: &Path) -> Result { let raw = file::read_config_to_string(path)?; let mut raw: toml::Value = toml::from_str(&raw).map_err(|err| { crate::config::config_file::diagnostic::hide_linked_source(err, &raw, path) })?; let tera_v1_from_env = tera_v1_from_env_config(&raw); if let Some(settings) = raw.get_mut("settings").and_then(toml::Value::as_table_mut) { strip_local_only_settings(settings, path, crate::config::is_global_config(path)); strip_env_only_settings(settings, path); // After the strips, so a setting that will not survive them is // never rewritten. resolve_aqua_registry_paths(settings, path); resolve_age_paths(settings, path)?; resolve_dotfiles_root_path(settings, path); resolve_write_target_paths(settings, path); resolve_task_disable_paths(settings, path); } if let Some(settings) = raw.get_mut("settings").and_then(toml::Value::as_table_mut) { for leaf in ["uvx", "registry_url"] { let legacy = settings .get("pipx") .and_then(|value| value.get(leaf)) .cloned(); if let Some(legacy) = legacy { let preferred = settings .entry("pypi") .or_insert_with(|| toml::Value::Table(toml::Table::new())); if let Some(preferred) = preferred.as_table_mut() { if preferred.get(leaf).is_some_and(|value| value != &legacy) { continue; } preferred.insert(leaf.to_owned(), legacy); if let Some(legacy) = settings.get_mut("pipx").and_then(toml::Value::as_table_mut) { legacy.remove(leaf); } } } } } let deprecated = deprecated_settings_in_toml_config(&raw); let settings_file: SettingsFile = raw.try_into()?; queue_deprecated_settings(deprecated); let mut settings = normalize_hidden_config_aliases(settings_file.settings); if settings.tera_v1.is_none() { settings.tera_v1 = tera_v1_from_env; } Ok(settings) } fn reset(cli_settings: Option) { *EXPLICIT_INLINE_SHELL.write().unwrap() = None; *CLI_SETTINGS.lock().unwrap() = cli_settings; mise_settings::clear(); // Clear caches that depend on settings and environment crate::config::config_file::config_root::reset(); crate::toolset::install_state::reset_tools(); TRUSTED_PATHS_RESOLVED.lock().unwrap().clear(); } fn reload() -> Result<()> { *EXPLICIT_INLINE_SHELL.write().unwrap() = None; crate::config::config_file::config_root::reset(); crate::toolset::install_state::reset_tools(); TRUSTED_PATHS_RESOLVED.lock().unwrap().clear(); rebuild() } fn override_with(updater: impl FnOnce(&mut SettingsPartial)) -> Result<()> { *EXPLICIT_INLINE_SHELL.write().unwrap() = None; let mut lock = CLI_SETTINGS.lock().unwrap(); let previous = lock.clone(); updater(lock.get_or_insert_with(SettingsPartial::empty)); drop(lock); crate::toolset::install_state::reset_tools(); TRUSTED_PATHS_RESOLVED.lock().unwrap().clear(); let result = rebuild(); if result.is_err() { *CLI_SETTINGS.lock().unwrap() = previous; } result } fn lockfile_platforms(&self) -> Result>> { match &self.lockfile_platforms { Some(platforms) if !platforms.is_empty() => { Ok(Some(Platform::parse_multiple(platforms)?)) } _ => Ok(None), } } fn trusted_config_paths_as_written(&self) -> impl Iterator + '_ { self.trusted_config_paths .iter() .filter(|p| !p.to_string_lossy().is_empty()) .map(file::replace_path) // A relative entry would resolve against the current directory, which may be a // repository that must not choose what mise trusts. .filter(|p| { if !p.is_absolute() { warn_while_loading_settings(format!( "ignoring trusted_config_paths entry {}: it must be an absolute path or start with ~/", crate::ui::style::display_path_escaped(p) )); } p.is_absolute() }) } fn trusted_config_paths(&self) -> impl Iterator + '_ { self.trusted_config_paths_as_written().filter_map(|p| { if let Some(resolved) = TRUSTED_PATHS_RESOLVED.lock().unwrap().get(&p) { return resolved.clone(); } // Not `canonicalize_cached`: its own process-wide cache would survive a reset and // keep a symlink entry pointing at its old target. let resolved = p.canonicalize().ok(); TRUSTED_PATHS_RESOLVED .lock() .unwrap() .insert(p, resolved.clone()); resolved }) } fn global_tools_file(&self) -> PathBuf { env::var_path("MISE_GLOBAL_CONFIG_FILE") .or_else(|| env::var_path("MISE_CONFIG_FILE")) .unwrap_or_else(|| { if self.asdf_compat { env::HOME.join(&*env::MISE_DEFAULT_TOOL_VERSIONS_FILENAME) } else { dirs::CONFIG.join("config.toml") } }) } fn system_installs_dir(&self) -> &Path { dirs::system_installs_dir(self) } fn env_files(&self) -> Vec { let mut files = vec![]; if let Some(cwd) = &*dirs::CWD && let Some(env_file) = &self.env_file { let names = env_file .iter() .map(|name| name.to_string_lossy().to_string()) .collect::>(); // An absolute name matches in every directory, so keep only its first (nearest) // occurrence. Reversed below, the loader would otherwise see it at the farthest // directory and let a nearer `.env` override a file the user listed after it. let mut seen = HashSet::new(); for p in FindUp::new(cwd, &names) { if seen.insert(p.clone()) { files.push(p); } } } files.into_iter().rev().collect() } fn as_dict(&self) -> eyre::Result { let s = toml::to_string(self)?; let mut table: toml::Table = toml::from_str(&s)?; table.insert( "all_compile".to_string(), toml::Value::Boolean(self.all_compile()), ); redact_settings_table(&mut table); Ok(table) } fn cache_prune_age_duration(&self) -> Option { let age = duration::parse_duration(&self.cache_prune_age).unwrap(); // Exactly `0s` is the documented way to keep cache files indefinitely. // Truncating to whole seconds would give a sub-second age that meaning // instead of the aggressive prune it asks for. if age.is_zero() { None } else { Some(age) } } fn prune_forget_unused_after_duration(&self) -> eyre::Result> { let age = duration::parse_duration(&self.prune.forget_unused_after)?; Ok((!age.is_zero()).then_some(age)) } fn upgrade_prune_after_duration(&self) -> eyre::Result { duration::parse_duration(&self.upgrade.prune_after) } fn tool_update_check_duration(&self) -> eyre::Result { duration::parse_duration(&self.tool_update.check_duration) } #[cfg(feature = "self_update")] fn self_update_check_duration(&self) -> eyre::Result { let interval = self.self_update.auto.interval(); duration::parse_duration(interval.unwrap_or(&self.self_update.check_duration)) } fn fetch_remote_versions_timeout(&self) -> Duration { network::fetch_remote_versions_timeout(self) } fn fetch_remote_versions_cache(&self) -> Option { network::fetch_remote_versions_cache(self) } fn http_timeout(&self) -> Duration { network::http_timeout(self) } fn http_download_timeout(&self) -> Duration { network::http_download_timeout(self) } fn http_retries(&self) -> i64 { network::http_retries(self) } fn offline(&self) -> bool { network::offline(self) } fn prefer_offline(&self) -> bool { network::prefer_offline(self) } fn env_cache_ttl(&self) -> Duration { duration::parse_duration(&self.env_cache_ttl).unwrap() } fn aqua_registry_cache_ttl(&self) -> Duration { self.aqua .registry_cache_ttl .as_deref() .map(duration::parse_duration) .transpose() .unwrap() .unwrap_or(crate::aqua::aqua_registry_wrapper::DEFAULT_AQUA_REGISTRY_CACHE_TTL) } fn registry_cache_ttl(&self) -> Duration { self.registry_cache_ttl .as_deref() .map(duration::parse_duration) .transpose() .unwrap() .unwrap_or(duration::HOURLY) } fn task_timeout_duration(&self) -> Option { self.task .timeout .as_ref() .and_then(|s| duration::parse_duration(s).ok()) } fn task_lock_timeout_duration(&self) -> Option { self.task .lock_timeout .as_ref() .and_then(|s| duration::parse_duration(s).ok()) } fn default_inline_shell(&self) -> Result> { mise_util::shells::default_inline_shell(self) } fn implicit_inline_shell(&self) -> bool { if cfg!(windows) { return false; } if let Some(explicit) = *EXPLICIT_INLINE_SHELL.read().unwrap() { return !explicit; } let explicit = std::env::var_os("MISE_UNIX_DEFAULT_INLINE_SHELL_ARGS").is_some() || Self::cli_settings_layer() .unix_default_inline_shell_args .is_some() // The setting is global-only, so no project file can hold it, and // parsing a project file renders its templates: hooks and exec() // run from the prompt hook in a project that is not trusted. || Self::settings_layers_from(None, SettingsTrustPolicy::GlobalOnly) .iter() .any(|layer| layer.unix_default_inline_shell_args.is_some()); *EXPLICIT_INLINE_SHELL.write().unwrap() = Some(explicit); !explicit } fn default_file_shell(&self) -> Result> { mise_util::shells::default_file_shell(self) } fn maybe_no_profile(&self, shell: &mut Vec) { mise_util::shells::maybe_no_profile(self, shell) } fn no_config() -> bool { *env::MISE_NO_CONFIG || !*crate::env::IS_RUNNING_AS_SHIM && env::ARGS .read() .unwrap() .iter() .take_while(|a| *a != "--") .any(|a| a == "--no-config") } fn no_env() -> bool { *env::MISE_NO_ENV || !*crate::env::IS_RUNNING_AS_SHIM && env::ARGS .read() .unwrap() .iter() .take_while(|a| *a != "--") .any(|a| a == "--no-env") } fn no_hooks() -> bool { *env::MISE_NO_HOOKS || !*crate::env::IS_RUNNING_AS_SHIM && env::ARGS .read() .unwrap() .iter() .take_while(|a| *a != "--") .any(|a| a == "--no-hooks") } fn safe_mode() -> bool { if is_loaded() { return Settings::get().safe; } // Settings not loaded (e.g. the config parse pass after Config::reset). // Use the last settings that were cached, which capture `safe` set via // global config; before any load, fall back to the env var. match mise_settings::last_cached() { Some(settings) => settings.safe, None => crate::env::var_is_true("MISE_SAFE"), } } fn ensure_not_safe(operation: &str) -> Result<()> { if Settings::safe_mode() { bail!( "{operation} is disabled in safe mode (MISE_SAFE=1)\nSee https://mise.jdx.dev/configuration/settings.html#safe" ); } Ok(()) } } /// Loading steps shared by the methods of [`SettingsExt`] and [`load`]. trait SettingsInternal: Sized { /// Reads explicit confirmation only from the CLI settings layer. fn cli_yes_from(settings: Option<&SettingsPartial>) -> bool; fn compile_setting( &self, purpose: CompilePurpose, tool: &str, compile: Option, ) -> Option; fn cli_settings_layer() -> SettingsPartial; /// Load settings sources for an explicit root, or the current directory when `root` is `None`. /// /// This shares source ordering and file parsing with the normal settings load. It deliberately /// does not update process-global settings state or apply the post-load process side effects in /// [`Self::try_get`]. Root-specific callers can require trusted project files without /// reproducing config discovery or precedence rules. fn load_sources_from(root: Option<&Path>, policy: SettingsLoadPolicy) -> Result; /// Load eligible config-file settings layers in precedence order and combine settings whose /// semantics are additive across files. fn settings_layers_from( root: Option<&Path>, trust_policy: SettingsTrustPolicy, ) -> Vec; fn flush_pending_warnings_now(); fn normalize_pypi_aliases(&mut self) -> Result<()>; /// Sets deprecated settings to new names fn set_hidden_configs(&mut self); } impl SettingsInternal for Settings { fn cli_yes_from(settings: Option<&SettingsPartial>) -> bool { settings.and_then(|settings| settings.yes).unwrap_or(false) } fn compile_setting( &self, purpose: CompilePurpose, tool: &str, compile: Option, ) -> Option { if matches!(purpose, CompilePurpose::Install) { warn_implicit_all_compile_default_deprecated(tool, self.all_compile, compile); } effective_compile_setting(self.all_compile(), compile) } fn cli_settings_layer() -> SettingsPartial { normalize_hidden_config_aliases(CLI_SETTINGS.lock().unwrap().clone().unwrap_or_default()) } fn load_sources_from(root: Option<&Path>, policy: SettingsLoadPolicy) -> Result { let policy = if PACKAGE_QUERY_SETTINGS.load(Ordering::Relaxed) { SettingsLoadPolicy::ENVIRONMENT_ONLY } else { policy }; if policy.trust == SettingsTrustPolicy::TrustedOnly && !is_loaded() { bail!("trusted settings resolution requires the base settings to be loaded"); } let mut builder = Self::builder().preloaded(Self::cli_settings_layer()); if [ "MISE_PYPI_UVX", "MISE_PIPX_UVX", "MISE_PYPI_REGISTRY_URL", "MISE_PIPX_REGISTRY_URL", ] .iter() .any(|name| std::env::var_os(name).is_some()) { let mut env_aliases = Self::builder().preloaded(env_settings_layer()?).load()?; env_aliases.normalize_pypi_aliases()?; let mut alias_layer = SettingsPartial::default(); // Normalize the environment as its own source before layering it over files. if std::env::var_os("MISE_PYPI_UVX").is_some() || std::env::var_os("MISE_PIPX_UVX").is_some() { alias_layer.pypi.uvx = env_aliases.pypi.uvx; alias_layer.pipx.uvx = env_aliases.pypi.uvx; } if std::env::var_os("MISE_PYPI_REGISTRY_URL").is_some() || std::env::var_os("MISE_PIPX_REGISTRY_URL").is_some() { alias_layer.pypi.registry_url = env_aliases.pypi.registry_url.clone(); alias_layer.pipx.registry_url = env_aliases.pypi.registry_url; } builder = builder.preloaded(alias_layer); } if let Some(alias_layer) = self_update_env_alias_layer()? { builder = builder.preloaded(alias_layer); } builder = builder.preloaded(env_settings_layer()?); if policy.source == SettingsSourcePolicy::Hierarchy { for layer in Self::settings_layers_from(root, policy.trust) { if matches!((&layer.pypi.uvx, &layer.pipx.uvx), (Some(a), Some(b)) if a != b) || matches!((&layer.pypi.registry_url, &layer.pipx.registry_url), (Some(a), Some(b)) if a != b) { bail!("conflicting pypi and pipx settings in the same file"); } builder = builder.preloaded(layer); } builder = builder.preloaded(DEFAULT_SETTINGS.clone()); } let mut settings = builder.load()?; settings.normalize_pypi_aliases()?; normalize_storage_dirs(&mut settings)?; if let Some((pattern, err)) = mise_util::versions_host::invalid_exclude_pattern(&settings.versions_host_exclude) { bail!("settings.versions_host_exclude has an invalid pattern {pattern:?}: {err}"); } validate_settings_enum_values(&settings)?; settings.validate_string_choices()?; Ok(settings) } fn settings_layers_from( root: Option<&Path>, trust_policy: SettingsTrustPolicy, ) -> Vec { // In safe mode, ignore `[settings]` from project (non-global) config so // an untrusted repo cannot change mise's behavior during resolution // (e.g. disable verification, redirect a backend/registry). Global and // system config is operator-owned and still applies. let safe_mode = Settings::safe_mode(); let paths = match root { Some(root) => load_config_paths_from(root, &TOML_CONFIG_FILENAMES, false), None => load_config_paths(&TOML_CONFIG_FILENAMES, false), }; let mut layers = paths .into_iter() .filter(|path| !safe_mode || crate::config::is_global_config(path)) .filter(|path| match trust_policy { SettingsTrustPolicy::AsDiscovered => true, SettingsTrustPolicy::TrustedOnly => { let usable = crate::config::is_global_config(path) || crate::config::config_file::is_path_trusted(path); if !usable { debug!("ignoring settings in untrusted config: {}", path.display()); } usable } SettingsTrustPolicy::GlobalOnly => crate::config::is_global_config(path), }) // A global config may be a `.tool-versions` file, which holds no settings // and is not TOML. .filter(|path| { !matches!( super::config_file::detect_config_file_type_by_filename(path), Some(super::config_file::ConfigFileType::ToolVersions) ) }) .filter_map(|path| match parse_settings_file_once(&path) { Ok(config) => Some(config), Err(err) => { // Name the file. mise reads several settings files and two of them can fail // with byte-identical parser text, which leaves the reports // indistinguishable -- to the reader, and to the queue that collapses repeats. warn_while_loading_settings(format!( "Error loading settings file {}: {err}", file::display_path(&path) )); None } }) .collect::>(); merge_settings_file_layers(&mut layers); layers } fn flush_pending_warnings_now() { // Readiness is set under both queue locks so a producer cannot read "not ready" and then // insert into a set this call has already taken. let (pending_files, pending) = { let mut files = PENDING_SETTINGS_WARNINGS.lock().unwrap(); let mut deprecated = PENDING_DEPRECATED_SETTINGS.lock().unwrap(); WARNINGS_READY.store(true, Ordering::SeqCst); ( std::mem::take(&mut *files), std::mem::take(&mut *deprecated), ) }; // Outside the locks: these warn, and warning re-enters the queue helpers. warn_deprecated_env_settings(); for msg in pending_files { warn_once!("{msg}"); } for key in pending { warn_deprecated_now(key); } } fn normalize_pypi_aliases(&mut self) -> Result<()> { fn merge( preferred: &mut Option, legacy: &mut Option, name: &str, ) -> Result<()> { if let (Some(a), Some(b)) = (preferred.as_ref(), legacy.as_ref()) && a != b { eyre::bail!("conflicting pypi.{name} and pipx.{name} settings"); } if preferred.is_none() { *preferred = legacy.take(); } else { legacy.take(); } Ok(()) } merge( &mut self.pypi.registry_url, &mut self.pipx.registry_url, "registry_url", )?; merge(&mut self.pypi.uvx, &mut self.pipx.uvx, "uvx")?; self.pypi .registry_url .get_or_insert_with(|| "https://pypi.org/pypi/{}/json".to_owned()); Ok(()) } fn set_hidden_configs(&mut self) { if let Some(v) = self.install_before.take() { warn_deprecated("install_before"); if self.minimum_release_age.is_none() { self.minimum_release_age = Some(v); } } // Migrate task_* settings to task.* (must run before auto_install override below) if let Some(v) = self.task_disable_paths.take() && !v.is_empty() { warn_deprecated("task_disable_paths"); self.task.disable_paths.extend(v); } if let Some(v) = self.task_output.take() { warn_deprecated("task_output"); self.task.output = Some(v); } if let Some(v) = self.task_remote_no_cache { warn_deprecated("task_remote_no_cache"); self.task.remote_no_cache = Some(v); } if let Some(v) = self.task_run_auto_install { warn_deprecated("task_run_auto_install"); self.task.run_auto_install = v; } if let Some(v) = self.task_show_full_cmd { warn_deprecated("task_show_full_cmd"); self.task.show_full_cmd = v; } if let Some(v) = self.task_skip.take() && !v.is_empty() { warn_deprecated("task_skip"); self.task.skip.extend(v); } if let Some(v) = self.task_skip_depends { warn_deprecated("task_skip_depends"); self.task.skip_depends = v; } if let Some(v) = self.task_timeout.take() { warn_deprecated("task_timeout"); self.task.timeout = Some(v); } if let Some(v) = self.task_timings { warn_deprecated("task_timings"); self.task.timings = Some(v); } if !self.auto_install { self.exec_auto_install = false; self.not_found_auto_install = false; self.task.run_auto_install = false; } if let Some(go_default_packages_file) = &self.go_default_packages_file { self.go.default_packages_file = go_default_packages_file.clone(); } if let Some(go_download_mirror) = &self.go_download_mirror { self.go.download_mirror = go_download_mirror.clone(); } if let Some(go_repo) = &self.go_repo { self.go.repo = go_repo.clone(); } if let Some(go_set_gobin) = self.go_set_gobin { self.go.set_gobin = Some(go_set_gobin); } if let Some(go_set_gopath) = self.go_set_gopath { self.go.set_gopath = go_set_gopath; } if let Some(go_set_goroot) = self.go_set_goroot { self.go.set_goroot = go_set_goroot; } if let Some(go_skip_checksum) = self.go_skip_checksum { self.go.skip_checksum = go_skip_checksum; } if self.npm.bun { self.npm.package_manager = NpmPackageManager::Bun; } if self.shorthands_file.is_some() { warn_deprecated("shorthands_file"); } if let Some(registry_url) = self.aqua.registry_url.take() { warn_deprecated("aqua.registry_url"); if self.aqua.registries.is_none() { self.aqua.registries = Some(vec![registry_url]); } } } } /// Point [`Settings::try_get`] at [`load`]. Runs first thing in `main` and in the test /// harness's constructor, before anything reads settings. pub(crate) fn register_loader() { mise_settings::set_loader(load); } /// Build settings from every source and make them the ones [`Settings::get`] returns. /// /// On failure the settings cached so far stay current: the caller propagates the error, and /// nothing between here and the exit has to cope with an empty cache. fn rebuild() -> Result<()> { let settings = load().wrap_err("failed to reload settings")?; mise_settings::store(settings); Ok(()) } /// Build settings from every source. Registered with [`mise_settings::set_loader`], so /// [`Settings::try_get`] runs this, and caches the result, when nothing is cached. fn load() -> Result> { time!("try_get"); let _env_layer = SharedEnvLayer::start(); // Initial pass to obtain cd option let mut settings = Settings::load_sources_from(None, SettingsLoadPolicy::ENVIRONMENT_ONLY)?; time!("try_get load1"); if let Some(mut cd) = settings.cd { static ORIG_PATH: Lazy> = Lazy::new(env::current_dir); if cd.is_relative() { cd = ORIG_PATH.as_ref()?.join(cd); } env::set_current_dir(cd)?; } // Reload settings after current directory option processed. A project's `[settings]` can // repoint downloads and build commands, so they apply only once that project is trusted, // just like its `[tools]` and `[env]`. Deciding trust reads a few settings of its own, so // publish the ones no project file can influence first. let previous = mise_settings::is_loaded() .then(mise_settings::last_cached) .flatten(); // The files parsed below record their ignored write targets again, so a reload forgets one a // project no longer sets. A failed load keeps the records that match the kept settings. let previous_ignored_write_targets = std::mem::take(&mut *IGNORED_WRITE_TARGETS.lock().unwrap()); LOAD_PARSE_CACHE.set(Some(ParseCache::new())); let bootstrap = Settings::load_sources_from(None, SettingsLoadPolicy::GLOBAL_HIERARCHY); let bootstrap = match bootstrap { Ok(bootstrap) => bootstrap, Err(err) => { LOAD_PARSE_CACHE.set(None); *IGNORED_WRITE_TARGETS.lock().unwrap() = previous_ignored_write_targets; return Err(err); } }; mise_settings::store(Arc::new(bootstrap)); BOOTSTRAPPING.store(true, Ordering::Relaxed); let trusted = Settings::load_sources_from(None, SettingsLoadPolicy::TRUSTED_HIERARCHY); BOOTSTRAPPING.store(false, Ordering::Relaxed); LOAD_PARSE_CACHE.set(None); settings = match trusted { Ok(settings) => settings, Err(err) => { // A failed reload keeps the settings that were current before it. match previous { Some(previous) => mise_settings::store(previous), None => mise_settings::clear(), } *IGNORED_WRITE_TARGETS.lock().unwrap() = previous_ignored_write_targets; return Err(err); } }; time!("try_get load2"); if !settings.legacy_version_file { settings.idiomatic_version_file = Some(false); } if settings.raw { settings.jobs = 1; } else { settings.jobs = crate::jobs::normalize(settings.jobs); } // Handle NO_COLOR environment variable if *env::NO_COLOR { settings.color = false; } normalize_verbosity(&mut settings); validate_auto_update("self_update.auto", &mut settings.self_update.auto); validate_auto_update( "tool_update.global_auto", &mut settings.tool_update.global_auto, ); if settings.python.uv_venv_auto.is_legacy_true() { deprecated_at!( "2026.7.0", "2027.7.0", "python.uv_venv_auto.true", "python.uv_venv_auto=true is deprecated. Use python.uv_venv_auto=\"create|source\" or \"source\" instead." ); } if !settings.generate_lockfiles() { warn_deprecated(LOCKFILE_MODE_MERGE); } if !settings.color { console::set_colors_enabled(false); console::set_colors_enabled_stderr(false); } else if *env::CLICOLOR_FORCE == Some(true) { console::set_colors_enabled(true); console::set_colors_enabled_stderr(true); } else if *env::CLICOLOR == Some(false) { console::set_colors_enabled(false); console::set_colors_enabled_stderr(false); } else if *mise_util::env::IS_CI && !mise_util::testing::in_tests() { console::set_colors_enabled_stderr(true); } if settings.ci { settings.yes = true; } if settings.gpg_verify.is_some() { settings.node.gpg_verify = settings.node.gpg_verify.or(settings.gpg_verify); settings.swift.gpg_verify = settings.swift.gpg_verify.or(settings.gpg_verify); } settings.set_hidden_configs(); if mise_util::testing::in_tests() { settings.experimental = true; } trace!("Settings: {:#?}", redacted_settings_for_debug(&settings)); let settings = Arc::new(settings); mise_tls::set_ipv4_only(settings.ipv4_only); mise_tls::set_extra_ca_certs( settings .extra_ca_certs .as_deref() .map(file::replace_path) .as_deref(), ); // Replace the bootstrap snapshot published above; the loader's own result is not cached // once the cache has changed underneath it. mise_settings::store(settings.clone()); let system_installs_changed = settings.system_installs_dir() != *env::MISE_SYSTEM_INSTALLS_DIR; if system_installs_changed { crate::toolset::install_state::reset_tools(); TRUSTED_PATHS_RESOLVED.lock().unwrap().clear(); } time!("try_get done"); Ok(settings) } fn redacted_settings_for_debug(settings: &Settings) -> Settings { let mut debug_settings = settings.clone(); for secret in [ &mut debug_settings.task.cache.remote_token, &mut debug_settings.task.cache_remote_token, &mut debug_settings.sops.age_key, ] { if secret.is_some() { *secret = Some("[redacted]".to_string()); } } debug_settings } pub(crate) const DEFAULT_NODE_MIRROR_URL: &str = "https://nodejs.org/dist/"; /// Node build settings that fall back to the environment variables node-build reads. pub(crate) trait SettingsNodeExt { fn mirror_url(&self) -> Url; fn ninja(&self) -> bool; fn concurrency(&self) -> Option; fn default_packages_file(&self) -> PathBuf; fn cflags(&self) -> Option; fn configure_opts(&self) -> Option; fn make_opts(&self) -> Option; fn make_install_opts(&self) -> Option; fn configure_cmd(&self, install_path: &Path) -> String; fn make_cmd(&self) -> String; fn make_install_cmd(&self) -> String; } impl SettingsNodeExt for SettingsNode { fn mirror_url(&self) -> Url { let s = self .mirror_url .clone() .or(env::var("NODE_BUILD_MIRROR_URL").ok()) .unwrap_or_else(|| DEFAULT_NODE_MIRROR_URL.to_string()); Url::parse(&s).unwrap() } fn ninja(&self) -> bool { self.ninja.unwrap_or_else(|| which::which("ninja").is_ok()) } fn concurrency(&self) -> Option { self.concurrency .map(|c| std::cmp::max(c, 1) as usize) .or_else(|| { if self.ninja() { None } else { Some(num_cpus::get_physical()) } }) } fn default_packages_file(&self) -> PathBuf { self.default_packages_file .clone() .or_else(|| { env::var("NODE_DEFAULT_PACKAGES_FILE") .ok() .map(PathBuf::from) }) .unwrap_or_else(|| { let p = env::HOME.join(".default-nodejs-packages"); if p.exists() { return p; } let p = env::HOME.join(".default-node-packages"); if p.exists() { return p; } env::HOME.join(".default-npm-packages") }) } fn cflags(&self) -> Option { self.cflags.clone().or_else(|| env::var("NODE_CFLAGS").ok()) } fn configure_opts(&self) -> Option { self.configure_opts .clone() .or_else(|| env::var("NODE_CONFIGURE_OPTS").ok()) } fn make_opts(&self) -> Option { self.make_opts .clone() .or_else(|| env::var("NODE_MAKE_OPTS").ok()) } fn make_install_opts(&self) -> Option { self.make_install_opts .clone() .or_else(|| env::var("NODE_MAKE_INSTALL_OPTS").ok()) } fn configure_cmd(&self, install_path: &Path) -> String { let mut configure_cmd = format!("./configure --prefix={}", install_path.display()); if self.ninja() { configure_cmd.push_str(" --ninja"); } if let Some(opts) = self.configure_opts() { configure_cmd.push_str(&format!(" {opts}")); } configure_cmd } fn make_cmd(&self) -> String { let mut make_cmd = self.make.clone().unwrap_or_else(|| "make".into()); if let Some(concurrency) = self.concurrency() { make_cmd.push_str(&format!(" -j{concurrency}")); } if let Some(opts) = self.make_opts() { make_cmd.push_str(&format!(" {opts}")); } make_cmd } fn make_install_cmd(&self) -> String { let make = self.make.clone().unwrap_or_else(|| "make".into()); let mut make_install_cmd = format!("{} install", make); if let Some(opts) = self.make_install_opts() { make_install_cmd.push_str(&format!(" {opts}")); } make_install_cmd } } #[cfg(test)] mod tests { use super::*; #[test] fn cli_yes_only_reads_the_cli_layer() { let mut cli = SettingsPartial::empty(); assert!(!Settings::cli_yes_from(Some(&cli))); cli.yes = Some(true); assert!(Settings::cli_yes_from(Some(&cli))); assert!(!Settings::cli_yes_from(None)); } /// Only `0s` keeps cache files indefinitely. A sub-second age is an /// aggressive prune, not a disabled one. #[test] fn only_a_zero_cache_prune_age_disables_pruning() { let age = |age: &str| { Settings { cache_prune_age: age.into(), ..Default::default() } .cache_prune_age_duration() }; assert_eq!(age("0s"), None); assert_eq!(age("500ms"), Some(Duration::from_millis(500))); assert_eq!(age("30d"), Some(Duration::from_secs(30 * 24 * 60 * 60))); } #[test] fn lockfile_mode_defaults_and_explicit_choices() { let mut settings = Settings::builder().load().unwrap(); assert!(settings.generate_lockfiles()); settings.lockfile_mode = "merge".into(); assert!(!settings.generate_lockfiles()); settings.lockfile_mode = "generate".into(); assert!(settings.generate_lockfiles()); assert!(validate_setting_choice("lockfile_mode", "merge").is_ok()); assert_eq!( validate_setting_choice("lockfile_mode", "invalid") .unwrap_err() .to_string(), "invalid lockfile_mode value \"invalid\"; expected one of: merge, generate" ); } #[test] fn test_validate_string_choices() { let mut settings = Settings::builder().load().unwrap(); assert!(settings.validate_string_choices().is_ok()); for value in ["never", "if_other_versions_installed", "always"] { settings.status.missing_tools = value.into(); assert!(settings.validate_string_choices().is_ok(), "{value}"); assert_eq!(settings.status.missing_tools().to_string(), value); } for value in ["exe", "file", "hardlink", "symlink"] { settings.windows_shim_mode = value.into(); assert!(settings.validate_string_choices().is_ok(), "{value}"); } settings.status.missing_tools = "sometimes".into(); assert_eq!( settings.validate_string_choices().unwrap_err().to_string(), "invalid status.missing_tools value \"sometimes\"; expected one of: never, if_other_versions_installed, always" ); // Never panics, even on settings that skipped validation. assert_eq!( settings.status.missing_tools(), SettingsStatusMissingTools::IfOtherVersionsInstalled ); settings.status.missing_tools = "always".into(); settings.windows_shim_mode = "copy".into(); assert_eq!( settings.validate_string_choices().unwrap_err().to_string(), "invalid windows_shim_mode value \"copy\"; expected one of: exe, file, hardlink, symlink" ); } /// File-backed exclusions are inherited in low-to-high precedence order and deduplicated. #[test] fn test_merge_minimum_release_age_excludes() { let mut local = SettingsPartial::empty(); local.minimum_release_age_excludes = Some(sv(&["local", "shared"])); let mut global = SettingsPartial::empty(); global.minimum_release_age_excludes = Some(sv(&["global", "shared"])); let unrelated = SettingsPartial::empty(); let mut layers = vec![local, unrelated, global]; merge_settings_file_layers(&mut layers); assert_eq!( layers[0].minimum_release_age_excludes, Some(sv(&["global", "shared", "local"])) ); assert!(layers[1].minimum_release_age_excludes.is_none()); assert!(layers[2].minimum_release_age_excludes.is_none()); } /// `normalize_verbosity` is the whole answer to "what level is this run at", and it is now /// reached from two places -- the settings load and `cli_log_level`. Pin the precedence so the /// two cannot drift apart. #[test] fn test_normalize_verbosity_quiet_lowers_the_level() { let mut settings = Settings { quiet: true, ..Default::default() }; normalize_verbosity(&mut settings); assert_eq!(settings.log_level, "error"); } #[test] fn test_normalize_verbosity_verbose_outranks_quiet() { let mut settings = Settings { quiet: true, verbose: true, ..Default::default() }; normalize_verbosity(&mut settings); assert_eq!(settings.log_level, "debug"); assert!(!settings.quiet); } #[test] fn test_normalize_verbosity_keeps_trace_above_verbose() { let mut settings = Settings { trace: true, verbose: true, ..Default::default() }; normalize_verbosity(&mut settings); assert_eq!(settings.log_level, "trace"); } #[test] fn default_all_compile_is_limited_to_alpine_and_deprecated_nixos_behavior() { assert!(default_all_compile(Some("alpine"))); assert!(default_all_compile(Some("nixos"))); assert!(!default_all_compile(Some("ubuntu"))); assert!(!default_all_compile(None)); } #[test] fn all_compile_preserves_unset_and_explicit_values() { let mut settings = Settings::default(); assert_eq!(settings.all_compile, None); assert!(!settings.all_compile()); assert_eq!( settings.as_dict().unwrap().get("all_compile"), Some(&toml::Value::Boolean(false)) ); settings.all_compile = Some(true); assert!(settings.all_compile()); assert_eq!( settings.as_dict().unwrap().get("all_compile"), Some(&toml::Value::Boolean(true)) ); settings.all_compile = Some(false); assert!(!settings.all_compile()); assert_eq!( settings.as_dict().unwrap().get("all_compile"), Some(&toml::Value::Boolean(false)) ); } #[test] fn explicit_compile_ignores_the_implicit_distro_default() { // The distro default is a resolved `all_compile` of true with nothing set explicitly. let distro_default = default_all_compile(Some("alpine")); assert!(distro_default); assert_eq!(effective_compile_setting(distro_default, None), Some(true)); assert_eq!(explicit_compile_setting(None, None), None); assert_eq!(explicit_compile_setting(None, Some(false)), Some(false)); assert_eq!(explicit_compile_setting(Some(true), None), Some(true)); assert_eq!( explicit_compile_setting(Some(true), Some(false)), Some(false) ); assert_eq!(explicit_compile_setting(Some(false), None), None); } #[test] fn compile_warning_only_applies_to_implicit_distro_values() { assert!(compile_inherits_distro_all_compile_default( Some("nixos"), "nixos", None, None )); assert!(!compile_inherits_distro_all_compile_default( Some("nixos"), "nixos", Some(true), None )); assert!(!compile_inherits_distro_all_compile_default( Some("nixos"), "nixos", Some(false), None )); assert!(!compile_inherits_distro_all_compile_default( Some("nixos"), "nixos", None, Some(true) )); assert!(!compile_inherits_distro_all_compile_default( Some("nixos"), "nixos", None, Some(false) )); assert!(!compile_inherits_distro_all_compile_default( Some("alpine"), "nixos", None, None )); assert!(compile_inherits_distro_all_compile_default( Some("alpine"), "alpine", None, None )); assert!(!compile_inherits_distro_all_compile_default( Some("alpine"), "alpine", Some(true), None )); assert!(!compile_inherits_distro_all_compile_default( Some("alpine"), "alpine", Some(false), None )); assert!(!compile_inherits_distro_all_compile_default( Some("alpine"), "alpine", None, Some(true) )); assert!(!compile_inherits_distro_all_compile_default( Some("alpine"), "alpine", None, Some(false) )); assert!(!compile_inherits_distro_all_compile_default( Some("nixos"), "alpine", None, None )); assert!(!compile_inherits_distro_all_compile_default( None, "nixos", None, None )); assert!(!compile_inherits_distro_all_compile_default( None, "alpine", None, None )); } #[test] fn effective_compile_prefers_tool_setting_then_global_source_setting() { assert_eq!(effective_compile_setting(true, None), Some(true)); assert_eq!(effective_compile_setting(false, None), None); assert_eq!(effective_compile_setting(true, Some(true)), Some(true)); assert_eq!(effective_compile_setting(true, Some(false)), Some(false)); } #[test] fn debug_settings_redact_remote_cache_token() { let mut settings = Settings::default(); settings.task.cache.remote_token = Some("super-secret-token".to_string()); settings.sops.age_key = Some("AGE-SECRET-KEY-1SECRET".to_string()); let debug = format!("{:?}", redacted_settings_for_debug(&settings)); assert!(!debug.contains("super-secret-token")); assert!(!debug.contains("AGE-SECRET-KEY-1SECRET")); assert!(debug.contains("[redacted]")); } #[test] fn settings_dictionary_redacts_the_age_key() { let mut settings = Settings::default(); settings.sops.age_key = Some("AGE-SECRET-KEY-1SECRET".to_string()); settings.sops.age_key_file = Some("/keys/age.txt".into()); let encoded = toml::to_string(&settings.as_dict().unwrap()).unwrap(); assert!(!encoded.contains("AGE-SECRET-KEY-1SECRET"), "{encoded}"); assert!(encoded.contains("/keys/age.txt"), "{encoded}"); } #[test] fn settings_dictionary_redacts_remote_cache_token() { let mut settings = Settings::default(); settings.task.cache.remote_token = Some("super-secret-token".to_string()); let table = settings.as_dict().unwrap(); let encoded = toml::to_string(&table).unwrap(); assert!(!encoded.contains("super-secret-token")); assert!(encoded.contains("[redacted]")); } #[test] fn settings_partial_dictionary_omits_empty_nested_groups() { let settings = toml::from_str::("[task.cache]") .unwrap() .as_table() .unwrap() .clone(); let partial = settings_partial_from_table(settings); assert!( !Settings::partial_as_dict(&partial) .unwrap() .contains_key("task") ); } #[test] fn settings_partial_dictionary_preserves_empty_map_values() { let settings = toml::from_str::("url_replacements = {}") .unwrap() .as_table() .unwrap() .clone(); let partial = settings_partial_from_table(settings); assert_eq!( Settings::partial_as_dict(&partial) .unwrap() .get("url_replacements"), Some(&toml::Value::Table(toml::Table::new())) ); } fn credential_command_settings_table() -> toml::Table { toml::from_str::( r#" [github] credential_command = "echo github-token" [gitlab] credential_command = "echo gitlab-token" [forgejo] credential_command = "echo forgejo-token" "#, ) .unwrap() .as_table() .unwrap() .clone() } fn default_shell_args_settings_table() -> toml::Table { toml::from_str::( r#" unix_default_file_shell_args = "malicious-unix-file-shell" unix_default_inline_shell_args = "malicious-unix-inline-shell" windows_default_file_shell_args = "malicious-windows-file-shell" windows_default_inline_shell_args = "malicious-windows-inline-shell" "#, ) .unwrap() .as_table() .unwrap() .clone() } fn settings_partial_from_table(settings: toml::Table) -> SettingsPartial { let mut root = toml::Table::new(); root.insert("settings".to_string(), toml::Value::Table(settings)); let settings_file: SettingsFile = toml::Value::Table(root).try_into().unwrap(); settings_file.settings } fn sv(v: &[&str]) -> Vec { v.iter().map(|s| s.to_string()).collect() } /// The shape #5791 reported: the setting is accepted into the file, so without this it /// survives into the partial and `mise settings get` echoes it back while the config /// loader — which already ran — never saw it. /// The global-only pass that bootstraps trust and the trusted pass after it both read the /// config files, but a file must only be parsed once per load, and reads outside a load /// must not be served from a cache. #[test] fn test_load_parses_each_settings_file_once() { let _settings = crate::test::SettingsGuard::lock(); let layers = || Settings::settings_layers_from(None, SettingsTrustPolicy::AsDiscovered); let parses = || PARSE_COUNTS.with_borrow(|counts| counts.values().sum::()); LOAD_PARSE_CACHE.set(Some(ParseCache::new())); let before = parses(); layers(); let first_pass = parses() - before; layers(); let second_pass = parses() - before - first_pass; LOAD_PARSE_CACHE.set(None); // The unit-test config directory always holds at least one settings file. assert!(first_pass >= 1, "no settings file was parsed"); assert_eq!(second_pass, 0, "the second pass re-parsed a cached file"); let before = parses(); layers(); assert_eq!( parses() - before, first_pass, "a read outside a load was cached" ); } /// A relative entry must not be looked up in the current directory, where `.` always /// exists and a repository can provide any other name. #[test] fn test_trusted_config_paths_ignores_relative_entries() { let _settings = crate::test::SettingsGuard::lock(); let dir = tempfile::tempdir().unwrap(); let absolute = dir.path().canonicalize().unwrap(); let mut partial = SettingsPartial::empty(); partial.trusted_config_paths = Some([PathBuf::from("."), absolute.clone()].into()); Settings::reset(Some(partial)); let settings = Settings::get(); assert_eq!( settings.trusted_config_paths_as_written().collect_vec(), vec![absolute.clone()] ); assert_eq!( settings.trusted_config_paths().collect_vec(), vec![absolute] ); } /// One load reads the environment's settings once for its three passes, and a load after /// it reads the environment again, so a variable changed in between takes effect. #[test] fn test_load_reads_the_environment_once() { let _settings = crate::test::SettingsGuard::lock(); let reads = || ENV_LAYER_READS.get(); let before = reads(); let settings = load(); assert!(settings.is_ok(), "{:?}", settings.err()); assert_eq!(reads() - before, 1); let before = reads(); let settings = load(); assert!(settings.is_ok(), "{:?}", settings.err()); assert_eq!( reads() - before, 1, "a later load reused the first one's read" ); let before = reads(); assert!(env_settings_layer().is_ok()); assert!(env_settings_layer().is_ok()); assert_eq!(reads() - before, 2, "a read outside a load was shared"); } /// `load` must open the cache for its two passes and close it afterwards, or the first /// settings reload after an edit would keep serving the old values. #[test] fn test_load_closes_its_parse_cache() { let _settings = crate::test::SettingsGuard::lock(); // Tests may share a thread (`RUST_TEST_THREADS=1`), so count only this load's parses. PARSE_COUNTS.with_borrow_mut(|counts| counts.clear()); let settings = load(); assert!(settings.is_ok(), "{:?}", settings.err()); assert!(LOAD_PARSE_CACHE.with_borrow(Option::is_none)); assert!(LOAD_ENV_LAYER.with_borrow(Option::is_none)); // Every file the real load touched was parsed exactly once. PARSE_COUNTS.with_borrow(|counts| { assert!(counts.values().all(|n| *n == 1), "{counts:?}"); }); } /// The shape #5791 reported: the setting is accepted into the file, so without this it /// survives into the partial and `mise settings get` echoes it back while the config /// loader — which already ran — never saw it. #[test] fn test_parse_settings_file_strips_env_only_settings() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [settings] default_config_filename = ".mise.toml" default_tool_versions_filename = ".tool-versions-custom" "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.default_config_filename, None); assert_eq!(partial.default_tool_versions_filename, None); } #[test] fn test_parse_settings_file_resolves_task_disable_paths_from_config_root() { let dir = tempfile::tempdir().unwrap(); let config_dir = dir.path().join(".mise"); std::fs::create_dir_all(&config_dir).unwrap(); let path = config_dir.join("config.toml"); let absolute = dir.path().join("absolute"); std::fs::write( &path, format!( r#" [settings.task] disable_paths = ["tasks/generated", '{}'] "#, absolute.display() ), ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!( partial.task.disable_paths, Some(BTreeSet::from([ dir.path().join("tasks/generated"), absolute, ])) ); } /// Unlike `global_only`, being in the *global* config does not rescue these — the loader /// has read the file by the time the value would be applied either way. #[test] fn test_parse_settings_file_strips_env_only_settings_from_global_too() { let mut settings = toml::Table::new(); settings.insert( "global_config_file".to_string(), toml::Value::String("/tmp/elsewhere.toml".to_string()), ); strip_env_only_settings(&mut settings, Path::new("/tmp/global-config.toml")); assert!(settings.get("global_config_file").is_none()); } #[test] fn test_parse_settings_file_strips_local_credential_commands() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [settings.github] credential_command = "echo github-token" [settings.gitlab] credential_command = "echo gitlab-token" [settings.forgejo] credential_command = "echo forgejo-token" "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.github.credential_command, None); assert_eq!(partial.gitlab.credential_command, None); assert_eq!(partial.forgejo.credential_command, None); } /// A repository must not name a host that then receives the GitHub token. #[test] fn test_parse_settings_file_strips_local_github_enterprise_hosts() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("mise.toml"); std::fs::write( &path, r#" [settings.github] enterprise_hosts = ["attacker.example"] "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.github.enterprise_hosts, None); } #[test] fn test_parse_settings_file_strips_local_history_describe_command() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [settings.history] describe_command = "cat dotfiles" "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.history.describe_command, None); } #[test] fn test_parse_settings_file_strips_local_self_update_sources() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("mise.toml"); std::fs::write( &path, r#" [settings.self_update] api_url = "https://github.example.com/api/v3" repository = "acme/mise" "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.self_update.api_url, None); assert_eq!(partial.self_update.repository, None); } #[test] fn test_quiet_ignored_settings_guard_nests() { assert!(!QuietIgnoredSettings::active()); { let _outer = QuietIgnoredSettings::new(); { let _inner = QuietIgnoredSettings::new(); assert!(QuietIgnoredSettings::active()); } assert!(QuietIgnoredSettings::active()); } assert!(!QuietIgnoredSettings::active()); } #[test] fn test_global_config_preserves_credential_commands() { let path = Path::new("/tmp/global-config.toml"); let mut settings = credential_command_settings_table(); strip_local_only_settings(&mut settings, path, true); let partial = settings_partial_from_table(settings); assert_eq!( partial.github.credential_command.as_deref(), Some("echo github-token") ); assert_eq!( partial.gitlab.credential_command.as_deref(), Some("echo gitlab-token") ); assert_eq!( partial.forgejo.credential_command.as_deref(), Some("echo forgejo-token") ); } #[test] fn test_global_config_preserves_history_describe_command() { let path = Path::new("/tmp/global-config.toml"); let mut settings = toml::from_str::( r#" [history] describe_command = "cat dotfiles" "#, ) .unwrap() .as_table() .unwrap() .clone(); strip_local_only_settings(&mut settings, path, true); let partial = settings_partial_from_table(settings); assert_eq!( partial.history.describe_command.as_deref(), Some("cat dotfiles") ); } #[test] fn test_local_config_records_ignored_write_targets() { let path = Path::new("/tmp/project-with-write-target/mise.toml"); let mut settings = toml::from_str::( r#" [write_targets] packages = "mise.toml" "#, ) .unwrap() .as_table() .unwrap() .clone(); strip_local_only_settings(&mut settings, path, false); let partial = settings_partial_from_table(settings); assert_eq!(partial.write_targets.packages, None); assert!(ignored_write_target("write_targets.packages").is_some()); } #[test] fn test_local_config_strips_default_shell_args() { let path = Path::new("/tmp/.mise.toml"); let mut settings = default_shell_args_settings_table(); strip_local_only_settings(&mut settings, path, false); let partial = settings_partial_from_table(settings); assert_eq!(partial.unix_default_file_shell_args, None); assert_eq!(partial.unix_default_inline_shell_args, None); assert_eq!(partial.windows_default_file_shell_args, None); assert_eq!(partial.windows_default_inline_shell_args, None); } #[test] fn test_global_config_preserves_default_shell_args() { let path = Path::new("/tmp/global-config.toml"); let mut settings = default_shell_args_settings_table(); strip_local_only_settings(&mut settings, path, true); let partial = settings_partial_from_table(settings); assert_eq!( partial.unix_default_file_shell_args.as_deref(), Some("malicious-unix-file-shell") ); assert_eq!( partial.unix_default_inline_shell_args.as_deref(), Some("malicious-unix-inline-shell") ); assert_eq!( partial.windows_default_file_shell_args.as_deref(), Some("malicious-windows-file-shell") ); assert_eq!( partial.windows_default_inline_shell_args.as_deref(), Some("malicious-windows-inline-shell") ); } #[test] fn test_parse_settings_file_strips_non_global_trust_controls() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [settings] ci = "true" paranoid = true trusted_config_paths = ["/"] yes = true "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.ci, None); assert_eq!(partial.paranoid, None); assert_eq!(partial.trusted_config_paths, None); assert_eq!(partial.yes, None); } #[test] fn test_parse_settings_file_reads_tera_v1_from_env_directive() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" env.MISE_TERA_V1 = true "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.tera_v1, Some(true)); } #[test] fn test_parse_settings_file_reads_tera_v1_from_env_value_directive() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [env] MISE_TERA_V1 = { value = "1" } "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.tera_v1, Some(true)); } #[test] fn test_parse_settings_file_prefers_explicit_tera_v1_setting() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(".mise.toml"); std::fs::write( &path, r#" [settings] tera_v1 = false [env] MISE_TERA_V1 = true "#, ) .unwrap(); let partial = Settings::parse_settings_file(&path).unwrap(); assert_eq!(partial.tera_v1, Some(false)); } /// Run the rewrite over a `[settings]` block and return the resulting /// `aqua.registries` entries, as `parse_settings_file` would see them. fn rewritten_registries(dir: &Path, body: &str) -> Vec { let mut settings = toml::from_str::(body).unwrap(); resolve_aqua_registry_paths(&mut settings, &dir.join(".mise.toml")); settings["aqua"]["registries"] .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap().to_string()) .collect() } /// discussion #4306: a registry committed next to the project could not be /// referenced, because a relative entry failed as `relative URL without a /// base`. #[test] fn relative_aqua_registry_resolves_against_config_root() { let dir = tempfile::tempdir().unwrap(); let registries = rewritten_registries(dir.path(), r#"aqua.registries = ["registry.yaml"]"#); let expected = Url::from_file_path(dir.path().join("registry.yaml")) .unwrap() .to_string(); assert_eq!(registries, vec![expected]); } /// `aqua.registries = [..]` and `[aqua]` + `registries = [..]` parse to the /// same nested table, so both spellings must be picked up. #[test] fn table_form_registries_also_resolve() { let dir = tempfile::tempdir().unwrap(); let registries = rewritten_registries( dir.path(), r#" [aqua] registries = ["registry.yaml"] "#, ); let expected = Url::from_file_path(dir.path().join("registry.yaml")) .unwrap() .to_string(); assert_eq!(registries, vec![expected]); } #[test] fn absolute_registry_urls_are_left_alone() { let dir = tempfile::tempdir().unwrap(); let registries = rewritten_registries( dir.path(), r#" aqua.registries = [ "https://github.com/aquaproj/aqua-registry", "file:///somewhere/registry.yaml", ] "#, ); assert_eq!( registries, vec![ "https://github.com/aquaproj/aqua-registry".to_string(), "file:///somewhere/registry.yaml".to_string(), ] ); } #[test] fn parent_relative_registry_path_is_normalized() { let dir = tempfile::tempdir().unwrap(); let registries = rewritten_registries( dir.path(), r#"aqua.registries = ["../shared/registry.yaml"]"#, ); assert!( !registries[0].contains(".."), "expected `..` to be normalized away, got {}", registries[0] ); } #[test] fn registries_without_aqua_table_are_untouched() { let dir = tempfile::tempdir().unwrap(); let mut settings = toml::from_str::("offline = true").unwrap(); resolve_aqua_registry_paths(&mut settings, &dir.path().join(".mise.toml")); assert_eq!(settings["offline"].as_bool(), Some(true)); } #[test] fn age_paths_resolve_against_the_declaring_config_root() { let dir = tempfile::tempdir().unwrap(); let config_path = dir.path().join("mise.toml"); let mut settings = toml::from_str::( r#" [age] key_file = "keys/age.txt" identity_files = ["identities/first.txt", "{{ config_root }}/second.txt"] ssh_identity_files = ["ssh/id_ed25519"] "#, ) .unwrap(); resolve_age_paths(&mut settings, &config_path).unwrap(); assert_eq!( settings["age"]["key_file"].as_str(), Some(dir.path().join("keys/age.txt").to_str().unwrap()) ); assert_eq!( settings["age"]["identity_files"][0].as_str(), Some(dir.path().join("identities/first.txt").to_str().unwrap()) ); assert_eq!( Path::new(settings["age"]["identity_files"][1].as_str().unwrap()), dir.path().join("second.txt") ); assert_eq!( settings["age"]["ssh_identity_files"][0].as_str(), Some(dir.path().join("ssh/id_ed25519").to_str().unwrap()) ); } #[test] fn age_paths_preserve_absolute_and_home_relative_paths() { let dir = tempfile::tempdir().unwrap(); let absolute = dir.path().join("absolute.txt"); let mut age = toml::Table::new(); age.insert( "key_file".into(), toml::Value::String(absolute.to_string_lossy().into_owned()), ); age.insert( "identity_files".into(), toml::Value::Array(vec![toml::Value::String("~/identity.txt".into())]), ); let mut settings = toml::Table::new(); settings.insert("age".into(), toml::Value::Table(age)); resolve_age_paths(&mut settings, &dir.path().join("mise.toml")).unwrap(); assert_eq!( settings["age"]["key_file"].as_str(), Some(absolute.to_str().unwrap()) ); assert_eq!( settings["age"]["identity_files"][0].as_str(), Some("~/identity.txt") ); } #[test] fn write_targets_resolve_against_the_declaring_config_root() { let dir = tempfile::tempdir().unwrap(); let config_path = dir.path().join("mise.toml"); let mut settings = toml::from_str::( r#" [write_targets] tools = "tools.toml" packages = "{{ xdg_config_home }}/mise/packages.toml" dotfiles = "~/dotfiles.toml" "#, ) .unwrap(); resolve_write_target_paths(&mut settings, &config_path); assert_eq!( settings["write_targets"]["tools"].as_str(), Some(dir.path().join("tools.toml").to_str().unwrap()) ); assert_eq!( Path::new(settings["write_targets"]["packages"].as_str().unwrap()), env::XDG_CONFIG_HOME.join("mise/packages.toml") ); assert_eq!( settings["write_targets"]["dotfiles"].as_str(), Some("~/dotfiles.toml") ); } #[test] fn dotfiles_root_renders_templates_and_keeps_plain_paths() { let dir = tempfile::tempdir().unwrap(); let config_path = dir.path().join("mise.toml"); let mut settings = toml::from_str::( r#" [dotfiles] root = "{{ mise_config_dir }}/home" "#, ) .unwrap(); resolve_dotfiles_root_path(&mut settings, &config_path); assert_eq!( Path::new(settings["dotfiles"]["root"].as_str().unwrap()), env::MISE_CONFIG_DIR.join("home") ); let mut settings = toml::from_str::("[dotfiles]\nroot = \"dotfiles\"\n").unwrap(); resolve_dotfiles_root_path(&mut settings, &config_path); assert_eq!(settings["dotfiles"]["root"].as_str(), Some("dotfiles")); let mut settings = toml::from_str::("[dotfiles]\nroot = \"{{ missing_variable }}\"\n") .unwrap(); resolve_dotfiles_root_path(&mut settings, &config_path); assert_eq!( settings["dotfiles"]["root"].as_str(), Some("{{ missing_variable }}") ); } #[test] fn invalid_write_target_template_is_left_for_the_write_check_to_reject() { let dir = tempfile::tempdir().unwrap(); let mut settings = toml::from_str::( r#" [write_targets] tools = "{{ missing_variable }}" "#, ) .unwrap(); resolve_write_target_paths(&mut settings, &dir.path().join("mise.toml")); assert_eq!( settings["write_targets"]["tools"].as_str(), Some("{{ missing_variable }}") ); } #[test] fn invalid_age_path_template_names_the_setting_and_file() { let dir = tempfile::tempdir().unwrap(); let config_path = dir.path().join("mise.toml"); let mut settings = toml::from_str::( r#" [age] key_file = "{{ missing_variable }}" "#, ) .unwrap(); let err = resolve_age_paths(&mut settings, &config_path) .unwrap_err() .to_string(); assert!(err.contains("settings.age.key_file"), "{err}"); assert!(err.contains("mise.toml"), "{err}"); } /// A drive-letter path parses as a URL whose scheme is one character, so it /// must not be mistaken for an absolute URL and left unusable. #[cfg(windows)] #[test] fn windows_drive_registry_path_is_treated_as_a_path() { let dir = tempfile::tempdir().unwrap(); let registries = rewritten_registries(dir.path(), r#"aqua.registries = ['C:\reg\registry.yaml']"#); assert_eq!(registries.len(), 1); assert!( registries[0].starts_with("file:///C:/reg/"), "expected a file URL, got {}", registries[0] ); } #[test] fn test_deprecated_settings_in_toml_table_detects_nested_settings() { let settings = toml::from_str::( r#" tera_v1 = true [aqua] registry_url = "https://example.com/aqua-registry" "#, ) .unwrap() .as_table() .unwrap() .clone(); let deprecated = deprecated_settings_in_toml_table(&settings); assert!(deprecated.contains(&"tera_v1")); assert!(deprecated.contains(&"aqua.registry_url")); } #[test] fn test_settings_without_effect_are_deprecated() { let settings = toml::from_str::( r#" plugin_autoupdate_last_check_duration = "1d" [sops] age_recipients = "age1example" [task.cache] stats_report = "stats.json" "#, ) .unwrap() .as_table() .unwrap() .clone(); let keys = [ "plugin_autoupdate_last_check_duration", "sops.age_recipients", "task.cache.stats_report", ]; let deprecated = deprecated_settings_in_toml_table(&settings); for key in keys { assert!(deprecated.contains(&key), "{key} is not deprecated"); let meta = SETTINGS_META.get(key).unwrap(); assert!( meta.deprecated_warn_at.is_some() && meta.deprecated_remove_at.is_some(), "{key} has no warn_at/remove_at, so setting it never warns" ); } } #[test] fn test_deprecated_settings_in_env_directives_detects_setting_env() { let raw = toml::from_str::( r#" [env] MISE_TERA_V1 = true "#, ) .unwrap(); assert_eq!(deprecated_settings_in_env_directives(&raw), vec!["tera_v1"]); } #[test] fn test_deprecated_settings_in_env_directives_ignores_unset_env() { let raw = toml::from_str::( r#" [env] MISE_TERA_V1 = { unset = true } "#, ) .unwrap(); assert!(deprecated_settings_in_env_directives(&raw).is_empty()); } #[test] fn test_deprecated_settings_in_env_directives_ignores_child_only_env() { let raw = toml::from_str::( r#" [env] MISE_SHORTHANDS_FILE = "~/.mise-shorthands" "#, ) .unwrap(); assert!(deprecated_settings_in_env_directives(&raw).is_empty()); } #[test] fn test_global_config_preserves_trust_controls() { let path = Path::new("/tmp/global-config.toml"); let mut settings = toml::from_str::( r#" ci = "true" paranoid = true trusted_config_paths = ["/"] yes = true "#, ) .unwrap() .as_table() .unwrap() .clone(); strip_local_only_settings(&mut settings, path, true); let partial = settings_partial_from_table(settings); assert_eq!(partial.ci, Some(true)); assert_eq!(partial.paranoid, Some(mise_settings::Paranoid::all())); assert_eq!( partial.trusted_config_paths, Some([PathBuf::from("/")].into_iter().collect()) ); assert_eq!(partial.yes, Some(true)); } #[test] fn test_generated_collection_enum_validation() { let mut settings = Settings::builder().load().unwrap(); settings.locked_scopes = BTreeSet::from(["projct".to_string()]); assert_eq!( validate_settings_enum_values(&settings) .unwrap_err() .to_string(), "invalid locked_scopes value \"projct\"; expected one of: project, global, system" ); } #[test] fn test_offline_default_is_false() { let _settings = crate::test::SettingsGuard::lock(); Settings::reset(None); let settings = Settings::get(); // When neither setting nor env var is set, offline should be false // (env::OFFLINE is process-global so we can't easily toggle it, // but the setting field defaults to false) assert!(!settings.offline); } #[test] fn test_prefer_offline_default_is_false() { let _settings = crate::test::SettingsGuard::lock(); Settings::reset(None); let settings = Settings::get(); assert!(!settings.prefer_offline); } /// Settings that name the program mise runs for a step it did not get from the user's own /// config. A project config must not choose them, trusted or not, so each has to be /// `global_only`: `strip_local_only_settings` only drops marked keys. #[test] fn test_command_selecting_settings_are_global_only() { let keys = [ "system_packages.elevate_with", "unix_default_file_shell_args", "unix_default_inline_shell_args", "windows_default_file_shell_args", "windows_default_inline_shell_args", ]; for key in keys { let meta = SETTINGS_META .get(key) .unwrap_or_else(|| panic!("{key} setting should exist")); assert!(meta.global_only, "{key} must be global_only"); } } #[test] fn test_cargo_binstall_quickinstall_setting() { let settings = Settings::builder().load().unwrap(); assert!(!settings.cargo.binstall_quickinstall); let meta = SETTINGS_META .get("cargo.binstall_quickinstall") .expect("cargo.binstall_quickinstall setting should exist"); assert_eq!(meta.env, Some("MISE_CARGO_BINSTALL_QUICKINSTALL")); } #[test] fn test_three_level_task_cache_setting() { let settings = Settings::builder().load().unwrap(); assert_eq!( settings.task.cache.remote_mode, crate::cache::CacheRemoteMode::ReadWrite ); let meta = SETTINGS_META .get("task.cache.remote_mode") .expect("task.cache.remote_mode setting should exist"); assert_eq!(meta.env, Some("MISE_TASK_CACHE_REMOTE_MODE")); } #[test] fn test_offline_setting_enables_offline() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.offline = Some(true); Settings::reset(Some(partial)); let settings = Settings::get(); assert!(settings.offline()); } /// Startup builds the settings before it parses the flags. Flags that set nothing keep that /// build; flags that set something, or replace flags that did, rebuild it. #[test] fn test_add_cli_matches_rebuilds_only_for_flags_that_set_something() { let _settings = crate::test::SettingsGuard::lock(); Settings::reset(None); let before = Settings::get(); Settings::add_cli_matches(SettingsPartial::empty()); assert!(std::sync::Arc::ptr_eq(&before, &Settings::get())); let mut partial = SettingsPartial::empty(); partial.offline = Some(true); Settings::add_cli_matches(partial); assert!(Settings::get().offline()); Settings::add_cli_matches(SettingsPartial::empty()); assert!(!Settings::get().offline()); } #[test] fn test_reload_preserves_cli_settings() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.offline = Some(true); Settings::reset(Some(partial)); assert!(Settings::get().offline()); Settings::reload().unwrap(); assert!(Settings::get().offline()); } /// A reload that cannot build settings reports the error and keeps the previous settings, /// rather than emptying the cache for the next `Settings::get()` to unwrap (#13923). #[test] fn test_failed_reload_keeps_previous_settings() { let _settings = crate::test::SettingsGuard::lock(); Settings::reset(None); let before = Settings::get(); let mut env = crate::test::EnvVarGuard::new(); env.set("MISE_YES", "maybe"); let err = Settings::reload().unwrap_err(); assert!(format!("{err:#}").contains("MISE_YES"), "{err:#}"); let err = Settings::override_with(|s| s.offline = Some(true)).unwrap_err(); assert!(format!("{err:#}").contains("MISE_YES"), "{err:#}"); let after = Settings::get(); assert!(Arc::ptr_eq(&before, &after)); // The override that could not be applied is not waiting in the CLI layer for the next // reload to pick it up. drop(env); Settings::reload().unwrap(); assert!(!Settings::get().offline); } #[test] fn test_offline_implies_prefer_offline() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.offline = Some(true); Settings::reset(Some(partial)); let settings = Settings::get(); assert!(settings.prefer_offline()); } #[test] fn test_prefer_offline_setting() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.prefer_offline = Some(true); Settings::reset(Some(partial)); let settings = Settings::get(); assert!(settings.prefer_offline()); // prefer_offline does NOT imply offline assert!(!settings.offline); } #[test] fn test_install_before_hidden_alias_sets_minimum_release_age() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.install_before = Some("7d".to_string()); Settings::reset(Some(partial)); let settings = Settings::get(); assert_eq!(settings.minimum_release_age.as_deref(), Some("7d")); } #[test] fn test_minimum_release_age_hidden_alias_wins_over_install_before() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.install_before = Some("7d".to_string()); partial.minimum_release_age = Some("3d".to_string()); Settings::reset(Some(partial)); let settings = Settings::get(); assert_eq!(settings.minimum_release_age.as_deref(), Some("3d")); } #[test] fn test_auto_update_hidden_aliases_set_self_update_settings() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.auto_update = Some(true); partial.auto_update_check_duration = Some("1d".to_string()); Settings::reset(Some(partial)); let settings = Settings::get(); assert_eq!(settings.self_update.auto, AutoUpdate::On); assert_eq!(settings.self_update.check_duration, "1d"); } #[test] fn test_invalid_auto_update_interval_turns_it_off() { let mut value = AutoUpdate::Every("soon".to_string()); validate_auto_update("self_update.auto", &mut value); assert_eq!(value, AutoUpdate::Off); let mut value = AutoUpdate::Every("6h".to_string()); validate_auto_update("self_update.auto", &mut value); assert_eq!(value, AutoUpdate::Every("6h".to_string())); } #[cfg(feature = "self_update")] #[test] fn test_self_update_auto_interval_overrides_check_duration() { let _settings = crate::test::SettingsGuard::lock(); let mut partial = SettingsPartial::empty(); partial.self_update.check_duration = Some("2d".to_string()); Settings::reset(Some(partial.clone())); assert_eq!( Settings::get().self_update_check_duration().unwrap(), Duration::from_secs(2 * 24 * 60 * 60) ); partial.self_update.auto = Some(AutoUpdate::Every("6h".to_string())); Settings::reset(Some(partial)); let settings = Settings::get(); assert!(settings.self_update.auto.is_on()); assert_eq!( settings.self_update_check_duration().unwrap(), Duration::from_secs(6 * 60 * 60) ); } #[test] fn test_self_update_settings_win_over_auto_update_hidden_aliases() { let settings_file: SettingsFile = toml::from_str( r#" [settings] auto_update = true auto_update_check_duration = "1d" self_update.auto = false self_update.check_duration = "2d" "#, ) .unwrap(); let partial = normalize_hidden_config_aliases(settings_file.settings); assert_eq!(partial.auto_update, None); assert_eq!(partial.auto_update_check_duration, None); assert_eq!(partial.self_update.auto, Some(AutoUpdate::Off)); assert_eq!(partial.self_update.check_duration.as_deref(), Some("2d")); } #[test] fn test_task_cache_hidden_aliases_map_to_nested_settings() { let settings_file: SettingsFile = toml::from_str( r#" [settings.task] cache_remote_mode = "read-only" cache_remote_token = "secret" cache_remote_url = "https://old.example.com" [settings.task.cache] remote_url = "https://new.example.com" "#, ) .unwrap(); let partial = normalize_hidden_config_aliases(settings_file.settings); assert_eq!(partial.task.cache_remote_mode, None); assert_eq!(partial.task.cache_remote_token, None); assert_eq!(partial.task.cache_remote_url, None); assert_eq!( partial.task.cache.remote_mode, Some(crate::cache::CacheRemoteMode::ReadOnly) ); assert_eq!( partial.task.cache.remote_url.as_deref(), Some("https://new.example.com") ); assert_eq!(partial.task.cache.remote_token.as_deref(), Some("secret")); } #[test] fn test_aqua_registry_url_accepts_single_string() { let settings_file: SettingsFile = toml::from_str( r#" [settings] aqua.registry_url = "https://example.com/registry" "#, ) .unwrap(); assert_eq!( settings_file.settings.aqua.registry_url, Some("https://example.com/registry".to_string()) ); } #[test] fn test_aqua_registries_accepts_list() { let settings_file: SettingsFile = toml::from_str( r#" [settings] aqua.registries = [ "https://example.com/first", "https://example.com/second", ] "#, ) .unwrap(); assert_eq!( settings_file.settings.aqua.registries, Some(vec![ "https://example.com/first".to_string(), "https://example.com/second".to_string(), ]) ); } #[test] fn test_aqua_registry_url_sets_registries() { let mut settings = Settings::default(); settings.aqua.registry_url = Some("https://example.com/legacy".to_string()); settings.set_hidden_configs(); assert_eq!(settings.aqua.registry_url, None); assert_eq!( settings.aqua.registries, Some(vec!["https://example.com/legacy".to_string()]) ); } #[test] fn test_aqua_registries_overrides_registry_url() { let mut settings = Settings::default(); settings.aqua.registry_url = Some("https://example.com/legacy".to_string()); settings.aqua.registries = Some(vec!["https://example.com/new".to_string()]); settings.set_hidden_configs(); assert_eq!(settings.aqua.registry_url, None); assert_eq!( settings.aqua.registries, Some(vec!["https://example.com/new".to_string()]) ); } #[test] fn test_settings_node_build_cmds() { let node = SettingsNode::default(); let path = Path::new("/tmp/install"); // Defaults assert!( node.configure_cmd(path) .starts_with("./configure --prefix=/tmp/install") ); assert!(node.make_cmd().starts_with("make")); assert_eq!(node.make_install_cmd(), "make install"); } #[test] fn test_settings_node_build_cmds_with_opts() { let node = SettingsNode { configure_opts: Some("--verbose".to_string()), make_opts: Some("-s".to_string()), make_install_opts: Some("--no-strip".to_string()), make: Some("gmake".to_string()), concurrency: Some(4), ..Default::default() }; let path = Path::new("/tmp/install"); assert!(node.configure_cmd(path).contains("--verbose")); assert!(node.make_cmd().starts_with("gmake -j4 -s")); assert_eq!(node.make_install_cmd(), "gmake install --no-strip"); } #[test] fn pypi_settings_aliases_merge_and_reject_conflicts() { let mut settings = Settings::default(); settings.pipx.uvx = Some(false); settings.normalize_pypi_aliases().unwrap(); assert_eq!(settings.pypi.uvx, Some(false)); assert_eq!(settings.pipx.uvx, None); settings.pipx.uvx = Some(true); assert!(settings.normalize_pypi_aliases().is_err()); } }