From 651b7058e4fd41f8e77a7482d5d2428e5419ac27 Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Sat, 22 Aug 2026 16:17:06 +0000 Subject: [PATCH 1/3] feat(self-update): add automatic updates with re-exec --- docs/installing-mise.md | 10 ++ schema/mise.json | 10 ++ settings.toml | 23 ++++ src/cli/mod.rs | 4 + src/cli/self_update.rs | 233 ++++++++++++++++++++++++++++++++++++ src/cli/self_update_stub.rs | 7 ++ src/config/settings.rs | 5 + src/lock_file.rs | 13 ++ 8 files changed, 305 insertions(+) diff --git a/docs/installing-mise.md b/docs/installing-mise.md index cd59a8df62a..2bd747e0270 100644 --- a/docs/installing-mise.md +++ b/docs/installing-mise.md @@ -21,6 +21,16 @@ not become available as quickly after a mise release. ::: tip Which methods auto-update? Package managers (apt, dnf, brew, pacman, etc.) update mise when you update system packages. Other methods can be updated with `mise self-update`. + +For installations that support `mise self-update`, automatic updates can be enabled globally: + +```sh +mise settings set auto_update true +``` + +mise then periodically checks before eligible interactive commands, installs a newer release without +updating plugins, and re-runs the original command with the new binary. Configure the interval with +[`auto_update_check_duration`](/configuration/settings.html#auto_update_check_duration). ::: ::: tip Keep mise up to date diff --git a/schema/mise.json b/schema/mise.json index c618e284f24..100f5d21250 100644 --- a/schema/mise.json +++ b/schema/mise.json @@ -633,6 +633,16 @@ "type": "string" } }, + "auto_update": { + "default": false, + "description": "Automatically update mise before running eligible commands.", + "type": "boolean" + }, + "auto_update_check_duration": { + "default": "7d", + "description": "How often to check for a new mise release when auto-update is enabled.", + "type": "string" + }, "cache_prune_age": { "default": "30d", "description": "Delete files in cache that have not been accessed in this duration", diff --git a/settings.toml b/settings.toml index 4db3b1a9354..26a415911dc 100644 --- a/settings.toml +++ b/settings.toml @@ -269,6 +269,29 @@ parse_env = "list_by_comma" rust_type = "Vec" type = "ListString" +[auto_update] +default = false +description = "Automatically update mise before running eligible commands." +docs = """ +When enabled, mise periodically checks for a newer release before running commands that permit +network access. If an update is available, mise installs it without updating plugins, then re-runs +the original command with the new binary. + +Automatic updates are skipped in CI, offline and prefer-offline modes, non-interactive sessions, +shell integration commands, and installations whose packager disabled self-update. This setting is +global-only so a project's configuration cannot opt users into replacing their mise binary. +""" +env = "MISE_AUTO_UPDATE" +global_only = true +type = "Bool" + +[auto_update_check_duration] +default = "7d" +description = "How often to check for a new mise release when auto-update is enabled." +env = "MISE_AUTO_UPDATE_CHECK_DURATION" +global_only = true +type = "Duration" + [cache_prune_age] default = "30d" description = "Delete files in cache that have not been accessed in this duration" diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 393af627b76..7d47e7f92c5 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -738,6 +738,7 @@ impl Cli { async fn run_inner(args: &Vec) -> Result<()> { crate::env::ARGS.write().unwrap().clone_from(args); + let original_cwd = std::env::current_dir().ok(); // Load .miserc.toml early, before MISE_ENV and other early settings are accessed. // This allows setting MISE_ENV in a config file instead of only via env vars. crate::config::miserc::init()?; @@ -789,6 +790,9 @@ impl Cli { validate_cd_path(&cli.cd)?; measure!("add_cli_matches", { Settings::add_cli_matches(&cli) }); let _ = measure!("settings", { Settings::try_get() }); + measure!("auto_update", { + self_update::maybe_auto_update(args, original_cwd.as_deref()).await? + }); measure!("trust_active_config", { config_file::trust_active_config()? }); diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index 330f5faad3c..3cd2aa62069 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -16,6 +16,24 @@ use std::fs; #[cfg(target_os = "macos")] use std::path::Path; use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +const AUTO_UPDATE_REEXEC_ENV: &str = "__MISE_AUTO_UPDATE_REEXEC"; +const AUTO_UPDATE_SKIP_COMMANDS: &[&str] = &[ + "activate", + "completion", + "deactivate", + "doctor", + "hook-env", + "implode", + "self-update", + "settings", + "shell", + "usage", + "v", + "version", +]; #[derive(Debug, Default, serde::Deserialize)] struct InstructionsToml { @@ -76,6 +94,137 @@ pub(crate) fn append_self_update_instructions(mut message: String) -> String { message } +pub(crate) async fn maybe_auto_update( + args: &[String], + original_cwd: Option<&std::path::Path>, +) -> Result<()> { + let Ok(settings) = Settings::try_get() else { + return Ok(()); + }; + let command = crate::cli::first_non_global_arg_idx_cached(args) + .and_then(|idx| args.get(idx)) + .map(String::as_str); + if !auto_update_eligible(AutoUpdateContext { + enabled: settings.auto_update, + offline: settings.offline(), + prefer_offline: settings.prefer_offline(), + ci: settings.ci || ci_info::is_ci(), + attended: console::user_attended_stderr(), + already_reexecuted: env::var_os(AUTO_UPDATE_REEXEC_ENV).is_some(), + self_update_available: SelfUpdate::is_available(), + command, + }) { + return Ok(()); + } + + let lock_path = crate::dirs::CACHE.join("auto-update"); + let update_lock = match crate::lock_file::LockFile::new(&lock_path).try_lock() { + Ok(Some(lock)) => lock, + Ok(None) => { + debug!("skipping auto-update because another mise process is updating"); + return Ok(()); + } + Err(err) => { + debug!("automatic mise update could not acquire its lock: {err:#}"); + return Ok(()); + } + }; + let last_check_path = crate::dirs::CACHE.join("auto-update-last-check"); + let check_duration = settings.auto_update_check_duration(); + if !auto_update_check_due(&last_check_path, check_duration) { + return Ok(()); + } + if let Err(err) = crate::file::write(&last_check_path, "") { + debug!("automatic mise update could not record its check: {err:#}"); + return Ok(()); + } + let Some(version) = crate::cli::version::check_for_new_version(check_duration).await else { + return Ok(()); + }; + + let update = SelfUpdate { + version: Some(version), + force: false, + yes: true, + no_plugins: true, + }; + if let Err(err) = update.run().await { + debug!("automatic mise update failed: {err:#}"); + return Ok(()); + } + drop(update_lock); + reexec(args, original_cwd) +} + +fn auto_update_check_due(path: &std::path::Path, duration: Duration) -> bool { + crate::file::modified_duration(path).map_or(true, |age| age >= duration) +} + +#[derive(Clone, Copy)] +struct AutoUpdateContext<'a> { + enabled: bool, + offline: bool, + prefer_offline: bool, + ci: bool, + attended: bool, + already_reexecuted: bool, + self_update_available: bool, + command: Option<&'a str>, +} + +fn auto_update_eligible(context: AutoUpdateContext<'_>) -> bool { + context.enabled + && !context.offline + && !context.prefer_offline + && !context.ci + && context.attended + && !context.already_reexecuted + && context.self_update_available + && context + .command + .is_some_and(|command| !AUTO_UPDATE_SKIP_COMMANDS.contains(&command)) +} + +#[cfg(unix)] +fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { + use std::os::unix::process::CommandExt; + + let mut command = Command::new(&*env::MISE_BIN); + command + .args(std::env::args_os().skip(1)) + .env(AUTO_UPDATE_REEXEC_ENV, "1"); + if let Some(cwd) = original_cwd { + command.current_dir(cwd); + } + let err = command.exec(); + warn!("mise was updated but could not re-execute the command: {err}"); + Ok(()) +} + +#[cfg(windows)] +fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { + let mut command = Command::new(&*env::MISE_BIN); + command + .args(std::env::args_os().skip(1)) + .env(AUTO_UPDATE_REEXEC_ENV, "1"); + if let Some(cwd) = original_cwd { + command.current_dir(cwd); + } + let status = command.status()?; + Err(crate::request_exit(status.code().unwrap_or(1))) +} + +#[cfg(not(any(unix, windows)))] +fn reexec(args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { + let mut command = Command::new(&*env::MISE_BIN); + command.args(&args[1..]).env(AUTO_UPDATE_REEXEC_ENV, "1"); + if let Some(cwd) = original_cwd { + command.current_dir(cwd); + } + let status = command.status()?; + Err(crate::request_exit(status.code().unwrap_or(1))) +} + /// Updates mise itself. /// /// Uses the GitHub Releases API to find the latest release and binary. @@ -499,6 +648,90 @@ impl SelfUpdate { } } +#[cfg(test)] +mod auto_update_tests { + use super::*; + + fn eligible_context() -> AutoUpdateContext<'static> { + AutoUpdateContext { + enabled: true, + offline: false, + prefer_offline: false, + ci: false, + attended: true, + already_reexecuted: false, + self_update_available: true, + command: Some("install"), + } + } + + #[test] + fn eligible_interactive_command_updates() { + assert!(auto_update_eligible(eligible_context())); + } + + #[test] + fn safety_conditions_disable_auto_update() { + let context = eligible_context(); + for ineligible in [ + AutoUpdateContext { + enabled: false, + ..context + }, + AutoUpdateContext { + offline: true, + ..context + }, + AutoUpdateContext { + prefer_offline: true, + ..context + }, + AutoUpdateContext { + ci: true, + ..context + }, + AutoUpdateContext { + attended: false, + ..context + }, + AutoUpdateContext { + already_reexecuted: true, + ..context + }, + AutoUpdateContext { + self_update_available: false, + ..context + }, + ] { + assert!(!auto_update_eligible(ineligible)); + } + } + + #[test] + fn shell_and_management_commands_do_not_update() { + for command in AUTO_UPDATE_SKIP_COMMANDS { + assert!(!auto_update_eligible(AutoUpdateContext { + command: Some(command), + ..eligible_context() + })); + } + assert!(!auto_update_eligible(AutoUpdateContext { + command: None, + ..eligible_context() + })); + } + + #[test] + fn automatic_update_attempts_are_throttled() { + let temp = tempfile::tempdir().unwrap(); + let marker = temp.path().join("last-check"); + assert!(auto_update_check_due(&marker, Duration::from_secs(60))); + std::fs::write(&marker, "").unwrap(); + assert!(!auto_update_check_due(&marker, Duration::from_secs(60))); + assert!(auto_update_check_due(&marker, Duration::ZERO)); + } +} + #[cfg(all(test, windows))] mod tests { use super::*; diff --git a/src/cli/self_update_stub.rs b/src/cli/self_update_stub.rs index 82ec54c49b1..e1bd77fef9c 100644 --- a/src/cli/self_update_stub.rs +++ b/src/cli/self_update_stub.rs @@ -4,6 +4,13 @@ use std::path::PathBuf; use crate::env; +pub(crate) async fn maybe_auto_update( + _args: &[String], + _original_cwd: Option<&std::path::Path>, +) -> crate::Result<()> { + Ok(()) +} + #[derive(Debug, Default, clap::Args)] pub(crate) struct SelfUpdate { /// Update to a specific version diff --git a/src/config/settings.rs b/src/config/settings.rs index ad0b77ca710..df2a5b7ed3c 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -1187,6 +1187,11 @@ impl Settings { if age.as_secs() == 0 { None } else { Some(age) } } + #[cfg(feature = "self_update")] + pub(crate) fn auto_update_check_duration(&self) -> Duration { + duration::parse_duration(&self.auto_update_check_duration).unwrap() + } + pub(crate) fn fetch_remote_versions_timeout(&self) -> Duration { let timeout = self.configured_fetch_remote_versions_timeout(); if self.bound_remote_version_lookups() { diff --git a/src/lock_file.rs b/src/lock_file.rs index fc0721bd4f8..46b819d4a1b 100644 --- a/src/lock_file.rs +++ b/src/lock_file.rs @@ -43,6 +43,19 @@ impl LockFile { } Ok(lock) } + + #[cfg(feature = "self_update")] + pub(crate) fn try_lock(self) -> Result> { + if let Some(parent) = self.path.parent() { + create_dir_all(parent)?; + } + let mut lock = fslock::LockFile::open(&self.path)?; + if lock.try_lock()? { + Ok(Some(lock)) + } else { + Ok(None) + } + } } pub(crate) fn get(path: &Path, force: bool) -> eyre::Result> { From 0d33e84e3b0e50bbbf201e93e58ac2c28bc6c7db Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Sat, 22 Aug 2026 16:23:29 +0000 Subject: [PATCH 2/3] feat(version): promote optimized binaries and auto-update --- docs/installing-mise.md | 5 ++- src/cli/mod.rs | 1 + src/cli/self_update.rs | 1 + src/cli/version.rs | 89 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 2 deletions(-) diff --git a/docs/installing-mise.md b/docs/installing-mise.md index 2bd747e0270..3eb2734363e 100644 --- a/docs/installing-mise.md +++ b/docs/installing-mise.md @@ -16,8 +16,9 @@ This page lists various ways to install `mise` on your system. The official single-binary release installed by `mise.run` is the preferred method on macOS and Linux. These binaries are built with mise's optimized release profile and can be updated immediately -with `mise self-update`. Package-manager builds, including Homebrew, may be less optimized and may -not become available as quickly after a mise release. +with `mise self-update`. Prefer them over third-party package builds: the Homebrew formula is +typically 20–30% slower and about 40% larger, and package-manager releases may also lag behind a mise +release. ::: tip Which methods auto-update? Package managers (apt, dnf, brew, pacman, etc.) update mise when you update system packages. Other methods can be updated with `mise self-update`. diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 7d47e7f92c5..f6178e9050b 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -811,6 +811,7 @@ impl Cli { trace!("MISE_BIN: {}", crate::env::MISE_BIN.display_user()); if print_version { version::show_latest().await; + version::show_version_hint(); return Err(request_exit(0)); } let _remote_task_artifacts = crate::task::task_fetcher::RemoteTaskArtifactsGuard::new(); diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index 3cd2aa62069..4e33aecd8a5 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -411,6 +411,7 @@ impl SelfUpdate { } else { miseprintln!("mise is already up to date"); } + crate::cli::version::show_auto_update_hint(); if !self.no_plugins { cmd!(&*env::MISE_BIN, "plugins", "update").run()?; } diff --git a/src/cli/version.rs b/src/cli/version.rs index a8bde80680a..f37f20d46fa 100644 --- a/src/cli/version.rs +++ b/src/cli/version.rs @@ -8,6 +8,7 @@ use versions::Versioning; use crate::build_time::BUILD_TIME; use crate::cli::self_update::{SelfUpdate, upgrade_instructions_or_hint}; +use crate::config::Settings; use crate::file::modified_duration; use crate::ui::style; use crate::{dirs, duration, env, file}; @@ -32,6 +33,7 @@ impl Version { } else { show_version()?; show_latest().await; + show_version_hint(); } Ok(()) } @@ -132,6 +134,72 @@ pub(crate) async fn show_latest() { } } +#[derive(Debug, PartialEq)] +enum VersionHint { + AutoUpdate, + Homebrew, + OptimizedBinary, +} + +fn select_version_hint( + self_update_available: bool, + auto_update: bool, + homebrew: bool, +) -> Option { + if self_update_available { + (!auto_update).then_some(VersionHint::AutoUpdate) + } else if homebrew { + Some(VersionHint::Homebrew) + } else { + Some(VersionHint::OptimizedBinary) + } +} + +pub(crate) fn show_auto_update_hint() { + let Ok(settings) = Settings::try_get() else { + return; + }; + if select_version_hint(SelfUpdate::is_available(), settings.auto_update, false) + == Some(VersionHint::AutoUpdate) + { + hint!( + "auto_update", + "keep mise updated automatically with", + "mise settings set auto_update true" + ); + } +} + +pub(crate) fn show_version_hint() { + let Ok(settings) = Settings::try_get() else { + return; + }; + match select_version_hint( + SelfUpdate::is_available(), + settings.auto_update, + is_homebrew_install(), + ) { + Some(VersionHint::AutoUpdate) => show_auto_update_hint(), + Some(VersionHint::Homebrew) => hint!( + "optimized_mise_homebrew", + "Homebrew's mise formula is typically 20–30% slower and about 40% larger than the optimized mise.run binary; replace it with", + "brew uninstall mise && curl https://mise.run | sh" + ), + Some(VersionHint::OptimizedBinary) => hint!( + "optimized_mise_binary", + "third-party package builds may be slower and larger than mise's optimized binary; install the official build with", + "curl https://mise.run | sh" + ), + None => {} + } +} + +fn is_homebrew_install() -> bool { + std::fs::canonicalize(&*env::MISE_BIN) + .ok() + .is_some_and(|path| path.components().any(|part| part.as_os_str() == "Cellar")) +} + pub(crate) async fn check_for_new_version(cache_duration: Duration) -> Option { if let Some(latest) = get_latest_version(cache_duration) .await @@ -312,4 +380,25 @@ mod tests { Cached::Fresh(Some("0.0.1".to_string())) ); } + + #[test] + fn version_hint_promotes_auto_update_for_official_binaries() { + assert_eq!( + select_version_hint(true, false, false), + Some(VersionHint::AutoUpdate) + ); + assert_eq!(select_version_hint(true, true, false), None); + } + + #[test] + fn version_hint_promotes_optimized_binaries_for_package_installs() { + assert_eq!( + select_version_hint(false, false, true), + Some(VersionHint::Homebrew) + ); + assert_eq!( + select_version_hint(false, false, false), + Some(VersionHint::OptimizedBinary) + ); + } } From dc55546831ede2c01d0b80101b441ace1e35110f Mon Sep 17 00:00:00 2001 From: default <216188+jdx@users.noreply.github.com> Date: Sat, 22 Aug 2026 16:46:56 +0000 Subject: [PATCH 3/3] fix(self-update): address automatic update review feedback --- docs/installing-mise.md | 5 +- src/cli/mod.rs | 61 ++++++++++++++++++- src/cli/self_update.rs | 116 +++++++++++++++++++----------------- src/cli/self_update_stub.rs | 1 + src/cli/version.rs | 32 +++++++--- src/config/settings.rs | 4 +- 6 files changed, 150 insertions(+), 69 deletions(-) diff --git a/docs/installing-mise.md b/docs/installing-mise.md index 3eb2734363e..60e4ffa9531 100644 --- a/docs/installing-mise.md +++ b/docs/installing-mise.md @@ -16,9 +16,8 @@ This page lists various ways to install `mise` on your system. The official single-binary release installed by `mise.run` is the preferred method on macOS and Linux. These binaries are built with mise's optimized release profile and can be updated immediately -with `mise self-update`. Prefer them over third-party package builds: the Homebrew formula is -typically 20–30% slower and about 40% larger, and package-manager releases may also lag behind a mise -release. +with `mise self-update`. Prefer them over third-party package builds: the Homebrew formula can be +substantially slower and larger, and package-manager releases may also trail a mise release. ::: tip Which methods auto-update? Package managers (apt, dnf, brew, pacman, etc.) update mise when you update system packages. Other methods can be updated with `mise self-update`. diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f6178e9050b..450fc03d4ca 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -288,6 +288,28 @@ pub(crate) fn expand_deferred_subcommands(mut command: clap::Command) -> clap::C } impl Commands { + /// Whether this parsed command may trigger a pre-command automatic update. + /// + /// This operates on clap's canonical command variant so aliases such as + /// `dr` inherit the same policy as `doctor`. + fn allows_auto_update(&self) -> bool { + !matches!( + self, + Self::Activate(_) + | Self::Completion(_) + | Self::Deactivate(_) + | Self::Doctor(_) + | Self::HookEnv(_) + | Self::HookNotFound(_) + | Self::Implode(_) + | Self::SelfUpdate(_) + | Self::Settings(_) + | Self::Shell(_) + | Self::Usage(_) + | Self::Version(_) + ) + } + fn implicitly_trusts_active_config(&self) -> bool { matches!( self, @@ -790,8 +812,18 @@ impl Cli { validate_cd_path(&cli.cd)?; measure!("add_cli_matches", { Settings::add_cli_matches(&cli) }); let _ = measure!("settings", { Settings::try_get() }); + let auto_update_command_eligible = !print_version + && cli + .command + .as_ref() + .is_some_and(Commands::allows_auto_update); measure!("auto_update", { - self_update::maybe_auto_update(args, original_cwd.as_deref()).await? + self_update::maybe_auto_update( + args, + original_cwd.as_deref(), + auto_update_command_eligible, + ) + .await? }); measure!("trust_active_config", { config_file::trust_active_config()? @@ -1041,6 +1073,33 @@ mod tests { } } + #[test] + fn shell_commands_and_aliases_do_not_allow_auto_update() { + for args in [ + vec!["mise", "doctor"], + vec!["mise", "dr"], + vec!["mise", "hook-env"], + vec!["mise", "hook-not-found", "missing-bin"], + vec!["mise", "version"], + vec!["mise", "v"], + ] { + let cli = Cli::try_parse_from(&args).unwrap(); + assert!( + !cli.command + .as_ref() + .is_some_and(Commands::allows_auto_update), + "expected {args:?} to skip automatic updates" + ); + } + + let cli = Cli::try_parse_from(["mise", "install"]).unwrap(); + assert!( + cli.command + .as_ref() + .is_some_and(Commands::allows_auto_update) + ); + } + /// Guards [`GLOBAL_FLAGS_WITH_VALUES`]. It is hardcoded so that startup does /// not have to build the clap tree; this keeps it honest. If you added a /// value-taking flag to `Cli`, add it to that list too. diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index 4e33aecd8a5..c9e36c79f01 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -12,6 +12,7 @@ use crate::env; #[cfg(windows)] use crate::file::MAX_PATH; use std::collections::BTreeMap; +use std::ffi::OsStr; use std::fs; #[cfg(target_os = "macos")] use std::path::Path; @@ -20,21 +21,6 @@ use std::process::Command; use std::time::Duration; const AUTO_UPDATE_REEXEC_ENV: &str = "__MISE_AUTO_UPDATE_REEXEC"; -const AUTO_UPDATE_SKIP_COMMANDS: &[&str] = &[ - "activate", - "completion", - "deactivate", - "doctor", - "hook-env", - "implode", - "self-update", - "settings", - "shell", - "usage", - "v", - "version", -]; - #[derive(Debug, Default, serde::Deserialize)] struct InstructionsToml { message: Option, @@ -94,16 +80,16 @@ pub(crate) fn append_self_update_instructions(mut message: String) -> String { message } +/// Checks for and installs an update before an eligible interactive command. +/// Failures are deliberately non-fatal so the requested command still runs. pub(crate) async fn maybe_auto_update( args: &[String], original_cwd: Option<&std::path::Path>, + command_eligible: bool, ) -> Result<()> { let Ok(settings) = Settings::try_get() else { return Ok(()); }; - let command = crate::cli::first_non_global_arg_idx_cached(args) - .and_then(|idx| args.get(idx)) - .map(String::as_str); if !auto_update_eligible(AutoUpdateContext { enabled: settings.auto_update, offline: settings.offline(), @@ -112,7 +98,7 @@ pub(crate) async fn maybe_auto_update( attended: console::user_attended_stderr(), already_reexecuted: env::var_os(AUTO_UPDATE_REEXEC_ENV).is_some(), self_update_available: SelfUpdate::is_available(), - command, + command_eligible, }) { return Ok(()); } @@ -130,7 +116,13 @@ pub(crate) async fn maybe_auto_update( } }; let last_check_path = crate::dirs::CACHE.join("auto-update-last-check"); - let check_duration = settings.auto_update_check_duration(); + let check_duration = match settings.auto_update_check_duration() { + Ok(duration) => duration, + Err(err) => { + debug!("automatic mise update has an invalid check duration: {err:#}"); + return Ok(()); + } + }; if !auto_update_check_due(&last_check_path, check_duration) { return Ok(()); } @@ -138,7 +130,10 @@ pub(crate) async fn maybe_auto_update( debug!("automatic mise update could not record its check: {err:#}"); return Ok(()); } - let Some(version) = crate::cli::version::check_for_new_version(check_duration).await else { + // The marker above is the auto-update throttle. Bypass the separate shared + // version cache so a shorter-lived `mise version` lookup cannot make this + // due check accept stale data and advance the marker for another interval. + let Some(version) = crate::cli::version::check_for_new_version(Duration::ZERO).await else { return Ok(()); }; @@ -156,12 +151,14 @@ pub(crate) async fn maybe_auto_update( reexec(args, original_cwd) } +/// Returns whether the automatic-update attempt marker has expired. fn auto_update_check_due(path: &std::path::Path, duration: Duration) -> bool { crate::file::modified_duration(path).map_or(true, |age| age >= duration) } +/// Runtime conditions that gate automatic updates. #[derive(Clone, Copy)] -struct AutoUpdateContext<'a> { +struct AutoUpdateContext { enabled: bool, offline: bool, prefer_offline: bool, @@ -169,10 +166,11 @@ struct AutoUpdateContext<'a> { attended: bool, already_reexecuted: bool, self_update_available: bool, - command: Option<&'a str>, + command_eligible: bool, } -fn auto_update_eligible(context: AutoUpdateContext<'_>) -> bool { +/// Applies the automatic-update safety policy without side effects. +fn auto_update_eligible(context: AutoUpdateContext) -> bool { context.enabled && !context.offline && !context.prefer_offline @@ -180,22 +178,29 @@ fn auto_update_eligible(context: AutoUpdateContext<'_>) -> bool { && context.attended && !context.already_reexecuted && context.self_update_available - && context - .command - .is_some_and(|command| !AUTO_UPDATE_SKIP_COMMANDS.contains(&command)) + && context.command_eligible } -#[cfg(unix)] -fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { - use std::os::unix::process::CommandExt; - +/// Builds the replacement process with the original arguments, directory, and +/// a recursion guard shared by every platform-specific re-exec path. +fn build_reexec_command(args: I, original_cwd: Option<&std::path::Path>) -> Command +where + I: IntoIterator, + S: AsRef, +{ let mut command = Command::new(&*env::MISE_BIN); - command - .args(std::env::args_os().skip(1)) - .env(AUTO_UPDATE_REEXEC_ENV, "1"); + command.args(args).env(AUTO_UPDATE_REEXEC_ENV, "1"); if let Some(cwd) = original_cwd { command.current_dir(cwd); } + command +} + +#[cfg(unix)] +fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { + use std::os::unix::process::CommandExt; + + let mut command = build_reexec_command(std::env::args_os().skip(1), original_cwd); let err = command.exec(); warn!("mise was updated but could not re-execute the command: {err}"); Ok(()) @@ -203,24 +208,14 @@ fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<() #[cfg(windows)] fn reexec(_args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { - let mut command = Command::new(&*env::MISE_BIN); - command - .args(std::env::args_os().skip(1)) - .env(AUTO_UPDATE_REEXEC_ENV, "1"); - if let Some(cwd) = original_cwd { - command.current_dir(cwd); - } + let mut command = build_reexec_command(std::env::args_os().skip(1), original_cwd); let status = command.status()?; Err(crate::request_exit(status.code().unwrap_or(1))) } #[cfg(not(any(unix, windows)))] fn reexec(args: &[String], original_cwd: Option<&std::path::Path>) -> Result<()> { - let mut command = Command::new(&*env::MISE_BIN); - command.args(&args[1..]).env(AUTO_UPDATE_REEXEC_ENV, "1"); - if let Some(cwd) = original_cwd { - command.current_dir(cwd); - } + let mut command = build_reexec_command(&args[1..], original_cwd); let status = command.status()?; Err(crate::request_exit(status.code().unwrap_or(1))) } @@ -653,7 +648,7 @@ impl SelfUpdate { mod auto_update_tests { use super::*; - fn eligible_context() -> AutoUpdateContext<'static> { + fn eligible_context() -> AutoUpdateContext { AutoUpdateContext { enabled: true, offline: false, @@ -662,7 +657,7 @@ mod auto_update_tests { attended: true, already_reexecuted: false, self_update_available: true, - command: Some("install"), + command_eligible: true, } } @@ -709,19 +704,28 @@ mod auto_update_tests { } #[test] - fn shell_and_management_commands_do_not_update() { - for command in AUTO_UPDATE_SKIP_COMMANDS { - assert!(!auto_update_eligible(AutoUpdateContext { - command: Some(command), - ..eligible_context() - })); - } + fn ineligible_commands_do_not_update() { assert!(!auto_update_eligible(AutoUpdateContext { - command: None, + command_eligible: false, ..eligible_context() })); } + #[test] + fn reexec_preserves_arguments_directory_and_guard() { + use std::ffi::OsString; + + let cwd = std::path::Path::new("a directory"); + let args = [OsString::from("install"), OsString::from("node@22 beta")]; + let command = build_reexec_command(&args, Some(cwd)); + + assert_eq!(command.get_args().collect::>(), args); + assert_eq!(command.get_current_dir(), Some(cwd)); + assert!(command.get_envs().any(|(key, value)| { + key == AUTO_UPDATE_REEXEC_ENV && value == Some(OsStr::new("1")) + })); + } + #[test] fn automatic_update_attempts_are_throttled() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/cli/self_update_stub.rs b/src/cli/self_update_stub.rs index e1bd77fef9c..e0dec9639d8 100644 --- a/src/cli/self_update_stub.rs +++ b/src/cli/self_update_stub.rs @@ -7,6 +7,7 @@ use crate::env; pub(crate) async fn maybe_auto_update( _args: &[String], _original_cwd: Option<&std::path::Path>, + _command_eligible: bool, ) -> crate::Result<()> { Ok(()) } diff --git a/src/cli/version.rs b/src/cli/version.rs index f37f20d46fa..4bc23ba9991 100644 --- a/src/cli/version.rs +++ b/src/cli/version.rs @@ -139,17 +139,21 @@ enum VersionHint { AutoUpdate, Homebrew, OptimizedBinary, + OptimizedBinaryWindows, } fn select_version_hint( self_update_available: bool, auto_update: bool, homebrew: bool, + windows: bool, ) -> Option { if self_update_available { (!auto_update).then_some(VersionHint::AutoUpdate) } else if homebrew { Some(VersionHint::Homebrew) + } else if windows { + Some(VersionHint::OptimizedBinaryWindows) } else { Some(VersionHint::OptimizedBinary) } @@ -159,8 +163,12 @@ pub(crate) fn show_auto_update_hint() { let Ok(settings) = Settings::try_get() else { return; }; - if select_version_hint(SelfUpdate::is_available(), settings.auto_update, false) - == Some(VersionHint::AutoUpdate) + if select_version_hint( + SelfUpdate::is_available(), + settings.auto_update, + false, + cfg!(windows), + ) == Some(VersionHint::AutoUpdate) { hint!( "auto_update", @@ -178,11 +186,12 @@ pub(crate) fn show_version_hint() { SelfUpdate::is_available(), settings.auto_update, is_homebrew_install(), + cfg!(windows), ) { Some(VersionHint::AutoUpdate) => show_auto_update_hint(), Some(VersionHint::Homebrew) => hint!( "optimized_mise_homebrew", - "Homebrew's mise formula is typically 20–30% slower and about 40% larger than the optimized mise.run binary; replace it with", + "Homebrew's mise formula can be substantially slower and larger than the optimized mise.run binary; replace it with", "brew uninstall mise && curl https://mise.run | sh" ), Some(VersionHint::OptimizedBinary) => hint!( @@ -190,6 +199,11 @@ pub(crate) fn show_version_hint() { "third-party package builds may be slower and larger than mise's optimized binary; install the official build with", "curl https://mise.run | sh" ), + Some(VersionHint::OptimizedBinaryWindows) => hint!( + "optimized_mise_binary", + "third-party package builds may be slower and larger than mise's optimized binary; download the official build from", + "https://github.com/jdx/mise/releases/latest" + ), None => {} } } @@ -384,21 +398,25 @@ mod tests { #[test] fn version_hint_promotes_auto_update_for_official_binaries() { assert_eq!( - select_version_hint(true, false, false), + select_version_hint(true, false, false, false), Some(VersionHint::AutoUpdate) ); - assert_eq!(select_version_hint(true, true, false), None); + assert_eq!(select_version_hint(true, true, false, false), None); } #[test] fn version_hint_promotes_optimized_binaries_for_package_installs() { assert_eq!( - select_version_hint(false, false, true), + select_version_hint(false, false, true, false), Some(VersionHint::Homebrew) ); assert_eq!( - select_version_hint(false, false, false), + select_version_hint(false, false, false, false), Some(VersionHint::OptimizedBinary) ); + assert_eq!( + select_version_hint(false, false, false, true), + Some(VersionHint::OptimizedBinaryWindows) + ); } } diff --git a/src/config/settings.rs b/src/config/settings.rs index df2a5b7ed3c..db10a8598e2 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -1188,8 +1188,8 @@ impl Settings { } #[cfg(feature = "self_update")] - pub(crate) fn auto_update_check_duration(&self) -> Duration { - duration::parse_duration(&self.auto_update_check_duration).unwrap() + pub(crate) fn auto_update_check_duration(&self) -> eyre::Result { + duration::parse_duration(&self.auto_update_check_duration) } pub(crate) fn fetch_remote_versions_timeout(&self) -> Duration {