repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/self_update.rs
src/cli/self_update.rs
use color_eyre::Result; use color_eyre::eyre::bail; use console::style; use self_update::backends::github::Update; use self_update::{Status, cargo_crate_version}; use crate::cli::version::{ARCH, OS}; use crate::config::Settings; use crate::env; use std::collections::BTreeMap; use std::fs; #[cfg(target_os = "macos")] use std::path::Path; use std::path::PathBuf; #[derive(Debug, Default, serde::Deserialize)] struct InstructionsToml { message: Option<String>, #[serde(flatten)] commands: BTreeMap<String, String>, } fn read_instructions_file(path: &PathBuf) -> Option<String> { let body = fs::read_to_string(path).ok()?; let parsed: InstructionsToml = toml::from_str(&body).ok()?; if let Some(msg) = parsed.message { return Some(msg); } if let Some((_k, v)) = parsed.commands.into_iter().next() { return Some(v); } None } pub fn upgrade_instructions_text() -> Option<String> { if let Some(path) = &*env::MISE_SELF_UPDATE_INSTRUCTIONS && let Some(msg) = read_instructions_file(path) { return Some(msg); } None } /// Appends self-update guidance and packaging instructions (if any) to a message. pub fn append_self_update_instructions(mut message: String) -> String { if SelfUpdate::is_available() { message.push_str("\nRun `mise self-update` to update mise"); } if let Some(instructions) = upgrade_instructions_text() { message.push('\n'); message.push_str(&instructions); } message } /// Updates mise itself. /// /// Uses the GitHub Releases API to find the latest release and binary. /// By default, this will also update any installed plugins. /// Uses the `GITHUB_API_TOKEN` environment variable if set for higher rate limits. /// /// This command is not available if mise is installed via a package manager. #[derive(Debug, Default, clap::Args)] #[clap(verbatim_doc_comment)] pub struct SelfUpdate { /// Update to a specific version version: Option<String>, /// Update even if already up to date #[clap(long, short)] force: bool, /// Skip confirmation prompt #[clap(long, short)] yes: bool, /// Disable auto-updating plugins #[clap(long)] no_plugins: bool, } impl SelfUpdate { pub async fn run(self) -> Result<()> { if !Self::is_available() && !self.force { if let Some(instructions) = upgrade_instructions_text() { warn!("{}", instructions); } bail!("mise is installed via a package manager, cannot update"); } let status = self.do_update()?; if status.updated() { let version = style(status.version()).bright().yellow(); miseprintln!("Updated mise to {version}"); } else { miseprintln!("mise is already up to date"); } if !self.no_plugins { cmd!(&*env::MISE_BIN, "plugins", "update").run()?; } Ok(()) } fn do_update(&self) -> Result<Status> { let mut update = Update::configure(); if let Some(token) = &*env::GITHUB_TOKEN { update.auth_token(token); } #[cfg(windows)] let bin_path_in_archive = "mise/bin/mise.exe"; #[cfg(not(windows))] let bin_path_in_archive = "mise/bin/mise"; update .repo_owner("jdx") .repo_name("mise") .bin_name("mise") .current_version(cargo_crate_version!()) .bin_path_in_archive(bin_path_in_archive); let settings = Settings::try_get(); let v = self .version .clone() .map_or_else( || -> Result<String> { Ok(update.build()?.get_latest_release()?.version) }, Ok, ) .map(|v| format!("v{v}"))?; let target = format!("{}-{}", *OS, *ARCH); #[cfg(target_env = "musl")] let target = format!("{target}-musl"); if self.force || self.version.is_some() { update.target_version_tag(&v); } #[cfg(windows)] let target = format!("mise-{v}-{target}.zip"); #[cfg(not(windows))] let target = format!("mise-{v}-{target}.tar.gz"); let status = update .verifying_keys([*include_bytes!("../../zipsign.pub")]) .show_download_progress(true) .target(&target) .no_confirm(settings.is_ok_and(|s| s.yes) || self.yes) .build()? .update()?; // Verify macOS binary signature after update #[cfg(target_os = "macos")] if status.updated() { Self::verify_macos_signature(&env::MISE_BIN)?; } Ok(status) } pub fn is_available() -> bool { if let Some(b) = *env::MISE_SELF_UPDATE_AVAILABLE { return b; } let has_disable = env::MISE_SELF_UPDATE_DISABLED_PATH.is_some(); let has_instructions = env::MISE_SELF_UPDATE_INSTRUCTIONS.is_some(); !(has_disable || has_instructions) } #[cfg(target_os = "macos")] fn verify_macos_signature(binary_path: &Path) -> Result<()> { use std::process::Command; debug!( "Verifying macOS code signature for: {}", binary_path.display() ); // Check if codesign is available let codesign_check = Command::new("which").arg("codesign").output(); if codesign_check.is_err() || !codesign_check.unwrap().status.success() { warn!("codesign command not found in PATH, skipping binary signature verification"); warn!("This is unusual on macOS - consider verifying your system installation"); return Ok(()); } // Verify signature and identifier in one step using --test-requirement let output = Command::new("codesign") .args([ "--verify", "--deep", "--strict", "-R=identifier \"dev.jdx.mise\"", ]) .arg(binary_path) .output()?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); bail!( "macOS binary signature verification failed (invalid signature or incorrect identifier): {}", stderr.trim() ); } debug!("macOS binary signature verified successfully"); Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/install.rs
src/cli/install.rs
use std::collections::HashSet; use std::str::FromStr; use std::sync::Arc; use crate::cli::args::ToolArg; use crate::config::Config; use crate::config::Settings; use crate::duration::parse_into_timestamp; use crate::hooks::Hooks; use crate::toolset::{InstallOptions, ResolveOptions, ToolRequest, ToolSource, Toolset}; use crate::{config, env, hooks}; use eyre::Result; use itertools::Itertools; use jiff::Timestamp; /// Install a tool version /// /// Installs a tool version to `~/.local/share/mise/installs/<PLUGIN>/<VERSION>` /// Installing alone will not activate the tools so they won't be in PATH. /// To install and/or activate in one command, use `mise use` which will create a `mise.toml` file /// in the current directory to activate this tool when inside the directory. /// Alternatively, run `mise exec <TOOL>@<VERSION> -- <COMMAND>` to execute a tool without creating config files. /// /// Tools will be installed in parallel. To disable, set `--jobs=1` or `MISE_JOBS=1` #[derive(Debug, clap::Args)] #[clap(visible_alias = "i", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Install { /// Tool(s) to install /// e.g.: node@20 #[clap(value_name = "TOOL@VERSION")] tool: Option<Vec<ToolArg>>, /// Force reinstall even if already installed #[clap(long, short, requires = "tool")] force: bool, /// Number of jobs to run in parallel /// [default: 4] #[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)] jobs: Option<usize>, /// Show what would be installed without actually installing #[clap(long, short = 'n', verbatim_doc_comment)] dry_run: bool, /// Show installation output /// /// This argument will print plugin output such as download, configuration, and compilation output. #[clap(long, short, action = clap::ArgAction::Count)] verbose: u8, /// Only install versions released before this date /// /// Supports absolute dates like "2024-06-01" and relative durations like "90d" or "1y". #[clap(long, verbatim_doc_comment)] before: Option<String>, /// Directly pipe stdin/stdout/stderr from plugin to user /// Sets --jobs=1 #[clap(long, overrides_with = "jobs")] raw: bool, } impl Install { #[async_backtrace::framed] pub async fn run(self) -> Result<()> { let config = Config::get().await?; match &self.tool { Some(runtime) => { let original_tool_args = env::TOOL_ARGS.read().unwrap().clone(); env::TOOL_ARGS.write().unwrap().clone_from(runtime); self.install_runtimes(config, runtime, original_tool_args) .await? } None => self.install_missing_runtimes(config).await?, }; Ok(()) } #[async_backtrace::framed] async fn install_runtimes( &self, mut config: Arc<Config>, runtimes: &[ToolArg], original_tool_args: Vec<ToolArg>, ) -> Result<()> { let trs = config.get_tool_request_set().await?; // Expand wildcards (e.g., "pipx:*") to actual ToolArgs from config let mut has_unmatched_wildcard = false; let expanded_runtimes: Vec<ToolArg> = runtimes .iter() .flat_map(|ta| { if let Some(backend_prefix) = ta.ba.short.strip_suffix(":*") { // Find all tools in config with this backend prefix let matching: Vec<_> = trs .tools .keys() .filter(|ba| { ba.short.starts_with(&format!("{backend_prefix}:")) && ba.tool_name != "*" }) .filter_map(|ba| ToolArg::from_str(&ba.short).ok()) .collect(); if matching.is_empty() { warn!("no tools found in config matching {}", ta.ba.short); has_unmatched_wildcard = true; } return matching; } vec![ta.clone()] }) .collect(); // If only wildcards were provided and none matched, exit early if expanded_runtimes.is_empty() && has_unmatched_wildcard { return Ok(()); } let tools: HashSet<String> = expanded_runtimes .iter() .map(|ta| ta.ba.short.clone()) .collect(); let mut ts: Toolset = trs.filter_by_tool(tools).into(); let tool_versions = self.get_requested_tool_versions(&ts, &expanded_runtimes)?; let mut versions = if tool_versions.is_empty() { warn!("no runtimes to install"); warn!("specify a version with `mise install <PLUGIN>@<VERSION>`"); vec![] } else { ts.install_all_versions(&mut config, tool_versions, &self.install_opts()?) .await? }; // because we may be installing a tool that is not in config, we need to restore the original tool args and reset everything env::TOOL_ARGS .write() .unwrap() .clone_from(&original_tool_args); let config = Config::reset().await?; let ts = config.get_toolset().await?; let current_versions = ts.list_current_versions(); // ensure that only current versions are sent to lockfile rebuild versions.retain(|tv| current_versions.iter().any(|(_, cv)| tv == cv)); // Skip rebuilding shims and symlinks in dry-run mode if !self.dry_run { config::rebuild_shims_and_runtime_symlinks(&config, ts, &versions).await?; } Ok(()) } fn install_opts(&self) -> Result<InstallOptions> { Ok(InstallOptions { force: self.force, jobs: self.jobs, raw: self.raw, missing_args_only: false, resolve_options: ResolveOptions { use_locked_version: true, latest_versions: true, before_date: self.get_before_date()?, }, dry_run: self.dry_run, locked: Settings::get().locked, ..Default::default() }) } /// Get the before_date from CLI flag or settings fn get_before_date(&self) -> Result<Option<Timestamp>> { if let Some(before) = &self.before { return Ok(Some(parse_into_timestamp(before)?)); } if let Some(before) = &Settings::get().install_before { return Ok(Some(parse_into_timestamp(before)?)); } Ok(None) } fn get_requested_tool_versions( &self, ts: &Toolset, runtimes: &[ToolArg], ) -> Result<Vec<ToolRequest>> { let mut requests = vec![]; for ta in ToolArg::double_tool_condition(runtimes)? { match ta.tvr { // user provided an explicit version Some(tv) => requests.push(tv), None => { match ts.versions.get(ta.ba.as_ref()) { // the tool is in config so fetch the params from config // this may match multiple versions of one tool (e.g.: python) Some(tvl) => { for tvr in &tvl.requests { requests.push(tvr.clone()); } } // in this case the user specified a tool which is not in config // so we default to @latest with no options None => { let tvr = ToolRequest::Version { backend: ta.ba.clone(), version: "latest".into(), options: ta.ba.opts(), source: ToolSource::Argument, }; requests.push(tvr); } } } } } Ok(requests) } async fn install_missing_runtimes(&self, mut config: Arc<Config>) -> eyre::Result<()> { let trs = measure!("get_tool_request_set", { config.get_tool_request_set().await? }); // Check for tools that don't exist in the registry // These were tracked during build() before being filtered out for ba in &trs.unknown_tools { // This will error with a proper message like "tool not found in mise tool registry" ba.backend()?; } let versions = measure!("fetching missing runtimes", { trs.missing_tools(&config) .await .into_iter() .cloned() .collect_vec() }); let versions = if versions.is_empty() { measure!("run_postinstall_hook", { info!("all tools are installed"); hooks::run_one_hook( &config, config.get_toolset().await?, Hooks::Postinstall, None, ) .await; vec![] }) } else { let mut ts = Toolset::from(trs.clone()); measure!("install_all_versions", { ts.install_all_versions(&mut config, versions, &self.install_opts()?) .await? }) }; // Skip rebuilding shims and symlinks in dry-run mode if !self.dry_run { measure!("rebuild_shims_and_runtime_symlinks", { let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(&config, ts, &versions).await?; }); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise install node@20.0.0</bold> # install specific node version $ <bold>mise install node@20</bold> # install fuzzy node version $ <bold>mise install node</bold> # install version specified in mise.toml $ <bold>mise install</bold> # installs everything specified in mise.toml "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/watch.rs
src/cli/watch.rs
use crate::Result; use crate::cli::Cli; use crate::cli::args::BackendArg; use crate::cmd; use crate::config::Config; use crate::env; use crate::exit::exit; use crate::toolset::ToolsetBuilder; use clap::{CommandFactory, ValueEnum, ValueHint}; use console::style; use eyre::bail; use itertools::Itertools; use std::cmp::PartialEq; use std::iter::once; use std::path::PathBuf; /// Run task(s) and watch for changes to rerun it /// /// This command uses the `watchexec` tool to watch for changes to files and rerun the specified task(s). /// It must be installed for this command to work, but you can install it with `mise use -g watchexec@latest`. #[derive(Debug, clap::Args)] #[clap(visible_alias = "w", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Watch { /// Tasks to run /// Can specify multiple tasks by separating with `:::` /// e.g.: `mise run task1 arg1 arg2 ::: task2 arg1 arg2` #[clap(allow_hyphen_values = true, verbatim_doc_comment)] task: Option<String>, /// Tasks to run #[clap(short, long, verbatim_doc_comment, hide = true)] task_flag: Vec<String>, /// Task and arguments to run #[clap(allow_hyphen_values = true, trailing_var_arg = true)] args: Vec<String>, /// Files to watch /// Defaults to sources from the task(s) #[clap(short, long, verbatim_doc_comment, hide = true)] glob: Vec<String>, /// Run only the specified tasks skipping all dependencies #[clap(long, verbatim_doc_comment)] pub skip_deps: bool, #[clap(flatten)] watchexec: WatchexecArgs, } impl Watch { pub async fn run(self) -> Result<()> { if let Some(task) = &self.task { if task == "-h" { self.get_clap_command().print_help()?; return Ok(()); } if task == "--help" { self.get_clap_command().print_long_help()?; return Ok(()); } } let config = Config::get().await?; let ts = ToolsetBuilder::new().build(&config).await?; if let Err(err) = which::which("watchexec") { let watchexec: BackendArg = "watchexec".into(); if !ts.versions.contains_key(&watchexec) { eprintln!("{}: {}", style("Error").red().bold(), err); eprintln!("{}: Install watchexec with:", style("Hint").bold()); eprintln!(" mise use -g watchexec@latest"); exit(1); } } let args = once(self.task) .flatten() .chain(self.task_flag.iter().cloned()) .chain(self.args.iter().cloned()) .collect::<Vec<_>>(); if args.is_empty() { bail!("No tasks specified"); } let tasks = crate::task::task_list::get_task_lists(&config, &args, false, false).await?; let mut args = vec![]; if let Some(delay_run) = self.watchexec.delay_run { args.push("--delay-run".to_string()); args.push(delay_run); } if let Some(poll) = self.watchexec.poll { args.push("--poll".to_string()); args.push(poll); } if let Some(signal) = self.watchexec.signal { args.push("--signal".to_string()); args.push(signal); } if let Some(stop_signal) = self.watchexec.stop_signal { args.push("--stop-signal".to_string()); args.push(stop_signal); } if self.watchexec.stop_timeout != "10s" { args.push("--stop-timeout".to_string()); args.push(self.watchexec.stop_timeout); } if self.watchexec.debounce != "50ms" { args.push("--debounce".to_string()); args.push(self.watchexec.debounce); } if self.watchexec.stdin_quit { args.push("--stdin-quit".to_string()); } if self.watchexec.no_vcs_ignore { args.push("--no-vcs-ignore".to_string()); } if self.watchexec.no_project_ignore { args.push("--no-project-ignore".to_string()); } if self.watchexec.no_global_ignore { args.push("--no-global-ignore".to_string()); } if self.watchexec.no_default_ignore { args.push("--no-default-ignore".to_string()); } if self.watchexec.no_discover_ignore { args.push("--no-discover-ignore".to_string()); } if self.watchexec.ignore_nothing { args.push("--ignore-nothing".to_string()); } if self.watchexec.postpone { args.push("--postpone".to_string()); } if let Some(screen_clear) = self.watchexec.screen_clear { args.push("--clear".to_string()); if let ClearMode::Reset = screen_clear { args.push("reset".to_string()); } } if self.watchexec.restart { args.push("--restart".to_string()); } if self.watchexec.on_busy_update != OnBusyUpdate::DoNothing { args.push("--on-busy-update".to_string()); args.push(self.watchexec.on_busy_update.to_string()); } if !self.watchexec.signal_map.is_empty() { for signal_map in &self.watchexec.signal_map { args.push("--map-signal".to_string()); args.push(signal_map.to_string()); } } if !self.watchexec.recursive_paths.is_empty() { for path in &self.watchexec.recursive_paths { args.push("--watch".to_string()); args.push(path.to_string_lossy().to_string()); } } if !self.watchexec.non_recursive_paths.is_empty() { for path in &self.watchexec.non_recursive_paths { args.push("--watch-non-recursive".to_string()); args.push(path.to_string_lossy().to_string()); } } if !self.watchexec.filter_extensions.is_empty() { for ext in &self.watchexec.filter_extensions { args.push("--exts".to_string()); args.push(ext.to_string()); } } if !self.watchexec.filter_patterns.is_empty() { for pattern in &self.watchexec.filter_patterns { args.push("--filter".to_string()); args.push(pattern.to_string()); } } if let Some(watch_file) = &self.watchexec.watch_file { args.push("--watch-file".to_string()); args.push(watch_file.to_string_lossy().to_string()); } let globs = if self.glob.is_empty() { tasks .iter() .flat_map(|t| t.sources.clone()) .collect::<Vec<_>>() } else { self.glob.clone() }; if !globs.is_empty() { args.push("-f".to_string()); args.extend(itertools::intersperse(globs, "-f".to_string()).collect::<Vec<_>>()); } args.extend([ "--".to_string(), env::MISE_BIN.to_string_lossy().to_string(), "run".to_string(), ]); if self.skip_deps { args.push("--skip-deps".to_string()); } let task_args = itertools::intersperse( tasks.iter().map(|t| { let mut args = vec![t.name.to_string()]; args.extend(t.args.iter().map(|a| a.to_string())); args }), vec![":::".to_string()], ) .flatten() .collect_vec(); for arg in task_args { args.push(arg); } debug!("$ watchexec {}", args.join(" ")); let mut cmd = cmd::cmd("watchexec", &args); for (k, v) in ts.env_with_path(&config).await? { cmd = cmd.env(k, v); } cmd.run()?; Ok(()) } fn get_clap_command(&self) -> clap::Command { Cli::command() .get_subcommands() .find(|s| s.get_name() == "watch") .unwrap() .clone() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise watch build</bold> Runs the "build" tasks. Will re-run the tasks when any of its sources change. Uses "sources" from the tasks definition to determine which files to watch. $ <bold>mise watch build --glob src/**/*.rs</bold> Runs the "build" tasks but specify the files to watch with a glob pattern. This overrides the "sources" from the tasks definition. $ <bold>mise watch build --clear</bold> Extra arguments are passed to watchexec. See `watchexec --help` for details. $ <bold>mise watch serve --watch src --exts rs --restart</bold> Starts an api server, watching for changes to "*.rs" files in "./src" and kills/restarts the server when they change. "# ); //region watchexec const OPTSET_FILTERING: &str = "Filtering"; const OPTSET_COMMAND: &str = "Command"; const OPTSET_DEBUGGING: &str = "Debugging"; const OPTSET_OUTPUT: &str = "Output"; #[derive(Debug, clap::Args)] pub struct WatchexecArgs { /// Watch a specific file or directory /// /// By default, Watchexec watches the current directory. /// /// When watching a single file, it's often better to watch the containing directory instead, /// and filter on the filename. Some editors may replace the file with a new one when saving, /// and some platforms may not detect that or further changes. /// /// Upon starting, Watchexec resolves a "project origin" from the watched paths. See the help /// for '--project-origin' for more information. /// /// This option can be specified multiple times to watch multiple files or directories. /// /// The special value '/dev/null', provided as the only path watched, will cause Watchexec to /// not watch any paths. Other event sources (like signals or key events) may still be used. #[arg( short = 'w', long = "watch", help_heading = OPTSET_FILTERING, value_hint = ValueHint::AnyPath, value_name = "PATH", )] pub recursive_paths: Vec<PathBuf>, /// Watch a specific directory, non-recursively /// /// Unlike '-w', folders watched with this option are not recursed into. /// /// This option can be specified multiple times to watch multiple directories non-recursively. #[arg( short = 'W', long = "watch-non-recursive", help_heading = OPTSET_FILTERING, value_hint = ValueHint::AnyPath, value_name = "PATH", )] pub non_recursive_paths: Vec<PathBuf>, /// Watch files and directories from a file /// /// Each line in the file will be interpreted as if given to '-w'. /// /// For more complex uses (like watching non-recursively), use the argfile capability: build a /// file containing command-line options and pass it to watchexec with `@path/to/argfile`. /// /// The special value '-' will read from STDIN; this in incompatible with '--stdin-quit'. #[arg( short = 'F', long, help_heading = OPTSET_FILTERING, value_hint = ValueHint::AnyPath, value_name = "PATH", )] pub watch_file: Option<PathBuf>, /// Clear screen before running command /// /// If this doesn't completely clear the screen, try '--clear=reset'. #[arg( short = 'c', long = "clear", help_heading = OPTSET_OUTPUT, num_args = 0..=1, default_missing_value = "clear", value_name = "MODE", )] pub screen_clear: Option<ClearMode>, /// What to do when receiving events while the command is running /// /// Default is to 'do-nothing', which ignores events while the command is running, so that /// changes that occur due to the command are ignored, like compilation outputs. You can also /// use 'queue' which will run the command once again when the current run has finished if any /// events occur while it's running, or 'restart', which terminates the running command and starts /// a new one. Finally, there's 'signal', which only sends a signal; this can be useful with /// programs that can reload their configuration without a full restart. /// /// The signal can be specified with the '--signal' option. #[arg( short, long, default_value = "do-nothing", hide_default_value = true, value_name = "MODE" )] pub on_busy_update: OnBusyUpdate, /// Restart the process if it's still running /// /// This is a shorthand for '--on-busy-update=restart'. #[arg( short, long, conflicts_with_all = ["on_busy_update"], )] pub restart: bool, /// Send a signal to the process when it's still running /// /// Specify a signal to send to the process when it's still running. This implies /// '--on-busy-update=signal'; otherwise the signal used when that mode is 'restart' is /// controlled by '--stop-signal'. /// /// See the long documentation for '--stop-signal' for syntax. /// /// Signals are not supported on Windows at the moment, and will always be overridden to 'kill'. /// See '--stop-signal' for more on Windows "signals". #[arg( short, long, conflicts_with_all = ["restart"], value_name = "SIGNAL" )] pub signal: Option<String>, /// Signal to send to stop the command /// /// This is used by 'restart' and 'signal' modes of '--on-busy-update' (unless '--signal' is /// provided). The restart behaviour is to send the signal, wait for the command to exit, and if /// it hasn't exited after some time (see '--timeout-stop'), forcefully terminate it. /// /// The default on unix is "SIGTERM". /// /// Input is parsed as a full signal name (like "SIGTERM"), a short signal name (like "TERM"), /// or a signal number (like "15"). All input is case-insensitive. /// /// On Windows this option is technically supported but only supports the "KILL" event, as /// Watchexec cannot yet deliver other events. Windows doesn't have signals as such; instead it /// has termination (here called "KILL" or "STOP") and "CTRL+C", "CTRL+BREAK", and "CTRL+CLOSE" /// events. For portability the unix signals "SIGKILL", "SIGINT", "SIGTERM", and "SIGHUP" are /// respectively mapped to these. #[arg(long, value_name = "SIGNAL")] pub stop_signal: Option<String>, /// Time to wait for the command to exit gracefully /// /// This is used by the 'restart' mode of '--on-busy-update'. After the graceful stop signal /// is sent, Watchexec will wait for the command to exit. If it hasn't exited after this time, /// it is forcefully terminated. /// /// Takes a unit-less value in seconds, or a time span value such as "5min 20s". /// Providing a unit-less value is deprecated and will warn; it will be an error in the future. /// /// The default is 10 seconds. Set to 0 to immediately force-kill the command. /// /// This has no practical effect on Windows as the command is always forcefully terminated; see /// '--stop-signal' for why. #[arg( long, default_value = "10s", hide_default_value = true, value_name = "TIMEOUT" )] pub stop_timeout: String, /// Translate signals from the OS to signals to send to the command /// /// Takes a pair of signal names, separated by a colon, such as "TERM:INT" to map SIGTERM to /// SIGINT. The first signal is the one received by watchexec, and the second is the one sent to /// the command. The second can be omitted to discard the first signal, such as "TERM:" to /// not do anything on SIGTERM. /// /// If SIGINT or SIGTERM are mapped, then they no longer quit Watchexec. Besides making it hard /// to quit Watchexec itself, this is useful to send pass a Ctrl-C to the command without also /// terminating Watchexec and the underlying program with it, e.g. with "INT:INT". /// /// This option can be specified multiple times to map multiple signals. /// /// Signal syntax is case-insensitive for short names (like "TERM", "USR2") and long names (like /// "SIGKILL", "SIGHUP"). Signal numbers are also supported (like "15", "31"). On Windows, the /// forms "STOP", "CTRL+C", and "CTRL+BREAK" are also supported to receive, but Watchexec cannot /// yet deliver other "signals" than a STOP. #[arg(long = "map-signal", value_name = "SIGNAL:SIGNAL")] pub signal_map: Vec<String>, /// Time to wait for new events before taking action /// /// When an event is received, Watchexec will wait for up to this amount of time before handling /// it (such as running the command). This is essential as what you might perceive as a single /// change may actually emit many events, and without this behaviour, Watchexec would run much /// too often. Additionally, it's not infrequent that file writes are not atomic, and each write /// may emit an event, so this is a good way to avoid running a command while a file is /// partially written. /// /// An alternative use is to set a high value (like "30min" or longer), to save power or /// bandwidth on intensive tasks, like an ad-hoc backup script. In those use cases, note that /// every accumulated event will build up in memory. /// /// Takes a unit-less value in milliseconds, or a time span value such as "5sec 20ms". /// Providing a unit-less value is deprecated and will warn; it will be an error in the future. /// /// The default is 50 milliseconds. Setting to 0 is highly discouraged. #[arg( long, short, default_value = "50ms", hide_default_value = true, value_name = "TIMEOUT" )] pub debounce: String, /// Exit when stdin closes /// /// This watches the stdin file descriptor for EOF, and exits Watchexec gracefully when it is /// closed. This is used by some process managers to avoid leaving zombie processes around. #[arg(long)] pub stdin_quit: bool, /// Don't load gitignores /// /// Among other VCS exclude files, like for Mercurial, Subversion, Bazaar, DARCS, Fossil. Note /// that Watchexec will detect which of these is in use, if any, and only load the relevant /// files. Both global (like '~/.gitignore') and local (like '.gitignore') files are considered. /// /// This option is useful if you want to watch files that are ignored by Git. #[arg( long, help_heading = OPTSET_FILTERING, )] pub no_vcs_ignore: bool, /// Don't load project-local ignores /// /// This disables loading of project-local ignore files, like '.gitignore' or '.ignore' in the /// watched project. This is contrasted with '--no-vcs-ignore', which disables loading of Git /// and other VCS ignore files, and with '--no-global-ignore', which disables loading of global /// or user ignore files, like '~/.gitignore' or '~/.config/watchexec/ignore'. /// /// Supported project ignore files: /// /// - Git: .gitignore at project root and child directories, .git/info/exclude, and the file pointed to by `core.excludesFile` in .git/config. /// - Mercurial: .hgignore at project root and child directories. /// - Bazaar: .bzrignore at project root. /// - Darcs: _darcs/prefs/boring /// - Fossil: .fossil-settings/ignore-glob /// - Ripgrep/Watchexec/generic: .ignore at project root and child directories. /// /// VCS ignore files (Git, Mercurial, Bazaar, Darcs, Fossil) are only used if the corresponding /// VCS is discovered to be in use for the project/origin. For example, a .bzrignore in a Git /// repository will be discarded. #[arg( long, help_heading = OPTSET_FILTERING, verbatim_doc_comment, )] pub no_project_ignore: bool, /// Don't load global ignores /// /// This disables loading of global or user ignore files, like '~/.gitignore', /// '~/.config/watchexec/ignore', or '%APPDATA%\Bazzar\2.0\ignore'. Contrast with /// '--no-vcs-ignore' and '--no-project-ignore'. /// /// Supported global ignore files /// /// - Git (if core.excludesFile is set): the file at that path /// - Git (otherwise): the first found of $XDG_CONFIG_HOME/git/ignore, %APPDATA%/.gitignore, %USERPROFILE%/.gitignore, $HOME/.config/git/ignore, $HOME/.gitignore. /// - Bazaar: the first found of %APPDATA%/Bazzar/2.0/ignore, $HOME/.bazaar/ignore. /// - Watchexec: the first found of $XDG_CONFIG_HOME/watchexec/ignore, %APPDATA%/watchexec/ignore, %USERPROFILE%/.watchexec/ignore, $HOME/.watchexec/ignore. /// /// Like for project files, Git and Bazaar global files will only be used for the corresponding /// VCS as used in the project. #[arg( long, help_heading = OPTSET_FILTERING, verbatim_doc_comment, )] pub no_global_ignore: bool, /// Don't use internal default ignores /// /// Watchexec has a set of default ignore patterns, such as editor swap files, `*.pyc`, `*.pyo`, /// `.DS_Store`, `.bzr`, `_darcs`, `.fossil-settings`, `.git`, `.hg`, `.pijul`, `.svn`, and /// Watchexec log files. #[arg( long, help_heading = OPTSET_FILTERING, )] pub no_default_ignore: bool, /// Don't discover ignore files at all /// /// This is a shorthand for '--no-global-ignore', '--no-vcs-ignore', '--no-project-ignore', but /// even more efficient as it will skip all the ignore discovery mechanisms from the get go. /// /// Note that default ignores are still loaded, see '--no-default-ignore'. #[arg( long, help_heading = OPTSET_FILTERING, )] pub no_discover_ignore: bool, /// Don't ignore anything at all /// /// This is a shorthand for '--no-discover-ignore', '--no-default-ignore'. /// /// Note that ignores explicitly loaded via other command line options, such as '--ignore' or /// '--ignore-file', will still be used. #[arg( long, help_heading = OPTSET_FILTERING, )] pub ignore_nothing: bool, /// Wait until first change before running command /// /// By default, Watchexec will run the command once immediately. With this option, it will /// instead wait until an event is detected before running the command as normal. #[arg(long, short)] pub postpone: bool, /// Sleep before running the command /// /// This option will cause Watchexec to sleep for the specified amount of time before running /// the command, after an event is detected. This is like using "sleep 5 && command" in a shell, /// but portable and slightly more efficient. /// /// Takes a unit-less value in seconds, or a time span value such as "2min 5s". /// Providing a unit-less value is deprecated and will warn; it will be an error in the future. #[arg(long, value_name = "DURATION")] pub delay_run: Option<String>, /// Poll for filesystem changes /// /// By default, and where available, Watchexec uses the operating system's native file system /// watching capabilities. This option disables that and instead uses a polling mechanism, which /// is less efficient but can work around issues with some file systems (like network shares) or /// edge cases. /// /// Optionally takes a unit-less value in milliseconds, or a time span value such as "2s 500ms", /// to use as the polling interval. If not specified, the default is 30 seconds. /// Providing a unit-less value is deprecated and will warn; it will be an error in the future. /// /// Aliased as '--force-poll'. #[arg( long, alias = "force-poll", num_args = 0..=1, default_missing_value = "30s", value_name = "INTERVAL", )] pub poll: Option<String>, /// Use a different shell /// /// By default, Watchexec will use '$SHELL' if it's defined or a default of 'sh' on Unix-likes, /// and either 'pwsh', 'powershell', or 'cmd' (CMD.EXE) on Windows, depending on what Watchexec /// detects is the running shell. /// /// With this option, you can override that and use a different shell, for example one with more /// features or one which has your custom aliases and functions. /// /// If the value has spaces, it is parsed as a command line, and the first word used as the /// shell program, with the rest as arguments to the shell. /// /// The command is run with the '-c' flag (except for 'cmd' on Windows, where it's '/C'). /// /// The special value 'none' can be used to disable shell use entirely. In that case, the /// command provided to Watchexec will be parsed, with the first word being the executable and /// the rest being the arguments, and executed directly. Note that this parsing is rudimentary, /// and may not work as expected in all cases. /// /// Using 'none' is a little more efficient and can enable a stricter interpretation of the /// input, but it also means that you can't use shell features like globbing, redirection, /// control flow, logic, or pipes. /// /// Examples: /// /// Use without shell: /// /// $ watchexec -n -- zsh -x -o shwordsplit scr /// /// Use with powershell core: /// /// $ watchexec --shell=pwsh -- Test-Connection localhost /// /// Use with CMD.exe: /// /// $ watchexec --shell=cmd -- dir /// /// Use with a different unix shell: /// /// $ watchexec --shell=bash -- 'echo $BASH_VERSION' /// /// Use with a unix shell and options: /// /// $ watchexec --shell='zsh -x -o shwordsplit' -- scr #[arg( long, help_heading = OPTSET_COMMAND, value_name = "SHELL", )] pub shell: Option<String>, /// Shorthand for '--shell=none' #[arg( short = 'n', help_heading = OPTSET_COMMAND, )] pub no_shell: bool, /// Configure event emission /// /// Watchexec can emit event information when running a command, which can be used by the child /// process to target specific changed files. /// /// One thing to take care with is assuming inherent behaviour where there is only chance. /// Notably, it could appear as if the `RENAMED` variable contains both the original and the new /// path being renamed. In previous versions, it would even appear on some platforms as if the /// original always came before the new. However, none of this was true. It's impossible to /// reliably and portably know which changed path is the old or new, "half" renames may appear /// (only the original, only the new), "unknown" renames may appear (change was a rename, but /// whether it was the old or new isn't known), rename events might split across two debouncing /// boundaries, and so on. /// /// This option controls where that information is emitted. It defaults to 'none', which doesn't /// emit event information at all. The other options are 'environment' (deprecated), 'stdio', /// 'file', 'json-stdio', and 'json-file'. /// /// The 'stdio' and 'file' modes are text-based: 'stdio' writes absolute paths to the stdin of /// the command, one per line, each prefixed with `create:`, `remove:`, `rename:`, `modify:`, /// or `other:`, then closes the handle; 'file' writes the same thing to a temporary file, and /// its path is given with the $WATCHEXEC_EVENTS_FILE environment variable. /// /// There are also two JSON modes, which are based on JSON objects and can represent the full /// set of events Watchexec handles. Here's an example of a folder being created on Linux: /// /// ```json /// { /// "tags": [ /// { /// "kind": "path", /// "absolute": "/home/user/your/new-folder", /// "filetype": "dir" /// }, /// { /// "kind": "fs", /// "simple": "create", /// "full": "Create(Folder)" /// }, /// { /// "kind": "source", /// "source": "filesystem", /// } /// ], /// "metadata": { /// "notify-backend": "inotify" /// } /// } /// ``` /// /// The fields are as follows: /// /// - `tags`, structured event data. /// - `tags[].kind`, which can be: /// * 'path', along with: /// + `absolute`, an absolute path. /// + `filetype`, a file type if known ('dir', 'file', 'symlink', 'other'). /// * 'fs': /// + `simple`, the "simple" event type ('access', 'create', 'modify', 'remove', or 'other'). /// + `full`, the "full" event type, which is too complex to fully describe here, but looks like 'General(Precise(Specific))'. /// * 'source', along with: /// + `source`, the source of the event ('filesystem', 'keyboard', 'mouse', 'os', 'time', 'internal'). /// * 'keyboard', along with: /// + `keycode`. Currently only the value 'eof' is supported. /// * 'process', for events caused by processes: /// + `pid`, the process ID. /// * 'signal', for signals sent to Watchexec: /// + `signal`, the normalised signal name ('hangup', 'interrupt', 'quit', 'terminate', 'user1', 'user2'). /// * 'completion', for when a command ends: /// + `disposition`, the exit disposition ('success', 'error', 'signal', 'stop', 'exception', 'continued'). /// + `code`, the exit, signal, stop, or exception code. /// - `metadata`, additional information about the event. /// /// The 'json-stdio' mode will emit JSON events to the standard input of the command, one per /// line, then close stdin. The 'json-file' mode will create a temporary file, write the /// events to it, and provide the path to the file with the $WATCHEXEC_EVENTS_FILE /// environment variable. /// /// Finally, the 'environment' mode was the default until 2.0. It sets environment variables /// with the paths of the affected files, for filesystem events: /// /// $WATCHEXEC_COMMON_PATH is set to the longest common path of all of the below variables, /// and so should be prepended to each path to obtain the full/real path. Then: /// /// - $WATCHEXEC_CREATED_PATH is set when files/folders were created /// - $WATCHEXEC_REMOVED_PATH is set when files/folders were removed /// - $WATCHEXEC_RENAMED_PATH is set when files/folders were renamed /// - $WATCHEXEC_WRITTEN_PATH is set when files/folders were modified /// - $WATCHEXEC_META_CHANGED_PATH is set when files/folders' metadata were modified /// - $WATCHEXEC_OTHERWISE_CHANGED_PATH is set for every other kind of pathed event /// /// Multiple paths are separated by the system path separator, ';' on Windows and ':' on unix. /// Within each variable, paths are deduplicated and sorted in binary order (i.e. neither /// Unicode nor locale aware). /// /// This is the legacy mode, is deprecated, and will be removed in the future. The environment /// is a very restricted space, while also limited in what it can usefully represent. Large /// numbers of files will either cause the environment to be truncated, or may error or crash /// the process entirely. The $WATCHEXEC_COMMON_PATH is also unintuitive, as demonstrated by the /// multiple confused queries that have landed in my inbox over the years. #[arg( long, help_heading = OPTSET_COMMAND, verbatim_doc_comment, default_value = "none", hide_default_value = true, value_name = "MODE", required_if_eq("only_emit_events", "true"), )] pub emit_events_to: EmitEvents, /// Only emit events to stdout, run no commands. /// /// This is a convenience option for using Watchexec as a file watcher, without running any /// commands. It is almost equivalent to using `cat` as the command, except that it will not /// spawn a new process for each event. /// /// This option requires `--emit-events-to` to be set, and restricts the available modes to /// `stdio` and `json-stdio`, modifying their behaviour to write to stdout instead of the stdin /// of the command. #[arg( long, help_heading = OPTSET_OUTPUT, conflicts_with_all = ["manual"], )] pub only_emit_events: bool, /// Add env vars to the command /// /// This is a convenience option for setting environment variables for the command, without /// setting them for the Watchexec process itself. ///
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
true
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/upgrade.rs
src/cli/upgrade.rs
use std::sync::Arc; use crate::backend::pipx::PIPXBackend; use crate::cli::args::ToolArg; use crate::config::{Config, Settings, config_file}; use crate::duration::parse_into_timestamp; use crate::file::display_path; use crate::toolset::outdated_info::OutdatedInfo; use crate::toolset::{InstallOptions, ResolveOptions, ToolVersion, ToolsetBuilder}; use crate::ui::multi_progress_report::MultiProgressReport; use crate::ui::progress_report::SingleReport; use crate::{config, ui}; use console::Term; use demand::DemandOption; use eyre::{Context, Result, eyre}; use jiff::Timestamp; /// Upgrades outdated tools /// /// By default, this keeps the range specified in mise.toml. So if you have node@20 set, it will /// upgrade to the latest 20.x.x version available. See the `--bump` flag to use the latest version /// and bump the version in mise.toml. /// /// This will update mise.lock if it is enabled, see https://mise.jdx.dev/configuration/settings.html#lockfile #[derive(Debug, clap::Args)] #[clap(visible_alias = "up", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Upgrade { /// Tool(s) to upgrade /// e.g.: node@20 python@3.10 /// If not specified, all current tools will be upgraded #[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)] tool: Vec<ToolArg>, /// Display multiselect menu to choose which tools to upgrade #[clap(long, short, verbatim_doc_comment, conflicts_with = "tool")] interactive: bool, /// Number of jobs to run in parallel /// [default: 4] #[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)] jobs: Option<usize>, /// Upgrades to the latest version available, bumping the version in mise.toml /// /// For example, if you have `node = "20.0.0"` in your mise.toml but 22.1.0 is the latest available, /// this will install 22.1.0 and set `node = "22.1.0"` in your config. /// /// It keeps the same precision as what was there before, so if you instead had `node = "20"`, it /// would change your config to `node = "22"`. #[clap(long, short = 'l', verbatim_doc_comment)] bump: bool, /// Just print what would be done, don't actually do it #[clap(long, short = 'n', verbatim_doc_comment)] dry_run: bool, /// Only upgrade to versions released before this date /// /// Supports absolute dates like "2024-06-01" and relative durations like "90d" or "1y". /// This can be useful for reproducibility or security purposes. /// /// This only affects fuzzy version matches like "20" or "latest". /// Explicitly pinned versions like "22.5.0" are not filtered. #[clap(long, verbatim_doc_comment)] before: Option<String>, /// Directly pipe stdin/stdout/stderr from plugin to user /// Sets --jobs=1 #[clap(long, overrides_with = "jobs")] raw: bool, } impl Upgrade { pub async fn run(self) -> Result<()> { let mut config = Config::get().await?; let ts = ToolsetBuilder::new() .with_args(&self.tool) .build(&config) .await?; // Compute before_date once to ensure consistency when using relative durations let before_date = self.get_before_date()?; let opts = ResolveOptions { use_locked_version: false, latest_versions: true, before_date, }; // Filter tools to check before doing expensive version lookups let filter_tools = if !self.interactive && !self.tool.is_empty() { Some(self.tool.as_slice()) } else { None }; let mut outdated = ts .list_outdated_versions_filtered(&config, self.bump, &opts, filter_tools) .await; if self.interactive && !outdated.is_empty() { outdated = self.get_interactive_tool_set(&outdated)?; } if outdated.is_empty() { info!("All tools are up to date"); if !self.bump { hint!( "outdated_bump", r#"By default, `mise upgrade` only upgrades versions that match your config. Use `mise upgrade --bump` to upgrade all new versions."#, "" ); } } else { self.upgrade(&mut config, outdated, before_date).await?; } Ok(()) } async fn upgrade( &self, config: &mut Arc<Config>, outdated: Vec<OutdatedInfo>, before_date: Option<Timestamp>, ) -> Result<()> { let mpr = MultiProgressReport::get(); let mut ts = ToolsetBuilder::new() .with_args(&self.tool) .build(config) .await?; let mut outdated_with_config_files: Vec<(&OutdatedInfo, Arc<dyn config_file::ConfigFile>)> = vec![]; for o in outdated.iter() { if let (Some(path), Some(_bump)) = (o.source.path(), &o.bump) { match config_file::parse(path).await { Ok(cf) => outdated_with_config_files.push((o, cf)), Err(e) => warn!("failed to parse {}: {e}", display_path(path)), } } } let config_file_updates = outdated_with_config_files .iter() .filter(|(o, cf)| { if let Ok(trs) = cf.to_tool_request_set() && let Some(versions) = trs.tools.get(o.tool_request.ba()) && versions.len() != 1 { warn!("upgrading multiple versions with --bump is not yet supported"); return false; } true }) .collect::<Vec<_>>(); let to_remove = outdated .iter() .filter_map(|o| o.current.as_ref().map(|current| (o, current))) .collect::<Vec<_>>(); if self.dry_run { for (o, current) in &to_remove { miseprintln!("Would uninstall {}@{}", o.name, current); } for o in &outdated { miseprintln!("Would install {}@{}", o.name, o.latest); } for (o, cf) in &config_file_updates { miseprintln!( "Would bump {}@{} in {}", o.name, o.tool_request.version(), display_path(cf.get_path()) ); } return Ok(()); } let opts = InstallOptions { reason: "upgrade".to_string(), // TODO: can we remove this without breaking e2e/cli/test_upgrade? it may be causing tools to re-install force: true, jobs: self.jobs, raw: self.raw, resolve_options: ResolveOptions { use_locked_version: false, latest_versions: true, before_date, }, ..Default::default() }; // Collect all tool requests for parallel installation let tool_requests: Vec<_> = outdated.iter().map(|o| o.tool_request.clone()).collect(); // Install all tools in parallel let (successful_versions, install_error) = match ts.install_all_versions(config, tool_requests, &opts).await { Ok(versions) => (versions, eyre::Result::Ok(())), Err(e) => match e.downcast_ref::<crate::errors::Error>() { Some(crate::errors::Error::InstallFailed { successful_installations, .. }) => (successful_installations.clone(), eyre::Result::Err(e)), _ => (vec![], eyre::Result::Err(e)), }, }; // Only update config files for tools that were successfully installed for (o, cf) in config_file_updates { if successful_versions .iter() .any(|v| v.ba() == o.tool_version.ba()) { if let Err(e) = cf.replace_versions(o.tool_request.ba(), vec![o.tool_request.clone()]) { return Err(eyre!("Failed to update config for {}: {}", o.name, e)); } if let Err(e) = cf.save() { return Err(eyre!("Failed to save config for {}: {}", o.name, e)); } } } // Only uninstall old versions of tools that were successfully upgraded for (o, tv) in to_remove { if successful_versions .iter() .any(|v| v.ba() == o.tool_version.ba()) { let pr = mpr.add(&format!("uninstall {}@{}", o.name, tv)); if let Err(e) = self .uninstall_old_version(config, &o.tool_version, pr.as_ref()) .await { warn!("Failed to uninstall old version of {}: {}", o.name, e); } } } *config = Config::reset().await?; let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(config, ts, &successful_versions).await?; if successful_versions.iter().any(|v| v.short() == "python") { PIPXBackend::reinstall_all(config) .await .unwrap_or_else(|err| { warn!("failed to reinstall pipx tools: {err}"); }); } Self::print_summary(&outdated, &successful_versions)?; install_error } async fn uninstall_old_version( &self, config: &Arc<Config>, tv: &ToolVersion, pr: &dyn SingleReport, ) -> Result<()> { tv.backend()? .uninstall_version(config, tv, pr, self.dry_run) .await .wrap_err_with(|| format!("failed to uninstall {tv}"))?; pr.finish(); Ok(()) } fn print_summary(outdated: &[OutdatedInfo], successful_versions: &[ToolVersion]) -> Result<()> { let upgraded: Vec<_> = outdated .iter() .filter(|o| { successful_versions .iter() .any(|v| v.ba() == o.tool_version.ba() && v.version == o.latest) }) .collect(); if !upgraded.is_empty() { let s = if upgraded.len() == 1 { "" } else { "s" }; miseprintln!("\nUpgraded {} tool{}:", upgraded.len(), s); for o in &upgraded { let from = o.current.as_deref().unwrap_or("(none)"); miseprintln!(" {} {} → {}", o.name, from, o.latest); } } Ok(()) } fn get_interactive_tool_set(&self, outdated: &Vec<OutdatedInfo>) -> Result<Vec<OutdatedInfo>> { ui::ctrlc::show_cursor_after_ctrl_c(); let theme = crate::ui::theme::get_theme(); let mut ms = demand::MultiSelect::new("mise upgrade") .description("Select tools to upgrade") .filterable(true) .theme(&theme); for out in outdated { ms = ms.option(DemandOption::new(out.clone())); } match ms.run() { Ok(selected) => Ok(selected.into_iter().collect()), Err(e) => { Term::stderr().show_cursor()?; Err(eyre!(e)) } } } /// Get the before_date from CLI flag or settings fn get_before_date(&self) -> Result<Option<Timestamp>> { // CLI flag takes precedence over settings if let Some(before) = &self.before { return Ok(Some(parse_into_timestamp(before)?)); } // Fall back to settings if let Some(before) = &Settings::get().install_before { return Ok(Some(parse_into_timestamp(before)?)); } Ok(None) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Upgrades node to the latest version matching the range in mise.toml $ <bold>mise upgrade node</bold> # Upgrades node to the latest version and bumps the version in mise.toml $ <bold>mise upgrade node --bump</bold> # Upgrades all tools to the latest versions $ <bold>mise upgrade</bold> # Upgrades all tools to the latest versions and bumps the version in mise.toml $ <bold>mise upgrade --bump</bold> # Just print what would be done, don't actually do it $ <bold>mise upgrade --dry-run</bold> # Upgrades node and python to the latest versions $ <bold>mise upgrade node python</bold> # Show a multiselect menu to choose which tools to upgrade $ <bold>mise upgrade --interactive</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/registry.rs
src/cli/registry.rs
use crate::backend::backend_type::BackendType; use crate::config::Settings; use crate::registry::{REGISTRY, RegistryTool, tool_enabled}; use crate::ui::table::MiseTable; use eyre::{Result, bail}; use itertools::Itertools; use serde_derive::Serialize; /// List available tools to install /// /// This command lists the tools available in the registry as shorthand names. /// /// For example, `poetry` is shorthand for `asdf:mise-plugins/mise-poetry`. #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct Registry { /// Show only the specified tool's full name name: Option<String>, /// Show only tools for this backend #[clap(short, long)] backend: Option<BackendType>, /// Print all tools with descriptions for shell completions #[clap(long, hide = true)] complete: bool, /// Hide aliased tools #[clap(long)] hide_aliased: bool, /// Output in JSON format #[clap(long, short = 'J')] json: bool, } #[derive(Serialize)] struct RegistryToolOutput { short: String, backends: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] description: Option<String>, #[serde(skip_serializing_if = "Vec::is_empty")] aliases: Vec<String>, } impl Registry { pub async fn run(self) -> Result<()> { if let Some(name) = &self.name { if let Some(rt) = REGISTRY.get(name.as_str()) { if self.json { let tool = self.to_output(name, rt); miseprintln!("{}", serde_json::to_string_pretty(&tool)?); } else { miseprintln!("{}", self.filter_backends(rt).join(" ")); } } else { bail!("tool not found in registry: {name}"); } } else if self.complete { self.complete()?; } else if self.json { self.display_json()?; } else { self.display_table()?; } Ok(()) } fn filter_backends(&self, rt: &RegistryTool) -> Vec<&'static str> { if let Some(backend) = &self.backend { rt.backends() .into_iter() .filter(|full| full.starts_with(&format!("{backend}:"))) .collect() } else { rt.backends() } } fn to_output(&self, short: &str, rt: &RegistryTool) -> RegistryToolOutput { RegistryToolOutput { short: short.to_string(), backends: self .filter_backends(rt) .iter() .map(|s| s.to_string()) .collect(), description: rt.description.map(|s| s.to_string()), aliases: rt.aliases.iter().map(|s| s.to_string()).collect(), } } fn filtered_tools(&self) -> impl Iterator<Item = (&&'static str, &RegistryTool)> { REGISTRY .iter() .filter(|(short, _)| filter_enabled(short)) .filter(|(short, rt)| !self.hide_aliased || **short == rt.short) } fn display_table(&self) -> Result<()> { let mut table = MiseTable::new(false, &["Tool", "Backends"]); let data = self .filtered_tools() .map(|(short, rt)| (short.to_string(), self.filter_backends(rt).join(" "))) .filter(|(_, backends)| !backends.is_empty()) .sorted_by(|(a, _), (b, _)| a.cmp(b)) .map(|(short, backends)| vec![short, backends]) .collect_vec(); for row in data { table.add_row(row); } table.print() } fn complete(&self) -> Result<()> { self.filtered_tools() .map(|(short, rt)| { ( short.to_string(), rt.description .or(rt.backends().first().cloned()) .unwrap_or_default(), ) }) .sorted_by(|(a, _), (b, _)| a.cmp(b)) .for_each(|(short, description)| { println!( "{}:{}", short.replace(":", "\\:"), description.replace(":", "\\:") ); }); Ok(()) } fn display_json(&self) -> Result<()> { let tools: Vec<RegistryToolOutput> = self .filtered_tools() .map(|(short, rt)| self.to_output(short, rt)) .filter(|tool| !tool.backends.is_empty()) .sorted_by(|a, b| a.short.cmp(&b.short)) .collect(); miseprintln!("{}", serde_json::to_string_pretty(&tools)?); Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise registry</bold> node core:node poetry asdf:mise-plugins/mise-poetry ubi cargo:ubi-cli $ <bold>mise registry poetry</bold> asdf:mise-plugins/mise-poetry "# ); fn filter_enabled(short: &str) -> bool { tool_enabled( &Settings::get().enable_tools, &Settings::get().disable_tools, &short.to_string(), ) }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/mod.rs
src/cli/mod.rs
use crate::config::{Config, Settings}; use crate::exit::exit; use crate::task::TaskOutput; use crate::ui::{self, ctrlc}; use crate::{Result, backend}; use crate::{cli::args::ToolArg, path::PathExt}; use crate::{hook_env as hook_env_module, logger, migrate, shims}; use clap::{ArgAction, CommandFactory, Parser, Subcommand}; use eyre::bail; use std::path::PathBuf; mod activate; pub mod args; mod asdf; pub mod backends; mod bin_paths; mod cache; mod completion; mod config; mod current; mod deactivate; mod direnv; mod doctor; mod en; mod env; pub mod exec; mod external; mod fmt; mod generate; mod global; mod hook_env; mod hook_not_found; mod tool_alias; pub use hook_env::HookReason; mod implode; mod install; mod install_into; mod latest; mod link; mod local; mod lock; mod ls; mod ls_remote; mod mcp; mod outdated; mod plugins; mod prepare; mod prune; mod registry; #[cfg(debug_assertions)] mod render_help; mod reshim; pub mod run; mod search; #[cfg_attr(not(feature = "self_update"), path = "self_update_stub.rs")] pub mod self_update; mod set; mod settings; mod shell; mod shell_alias; mod sync; mod tasks; mod test_tool; mod tool; pub mod tool_stub; mod trust; mod uninstall; mod unset; mod unuse; mod upgrade; mod usage; mod r#use; pub mod version; mod watch; mod r#where; mod r#which; #[derive(clap::ValueEnum, Debug, Clone, strum::Display)] #[strum(serialize_all = "kebab-case")] pub enum LevelFilter { Trace, Debug, Info, Warning, Error, } #[derive(clap::Parser)] #[clap(name = "mise", about, long_about = LONG_ABOUT, after_long_help = AFTER_LONG_HELP, author = "Jeff Dickey <@jdx>", arg_required_else_help = true)] pub struct Cli { #[clap(subcommand)] pub command: Option<Commands>, /// Task to run #[clap(name = "TASK", long_help = LONG_TASK_ABOUT)] pub task: Option<String>, /// Task arguments #[clap(allow_hyphen_values = true, hide = true)] pub task_args: Option<Vec<String>>, #[clap(last = true, hide = true)] pub task_args_last: Vec<String>, /// Continue running tasks even if one fails #[clap(long, short = 'c', hide = true, verbatim_doc_comment)] pub continue_on_error: bool, /// Change directory before running command #[clap(short='C', long, global=true, value_name="DIR", value_hint=clap::ValueHint::DirPath)] pub cd: Option<PathBuf>, /// Set the environment for loading `mise.<ENV>.toml` #[clap(short = 'E', long, global = true)] pub env: Option<Vec<String>>, /// Force the operation #[clap(long, short, hide = true)] pub force: bool, /// Set the log output verbosity #[clap(long, short, hide = true, overrides_with = "prefix")] pub interleave: bool, /// How many jobs to run in parallel [default: 8] #[clap(long, short, global = true, env = "MISE_JOBS")] pub jobs: Option<usize>, /// Dry run, don't actually do anything #[clap(short = 'n', long, hide = true)] pub dry_run: bool, #[clap(long, short, hide = true, overrides_with = "interleave")] pub prefix: bool, /// Set the profile (environment) #[clap(short = 'P', long, global = true, hide = true, conflicts_with = "env")] pub profile: Option<Vec<String>>, /// Suppress non-error messages #[clap(short = 'q', long, global = true, overrides_with_all = &["silent", "trace", "verbose", "debug", "log_level"])] pub quiet: bool, #[clap(long, short, hide = true)] pub shell: Option<String>, /// Tool(s) to run in addition to what is in mise.toml files /// e.g.: node@20 python@3.10 #[clap( short, long, hide = true, value_name = "TOOL@VERSION", env = "MISE_QUIET" )] pub tool: Vec<ToolArg>, /// Show extra output (use -vv for even more) #[clap(short='v', long, global=true, action=ArgAction::Count, overrides_with_all = &["quiet", "silent", "trace", "debug"])] pub verbose: u8, #[clap(long, short = 'V', hide = true)] pub version: bool, /// Answer yes to all confirmation prompts #[clap(short = 'y', long, global = true)] pub yes: bool, /// Sets log level to debug #[clap(long, global = true, hide = true, overrides_with_all = &["quiet", "trace", "verbose", "silent", "log_level"])] pub debug: bool, #[clap(long, global = true, hide = true, value_name = "LEVEL", value_enum, overrides_with_all = &["quiet", "trace", "verbose", "silent", "debug"])] pub log_level: Option<LevelFilter>, /// Do not load any config files /// /// Can also use `MISE_NO_CONFIG=1` #[clap(long)] pub no_config: bool, /// Hides elapsed time after each task completes /// /// Default to always hide with `MISE_TASK_TIMINGS=0` #[clap(long, alias = "no-timing", hide = true, verbatim_doc_comment)] pub no_timings: bool, #[clap(long)] pub output: Option<TaskOutput>, /// Read/write directly to stdin/stdout/stderr instead of by line #[clap(long, global = true)] pub raw: bool, /// Require lockfile URLs to be present during installation /// /// Fails if tools don't have pre-resolved URLs in the lockfile for the current platform. /// This prevents API calls to GitHub, aqua registry, etc. /// Can also be enabled via MISE_LOCKED=1 or settings.locked=true #[clap(long, global = true, verbatim_doc_comment)] pub locked: bool, /// Suppress all task output and mise non-error messages #[clap(long, global = true, overrides_with_all = &["quiet", "trace", "verbose", "debug", "log_level"])] pub silent: bool, /// Shows elapsed time after each task completes /// /// Default to always show with `MISE_TASK_TIMINGS=1` #[clap(long, alias = "timing", verbatim_doc_comment, hide = true)] pub timings: bool, /// Sets log level to trace #[clap(long, global = true, hide = true, overrides_with_all = &["quiet", "silent", "verbose", "debug", "log_level"])] pub trace: bool, } #[derive(Subcommand, strum::Display)] #[strum(serialize_all = "kebab-case")] pub enum Commands { Activate(activate::Activate), ToolAlias(Box<tool_alias::ToolAlias>), Asdf(asdf::Asdf), Backends(backends::Backends), BinPaths(bin_paths::BinPaths), Cache(cache::Cache), Completion(completion::Completion), Config(config::Config), Current(current::Current), Deactivate(deactivate::Deactivate), Direnv(direnv::Direnv), Doctor(doctor::Doctor), En(en::En), Env(env::Env), Exec(exec::Exec), Fmt(fmt::Fmt), Generate(generate::Generate), Global(global::Global), HookEnv(hook_env::HookEnv), HookNotFound(hook_not_found::HookNotFound), Implode(implode::Implode), Install(install::Install), InstallInto(install_into::InstallInto), Latest(latest::Latest), Link(link::Link), Local(local::Local), Lock(lock::Lock), Ls(ls::Ls), LsRemote(ls_remote::LsRemote), Mcp(mcp::Mcp), Outdated(outdated::Outdated), Plugins(plugins::Plugins), Prepare(prepare::Prepare), Prune(prune::Prune), Registry(registry::Registry), #[cfg(debug_assertions)] RenderHelp(render_help::RenderHelp), Reshim(reshim::Reshim), Run(Box<run::Run>), Search(search::Search), #[cfg(feature = "self_update")] SelfUpdate(self_update::SelfUpdate), Set(set::Set), Settings(settings::Settings), Shell(shell::Shell), ShellAlias(shell_alias::ShellAlias), Sync(sync::Sync), Tasks(tasks::Tasks), TestTool(test_tool::TestTool), Tool(tool::Tool), ToolStub(tool_stub::ToolStub), Trust(trust::Trust), Uninstall(uninstall::Uninstall), Unset(unset::Unset), Unuse(unuse::Unuse), Upgrade(upgrade::Upgrade), Usage(usage::Usage), Use(r#use::Use), Version(version::Version), Watch(Box<watch::Watch>), Where(r#where::Where), Which(which::Which), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Activate(cmd) => cmd.run(), Self::ToolAlias(cmd) => cmd.run().await, Self::Asdf(cmd) => cmd.run().await, Self::Backends(cmd) => cmd.run().await, Self::BinPaths(cmd) => cmd.run().await, Self::Cache(cmd) => cmd.run(), Self::Completion(cmd) => cmd.run().await, Self::Config(cmd) => cmd.run().await, Self::Current(cmd) => cmd.run().await, Self::Deactivate(cmd) => cmd.run(), Self::Direnv(cmd) => cmd.run().await, Self::Doctor(cmd) => cmd.run().await, Self::En(cmd) => cmd.run().await, Self::Env(cmd) => cmd.run().await, Self::Exec(cmd) => cmd.run().await, Self::Fmt(cmd) => cmd.run(), Self::Generate(cmd) => cmd.run().await, Self::Global(cmd) => cmd.run().await, Self::HookEnv(cmd) => cmd.run().await, Self::HookNotFound(cmd) => cmd.run().await, Self::Implode(cmd) => cmd.run(), Self::Install(cmd) => cmd.run().await, Self::InstallInto(cmd) => cmd.run().await, Self::Latest(cmd) => cmd.run().await, Self::Link(cmd) => cmd.run().await, Self::Local(cmd) => cmd.run().await, Self::Lock(cmd) => cmd.run().await, Self::Ls(cmd) => cmd.run().await, Self::LsRemote(cmd) => cmd.run().await, Self::Mcp(cmd) => cmd.run().await, Self::Outdated(cmd) => cmd.run().await, Self::Plugins(cmd) => cmd.run().await, Self::Prepare(cmd) => cmd.run().await, Self::Prune(cmd) => cmd.run().await, Self::Registry(cmd) => cmd.run().await, #[cfg(debug_assertions)] Self::RenderHelp(cmd) => cmd.run(), Self::Reshim(cmd) => cmd.run().await, Self::Run(cmd) => (*cmd).run().await, Self::Search(cmd) => cmd.run().await, #[cfg(feature = "self_update")] Self::SelfUpdate(cmd) => cmd.run().await, Self::Set(cmd) => cmd.run().await, Self::Settings(cmd) => cmd.run().await, Self::Shell(cmd) => cmd.run().await, Self::ShellAlias(cmd) => cmd.run().await, Self::Sync(cmd) => cmd.run().await, Self::Tasks(cmd) => cmd.run().await, Self::TestTool(cmd) => cmd.run().await, Self::Tool(cmd) => cmd.run().await, Self::ToolStub(cmd) => cmd.run().await, Self::Trust(cmd) => cmd.run().await, Self::Uninstall(cmd) => cmd.run().await, Self::Unset(cmd) => cmd.run().await, Self::Unuse(cmd) => cmd.run().await, Self::Upgrade(cmd) => cmd.run().await, Self::Usage(cmd) => cmd.run(), Self::Use(cmd) => cmd.run().await, Self::Version(cmd) => cmd.run().await, Self::Watch(cmd) => cmd.run().await, Self::Where(cmd) => cmd.run().await, Self::Which(cmd) => cmd.run().await, } } } fn get_global_flags(cmd: &clap::Command) -> (Vec<String>, Vec<String>) { let mut flags_with_values = Vec::new(); let mut boolean_flags = Vec::new(); for arg in cmd.get_arguments() { let takes_value = matches!( arg.get_action(), clap::ArgAction::Set | clap::ArgAction::Append ); let is_bool = matches!( arg.get_action(), clap::ArgAction::SetTrue | clap::ArgAction::SetFalse ); if takes_value { if let Some(long) = arg.get_long() { flags_with_values.push(format!("--{}", long)); } if let Some(short) = arg.get_short() { flags_with_values.push(format!("-{}", short)); } } else if is_bool { if let Some(long) = arg.get_long() { boolean_flags.push(format!("--{}", long)); } if let Some(short) = arg.get_short() { boolean_flags.push(format!("-{}", short)); } } } (flags_with_values, boolean_flags) } /// Get all flags (with values and boolean) from both global Cli and Run subcommand fn get_all_run_flags(cmd: &clap::Command) -> (Vec<String>, Vec<String>) { // Get global flags from Cli let (mut flags_with_values, mut boolean_flags) = get_global_flags(cmd); // Get run-specific flags from Run subcommand if let Some(run_cmd) = cmd.get_subcommands().find(|s| s.get_name() == "run") { let (run_vals, run_bools) = get_global_flags(run_cmd); flags_with_values.extend(run_vals); boolean_flags.extend(run_bools); } (flags_with_values, boolean_flags) } /// Prefix used to escape flags that should be passed to tasks, not mise const TASK_ARG_ESCAPE_PREFIX: &str = "\x00MISE_TASK_ARG\x00"; /// Escape flags after task names so clap doesn't parse them as mise flags. /// This preserves ::: separators for multi-task handling while preventing /// clap from consuming flags like --jobs that appear after task names. fn escape_task_args(cmd: &clap::Command, args: &[String]) -> Vec<String> { // If there's already a '--' separator, let clap handle everything normally if args.contains(&"--".to_string()) { return args.to_vec(); } // Find "run" position let run_pos = args.iter().position(|a| a == "run"); let run_pos = match run_pos { Some(pos) => pos, None => return args.to_vec(), // Not a run command }; let (flags_with_values, _) = get_all_run_flags(cmd); // Build result, escaping flags that appear after task names let mut result = args[..=run_pos].to_vec(); // Include up to and including "run" let mut in_task_args = false; // true after we've seen a task name let mut i = run_pos + 1; while i < args.len() { let arg = &args[i]; // ::: starts a new task, so reset to looking for task name if arg == ":::" { result.push(arg.clone()); in_task_args = false; i += 1; continue; } if !in_task_args { // Looking for task name - skip any mise flags if arg.starts_with('-') { // It's a flag - keep it as-is for mise to parse result.push(arg.clone()); // Check if this flag takes a value (and needs to consume the next arg) let flag_takes_value = if arg.starts_with("--") { if arg.contains('=') { false // --flag=value, no separate value } else { flags_with_values.iter().any(|f| f == arg) } } else if arg.len() > 2 { // Short flag with embedded value (e.g., -j4), no separate value needed false } else if arg.len() == 2 { let flag_name = &arg[..2]; flags_with_values.iter().any(|f| f == flag_name) } else { false }; if flag_takes_value && i + 1 < args.len() && !args[i + 1].starts_with('-') { i += 1; result.push(args[i].clone()); } } else { // Found task name result.push(arg.clone()); in_task_args = true; } } else { // In task args - escape flags so clap doesn't parse them if arg.starts_with('-') && arg != "-" { // Escape the flag result.push(format!("{}{}", TASK_ARG_ESCAPE_PREFIX, arg)); } else { result.push(arg.clone()); } } i += 1; } result } /// Unescape task args that were escaped by escape_task_args pub fn unescape_task_args(args: &[String]) -> Vec<String> { args.iter() .map(|arg| { if let Some(stripped) = arg.strip_prefix(TASK_ARG_ESCAPE_PREFIX) { stripped.to_string() } else { arg.clone() } }) .collect() } fn preprocess_args_for_naked_run(cmd: &clap::Command, args: &[String]) -> Vec<String> { // Check if this might be a naked run (no subcommand) if args.len() < 2 { return args.to_vec(); } // If there's already a '--' separator, let clap handle everything normally // (user explicitly separated task args) if args.contains(&"--".to_string()) { return args.to_vec(); } let (flags_with_values, _) = get_global_flags(cmd); // Skip global flags to find the first non-flag argument (subcommand or task) let mut i = 1; while i < args.len() { let arg = &args[i]; if !arg.starts_with('-') { // Found first non-flag argument break; } // Check if this flag takes a value let flag_takes_value = if arg.starts_with("--") { if arg.contains('=') { // --flag=value format, doesn't consume next arg i += 1; continue; } else { let flag_name = arg.split('=').next().unwrap(); flags_with_values.iter().any(|f| f == flag_name) } } else { // Short form: check if it's in flags_with_values list if arg.len() >= 2 { let flag_name = &arg[..2]; // Get -X part flags_with_values.iter().any(|f| f == flag_name) } else { false } }; if flag_takes_value && i + 1 < args.len() { // Skip both the flag and its value i += 2; } else { // Skip just the flag i += 1; } } // No non-flag argument found if i >= args.len() { return args.to_vec(); } // Extract all known subcommand names and aliases from the clap Command let known_subcommands: Vec<_> = cmd .get_subcommands() .flat_map(|s| std::iter::once(s.get_name()).chain(s.get_all_aliases())) .collect(); // Check if the first non-flag argument is a known subcommand if known_subcommands.contains(&args[i].as_str()) { return args.to_vec(); } // Special case: "help" should print help, not be treated as a task if args[i] == "help" || args[i] == "-h" || args[i] == "--help" { return args.to_vec(); } // This is a naked run - inject "run" subcommand so clap routes it correctly // Format: ["mise", "-q", "task", "arg1"] becomes ["mise", "-q", "run", "task", "arg1"] // This preserves global flags while making it an explicit run command let mut result = args[..i].to_vec(); // Keep program name + global flags result.push("run".to_string()); // Insert "run" subcommand result.extend_from_slice(&args[i..]); // Add task name and args result } impl Cli { pub async fn run(args: &Vec<String>) -> Result<()> { crate::env::ARGS.write().unwrap().clone_from(args); if *crate::env::MISE_TOOL_STUB && args.len() >= 2 { tool_stub::short_circuit_stub(&args[2..]).await?; } // Fast-path for hook-env: exit early if nothing has changed // This avoids expensive backend::load_tools() and config loading if hook_env_module::should_exit_early_fast() { return Ok(()); } measure!("logger", { logger::init() }); check_working_directory(); measure!("handle_shim", { shims::handle_shim().await })?; ctrlc::init(); let print_version = version::print_version_if_requested(args)?; let _ = measure!("backend::load_tools", { backend::load_tools().await }); // Pre-process args to handle naked runs before clap parsing let cmd = Cli::command(); let processed_args = preprocess_args_for_naked_run(&cmd, args); // Escape flags after task names so they go to tasks, not mise let processed_args = escape_task_args(&cmd, &processed_args); let cli = measure!("get_matches_from", { Cli::parse_from(processed_args.iter()) }); // Validate --cd path BEFORE Settings processes it and changes the directory validate_cd_path(&cli.cd)?; measure!("add_cli_matches", { Settings::add_cli_matches(&cli) }); let _ = measure!("settings", { Settings::try_get() }); measure!("logger", { logger::init() }); measure!("migrate", { migrate::run().await }); if let Err(err) = crate::cache::auto_prune() { warn!("auto_prune failed: {err:?}"); } debug!("ARGS: {}", &args.join(" ")); trace!("MISE_BIN: {}", crate::env::MISE_BIN.display_user()); if print_version { version::show_latest().await; exit(0); } let cmd = cli.get_command().await?; measure!("run {cmd}", { cmd.run().await }) } async fn get_command(self) -> Result<Commands> { if let Some(cmd) = self.command { Ok(cmd) } else { if let Some(task) = self.task { // Handle special case: "help", "-h", or "--help" as task should print help if task == "help" || task == "-h" || task == "--help" { Cli::command().print_help()?; exit(0); } let config = Config::get().await?; // Expand :task pattern to match tasks in current directory's config root let task = crate::task::expand_colon_task_syntax(&task, &config)?; // For monorepo task patterns (starting with //), we need to load // tasks from the entire monorepo, not just the current hierarchy let tasks = if task.starts_with("//") { let ctx = crate::task::TaskLoadContext::from_pattern(&task); config.tasks_with_context(Some(&ctx)).await? } else { config.tasks().await? }; if tasks.iter().any(|(_, t)| t.is_match(&task)) { return Ok(Commands::Run(Box::new(run::Run { task, args: self.task_args.unwrap_or_default(), args_last: self.task_args_last, cd: self.cd, continue_on_error: self.continue_on_error, dry_run: self.dry_run, force: self.force, interleave: self.interleave, is_linear: false, jobs: self.jobs, no_timings: self.no_timings, output: self.output, prefix: self.prefix, shell: self.shell, quiet: self.quiet, silent: self.silent, raw: self.raw, timings: self.timings, tmpdir: Default::default(), tool: Default::default(), output_handler: None, context_builder: Default::default(), executor: None, no_cache: Default::default(), timeout: None, skip_deps: false, no_prepare: false, }))); } else if let Some(cmd) = external::COMMANDS.get(&task) { external::execute( &task.into(), cmd.clone(), self.task_args .unwrap_or_default() .into_iter() .chain(self.task_args_last) .collect(), )?; exit(0); } } Cli::command().print_help()?; exit(1) } } } const LONG_ABOUT: &str = "mise manages dev tools, env vars, and runs tasks. https://github.com/jdx/mise"; const LONG_TASK_ABOUT: &str = r#"Task to run. Shorthand for `mise tasks run <TASK>`."#; static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise install node@20.0.0</bold> Install a specific node version $ <bold>mise install node@20</bold> Install a version matching a prefix $ <bold>mise install node</bold> Install the node version defined in config $ <bold>mise install</bold> Install all plugins/tools defined in config $ <bold>mise install cargo:ripgrep Install something via cargo $ <bold>mise install npm:prettier Install something via npm $ <bold>mise use node@20</bold> Use node-20.x in current project $ <bold>mise use -g node@20</bold> Use node-20.x as default $ <bold>mise use node@latest</bold> Use latest node in current directory $ <bold>mise up --interactive</bold> Show a menu to upgrade tools $ <bold>mise x -- npm install</bold> `npm install` w/ config loaded into PATH $ <bold>mise x node@20 -- node app.js</bold> `node app.js` w/ config + node-20.x on PATH $ <bold>mise set NODE_ENV=production</bold> Set NODE_ENV=production in config $ <bold>mise run build</bold> Run `build` tasks $ <bold>mise watch build</bold> Run `build` tasks repeatedly when files change $ <bold>mise settings</bold> Show settings in use $ <bold>mise settings color=0</bold> Disable color by modifying global config file "# ); /// Check if the current working directory exists and warn if not fn check_working_directory() { if std::env::current_dir().is_err() { // Try to get the directory path from PWD env var, which might still contain the old path let dir_path = std::env::var("PWD") .or_else(|_| std::env::var("OLDPWD")) .unwrap_or_else(|_| "(unknown)".to_string()); warn!( "Current directory does not exist or is not accessible: {}", dir_path ); } } /// Validate the --cd path if provided and return an error if it doesn't exist fn validate_cd_path(cd: &Option<PathBuf>) -> Result<()> { if let Some(path) = cd { if !path.exists() { bail!( "Directory specified with --cd does not exist: {}\n\ Please check the path and try again.", ui::style::epath(path) ); } if !path.is_dir() { bail!( "Path specified with --cd is not a directory: {}\n\ Please provide a valid directory path.", ui::style::epath(path) ); } } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_subcommands_are_sorted() { let cmd = Cli::command(); // Check all subcommands except watch (which has many watchexec passthrough args) for subcmd in cmd.get_subcommands() { if subcmd.get_name() != "watch" { clap_sort::assert_sorted(subcmd); } } } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/implode.rs
src/cli/implode.rs
use std::path::Path; use eyre::Result; use crate::config::Settings; use crate::file::remove_all; use crate::ui::prompt; use crate::{dirs, env, file}; /// Removes mise CLI and all related data /// /// Skips config directory by default. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment)] pub struct Implode { /// List directories that would be removed without actually removing them #[clap(long, short = 'n', verbatim_doc_comment)] dry_run: bool, /// Also remove config directory #[clap(long, verbatim_doc_comment)] config: bool, } impl Implode { pub fn run(self) -> Result<()> { let mut files = vec![*dirs::STATE, *dirs::DATA, *dirs::CACHE, &*env::MISE_BIN]; if self.config { files.push(&dirs::CONFIG); } for f in files.into_iter().filter(|d| d.exists()) { if self.dry_run { miseprintln!("rm -rf {}", f.display()); } if self.confirm_remove(f)? { if f.is_dir() { remove_all(f)?; } else { file::remove_file(f)?; } } } Ok(()) } fn confirm_remove(&self, f: &Path) -> Result<bool> { let settings = Settings::try_get()?; if self.dry_run { Ok(false) } else if settings.yes { Ok(true) } else { let r = prompt::confirm(format!("remove {} ?", f.display()))?; Ok(r) } } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/run.rs
src/cli/run.rs
use crate::errors::Error; use std::iter::once; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use super::args::ToolArg; use crate::cli::{Cli, unescape_task_args}; use crate::config::{Config, Settings}; use crate::duration; use crate::prepare::{PrepareEngine, PrepareOptions}; use crate::task::has_any_args_defined; use crate::task::task_helpers::task_needs_permit; use crate::task::task_list::{get_task_lists, resolve_depends}; use crate::task::task_output::TaskOutput; use crate::task::task_output_handler::OutputHandler; use crate::task::{Deps, Task}; use crate::toolset::{InstallOptions, ToolsetBuilder}; use crate::ui::{ctrlc, style}; use clap::{CommandFactory, ValueHint}; use eyre::{Result, bail, eyre}; use itertools::Itertools; use tokio::sync::Mutex; /// Run task(s) /// /// This command will run a task, or multiple tasks in parallel. /// Tasks may have dependencies on other tasks or on source files. /// If source is configured on a task, it will only run if the source /// files have changed. /// /// Tasks can be defined in mise.toml or as standalone scripts. /// In mise.toml, tasks take this form: /// /// [tasks.build] /// run = "npm run build" /// sources = ["src/**/*.ts"] /// outputs = ["dist/**/*.js"] /// /// Alternatively, tasks can be defined as standalone scripts. /// These must be located in `mise-tasks`, `.mise-tasks`, `.mise/tasks`, `mise/tasks` or /// `.config/mise/tasks`. /// The name of the script will be the name of the tasks. /// /// $ cat .mise/tasks/build<<EOF /// #!/usr/bin/env bash /// npm run build /// EOF /// $ mise run build #[derive(clap::Args)] #[clap(visible_alias = "r", verbatim_doc_comment, disable_help_flag = true, after_long_help = AFTER_LONG_HELP)] pub struct Run { /// Tasks to run /// Can specify multiple tasks by separating with `:::` /// e.g.: mise run task1 arg1 arg2 ::: task2 arg1 arg2 #[clap( allow_hyphen_values = true, verbatim_doc_comment, default_value = "default" )] pub task: String, /// Arguments to pass to the tasks. Use ":::" to separate tasks. #[clap(allow_hyphen_values = true)] pub args: Vec<String>, /// Arguments to pass to the tasks. Use ":::" to separate tasks. #[clap(allow_hyphen_values = true, hide = true, last = true)] pub args_last: Vec<String>, /// Continue running tasks even if one fails #[clap(long, short = 'c', verbatim_doc_comment)] pub continue_on_error: bool, /// Change to this directory before executing the command #[clap(short = 'C', long, value_hint = ValueHint::DirPath, long)] pub cd: Option<PathBuf>, /// Force the tasks to run even if outputs are up to date #[clap(long, short, verbatim_doc_comment)] pub force: bool, /// Print directly to stdout/stderr instead of by line /// Defaults to true if --jobs == 1 /// Configure with `task_output` config or `MISE_TASK_OUTPUT` env var #[clap( long, short, verbatim_doc_comment, hide = true, overrides_with = "prefix" )] pub interleave: bool, /// Number of tasks to run in parallel /// [default: 4] /// Configure with `jobs` config or `MISE_JOBS` env var #[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)] pub jobs: Option<usize>, /// Don't actually run the task(s), just print them in order of execution #[clap(long, short = 'n', verbatim_doc_comment)] pub dry_run: bool, /// Change how tasks information is output when running tasks /// /// - `prefix` - Print stdout/stderr by line, prefixed with the task's label /// - `interleave` - Print directly to stdout/stderr instead of by line /// - `replacing` - Stdout is replaced each time, stderr is printed as is /// - `timed` - Only show stdout lines if they are displayed for more than 1 second /// - `keep-order` - Print stdout/stderr by line, prefixed with the task's label, but keep the order of the output /// - `quiet` - Don't show extra output /// - `silent` - Don't show any output including stdout and stderr from the task except for errors #[clap(short, long, verbatim_doc_comment, env = "MISE_TASK_OUTPUT")] pub output: Option<TaskOutput>, /// Print stdout/stderr by line, prefixed with the task's label /// Defaults to true if --jobs > 1 /// Configure with `task_output` config or `MISE_TASK_OUTPUT` env var #[clap( long, short, verbatim_doc_comment, hide = true, overrides_with = "interleave" )] pub prefix: bool, /// Don't show extra output #[clap(long, short, verbatim_doc_comment, env = "MISE_QUIET")] pub quiet: bool, /// Read/write directly to stdin/stdout/stderr instead of by line /// Redactions are not applied with this option /// Configure with `raw` config or `MISE_RAW` env var #[clap(long, short, verbatim_doc_comment)] pub raw: bool, /// Shell to use to run toml tasks /// /// Defaults to `sh -c -o errexit -o pipefail` on unix, and `cmd /c` on Windows /// Can also be set with the setting `MISE_UNIX_DEFAULT_INLINE_SHELL_ARGS` or `MISE_WINDOWS_DEFAULT_INLINE_SHELL_ARGS` /// Or it can be overridden with the `shell` property on a task. #[clap(long, short, verbatim_doc_comment)] pub shell: Option<String>, /// Don't show any output except for errors #[clap(long, short = 'S', verbatim_doc_comment, env = "MISE_SILENT")] pub silent: bool, /// Tool(s) to run in addition to what is in mise.toml files /// e.g.: node@20 python@3.10 #[clap(short, long, value_name = "TOOL@VERSION")] pub tool: Vec<ToolArg>, #[clap(skip)] pub is_linear: bool, /// Do not use cache on remote tasks #[clap(long, verbatim_doc_comment, env = "MISE_TASK_REMOTE_NO_CACHE")] pub no_cache: bool, /// Skip automatic dependency preparation #[clap(long)] pub no_prepare: bool, /// Hides elapsed time after each task completes /// /// Default to always hide with `MISE_TASK_TIMINGS=0` #[clap(long, alias = "no-timing", verbatim_doc_comment)] pub no_timings: bool, /// Run only the specified tasks skipping all dependencies #[clap(long, verbatim_doc_comment, env = "MISE_TASK_SKIP_DEPENDS")] pub skip_deps: bool, /// Timeout for the task to complete /// e.g.: 30s, 5m #[clap(long, verbatim_doc_comment)] pub timeout: Option<String>, /// Shows elapsed time after each task completes /// /// Default to always show with `MISE_TASK_TIMINGS=1` #[clap(long, alias = "timing", verbatim_doc_comment, hide = true)] pub timings: bool, #[clap(skip)] pub tmpdir: PathBuf, #[clap(skip)] pub output_handler: Option<OutputHandler>, #[clap(skip)] pub context_builder: crate::task::task_context_builder::TaskContextBuilder, #[clap(skip)] pub executor: Option<crate::task::task_executor::TaskExecutor>, } impl Run { pub async fn run(mut self) -> Result<()> { // Check help flags before doing any work if self.task == "-h" { self.get_clap_command().print_help()?; return Ok(()); } if self.task == "--help" { self.get_clap_command().print_long_help()?; return Ok(()); } // Unescape task args early so we can check for help flags self.args = unescape_task_args(&self.args); // Check if --help or -h is in the task args BEFORE toolset/prepare // NOTE: Only check self.args, not self.args_last, because args_last contains // arguments after explicit -- which should always be passed through to the task let has_help_in_task_args = self.args.contains(&"--help".to_string()) || self.args.contains(&"-h".to_string()); let mut config = Config::get().await?; // Handle task help early to avoid unnecessary toolset/prepare work if has_help_in_task_args { // Build args list to get the task (filter out --help/-h for task lookup) let args = once(self.task.clone()) .chain( self.args .iter() .filter(|a| *a != "--help" && *a != "-h") .cloned(), ) .collect_vec(); let task_list = get_task_lists(&config, &args, false, false).await?; if let Some(task) = task_list.first() { // Get usage spec to check if task has defined args/flags let spec = task.parse_usage_spec_for_display(&config).await?; // Only show mise help if the task has usage args/flags defined // Otherwise, pass --help through to the underlying command if has_any_args_defined(&spec) { // Render help using usage library println!("{}", usage::docs::cli::render_help(&spec, &spec.cmd, true)); return Ok(()); } // Task has no usage defined - fall through to execute with --help passed to task } else { // No task found, show run command help self.get_clap_command().print_long_help()?; return Ok(()); } } // Build and install toolset so tools like npm are available for prepare let mut ts = ToolsetBuilder::new() .with_args(&self.tool) .with_default_to_latest(true) .build(&config) .await?; let opts = InstallOptions { jobs: self.jobs, raw: self.raw, ..Default::default() }; ts.install_missing_versions(&mut config, &opts).await?; // Run auto-enabled prepare steps (unless --no-prepare) if !self.no_prepare { let env = ts.env_with_path(&config).await?; let engine = PrepareEngine::new(config.clone())?; engine .run(PrepareOptions { auto_only: true, // Only run providers with auto=true env, ..Default::default() }) .await?; } if !self.skip_deps { self.skip_deps = Settings::get().task_skip_depends; } time!("run init"); let tmpdir = tempfile::tempdir()?; self.tmpdir = tmpdir.path().to_path_buf(); // Build args list - don't include args_last yet, they'll be added after task resolution let args = once(self.task.clone()) .chain(self.args.clone()) .collect_vec(); let mut task_list = get_task_lists(&config, &args, true, self.skip_deps).await?; // Args after -- go directly to tasks (no prefix) if !self.args_last.is_empty() { for task in &mut task_list { task.args.extend(self.args_last.clone()); } } time!("run get_task_lists"); // Apply global timeout for entire run if configured let timeout = if let Some(timeout_str) = &self.timeout { Some(duration::parse_duration(timeout_str)?) } else { Settings::get().task_timeout_duration() }; if let Some(timeout) = timeout { tokio::time::timeout(timeout, self.parallelize_tasks(config, task_list)) .await .map_err(|_| eyre!("mise run timed out after {:?}", timeout))?? } else { self.parallelize_tasks(config, task_list).await? } time!("run done"); Ok(()) } fn get_clap_command(&self) -> clap::Command { Cli::command() .get_subcommands() .find(|s| s.get_name() == "run") .unwrap() .clone() } async fn parallelize_tasks(mut self, mut config: Arc<Config>, tasks: Vec<Task>) -> Result<()> { time!("parallelize_tasks start"); ctrlc::exit_on_ctrl_c(false); // Step 1: Prepare tasks (resolve dependencies, fetch, validate) let tasks = self.prepare_tasks(&config, tasks).await?; let num_tasks = tasks.all().count(); // Step 2: Setup output handler and validate tasks self.setup_output_and_validate(&tasks)?; self.output = Some(self.output(None)); // Step 3: Install tools needed by tasks self.install_task_tools(&mut config, &tasks).await?; // Step 4: Create TaskExecutor after tool installation self.setup_executor()?; let timer = std::time::Instant::now(); let this = Arc::new(self); let config = config.clone(); // Step 4: Initialize scheduler and run tasks let mut scheduler = crate::task::task_scheduler::Scheduler::new(this.jobs()); let main_deps = Arc::new(Mutex::new(tasks)); // Pump deps leaves into scheduler let mut main_done_rx = scheduler.pump_deps(main_deps.clone()).await; let spawn_context = scheduler.spawn_context(config.clone()); scheduler .run_loop( &mut main_done_rx, main_deps.clone(), || this.is_stopping(), this.continue_on_error, |task, deps_for_remove| { let this = this.clone(); let spawn_context = spawn_context.clone(); async move { Self::spawn_sched_job(this, task, deps_for_remove, spawn_context).await } }, ) .await?; scheduler.join_all(this.continue_on_error).await?; // Step 5: Display results and handle failures let results_display = crate::task::task_results_display::TaskResultsDisplay::new( this.output_handler.clone().unwrap(), this.executor.as_ref().unwrap().failed_tasks.clone(), this.continue_on_error, this.timings(), ); results_display.display_results(num_tasks, timer); time!("parallelize_tasks done"); Ok(()) } async fn spawn_sched_job( this: Arc<Self>, task: Task, deps_for_remove: Arc<Mutex<Deps>>, ctx: crate::task::task_scheduler::SpawnContext, ) -> Result<()> { // If we're already stopping due to a previous failure and not in // continue-on-error mode, do not launch this task. Ensure we remove // it from the dependency graph so the scheduler can make progress. if this.is_stopping() && !this.continue_on_error { trace!( "aborting spawn before start (not continue-on-error): {} {}", task.name, task.args.join(" ") ); deps_for_remove.lock().await.remove(&task); return Ok(()); } let needs_permit = task_needs_permit(&task); let permit_opt = if needs_permit { let wait_start = std::time::Instant::now(); let p = Some(ctx.semaphore.clone().acquire_owned().await?); trace!( "semaphore acquired for {} after {}ms", task.name, wait_start.elapsed().as_millis() ); // If a failure occurred while we were waiting for a permit and we're not // in continue-on-error mode, skip launching this task. This prevents // subsequently queued tasks (e.g., from CLI ":::" groups) from running // after the first failure when --jobs=1 and ensures immediate stop. if this.is_stopping() && !this.continue_on_error { trace!( "aborting spawn after failure (not continue-on-error): {} {}", task.name, task.args.join(" ") ); // Remove from deps so the scheduler can drain and not hang deps_for_remove.lock().await.remove(&task); return Ok(()); } p } else { trace!("no semaphore needed for orchestrator task: {}", task.name); None }; ctx.in_flight .fetch_add(1, std::sync::atomic::Ordering::SeqCst); let in_flight_c = ctx.in_flight.clone(); trace!("running task: {task}"); ctx.jset.lock().await.spawn(async move { let _permit = permit_opt; let result = this .run_task_sched(&task, &ctx.config, ctx.sched_tx.clone()) .await; if let Err(err) = &result { let status = Error::get_exit_status(err); if !this.is_stopping() && status.is_none() { let prefix = task.estyled_prefix(); if Settings::get().verbose { this.eprint(&task, &prefix, &format!("{} {err:?}", style::ered("ERROR"))); } else { this.eprint(&task, &prefix, &format!("{} {err}", style::ered("ERROR"))); let mut current_err = err.source(); while let Some(e) = current_err { this.eprint(&task, &prefix, &format!("{} {e}", style::ered("ERROR"))); current_err = e.source(); } }; } this.add_failed_task(task.clone(), status); } deps_for_remove.lock().await.remove(&task); trace!("deps removed: {} {}", task.name, task.args.join(" ")); in_flight_c.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); result }); Ok(()) } // ============================================================================ // High-level workflow methods // ============================================================================ /// Prepare tasks: resolve dependencies, fetch remote tasks, create dependency graph async fn prepare_tasks(&mut self, config: &Arc<Config>, tasks: Vec<Task>) -> Result<Deps> { let mut tasks = resolve_depends(config, tasks).await?; let fetcher = crate::task::task_fetcher::TaskFetcher::new(self.no_cache); fetcher.fetch_tasks(&mut tasks).await?; let tasks = Deps::new(config, tasks).await?; self.is_linear = tasks.is_linear(); Ok(tasks) } /// Initialize output handler and validate tasks fn setup_output_and_validate(&mut self, tasks: &Deps) -> Result<()> { // Initialize OutputHandler AFTER is_linear is determined let output_config = crate::task::task_output_handler::OutputHandlerConfig { prefix: self.prefix, interleave: self.interleave, output: self.output, silent: self.silent, quiet: self.quiet, raw: self.raw, is_linear: self.is_linear, jobs: self.jobs, }; self.output_handler = Some(OutputHandler::new(output_config)); // Spawn timed output task if needed if self.output(None) == TaskOutput::Timed { let timed_outputs = self.output_handler.as_ref().unwrap().timed_outputs.clone(); tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_millis(100)); loop { { let mut outputs = timed_outputs.lock().unwrap(); for (prefix, out) in outputs.clone() { let (time, line) = out; if time.elapsed().unwrap().as_secs() >= 1 { if console::colors_enabled() { prefix_println!(prefix, "{line}\x1b[0m"); } else { prefix_println!(prefix, "{line}"); } outputs.shift_remove(&prefix); } } } interval.tick().await; } }); } // Validate and initialize task output for task in tasks.all() { self.validate_task(task)?; self.output_handler.as_mut().unwrap().init_task(task); } Ok(()) } /// Create TaskExecutor after tool installation to ensure caches are populated fn setup_executor(&mut self) -> Result<()> { let executor_config = crate::task::task_executor::TaskExecutorConfig { force: self.force, cd: self.cd.clone(), shell: self.shell.clone(), tool: self.tool.clone(), timings: self.timings, continue_on_error: self.continue_on_error, dry_run: self.dry_run, skip_deps: self.skip_deps, }; self.executor = Some(crate::task::task_executor::TaskExecutor::new( self.context_builder.clone(), self.output_handler.clone().unwrap(), executor_config, )); Ok(()) } /// Collect and install all tools needed by tasks async fn install_task_tools(&self, config: &mut Arc<Config>, tasks: &Deps) -> Result<()> { let installer = crate::task::task_tool_installer::TaskToolInstaller::new( &self.context_builder, &self.tool, ); installer.install_tools(config, tasks).await } // ============================================================================ // Helper methods // ============================================================================ fn eprint(&self, task: &Task, prefix: &str, line: &str) { self.output_handler .as_ref() .unwrap() .eprint(task, prefix, line); } fn output(&self, task: Option<&Task>) -> TaskOutput { self.output_handler.as_ref().unwrap().output(task) } fn jobs(&self) -> usize { self.output_handler.as_ref().unwrap().jobs() } fn is_stopping(&self) -> bool { self.executor .as_ref() .map(|e| e.is_stopping()) .unwrap_or(false) } async fn run_task_sched( &self, task: &Task, config: &Arc<Config>, sched_tx: Arc<tokio::sync::mpsc::UnboundedSender<(Task, Arc<Mutex<Deps>>)>>, ) -> Result<()> { self.executor .as_ref() .expect("executor must be initialized before running tasks") .run_task_sched(task, config, sched_tx) .await } fn add_failed_task(&self, task: Task, status: Option<i32>) { if let Some(executor) = &self.executor { executor.add_failed_task(task, status); } } fn validate_task(&self, task: &Task) -> Result<()> { use crate::file; use crate::ui; if let Some(path) = &task.file && path.exists() && !file::is_executable(path) { let dp = crate::file::display_path(path); let msg = format!("Script `{dp}` is not executable. Make it executable?"); if ui::confirm(msg)? { file::make_executable(path)?; } else { bail!("`{dp}` is not executable") } } Ok(()) } fn timings(&self) -> bool { !self.quiet(None) && !self.no_timings } fn quiet(&self, task: Option<&Task>) -> bool { self.output_handler.as_ref().unwrap().quiet(task) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Runs the "lint" tasks. This needs to either be defined in mise.toml # or as a standalone script. See the project README for more information. $ <bold>mise run lint</bold> # Forces the "build" tasks to run even if its sources are up-to-date. $ <bold>mise run build --force</bold> # Run "test" with stdin/stdout/stderr all connected to the current terminal. # This forces `--jobs=1` to prevent interleaving of output. $ <bold>mise run test --raw</bold> # Runs the "lint", "test", and "check" tasks in parallel. $ <bold>mise run lint ::: test ::: check</bold> # Execute multiple tasks each with their own arguments. $ <bold>mise run cmd1 arg1 arg2 ::: cmd2 arg1 arg2</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/en.rs
src/cli/en.rs
use crate::cli::exec::Exec; use std::path::PathBuf; use crate::env; /// Starts a new shell with the mise environment built from the current configuration /// /// This is an alternative to `mise activate` that allows you to explicitly start a mise session. /// It will have the tools and environment variables in the configs loaded. /// Note that changing directories will not update the mise environment. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct En { /// Directory to start the shell in #[clap(default_value = ".", verbatim_doc_comment, value_hint = clap::ValueHint::DirPath)] pub dir: PathBuf, /// Shell to start /// /// Defaults to $SHELL #[clap(verbatim_doc_comment, long, short = 's')] pub shell: Option<String>, } impl En { pub async fn run(self) -> eyre::Result<()> { env::set_current_dir(&self.dir)?; let shell = self.shell.unwrap_or((*env::SHELL).clone()); let command = shell_words::split(&shell).map_err(|e| eyre::eyre!(e))?; Exec { tool: vec![], raw: false, jobs: None, c: None, command: Some(command), no_prepare: false, } .run() .await } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise en .</bold> $ <bold>node -v</bold> v20.0.0 Skip loading bashrc: $ <bold>mise en -s "bash --norc"</bold> Skip loading zshrc: $ <bold>mise en -s "zsh -f"</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool.rs
src/cli/tool.rs
use crate::backend::SecurityFeature; use crate::ui::style; use eyre::Result; use itertools::Itertools; use serde_derive::Serialize; use crate::cli::args::BackendArg; use crate::config::Config; use crate::toolset::{ToolSource, ToolVersionOptions, ToolsetBuilder}; use crate::ui::table; /// Gets information about a tool #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Tool { /// Tool name to get information about tool: BackendArg, /// Output in JSON format #[clap(long, short = 'J')] json: bool, #[clap(flatten)] filter: ToolInfoFilter, } #[derive(Debug, Clone, clap::Args)] #[group(multiple = false)] pub struct ToolInfoFilter { /// Only show active versions #[clap(long)] active: bool, /// Only show backend field #[clap(long)] backend_: bool, /// Only show config source #[clap(long)] config_source: bool, /// Only show description field #[clap(long)] description: bool, /// Only show installed versions #[clap(long)] installed: bool, /// Only show requested versions #[clap(long)] requested: bool, /// Only show tool options #[clap(long)] tool_options: bool, } impl Tool { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let mut ts = ToolsetBuilder::new().build(&config).await?; ts.resolve(&config).await?; let tvl = ts.versions.get(&self.tool); let tv = tvl.map(|tvl| tvl.versions.first().unwrap()); let ba = tv.map(|tv| tv.ba()).unwrap_or_else(|| &self.tool); // Check if the backend exists and fail if it doesn't let backend = match ba.backend() { Ok(b) => Some(b), Err(e) => { // If no versions are configured for this tool, it's likely invalid if tvl.is_none() { return Err(e); } None } }; let (description, security) = if let Some(backend) = &backend { (backend.description().await, backend.security_info().await) } else { (None, vec![]) }; let info = ToolInfo { backend: ba.full(), description, installed_versions: ts .list_installed_versions(&config) .await? .into_iter() .filter(|(b, _)| b.ba().as_ref() == ba) .map(|(_, tv)| tv.version) .unique() .collect::<Vec<_>>(), active_versions: tvl.map(|tvl| { tvl.versions .iter() .map(|tv| tv.version.clone()) .collect::<Vec<_>>() }), requested_versions: tvl.map(|tvl| { tvl.requests .iter() .map(|tr| tr.version()) .collect::<Vec<_>>() }), config_source: tvl.map(|tvl| tvl.source.clone()), tool_options: ba.opts(), security, }; if self.json { self.output_json(info) } else { self.output_user(info) } } fn output_json(&self, info: ToolInfo) -> Result<()> { if self.filter.backend_ { miseprintln!("{}", serde_json::to_string_pretty(&info.backend)?); } else if self.filter.description { miseprintln!("{}", serde_json::to_string_pretty(&info.description)?); } else if self.filter.installed { miseprintln!( "{}", serde_json::to_string_pretty(&info.installed_versions)? ); } else if self.filter.active { miseprintln!("{}", serde_json::to_string_pretty(&info.active_versions)?); } else if self.filter.requested { miseprintln!( "{}", serde_json::to_string_pretty(&info.requested_versions)? ); } else if self.filter.config_source { miseprintln!("{}", serde_json::to_string_pretty(&info.config_source)?); } else if self.filter.tool_options { miseprintln!("{}", serde_json::to_string_pretty(&info.tool_options)?); } else { miseprintln!("{}", serde_json::to_string_pretty(&info)?); } Ok(()) } fn output_user(&self, info: ToolInfo) -> Result<()> { if self.filter.backend_ { miseprintln!("{}", info.backend); } else if self.filter.description { if let Some(description) = info.description { miseprintln!("{}", description); } else { miseprintln!("[none]"); } } else if self.filter.installed { let active_set = info .active_versions .as_ref() .map(|v| v.iter().collect::<std::collections::HashSet<_>>()) .unwrap_or_default(); let installed_with_bold = info .installed_versions .iter() .map(|v| { if active_set.contains(v) { style::nbold(v).to_string() } else { v.to_string() } }) .join(" "); miseprintln!("{}", installed_with_bold); } else if self.filter.active { if let Some(active_versions) = info.active_versions { miseprintln!("{}", active_versions.join(" ")); } else { miseprintln!("[none]"); } } else if self.filter.requested { if let Some(requested_versions) = info.requested_versions { miseprintln!("{}", requested_versions.join(" ")); } else { miseprintln!("[none]"); } } else if self.filter.config_source { if let Some(config_source) = info.config_source { miseprintln!("{}", config_source); } else { miseprintln!("[none]"); } } else if self.filter.tool_options { if info.tool_options.is_empty() { miseprintln!("[none]"); } else { for (k, v) in info.tool_options.opts { miseprintln!("{k}={v:?}"); } } } else { let mut table = vec![]; table.push(("Backend:", info.backend)); if let Some(description) = info.description { table.push(("Description:", description)); } // Bold currently active versions within the installed list for clarity let active_set = info .active_versions .as_ref() .map(|v| v.iter().collect::<std::collections::HashSet<_>>()) .unwrap_or_default(); let installed_with_bold = info .installed_versions .iter() .map(|v| { if active_set.contains(v) { style::nbold(v).to_string() } else { v.to_string() } }) .join(" "); table.push(("Installed Versions:", installed_with_bold)); if let Some(active_versions) = info.active_versions { table.push(( "Active Version:", style::nbold(active_versions.join(" ")).to_string(), )); } if let Some(requested_versions) = info.requested_versions { table.push(("Requested Version:", requested_versions.join(" "))); } if let Some(config_source) = info.config_source { table.push(("Config Source:", config_source.to_string())); } if info.tool_options.is_empty() { table.push(("Tool Options:", "[none]".to_string())); } else { table.push(( "Tool Options:", info.tool_options .opts .into_iter() .map(|(k, v)| format!("{k}={v:?}")) .join(","), )); } if info.security.is_empty() { table.push(("Security:", "[none]".to_string())); } else { let security_str = info .security .iter() .map(|f| match f { SecurityFeature::Checksum { algorithm } => { if let Some(alg) = algorithm { format!("checksum ({})", alg) } else { "checksum".to_string() } } SecurityFeature::GithubAttestations { .. } => { "github_attestations".to_string() } SecurityFeature::Slsa { level } => { if let Some(l) = level { format!("slsa (level {})", l) } else { "slsa".to_string() } } SecurityFeature::Cosign => "cosign".to_string(), SecurityFeature::Minisign { .. } => "minisign".to_string(), SecurityFeature::Gpg => "gpg".to_string(), }) .join(", "); table.push(("Security:", security_str)); } let mut table = tabled::Table::new(table); table::default_style(&mut table, true); miseprintln!("{table}"); } Ok(()) } } #[derive(Serialize)] struct ToolInfo { backend: String, description: Option<String>, installed_versions: Vec<String>, requested_versions: Option<Vec<String>>, active_versions: Option<Vec<String>>, config_source: Option<ToolSource>, tool_options: ToolVersionOptions, security: Vec<SecurityFeature>, } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tool node</bold> Backend: core Installed Versions: 20.0.0 22.0.0 Active Version: 20.0.0 Requested Version: 20 Config Source: ~/.config/mise/mise.toml Tool Options: [none] "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/activate.rs
src/cli/activate.rs
use std::path::{Path, PathBuf}; use crate::env::PATH_KEY; use crate::file::touch_dir; use crate::path_env::PathEnv; use crate::shell::{ActivateOptions, ActivatePrelude, Shell, ShellType, get_shell}; use crate::{dirs, env}; use eyre::Result; use itertools::Itertools; /// Initializes mise in the current shell session /// /// This should go into your shell's rc file or login shell. /// Otherwise, it will only take effect in the current session. /// (e.g. ~/.zshrc, ~/.zprofile, ~/.zshenv, ~/.bashrc, ~/.bash_profile, ~/.profile, ~/.config/fish/config.fish, or $PROFILE for powershell) /// /// Typically, this can be added with something like the following: /// /// echo 'eval "$(mise activate zsh)"' >> ~/.zshrc /// /// However, this requires that "mise" is in your PATH. If it is not, you need to /// specify the full path like this: /// /// echo 'eval "$(/path/to/mise activate zsh)"' >> ~/.zshrc /// /// Customize status output with `status` settings. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Activate { /// Shell type to generate the script for #[clap()] shell_type: Option<ShellType>, /// Suppress non-error messages #[clap(long, short)] quiet: bool, /// Shell type to generate the script for #[clap(long, short, hide = true)] shell: Option<ShellType>, /// Do not automatically call hook-env /// /// This can be helpful for debugging mise. If you run `eval "$(mise activate --no-hook-env)"`, then /// you can call `mise hook-env` manually which will output the env vars to stdout without actually /// modifying the environment. That way you can do things like `mise hook-env --trace` to get more /// information or just see the values that hook-env is outputting. #[clap(long)] no_hook_env: bool, /// Use shims instead of modifying PATH /// Effectively the same as: /// /// PATH="$HOME/.local/share/mise/shims:$PATH" /// /// `mise activate --shims` does not support all the features of `mise activate`. /// See https://mise.jdx.dev/dev-tools/shims.html#shims-vs-path for more information #[clap(long, verbatim_doc_comment)] shims: bool, /// Show "mise: <PLUGIN>@<VERSION>" message when changing directories #[clap(long, hide = true)] status: bool, } impl Activate { pub fn run(self) -> Result<()> { let shell = get_shell(self.shell_type.or(self.shell)) .expect("no shell provided. Run `mise activate zsh` or similar"); // touch ROOT to allow hook-env to run let _ = touch_dir(&dirs::DATA); let mise_bin = if cfg!(target_os = "linux") { // linux dereferences symlinks, so use argv0 instead PathBuf::from(&*env::ARGV0) } else { env::MISE_BIN.clone() }; match self.shims { true => self.activate_shims(shell.as_ref(), &mise_bin)?, false => self.activate(shell.as_ref(), &mise_bin)?, } Ok(()) } fn activate_shims(&self, shell: &dyn Shell, mise_bin: &Path) -> std::io::Result<()> { let exe_dir = mise_bin.parent().unwrap(); let mut prelude = vec![]; if let Some(p) = self.prepend_path(exe_dir) { prelude.push(p); } if let Some(p) = self.prepend_path(&dirs::SHIMS) { prelude.push(p); } miseprint!("{}", shell.format_activate_prelude(&prelude))?; Ok(()) } fn activate(&self, shell: &dyn Shell, mise_bin: &Path) -> std::io::Result<()> { let mut prelude = vec![]; if let Some(set_path) = remove_shims()? { prelude.push(set_path); } let exe_dir = mise_bin.parent().unwrap(); let mut flags = vec![]; if self.quiet { flags.push(" --quiet"); } if self.status { flags.push(" --status"); } if let Some(prepend_path) = self.prepend_path(exe_dir) { prelude.push(prepend_path); } miseprint!( "{}", shell.activate(ActivateOptions { exe: mise_bin.to_path_buf(), flags: flags.join(""), no_hook_env: self.no_hook_env, prelude, }) )?; Ok(()) } fn prepend_path(&self, p: &Path) -> Option<ActivatePrelude> { if is_dir_not_in_nix(p) && !is_dir_in_path(p) && !p.is_relative() { Some(ActivatePrelude::PrependEnv( PATH_KEY.to_string(), p.to_string_lossy().to_string(), )) } else { None } } } fn remove_shims() -> std::io::Result<Option<ActivatePrelude>> { let shims = dirs::SHIMS .canonicalize() .unwrap_or(dirs::SHIMS.to_path_buf()); if env::PATH .iter() .filter_map(|p| p.canonicalize().ok()) .contains(&shims) { let path_env = PathEnv::from_iter(env::PATH.clone()); // PathEnv automatically removes the shims directory let path = path_env.join().to_string_lossy().to_string(); Ok(Some(ActivatePrelude::SetEnv(PATH_KEY.to_string(), path))) } else { Ok(None) } } fn is_dir_in_path(dir: &Path) -> bool { let dir = dir.canonicalize().unwrap_or(dir.to_path_buf()); env::PATH .clone() .into_iter() .any(|p| p.canonicalize().unwrap_or(p) == dir) } fn is_dir_not_in_nix(dir: &Path) -> bool { !dir.canonicalize() .unwrap_or(dir.to_path_buf()) .starts_with("/nix/") } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>eval "$(mise activate bash)"</bold> $ <bold>eval "$(mise activate zsh)"</bold> $ <bold>mise activate fish | source</bold> $ <bold>execx($(mise activate xonsh))</bold> $ <bold>(&mise activate pwsh) | Out-String | Invoke-Expression</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/unset.rs
src/cli/unset.rs
use std::path::PathBuf; use eyre::Result; use crate::config::config_file::ConfigFile; use crate::config::config_file::mise_toml::MiseToml; use crate::{config, env}; /// Remove environment variable(s) from the config file. /// /// By default, this command modifies `mise.toml` in the current directory. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Unset { /// Environment variable(s) to remove /// e.g.: NODE_ENV #[clap(verbatim_doc_comment, value_name = "ENV_KEY")] keys: Vec<String>, /// Specify a file to use instead of `mise.toml` #[clap(short, long, value_hint = clap::ValueHint::FilePath)] file: Option<PathBuf>, /// Use the global config file #[clap(short, long, overrides_with = "file")] global: bool, } const AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Remove NODE_ENV from the current directory's config $ <bold>mise unset NODE_ENV</bold> # Remove NODE_ENV from the global config $ <bold>mise unset NODE_ENV -g</bold> "# ); impl Unset { pub async fn run(self) -> Result<()> { let filename = if let Some(file) = &self.file { file.clone() } else if self.global { config::global_config_path() } else { config::top_toml_config().unwrap_or(env::MISE_DEFAULT_CONFIG_FILENAME.clone().into()) }; let mut config = MiseToml::from_file(&filename).unwrap_or_default(); for name in self.keys.iter() { config.remove_env(name)?; } config.save() } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/latest.rs
src/cli/latest.rs
use color_eyre::eyre::{Result, bail}; use crate::cli::args::ToolArg; use crate::config::Config; use crate::toolset::ToolRequest; use crate::ui::multi_progress_report::MultiProgressReport; /// Gets the latest available version for a plugin /// /// Supports prefixes such as `node@20` to get the latest version of node 20. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Latest { /// Tool to get the latest version of #[clap(value_name = "TOOL@VERSION")] tool: ToolArg, /// The version prefix to use when querying the latest version /// same as the first argument after the "@" /// used for asdf compatibility #[clap(hide = true)] asdf_version: Option<String>, /// Show latest installed instead of available version #[clap(short, long)] installed: bool, } impl Latest { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let mut prefix = match self.tool.tvr { None => self.asdf_version, Some(ToolRequest::Version { version, .. }) => Some(version), _ => bail!("invalid version: {}", self.tool.style()), }; let backend = self.tool.ba.backend()?; let mpr = MultiProgressReport::get(); if let Some(plugin) = backend.plugin() { plugin.ensure_installed(&config, &mpr, false, false).await?; } if let Some(v) = prefix { prefix = Some(config.resolve_alias(&backend, &v).await?); } let latest_version = if self.installed { backend.latest_installed_version(prefix)? } else { backend.latest_version(&config, prefix).await? }; if let Some(version) = latest_version { miseprintln!("{}", version); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise latest node@20</bold> # get the latest version of node 20 20.0.0 $ <bold>mise latest node</bold> # get the latest stable version of node 20.0.0 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/hook_not_found.rs
src/cli/hook_not_found.rs
use crate::exit; use eyre::Result; use crate::config::{Config, Settings}; use crate::shell::ShellType; use crate::toolset::ToolsetBuilder; /// [internal] called by shell when a command is not found #[derive(Debug, clap::Args)] #[clap(hide = true)] pub struct HookNotFound { /// Attempted bin to run #[clap()] bin: String, /// Shell type to generate script for #[clap(long, short)] shell: Option<ShellType>, } impl HookNotFound { pub async fn run(self) -> Result<()> { let mut config = Config::get().await?; let settings = Settings::try_get()?; if settings.not_found_auto_install { let mut ts = ToolsetBuilder::new().build(&config).await?; if ts .install_missing_bin(&mut config, &self.bin) .await? .is_some() { return Ok(()); } } exit(127); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_stub.rs
src/cli/tool_stub.rs
use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use crate::backend::static_helpers::lookup_platform_key; use crate::config::Config; use crate::dirs; use crate::file; use crate::hash; use crate::toolset::{InstallOptions, ToolRequest, ToolSource, ToolVersionOptions}; use clap::Parser; use color_eyre::eyre::{Result, bail, eyre}; use eyre::ensure; use serde::{Deserialize, Deserializer}; use toml::Value; #[derive(Debug, Deserialize)] pub struct ToolStubFile { #[serde(default = "default_version")] pub version: String, pub bin: Option<String>, // defaults to filename if not specified pub tool: Option<String>, // explicit tool name override #[serde(default)] pub install_env: indexmap::IndexMap<String, String>, #[serde(default)] pub os: Option<Vec<String>>, #[serde(flatten, deserialize_with = "deserialize_tool_stub_options")] pub opts: indexmap::IndexMap<String, String>, #[serde(skip)] pub tool_name: String, } // Custom deserializer that converts TOML values to strings for storage in opts fn deserialize_tool_stub_options<'de, D>( deserializer: D, ) -> Result<indexmap::IndexMap<String, String>, D::Error> where D: Deserializer<'de>, { use serde::de::Error; let value = Value::deserialize(deserializer)?; let mut opts = indexmap::IndexMap::new(); if let Value::Table(table) = value { for (key, val) in table { // Skip known special fields that are handled separately if matches!( key.as_str(), "version" | "bin" | "tool" | "install_env" | "os" ) { continue; } // Convert TOML values to strings for storage let string_value = match val { Value::String(s) => s, Value::Table(_) | Value::Array(_) => { // For complex values (tables, arrays), serialize them as TOML strings toml::to_string(&val).map_err(D::Error::custom)? } Value::Integer(i) => i.to_string(), Value::Float(f) => f.to_string(), Value::Boolean(b) => b.to_string(), Value::Datetime(dt) => dt.to_string(), }; opts.insert(key, string_value); } } Ok(opts) } fn default_version() -> String { "latest".to_string() } fn has_http_backend_config(opts: &indexmap::IndexMap<String, String>) -> bool { // Check for top-level url if opts.contains_key("url") { return true; } // Check for platform-specific configs with urls for (key, value) in opts { if key.starts_with("platforms") && value.contains("url") { return true; } } false } /// Extract TOML content from a bootstrap script's comment block /// Looks for content between `# MISE_TOOL_STUB:` and `# :MISE_TOOL_STUB` markers fn extract_toml_from_bootstrap(content: &str) -> Option<String> { let start_marker = "# MISE_TOOL_STUB:"; let end_marker = "# :MISE_TOOL_STUB"; let start_pos = content.find(start_marker)?; let end_pos = content.find(end_marker)?; if start_pos >= end_pos { return None; } // Extract content between markers (skip the start marker line) let between = &content[start_pos + start_marker.len()..end_pos]; // Remove leading `# ` from each line to get the original TOML let toml = between .lines() .map(|line| line.strip_prefix("# ").unwrap_or(line)) .collect::<Vec<_>>() .join("\n"); Some(toml.trim().to_string()) } impl ToolStubFile { pub fn from_file(path: &Path) -> Result<Self> { let content = file::read_to_string(path)?; let stub_name = path .file_name() .and_then(|name| name.to_str()) .ok_or_else(|| eyre!("Invalid stub file name"))? .to_string(); // Check if this is a bootstrap script with embedded TOML let toml_content = if let Some(toml) = extract_toml_from_bootstrap(&content) { toml } else { content }; let mut stub: ToolStubFile = toml::from_str(&toml_content)?; // Determine tool name from tool field or derive from stub name // If no tool is specified, default to HTTP backend if HTTP config is present let tool_name = stub .tool .clone() .or_else(|| stub.opts.get("tool").map(|s| s.to_string())) .unwrap_or_else(|| { if has_http_backend_config(&stub.opts) { format!("http:{stub_name}") } else { stub_name.to_string() } }); // Set bin to filename if not specified if stub.bin.is_none() { stub.bin = Some(stub_name.to_string()); } stub.tool_name = tool_name; Ok(stub) } // Create a ToolRequest directly using ToolVersionOptions pub fn to_tool_request(&self, stub_path: &Path) -> Result<ToolRequest> { use crate::cli::args::BackendArg; let mut backend_arg = BackendArg::from(&self.tool_name); let source = ToolSource::ToolStub(stub_path.to_path_buf()); // Create ToolVersionOptions from our fields let mut opts = self.opts.clone(); opts.shift_remove("tool"); // Remove tool field since it's handled separately // Add bin field if present if let Some(bin) = &self.bin { opts.insert("bin".to_string(), bin.clone()); } let options = ToolVersionOptions { os: self.os.clone(), install_env: self.install_env.clone(), opts: opts.clone(), }; // Set options on the BackendArg so they're available to the backend backend_arg.set_opts(Some(options.clone())); // For HTTP backend with "latest" version, use URL+checksum hash as version for stability let version = if self.tool_name.starts_with("http:") && self.version == "latest" { if let Some(url) = lookup_platform_key(&options, "url").or_else(|| opts.get("url").cloned()) { // Include checksum in hash calculation for better version stability let checksum = lookup_platform_key(&options, "checksum") .or_else(|| opts.get("checksum").cloned()) .unwrap_or_default(); let hash_input = format!("{url}:{checksum}"); // Use first 8 chars of URL+checksum hash as version format!("url-{}", &hash::hash_to_str(&hash_input)[..8]) } else { self.version.clone() } } else { self.version.clone() }; ToolRequest::new_opts(backend_arg.into(), &version, options, source) } } // Cache just stores the binary path as a raw string // The mtime is already encoded in the cache key, so no need to store it struct BinPathCache; impl BinPathCache { fn cache_key(stub_path: &Path) -> Result<String> { let path_str = stub_path.to_string_lossy(); let mtime = stub_path.metadata()?.modified()?; let mtime_str = format!( "{:?}", mtime .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs() ); Ok(hash::hash_to_str(&format!("{path_str}:{mtime_str}"))) } fn cache_file_path(cache_key: &str) -> PathBuf { dirs::CACHE.join("tool-stubs").join(cache_key) } fn load(cache_key: &str) -> Option<PathBuf> { let cache_path = Self::cache_file_path(cache_key); if !cache_path.exists() { return None; } match file::read_to_string(&cache_path) { Ok(content) => { let bin_path = PathBuf::from(content.trim()); // Verify the cached binary still exists if bin_path.exists() { Some(bin_path) } else { // Clean up stale cache (missing binary) let _ = file::remove_file(&cache_path); None } } Err(_) => None, } } fn save(bin_path: &Path, cache_key: &str) -> Result<()> { let cache_path = Self::cache_file_path(cache_key); if let Some(parent) = cache_path.parent() { file::create_dir_all(parent)?; } file::write(&cache_path, bin_path.to_string_lossy().as_bytes())?; Ok(()) } } fn find_tool_version( toolset: &crate::toolset::Toolset, config: &std::sync::Arc<Config>, tool_name: &str, ) -> Option<crate::toolset::ToolVersion> { for (_backend, tv) in toolset.list_current_installed_versions(config) { if tv.ba().short == tool_name { return Some(tv); } } None } fn find_single_subdirectory(install_path: &Path) -> Option<PathBuf> { let Ok(entries) = std::fs::read_dir(install_path) else { return None; }; let dirs: Vec<_> = entries .filter_map(|entry| entry.ok()) .filter(|entry| entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)) .collect(); if dirs.len() == 1 { Some(dirs[0].path()) } else { None } } fn try_find_bin_in_path(base_path: &Path, bin: &str) -> Option<PathBuf> { let bin_path = base_path.join(bin); if bin_path.exists() && crate::file::is_executable(&bin_path) { Some(bin_path) } else { None } } fn list_executable_files(dir_path: &Path) -> Vec<String> { list_executable_files_recursive(dir_path, dir_path) } fn list_executable_files_recursive(base_path: &Path, current_path: &Path) -> Vec<String> { let Ok(entries) = std::fs::read_dir(current_path) else { return Vec::new(); }; let mut result = Vec::new(); for entry in entries.filter_map(|e| e.ok()) { let path = entry.path(); let filename = entry.file_name(); let filename_str = filename.to_string_lossy(); // Skip hidden files (starting with .) if filename_str.starts_with('.') { continue; } if path.is_dir() { // Recursively search subdirectories let subdir_files = list_executable_files_recursive(base_path, &path); result.extend(subdir_files); } else if path.is_file() && crate::file::is_executable(&path) { // Get the relative path from the base directory if let Ok(relative_path) = path.strip_prefix(base_path) { result.push(relative_path.to_string_lossy().to_string()); } } } result } fn resolve_bin_with_path( toolset: &crate::toolset::Toolset, config: &std::sync::Arc<Config>, bin: &str, tool_name: &str, ) -> Option<PathBuf> { let tv = find_tool_version(toolset, config, tool_name)?; let install_path = tv.install_path(); // Try direct path first if let Some(bin_path) = try_find_bin_in_path(&install_path, bin) { return Some(bin_path); } // If direct path doesn't work, try skipping a single top-level directory // This handles cases where the tarball has a single top-level directory let subdir_path = find_single_subdirectory(&install_path)?; try_find_bin_in_path(&subdir_path, bin) } async fn resolve_bin_simple( toolset: &crate::toolset::Toolset, config: &std::sync::Arc<Config>, bin: &str, ) -> Result<Option<PathBuf>> { if let Some((backend, tv)) = toolset.which(config, bin).await { backend.which(config, &tv, bin).await } else { Ok(None) } } fn is_bin_path(bin: &str) -> bool { bin.contains('/') || bin.contains('\\') } #[derive(Debug)] enum BinPathError { ToolNotFound(String), BinNotFound { tool_name: String, bin: String, available_bins: Vec<String>, }, } fn resolve_platform_specific_bin(stub: &ToolStubFile, stub_path: &Path) -> String { // Try to find platform-specific bin field first let platform_key = get_current_platform_key(); // Check for platform-specific bin field: platforms.{platform}.bin let platform_bin_key = format!("platforms.{platform_key}.bin"); if let Some(platform_bin) = stub.opts.get(&platform_bin_key) { return platform_bin.to_string(); } // Fall back to global bin field if let Some(bin) = &stub.bin { return bin.to_string(); } // Finally, fall back to stub filename (without extension) stub_path .file_stem() .and_then(|s| s.to_str()) .unwrap_or(&stub.tool_name) .to_string() } fn get_current_platform_key() -> String { use crate::config::Settings; let settings = Settings::get(); format!("{}-{}", settings.os(), settings.arch()) } async fn find_cached_or_resolve_bin_path( toolset: &crate::toolset::Toolset, config: &std::sync::Arc<Config>, stub: &ToolStubFile, stub_path: &Path, ) -> Result<Result<PathBuf, BinPathError>> { // Generate cache key from file path and mtime let cache_key = BinPathCache::cache_key(stub_path)?; // Try to load from cache first if let Some(bin_path) = BinPathCache::load(&cache_key) { return Ok(Ok(bin_path)); } // Cache miss - resolve the binary path let bin = resolve_platform_specific_bin(stub, stub_path); let bin_path = if is_bin_path(&bin) { resolve_bin_with_path(toolset, config, &bin, &stub.tool_name) } else { resolve_bin_simple(toolset, config, &bin).await? }; if let Some(bin_path) = bin_path { // Cache the result if let Err(e) = BinPathCache::save(&bin_path, &cache_key) { // Don't fail if caching fails, just log it crate::warn!("Failed to cache binary path: {e}"); } return Ok(Ok(bin_path)); } // Determine the specific error if is_bin_path(&bin) { // For path-based bins, check if the tool exists first if let Some(tv) = find_tool_version(toolset, config, &stub.tool_name) { let install_path = tv.install_path(); // List all executable files recursively from the install path let available_bins = list_executable_files(&install_path); Ok(Err(BinPathError::BinNotFound { tool_name: stub.tool_name.clone(), bin: bin.to_string(), available_bins, })) } else { Ok(Err(BinPathError::ToolNotFound(stub.tool_name.clone()))) } } else { // For simple bin names, first check if the tool itself exists if let Some(tv) = find_tool_version(toolset, config, &stub.tool_name) { // Tool exists, list its available executables let available_bins = list_executable_files(&tv.install_path()); Ok(Err(BinPathError::BinNotFound { tool_name: stub.tool_name.clone(), bin: bin.to_string(), available_bins, })) } else { // Tool doesn't exist Ok(Err(BinPathError::ToolNotFound(stub.tool_name.clone()))) } } } async fn execute_with_tool_request( stub: &ToolStubFile, config: &mut std::sync::Arc<Config>, args: Vec<String>, stub_path: &Path, ) -> Result<()> { // Use direct ToolRequest creation with ToolVersionOptions let tool_request = stub.to_tool_request(stub_path)?; // Create a toolset directly and add the tool request with its options let source = ToolSource::ToolStub(stub_path.to_path_buf()); let mut toolset = crate::toolset::Toolset::new(source); toolset.add_version(tool_request); // Resolve the toolset to populate current versions toolset.resolve(config).await?; // Ensure we have current versions after resolving ensure!( !toolset.list_current_versions().is_empty(), "No current versions found after resolving toolset" ); // Install the tool if it's missing let install_opts = InstallOptions { force: false, jobs: None, raw: false, missing_args_only: false, resolve_options: Default::default(), ..Default::default() }; toolset .install_missing_versions(config, &install_opts) .await?; toolset.notify_if_versions_missing(config).await; // Find the binary path using cache match find_cached_or_resolve_bin_path(&toolset, &*config, stub, stub_path).await? { Ok(bin_path) => { // Get the environment with proper PATH from toolset let env = toolset.env_with_path(config).await?; crate::cli::exec::exec_program(bin_path, args, env) } Err(e) => match e { BinPathError::ToolNotFound(tool_name) => { bail!("Tool '{}' not found", tool_name); } BinPathError::BinNotFound { tool_name, bin, available_bins, } => { if available_bins.is_empty() { bail!( "Tool '{}' does not have an executable named '{}'", tool_name, bin ); } else { bail!( "Tool '{}' does not have an executable named '{}'. Available executables: {}", tool_name, bin, available_bins.join(", ") ); } } }, } } /// Execute a tool stub /// /// Tool stubs are executable files containing TOML configuration that specify /// which tool to run and how to run it. They provide a convenient way to create /// portable, self-contained executables that automatically manage tool installation /// and execution. /// /// A tool stub consists of: /// - A shebang line: #!/usr/bin/env -S mise tool-stub /// - TOML configuration specifying the tool, version, and options /// - Optional comments describing the tool's purpose /// /// Example stub file: /// #!/usr/bin/env -S mise tool-stub /// # Node.js v20 development environment /// /// tool = "node" /// version = "20.0.0" /// bin = "node" /// /// The stub will automatically install the specified tool version if missing /// and execute it with any arguments passed to the stub. /// /// For more information, see: https://mise.jdx.dev/dev-tools/tool-stubs.html #[derive(Debug, Parser)] #[clap(disable_help_flag = true, disable_version_flag = true)] pub struct ToolStub { /// Path to the TOML tool stub file to execute /// /// The stub file must contain TOML configuration specifying the tool /// and version to run. At minimum, it should specify a 'version' field. /// Other common fields include 'tool', 'bin', and backend-specific options. #[clap(value_name = "FILE")] pub file: PathBuf, /// Arguments to pass to the tool /// /// All arguments after the stub file path will be forwarded to the /// underlying tool. Use '--' to separate mise arguments from tool arguments /// if needed. #[clap(trailing_var_arg = true, allow_hyphen_values = true)] pub args: Vec<String>, } impl ToolStub { pub async fn run(self) -> Result<()> { // Ignore clap parsing and use raw args from env::ARGS to avoid version flag interception let file_str = self.file.to_string_lossy(); // Find our file in the global args and take everything after it let args = { let global_args = crate::env::ARGS.read().unwrap(); let file_str_ref: &str = file_str.as_ref(); if let Some(file_pos) = global_args.iter().position(|arg| arg == file_str_ref) { global_args.get(file_pos + 1..).unwrap_or(&[]).to_vec() } else { vec![] } }; // Drop the lock before await let stub = ToolStubFile::from_file(&self.file)?; let mut config = Config::get().await?; return execute_with_tool_request(&stub, &mut config, args, &self.file).await; } } pub(crate) async fn short_circuit_stub(args: &[String]) -> Result<()> { // Early return if no args or not enough args for a stub if args.is_empty() { return Ok(()); } // Check if the first argument looks like a tool stub file path let potential_stub_path = std::path::Path::new(&args[0]); // Only proceed if it's an existing file with a reasonable extension if !potential_stub_path.exists() { return Ok(()); } // Generate cache key from file path and mtime let cache_key = BinPathCache::cache_key(potential_stub_path)?; // Check if we have a cached binary path if let Some(bin_path) = BinPathCache::load(&cache_key) { let args = args[1..].to_vec(); return crate::cli::exec::exec_program(bin_path, args, BTreeMap::new()); } // No cache hit, return Ok(()) to continue with normal processing Ok(()) }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/use.rs
src/cli/use.rs
use std::{ path::{Path, PathBuf}, sync::Arc, }; use console::{Term, style}; use eyre::{Result, bail, eyre}; use itertools::Itertools; use jiff::Timestamp; use path_absolutize::Absolutize; use crate::cli::args::{BackendArg, ToolArg}; use crate::config::config_file::ConfigFile; use crate::config::{Config, ConfigPathOptions, Settings, config_file, resolve_target_config_path}; use crate::duration::parse_into_timestamp; use crate::file::display_path; use crate::registry::REGISTRY; use crate::toolset::{ InstallOptions, ResolveOptions, ToolRequest, ToolSource, ToolVersion, ToolsetBuilder, }; use crate::ui::ctrlc; use crate::{config, env, file}; /// Installs a tool and adds the version to mise.toml. /// /// This will install the tool version if it is not already installed. /// By default, this will use a `mise.toml` file in the current directory. /// /// In the following order: /// - If `--global` is set, it will use the global config file. /// - If `--path` is set, it will use the config file at the given path. /// - If `--env` is set, it will use `mise.<env>.toml`. /// - If `MISE_DEFAULT_CONFIG_FILENAME` is set, it will use that instead. /// - If `MISE_OVERRIDE_CONFIG_FILENAMES` is set, it will the first from that list. /// - Otherwise just "mise.toml" or global config if cwd is home directory. /// /// Use the `--global` flag to use the global config file instead. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_alias = "u", after_long_help = AFTER_LONG_HELP)] pub struct Use { /// Tool(s) to add to config file /// /// e.g.: node@20, cargo:ripgrep@latest npm:prettier@3 /// If no version is specified, it will default to @latest /// /// Tool options can be set with this syntax: /// /// mise use ubi:BurntSushi/ripgrep[exe=rg] #[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)] tool: Vec<ToolArg>, /// Create/modify an environment-specific config file like .mise.<env>.toml #[clap(long, short, overrides_with_all = & ["global", "path"])] env: Option<String>, /// Force reinstall even if already installed #[clap(long, short, requires = "tool")] force: bool, /// Use the global config file (`~/.config/mise/config.toml`) instead of the local one #[clap(short, long, overrides_with_all = & ["path", "env"])] global: bool, /// Number of jobs to run in parallel /// [default: 4] #[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)] jobs: Option<usize>, /// Perform a dry run, showing what would be installed and modified without making changes #[clap(long, short = 'n', verbatim_doc_comment)] dry_run: bool, /// Specify a path to a config file or directory /// /// If a directory is specified, it will look for a config file in that directory following /// the rules above. #[clap(short, long, overrides_with_all = & ["global", "env"], value_hint = clap::ValueHint::FilePath)] path: Option<PathBuf>, /// Only install versions released before this date /// /// Supports absolute dates like "2024-06-01" and relative durations like "90d" or "1y". #[clap(long, verbatim_doc_comment)] before: Option<String>, /// Save fuzzy version to config file /// /// e.g.: `mise use --fuzzy node@20` will save 20 as the version /// this is the default behavior unless `MISE_PIN=1` #[clap(long, verbatim_doc_comment, overrides_with = "pin")] fuzzy: bool, /// Save exact version to config file /// e.g.: `mise use --pin node@20` will save 20.0.0 as the version /// Set `MISE_PIN=1` to make this the default behavior /// /// Consider using mise.lock as a better alternative to pinning in mise.toml: /// https://mise.jdx.dev/configuration/settings.html#lockfile #[clap(long, verbatim_doc_comment, overrides_with = "fuzzy")] pin: bool, /// Directly pipe stdin/stdout/stderr from plugin to user /// Sets `--jobs=1` #[clap(long, overrides_with = "jobs")] raw: bool, /// Remove the plugin(s) from config file #[clap(long, value_name = "PLUGIN", aliases = ["rm", "unset"])] remove: Vec<BackendArg>, } impl Use { pub async fn run(mut self) -> Result<()> { if self.tool.is_empty() && self.remove.is_empty() { self.tool = vec![self.tool_selector()?]; } env::TOOL_ARGS.write().unwrap().clone_from(&self.tool); let mut config = Config::get().await?; let mut ts = ToolsetBuilder::new() .with_global_only(self.global) .build(&config) .await?; let cf = self.get_config_file().await?; let mut resolve_options = ResolveOptions { latest_versions: false, use_locked_version: true, before_date: self.get_before_date()?, }; let versions: Vec<_> = self .tool .iter() .cloned() .map(|t| match t.tvr { Some(tvr) => { if tvr.version() == "latest" { // user specified `@latest` so we should resolve the latest version // TODO: this should only happen on this tool, not all of them resolve_options.latest_versions = true; resolve_options.use_locked_version = false; } Ok(tvr) } None => ToolRequest::new( t.ba, "latest", ToolSource::MiseToml(cf.get_path().to_path_buf()), ), }) .collect::<Result<_>>()?; let mut versions = ts .install_all_versions( &mut config, versions.clone(), &InstallOptions { reason: "use".to_string(), force: self.force, jobs: self.jobs, raw: self.raw, dry_run: self.dry_run, resolve_options, ..Default::default() }, ) .await?; let pin = self.pin || !self.fuzzy && (Settings::get().pin || Settings::get().asdf_compat); for (ba, tvl) in &versions.iter().chunk_by(|tv| tv.ba()) { let versions: Vec<_> = tvl .into_iter() .map(|tv| { let mut request = tv.request.clone(); if pin && let ToolRequest::Version { version: _version, source, options, backend, } = request { request = ToolRequest::Version { version: tv.version.clone(), source, options, backend, }; } request }) .collect(); cf.replace_versions(ba, versions)?; } if self.global { self.warn_if_hidden(&config, cf.get_path()).await; } for plugin_name in &self.remove { cf.remove_tool(plugin_name)?; } if !self.dry_run { cf.save()?; for tv in &mut versions { // update the source so the lockfile is updated correctly tv.request.set_source(cf.source()); } let config = Config::reset().await?; let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(&config, ts, &versions).await?; } self.render_success_message(cf.as_ref(), &versions, &self.remove)?; Ok(()) } async fn get_config_file(&self) -> Result<Arc<dyn ConfigFile>> { let cwd = env::current_dir()?; // Handle special case for --path that needs absolutize logic for compatibility let path = if let Some(p) = &self.path { let from_dir = config::config_file_from_dir(p).absolutize()?.to_path_buf(); if from_dir.starts_with(&cwd) { from_dir } else { p.clone() } } else { let opts = ConfigPathOptions { global: self.global, path: None, // handled above env: self.env.clone(), cwd: Some(cwd), prefer_toml: false, // mise use supports .tool-versions and other formats prevent_home_local: true, // When in HOME, use global config }; resolve_target_config_path(opts)? }; config_file::parse_or_init(&path).await } async fn warn_if_hidden(&self, config: &Arc<Config>, global: &Path) { let ts = ToolsetBuilder::new() .build(config) .await .unwrap_or_default(); let warn = |targ: &ToolArg, p| { let plugin = &targ.ba; let p = display_path(p); let global = display_path(global); warn!("{plugin} is defined in {p} which overrides the global config ({global})"); }; for targ in &self.tool { if let Some(tv) = ts.versions.get(targ.ba.as_ref()) && let ToolSource::MiseToml(p) | ToolSource::ToolVersions(p) = &tv.source && !file::same_file(p, global) { warn(targ, p); } } } fn render_success_message( &self, cf: &dyn ConfigFile, versions: &[ToolVersion], remove: &[BackendArg], ) -> Result<()> { let path = display_path(cf.get_path()); if self.dry_run { let mut messages = vec![]; if !versions.is_empty() { let tools = versions.iter().map(|t| t.style()).join(", "); messages.push(format!("add: {tools}")); } if !remove.is_empty() { let tools_to_remove = remove.iter().map(|r| r.to_string()).join(", "); messages.push(format!("remove: {tools_to_remove}")); } if !messages.is_empty() { miseprintln!( "{} would update {} ({})", style("mise").green(), style(&path).cyan().for_stderr(), messages.join(", ") ); } } else { if !versions.is_empty() { let tools = versions.iter().map(|t| t.style()).join(", "); miseprintln!( "{} {} tools: {tools}", style("mise").green(), style(&path).cyan().for_stderr(), ); } if !remove.is_empty() { let tools_to_remove = remove.iter().map(|r| r.to_string()).join(", "); miseprintln!( "{} {} removed: {tools_to_remove}", style("mise").green(), style(&path).cyan().for_stderr(), ); } } Ok(()) } fn tool_selector(&self) -> Result<ToolArg> { if !console::user_attended_stderr() { bail!("No tool specified and not running interactively"); } let theme = crate::ui::theme::get_theme(); let mut s = demand::Select::new("Tools") .description("Select a tool to install") .filtering(true) .filterable(true) .theme(&theme); for rt in REGISTRY.values().unique_by(|r| r.short) { if let Some(backend) = rt.backends().first() { // TODO: populate registry with descriptions from aqua and other sources // TODO: use the backend from the lockfile if available let description = rt.description.unwrap_or(backend); s = s.option(demand::DemandOption::new(rt).description(description)); } } ctrlc::show_cursor_after_ctrl_c(); match s.run() { Ok(rt) => rt.short.parse(), Err(err) => { Term::stderr().show_cursor()?; Err(eyre!(err)) } } } /// Get the before_date from CLI flag or settings fn get_before_date(&self) -> Result<Option<Timestamp>> { if let Some(before) = &self.before { return Ok(Some(parse_into_timestamp(before)?)); } if let Some(before) = &Settings::get().install_before { return Ok(Some(parse_into_timestamp(before)?)); } Ok(None) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # run with no arguments to use the interactive selector $ <bold>mise use</bold> # set the current version of node to 20.x in mise.toml of current directory # will write the fuzzy version (e.g.: 20) $ <bold>mise use node@20</bold> # set the current version of node to 20.x in ~/.config/mise/config.toml # will write the precise version (e.g.: 20.0.0) $ <bold>mise use -g --pin node@20</bold> # sets .mise.local.toml (which is intended not to be committed to a project) $ <bold>mise use --env local node@20</bold> # sets .mise.staging.toml (which is used if MISE_ENV=staging) $ <bold>mise use --env staging node@20</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/prepare.rs
src/cli/prepare.rs
use eyre::Result; use crate::config::Config; use crate::prepare::{PrepareEngine, PrepareOptions, PrepareStepResult}; use crate::toolset::{InstallOptions, ToolsetBuilder}; /// [experimental] Ensure project dependencies are ready /// /// Runs all applicable prepare steps for the current project. /// This checks if dependency lockfiles are newer than installed outputs /// (e.g., package-lock.json vs node_modules/) and runs install commands /// if needed. /// /// Providers with `auto = true` are automatically invoked before `mise x` and `mise run` /// unless skipped with the --no-prepare flag. #[derive(Debug, clap::Args)] #[clap(visible_alias = "prep", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Prepare { /// Force run all prepare steps even if outputs are fresh #[clap(long, short)] pub force: bool, /// Show what prepare steps are available #[clap(long)] pub list: bool, /// Only check if prepare is needed, don't run commands #[clap(long, short = 'n')] pub dry_run: bool, /// Run specific prepare rule(s) only #[clap(long)] pub only: Option<Vec<String>>, /// Skip specific prepare rule(s) #[clap(long)] pub skip: Option<Vec<String>>, } impl Prepare { pub async fn run(self) -> Result<()> { let mut config = Config::get().await?; let engine = PrepareEngine::new(config.clone())?; if self.list { self.list_providers(&engine)?; return Ok(()); } // Build and install toolset so tools like npm are available let mut ts = ToolsetBuilder::new() .with_default_to_latest(true) .build(&config) .await?; ts.install_missing_versions(&mut config, &InstallOptions::default()) .await?; // Get toolset environment with PATH let env = ts.env_with_path(&config).await?; let opts = PrepareOptions { dry_run: self.dry_run, force: self.force, only: self.only, skip: self.skip.unwrap_or_default(), env, ..Default::default() }; let result = engine.run(opts).await?; // Report results for step in &result.steps { match step { PrepareStepResult::Ran(id) => { miseprintln!("Prepared: {}", id); } PrepareStepResult::WouldRun(id) => { miseprintln!("[dry-run] Would prepare: {}", id); } PrepareStepResult::Fresh(id) => { debug!("Fresh: {}", id); } PrepareStepResult::Skipped(id) => { debug!("Skipped: {}", id); } } } if !result.had_work() && !self.dry_run { miseprintln!("All dependencies are up to date"); } Ok(()) } fn list_providers(&self, engine: &PrepareEngine) -> Result<()> { let providers = engine.list_providers(); if providers.is_empty() { miseprintln!("No prepare providers found for this project"); return Ok(()); } miseprintln!("Available prepare providers:"); for provider in providers { let sources = provider .sources() .iter() .map(|p| p.display().to_string()) .collect::<Vec<_>>() .join(", "); let outputs = provider .outputs() .iter() .map(|p| p.display().to_string()) .collect::<Vec<_>>() .join(", "); miseprintln!(" {}", provider.id()); miseprintln!(" sources: {}", sources); miseprintln!(" outputs: {}", outputs); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise prepare</bold> # Run all applicable prepare steps $ <bold>mise prepare --dry-run</bold> # Show what would run without executing $ <bold>mise prepare --force</bold> # Force run even if outputs are fresh $ <bold>mise prepare --list</bold> # List available prepare providers $ <bold>mise prepare --only npm</bold> # Run only npm prepare $ <bold>mise prepare --skip npm</bold> # Skip npm prepare <bold><underline>Configuration:</underline></bold> Configure prepare providers in mise.toml: ```toml # Built-in npm provider (auto-detects lockfile) [prepare.npm] auto = true # Auto-run before mise x/run # Custom provider [prepare.codegen] auto = true sources = ["schema/*.graphql"] outputs = ["src/generated/"] run = "npm run codegen" [prepare] disable = ["npm"] # Disable specific providers at runtime ``` "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/install_into.rs
src/cli/install_into.rs
use crate::cli::args::ToolArg; use crate::config::Config; use crate::install_context::InstallContext; use crate::toolset::ToolsetBuilder; use crate::ui::multi_progress_report::MultiProgressReport; use clap::ValueHint; use eyre::{Result, eyre}; use std::{path::PathBuf, sync::Arc}; /// Install a tool version to a specific path /// /// Used for building a tool to a directory for use outside of mise #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct InstallInto { /// Tool to install /// e.g.: node@20 #[clap(value_name = "TOOL@VERSION")] tool: ToolArg, /// Path to install the tool into #[clap(value_hint = ValueHint::DirPath)] path: PathBuf, } impl InstallInto { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let ts = Arc::new( ToolsetBuilder::new() .with_args(std::slice::from_ref(&self.tool)) .build(&config) .await?, ); let mut tv = ts .versions .get(self.tool.ba.as_ref()) .ok_or_else(|| eyre!("Tool not found"))? .versions .first() .unwrap() .clone(); let backend = tv.backend()?; let mpr = MultiProgressReport::get(); let install_ctx = InstallContext { config: config.clone(), ts: ts.clone(), pr: mpr.add(&tv.style()), force: true, dry_run: false, locked: false, // install-into doesn't support locked mode }; tv.install_path = Some(self.path.clone()); backend.install_version(install_ctx, tv).await?; Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # install node@20.0.0 into ./mynode $ <bold>mise install-into node@20.0.0 ./mynode && ./mynode/bin/node -v</bold> 20.0.0 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/where.rs
src/cli/where.rs
use eyre::Result; use crate::cli::args::ToolArg; use crate::config::Config; use crate::errors::Error; use crate::toolset::ToolsetBuilder; /// Display the installation path for a tool /// /// The tool must be installed for this to work. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Where { /// Tool(s) to look up /// e.g.: ruby@3 /// if "@<PREFIX>" is specified, it will show the latest installed version /// that matches the prefix /// otherwise, it will show the current, active installed version #[clap(required = true, value_name = "TOOL@VERSION", verbatim_doc_comment)] tool: ToolArg, /// the version prefix to use when querying the latest version /// same as the first argument after the "@" /// used for asdf compatibility #[clap(hide = true, verbatim_doc_comment)] asdf_version: Option<String>, } impl Where { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let tvr = match self.tool.tvr { Some(tvr) => tvr, None => match self.asdf_version { Some(version) => self.tool.with_version(&version).tvr.unwrap(), None => { let ts = ToolsetBuilder::new().build(&config).await?; ts.versions .get(self.tool.ba.as_ref()) .and_then(|tvr| tvr.requests.first().cloned()) .unwrap_or_else(|| self.tool.with_version("latest").tvr.unwrap()) } }, }; let tv = tvr.resolve(&config, &Default::default()).await?; if tv.backend()?.is_version_installed(&config, &tv, true) { miseprintln!("{}", tv.install_path().to_string_lossy()); Ok(()) } else { Err(Error::VersionNotInstalled( Box::new(tv.ba().clone()), tv.version, ))? } } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Show the latest installed version of node # If it is is not installed, errors $ <bold>mise where node@20</bold> /home/jdx/.local/share/mise/installs/node/20.0.0 # Show the current, active install directory of node # Errors if node is not referenced in any .tool-version file $ <bold>mise where node</bold> /home/jdx/.local/share/mise/installs/node/20.0.0 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/exec.rs
src/cli/exec.rs
use std::collections::BTreeMap; use std::ffi::OsString; use clap::ValueHint; use duct::IntoExecutablePath; #[cfg(not(any(test, windows)))] use eyre::{Result, bail}; #[cfg(any(test, windows))] use eyre::{Result, eyre}; use crate::cli::args::ToolArg; #[cfg(any(test, windows))] use crate::cmd; use crate::config::{Config, Settings}; use crate::env; use crate::prepare::{PrepareEngine, PrepareOptions}; use crate::toolset::{InstallOptions, ResolveOptions, ToolsetBuilder}; /// Execute a command with tool(s) set /// /// use this to avoid modifying the shell session or running ad-hoc commands with mise tools set. /// /// Tools will be loaded from mise.toml, though they can be overridden with <RUNTIME> args /// Note that only the plugin specified will be overridden, so if a `mise.toml` file /// includes "node 20" but you run `mise exec python@3.11`; it will still load node@20. /// /// The "--" separates runtimes from the commands to pass along to the subprocess. #[derive(Debug, clap::Args)] #[clap(visible_alias = "x", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Exec { /// Tool(s) to start /// e.g.: node@20 python@3.10 #[clap(value_name = "TOOL@VERSION")] pub tool: Vec<ToolArg>, /// Command string to execute (same as --command) #[clap(conflicts_with = "c", required_unless_present = "c", last = true)] pub command: Option<Vec<String>>, /// Command string to execute #[clap(short, long = "command", value_hint = ValueHint::CommandString, conflicts_with = "command")] pub c: Option<String>, /// Number of jobs to run in parallel /// [default: 4] #[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)] pub jobs: Option<usize>, /// Skip automatic dependency preparation #[clap(long)] pub no_prepare: bool, /// Directly pipe stdin/stdout/stderr from plugin to user /// Sets --jobs=1 #[clap(long, overrides_with = "jobs")] pub raw: bool, } impl Exec { #[async_backtrace::framed] pub async fn run(self) -> eyre::Result<()> { let mut config = Config::get().await?; // Check if any tool arg explicitly specified @latest // If so, resolve to the actual latest version from the registry (not just latest installed) let has_explicit_latest = self .tool .iter() .any(|t| t.tvr.as_ref().is_some_and(|tvr| tvr.version() == "latest")); let resolve_options = if has_explicit_latest { ResolveOptions { latest_versions: true, use_locked_version: false, ..Default::default() } } else { Default::default() }; let mut ts = measure!("toolset", { ToolsetBuilder::new() .with_args(&self.tool) .with_default_to_latest(true) .with_resolve_options(resolve_options.clone()) .build(&config) .await? }); let opts = InstallOptions { force: false, jobs: self.jobs, raw: self.raw, // prevent installing things in shims by checking for tty // also don't autoinstall if at least 1 tool is specified // in that case the user probably just wants that one tool missing_args_only: !self.tool.is_empty() || !Settings::get().exec_auto_install || *env::__MISE_SHIM, skip_auto_install: !Settings::get().exec_auto_install || !Settings::get().auto_install, resolve_options, ..Default::default() }; measure!("install_arg_versions", { ts.install_missing_versions(&mut config, &opts).await? }); // If we installed new versions for explicit @latest, re-resolve to pick up the installed versions if has_explicit_latest { ts.resolve_with_opts(&config, &opts.resolve_options).await?; } measure!("notify_if_versions_missing", { ts.notify_if_versions_missing(&config).await; }); let (program, mut args) = parse_command(&env::SHELL, &self.command, &self.c); let mut env = measure!("env_with_path", { ts.env_with_path(&config).await? }); // Run auto-enabled prepare steps (unless --no-prepare) if !self.no_prepare { let engine = PrepareEngine::new(config.clone())?; engine .run(PrepareOptions { auto_only: true, // Only run providers with auto=true env: env.clone(), ..Default::default() }) .await?; } // Ensure MISE_ENV is set in the spawned shell if it was specified via -E flag if !env::MISE_ENV.is_empty() { env.insert("MISE_ENV".to_string(), env::MISE_ENV.join(",")); } if program.rsplit('/').next() == Some("fish") { let mut cmd = vec![]; for (k, v) in env.iter().filter(|(k, _)| *k != "PATH") { cmd.push(format!( "set -gx {} {}", shell_escape::escape(k.into()), shell_escape::escape(v.into()) )); } // TODO: env is being calculated twice with final_env and env_with_path let (_, env_results) = ts.final_env(&config).await?; for p in ts.list_final_paths(&config, env_results).await? { cmd.push(format!( "fish_add_path -gm {}", shell_escape::escape(p.to_string_lossy()) )); } args.insert(0, cmd.join("\n")); args.insert(0, "-C".into()); } time!("exec"); exec_program(program, args, env) } } #[cfg(all(not(test), unix))] pub fn exec_program<T, U>(program: T, args: U, env: BTreeMap<String, String>) -> Result<()> where T: IntoExecutablePath, U: IntoIterator, U::Item: Into<OsString>, { for (k, v) in env.iter() { env::set_var(k, v); } let args = args.into_iter().map(Into::into).collect::<Vec<_>>(); let program = program.to_executable(); let err = exec::Command::new(program.clone()).args(&args).exec(); bail!("{:?} {err}", program.to_string_lossy()) } #[cfg(all(windows, not(test)))] pub fn exec_program<T, U>(program: T, args: U, env: BTreeMap<String, String>) -> Result<()> where T: IntoExecutablePath, U: IntoIterator, U::Item: Into<OsString>, { for (k, v) in env.iter() { env::set_var(k, v); } let cwd = crate::dirs::CWD.clone().unwrap_or_default(); let program = program.to_executable(); let path = env.get(&*env::PATH_KEY).map(OsString::from); let program = which::which_in(program, path, cwd)?; let cmd = cmd::cmd(program, args); // Windows does not support exec in the same way as Unix, // so we emulate it instead by not handling Ctrl-C and letting // the child process deal with it instead. win_exec::set_ctrlc_handler()?; let res = cmd.unchecked().run()?; match res.status.code() { Some(code) => { std::process::exit(code); } None => Err(eyre!("command failed: terminated by signal")), } } #[cfg(test)] pub fn exec_program<T, U>(program: T, args: U, env: BTreeMap<String, String>) -> Result<()> where T: IntoExecutablePath, U: IntoIterator, U::Item: Into<OsString>, { let mut cmd = cmd::cmd(program, args); for (k, v) in env.iter() { cmd = cmd.env(k, v); } let res = cmd.unchecked().run()?; match res.status.code() { Some(0) => Ok(()), Some(code) => Err(eyre!("command failed: exit code {}", code)), None => Err(eyre!("command failed: terminated by signal")), } } #[cfg(all(windows, not(test)))] mod win_exec { use eyre::{Result, eyre}; use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE}; use winapi::um::consoleapi::SetConsoleCtrlHandler; // Windows way of creating a process is to just go ahead and pop a new process // with given program and args into existence. But in unix-land, it instead happens // in a two-step process where you first fork the process and then exec the new program, // essentially replacing the current process with the new one. // We use Windows API to set a Ctrl-C handler that does nothing, essentially attempting // to emulate the ctrl-c behavior by not handling it ourselves, and propagating it to // the child process to handle it instead. // This is the same way cargo does it in cargo run. unsafe extern "system" fn ctrlc_handler(_: DWORD) -> BOOL { // This is a no-op handler to prevent Ctrl-C from terminating the process. // It allows the child process to handle Ctrl-C instead. TRUE } pub(super) fn set_ctrlc_handler() -> Result<()> { if unsafe { SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) } == FALSE { Err(eyre!("Could not set Ctrl-C handler.")) } else { Ok(()) } } } fn parse_command( shell: &str, command: &Option<Vec<String>>, c: &Option<String>, ) -> (String, Vec<String>) { match (&command, &c) { (Some(command), _) => { let (program, args) = command.split_first().unwrap(); (program.clone(), args.into()) } _ => ( shell.into(), vec![env::SHELL_COMMAND_FLAG.into(), c.clone().unwrap()], ), } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise exec node@20 -- node ./app.js</bold> # launch app.js using node-20.x $ <bold>mise x node@20 -- node ./app.js</bold> # shorter alias # Specify command as a string: $ <bold>mise exec node@20 python@3.11 --command "node -v && python -V"</bold> # Run a command in a different directory: $ <bold>mise x -C /path/to/project node@20 -- node ./app.js</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/current.rs
src/cli/current.rs
use console::style; use eyre::{Result, bail}; use crate::backend::Backend; use crate::cli::args::BackendArg; use crate::config::Config; use crate::toolset::{Toolset, ToolsetBuilder}; /// Shows current active and installed runtime versions /// /// This is similar to `mise ls --current`, but this only shows the runtime /// and/or version. It's designed to fit into scripts more easily. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, hide = true, after_long_help = AFTER_LONG_HELP)] pub struct Current { /// Plugin to show versions of /// e.g.: ruby, node, cargo:eza, npm:prettier, etc. #[clap()] plugin: Option<BackendArg>, } impl Current { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let ts = ToolsetBuilder::new().build(&config).await?; match &self.plugin { Some(ba) => { if let Some(plugin) = ba.backend()?.plugin() && !plugin.is_installed() { bail!("Plugin {ba} is not installed"); } self.one(ts, ba.backend()?.as_ref()).await } None => self.all(ts).await, } } async fn one(&self, ts: Toolset, tool: &dyn Backend) -> Result<()> { if let Some(plugin) = tool.plugin() && !plugin.is_installed() { warn!("Plugin {} is not installed", tool.id()); return Ok(()); } match ts .list_versions_by_plugin() .into_iter() .find(|(p, _)| p.id() == tool.id()) { Some((_, versions)) => { miseprintln!( "{}", versions .iter() .map(|v| v.version.to_string()) .collect::<Vec<_>>() .join(" ") ); } None => { warn!( "Plugin {} does not have a version set", style(tool.id()).blue().for_stderr() ); } }; Ok(()) } async fn all(&self, ts: Toolset) -> Result<()> { let config = Config::get().await?; for (plugin, versions) in ts.list_versions_by_plugin() { if versions.is_empty() { continue; } for tv in versions { if !plugin.is_version_installed(&config, tv, true) { let source = ts.versions.get(tv.ba()).unwrap().source.clone(); warn!( "{}@{} is specified in {}, but not installed", &tv.ba(), &tv.version, &source ); hint!( "tools_missing", "install missing tools with", "mise install" ); } } miseprintln!( "{} {}", &plugin.id(), versions .iter() .map(|v| v.version.to_string()) .collect::<Vec<_>>() .join(" ") ); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # outputs `.tool-versions` compatible format $ <bold>mise current</bold> python 3.11.0 3.10.0 shfmt 3.6.0 shellcheck 0.9.0 node 20.0.0 $ <bold>mise current node</bold> 20.0.0 # can output multiple versions $ <bold>mise current python</bold> 3.11.0 3.10.0 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/bin_paths.rs
src/cli/bin_paths.rs
use crate::cli::args::ToolArg; use crate::config::Config; use crate::toolset::ToolsetBuilder; use eyre::Result; /// List all the active runtime bin paths #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment)] pub struct BinPaths { /// Tool(s) to look up /// e.g.: ruby@3 #[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)] tool: Option<Vec<ToolArg>>, } impl BinPaths { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let mut tsb = ToolsetBuilder::new(); if let Some(tool) = &self.tool { tsb = tsb.with_args(tool); } let mut ts = tsb.build(&config).await?; if let Some(tool) = &self.tool { ts.versions.retain(|k, _| tool.iter().any(|t| *t.ba == **k)); } ts.notify_if_versions_missing(&config).await; for p in ts.list_paths(&config).await { miseprintln!("{}", p.display()); } Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/set.rs
src/cli/set.rs
use std::path::{Path, PathBuf}; use super::args::EnvVarArg; use crate::agecrypt; use crate::config::config_file::ConfigFile; use crate::config::config_file::mise_toml::MiseToml; use crate::config::env_directive::EnvDirective; use crate::config::{Config, ConfigPathOptions, Settings, resolve_target_config_path}; use crate::env::{self}; use crate::file::display_path; use crate::ui::table; use demand::Input; use eyre::{Result, bail, eyre}; use tabled::Tabled; /// Set environment variables in mise.toml /// /// By default, this command modifies `mise.toml` in the current directory. /// Use `-E <env>` to create/modify environment-specific config files like `mise.<env>.toml`. #[derive(Debug, clap::Args)] #[clap(aliases = ["ev", "env-vars"], verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Set { /// Environment variable(s) to set /// e.g.: NODE_ENV=production #[clap(value_name = "ENV_VAR", verbatim_doc_comment)] env_vars: Option<Vec<EnvVarArg>>, /// Create/modify an environment-specific config file like .mise.<env>.toml #[clap(short = 'E', long, overrides_with_all = &["global", "file"])] env: Option<String>, /// Set the environment variable in the global config file #[clap(short, long, verbatim_doc_comment, overrides_with_all = &["file", "env"])] global: bool, /// [experimental] Encrypt the value with age before storing #[clap(long, requires = "env_vars")] age_encrypt: bool, /// [experimental] Age identity file for encryption /// /// Defaults to ~/.config/mise/age.txt if it exists #[clap(long, value_name = "PATH", requires = "age_encrypt", value_hint = clap::ValueHint::FilePath)] age_key_file: Option<PathBuf>, /// [experimental] Age recipient (x25519 public key) for encryption /// /// Can be used multiple times. Requires --age-encrypt. #[clap(long, value_name = "RECIPIENT", requires = "age_encrypt")] age_recipient: Vec<String>, /// [experimental] SSH recipient (public key or path) for age encryption /// /// Can be used multiple times. Requires --age-encrypt. #[clap(long, value_name = "PATH_OR_PUBKEY", requires = "age_encrypt")] age_ssh_recipient: Vec<String>, /// Render completions #[clap(long, hide = true)] complete: bool, /// The TOML file to update /// /// Can be a file path or directory. If a directory is provided, will create/use mise.toml in that directory. /// Defaults to MISE_DEFAULT_CONFIG_FILENAME environment variable, or `mise.toml`. #[clap(long, verbatim_doc_comment, required = false, value_hint = clap::ValueHint::AnyPath)] file: Option<PathBuf>, /// Prompt for environment variable values #[clap(long)] prompt: bool, /// Remove the environment variable from config file /// /// Can be used multiple times. #[clap(long, value_name = "ENV_KEY", verbatim_doc_comment, visible_aliases = ["rm", "unset"], hide = true)] remove: Option<Vec<String>>, } impl Set { /// Decrypt a value if it's encrypted, otherwise return it as-is async fn decrypt_value_if_needed( key: &str, value: &str, directive: Option<&EnvDirective>, ) -> Result<String> { // If we have an Age directive, use the specialized decryption if let Some(EnvDirective::Age { .. }) = directive { agecrypt::decrypt_age_directive(directive.unwrap()) .await .map_err(|e| eyre!("[experimental] Failed to decrypt {}: {}", key, e)) } // Not encrypted, return as-is else { Ok(value.to_string()) } } pub async fn run(mut self) -> Result<()> { if self.complete { return self.complete().await; } match (&self.remove, &self.env_vars) { (None, None) => { return self.list_all().await; } (None, Some(env_vars)) if env_vars.iter().all(|ev| ev.value.is_none()) && !self.prompt => { return self.get().await; } _ => {} } let filename = self.filename()?; let mut mise_toml = get_mise_toml(&filename)?; if let Some(env_names) = &self.remove { for name in env_names { mise_toml.remove_env(name)?; } } if let Some(env_vars) = &self.env_vars && env_vars.len() == 1 && env_vars[0].value.is_none() && !self.prompt { let key = &env_vars[0].key; // Use Config's centralized env loading which handles decryption let full_config = Config::get().await?; let env = full_config.env().await?; match env.get(key) { Some(value) => { miseprintln!("{value}"); } None => bail!("Environment variable {key} not found"), } return Ok(()); } if let Some(mut env_vars) = self.env_vars.take() { // Prompt for values if requested if self.prompt { let theme = crate::ui::theme::get_theme(); for ev in &mut env_vars { if ev.value.is_none() { let prompt_msg = format!("Enter value for {}", ev.key); let value = Input::new(&prompt_msg) .password(self.age_encrypt) // Mask input if encrypting .theme(&theme) .run()?; ev.value = Some(value); } } } // Handle age encryption if requested if self.age_encrypt { Settings::get().ensure_experimental("age encryption")?; // Collect recipients once before the loop to avoid repeated I/O let recipients = self.collect_age_recipients().await?; for ev in env_vars { match ev.value { Some(value) => { let age_directive = agecrypt::create_age_directive(ev.key.clone(), &value, &recipients) .await?; if let crate::config::env_directive::EnvDirective::Age { value: encrypted_value, format, .. } = age_directive { mise_toml.update_env_age(&ev.key, &encrypted_value, format)?; } } None => bail!("{} has no value", ev.key), } } } else { for ev in env_vars { match ev.value { Some(value) => mise_toml.update_env(&ev.key, value)?, None => bail!("{} has no value", ev.key), } } } } mise_toml.save() } async fn complete(&self) -> Result<()> { for ev in self.cur_env().await? { println!("{}", ev.key); } Ok(()) } async fn list_all(self) -> Result<()> { let env = self.cur_env().await?; let mut table = tabled::Table::new(env); table::default_style(&mut table, false); miseprintln!("{table}"); Ok(()) } async fn get(self) -> Result<()> { // Determine config file path before moving env_vars let config_path = if let Some(file) = &self.file { Some(file.clone()) } else if self.env.is_some() { Some(self.filename()?) } else if !self.global { // Check for local config file when no specific file or environment is specified // Check for mise.toml in current directory first let cwd = env::current_dir()?; let mise_toml = cwd.join("mise.toml"); if mise_toml.exists() { Some(mise_toml) } else { // Fall back to .mise.toml if mise.toml doesn't exist let dot_mise_toml = cwd.join(".mise.toml"); if dot_mise_toml.exists() { Some(dot_mise_toml) } else { None // Fall back to global config if no local config exists } } } else { None }; let filter = self.env_vars.unwrap(); // Handle global config case first if config_path.is_none() { let config = Config::get().await?; let env_with_sources = config.env_with_sources().await?; // env_with_sources already contains decrypted values for eva in filter { if let Some((value, _source)) = env_with_sources.get(&eva.key) { miseprintln!("{value}"); } else { bail!("Environment variable {} not found", eva.key); } } return Ok(()); } // Get the config to access directives directly let config = MiseToml::from_file(&config_path.unwrap()).unwrap_or_default(); // For local configs, check directives directly let env_entries = config.env_entries()?; for eva in filter { match env_entries.iter().find_map(|ev| match ev { EnvDirective::Val(k, v, _) if k == &eva.key => Some((v.clone(), Some(ev))), EnvDirective::Age { key: k, value: v, .. } if k == &eva.key => Some((v.clone(), Some(ev))), _ => None, }) { Some((value, directive)) => { // this does not obey strict=false, since we want to fail if the decryption fails let decrypted = Self::decrypt_value_if_needed(&eva.key, &value, directive).await?; miseprintln!("{decrypted}"); } None => bail!("Environment variable {} not found", eva.key), } } Ok(()) } async fn cur_env(&self) -> Result<Vec<Row>> { let rows = if let Some(file) = &self.file { let config = MiseToml::from_file(file).unwrap_or_default(); config .env_entries()? .into_iter() .filter_map(|ed| match ed { EnvDirective::Val(key, value, _) => Some(Row { key, value, source: display_path(file), }), EnvDirective::Age { key, value, .. } => Some(Row { key, value, source: display_path(file), }), _ => None, }) .collect() } else if self.env.is_some() { // When -E flag is used, read from the environment-specific file let filename = self.filename()?; let config = MiseToml::from_file(&filename).unwrap_or_default(); config .env_entries()? .into_iter() .filter_map(|ed| match ed { EnvDirective::Val(key, value, _) => Some(Row { key, value, source: display_path(&filename), }), EnvDirective::Age { key, value, .. } => Some(Row { key, value, source: display_path(&filename), }), _ => None, }) .collect() } else { Config::get() .await? .env_with_sources() .await? .iter() .map(|(key, (value, source))| Row { key: key.clone(), value: value.clone(), source: display_path(source), }) .collect() }; Ok(rows) } fn filename(&self) -> Result<PathBuf> { let opts = ConfigPathOptions { global: self.global, path: self.file.clone(), env: self.env.clone(), cwd: None, // Use current working directory prefer_toml: true, // mise set only works with TOML files prevent_home_local: true, // When in HOME, use global config }; resolve_target_config_path(opts) } async fn collect_age_recipients(&self) -> Result<Vec<Box<dyn age::Recipient + Send>>> { use age::Recipient; let mut recipients: Vec<Box<dyn Recipient + Send>> = Vec::new(); // Add x25519 recipients from command line for recipient_str in &self.age_recipient { if let Some(recipient) = agecrypt::parse_recipient(recipient_str)? { recipients.push(recipient); } } // Add SSH recipients from command line for ssh_arg in &self.age_ssh_recipient { let path = Path::new(ssh_arg); if path.exists() { // It's a file path recipients.push(agecrypt::load_ssh_recipient_from_path(path).await?); } else { // Try to parse as a direct SSH public key if let Some(recipient) = agecrypt::parse_recipient(ssh_arg)? { recipients.push(recipient); } } } // If no recipients were provided, use defaults if recipients.is_empty() && (self.age_recipient.is_empty() && self.age_ssh_recipient.is_empty() && self.age_key_file.is_none()) { recipients = agecrypt::load_recipients_from_defaults().await?; } // Load recipients from key file if specified if let Some(key_file) = &self.age_key_file { let key_file_recipients = agecrypt::load_recipients_from_key_file(key_file).await?; recipients.extend(key_file_recipients); } if recipients.is_empty() { bail!( "[experimental] No age recipients provided. Use --age-recipient, --age-ssh-recipient, or --age-key-file" ); } Ok(recipients) } } fn get_mise_toml(filename: &Path) -> Result<MiseToml> { let path = env::current_dir()?.join(filename); let mise_toml = if path.exists() { MiseToml::from_file(&path)? } else { MiseToml::init(&path) }; Ok(mise_toml) } #[derive(Tabled, Debug, Clone)] struct Row { key: String, value: String, source: String, } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise set NODE_ENV=production</bold> $ <bold>mise set NODE_ENV</bold> production $ <bold>mise set -E staging NODE_ENV=staging</bold> # creates or modifies mise.staging.toml $ <bold>mise set</bold> key value source NODE_ENV production ~/.config/mise/config.toml $ <bold>mise set --prompt PASSWORD</bold> Enter value for PASSWORD: [hidden input] <bold><underline>[experimental] Age Encryption:</underline></bold> $ <bold>mise set --age-encrypt API_KEY=secret</bold> $ <bold>mise set --age-encrypt --prompt API_KEY</bold> Enter value for API_KEY: [hidden input] "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/hook_env.rs
src/cli/hook_env.rs
use crate::config::{Config, Settings}; use crate::direnv::DirenvDiff; use crate::env::{__MISE_DIFF, PATH_KEY, TERM_WIDTH}; use crate::env::{join_paths, split_paths}; use crate::env_diff::{EnvDiff, EnvDiffOperation, EnvMap}; use crate::file::display_rel_path; use crate::hook_env::{PREV_SESSION, WatchFilePattern}; use crate::shell::{ShellType, get_shell}; use crate::toolset::Toolset; use crate::{env, hook_env, hooks, watch_files}; use console::truncate_str; use eyre::Result; use indexmap::IndexSet; use itertools::Itertools; use std::collections::{BTreeSet, HashSet}; use std::ops::Deref; use std::path::PathBuf; use std::{borrow::Cow, sync::Arc}; #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] #[clap(rename_all = "lowercase")] pub enum HookReason { Precmd, Chpwd, } /// [internal] called by activate hook to update env vars directory change #[derive(Debug, clap::Args)] #[clap(hide = true)] pub struct HookEnv { /// Skip early exit check #[clap(long, short)] force: bool, /// Hide warnings such as when a tool is not installed #[clap(long, short)] quiet: bool, /// Shell type to generate script for #[clap(long, short)] shell: Option<ShellType>, /// Reason for calling hook-env (e.g., "precmd", "chpwd") #[clap(long, hide = true)] reason: Option<HookReason>, /// Show "mise: <PLUGIN>@<VERSION>" message when changing directories #[clap(long, hide = true)] status: bool, } impl HookEnv { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let watch_files = config.watch_files().await?; time!("hook-env"); if !self.force && hook_env::should_exit_early(watch_files.clone(), self.reason) { trace!("should_exit_early true"); return Ok(()); } time!("should_exit_early false"); let ts = config.get_toolset().await?; let shell = get_shell(self.shell).expect("no shell provided, use `--shell=zsh`"); miseprint!("{}", hook_env::clear_old_env(&*shell))?; let (mut mise_env, env_results) = ts.final_env(&config).await?; mise_env.remove(&*PATH_KEY); self.display_status(&config, ts, &mise_env).await?; let mut diff = EnvDiff::new(&env::PRISTINE_ENV, mise_env.clone()); let mut patches = diff.to_patches(); // For fish shell, filter out PATH operations from diff patches because // fish's PATH handling conflicts with setting PATH multiple times if shell.to_string() == "fish" { patches.retain(|p| match p { EnvDiffOperation::Add(k, _) | EnvDiffOperation::Change(k, _) | EnvDiffOperation::Remove(k) => k != &*PATH_KEY, }); } let (user_paths, tool_paths) = ts.list_final_paths_split(&config, env_results).await?; // Combine paths for __MISE_DIFF tracking (all mise-managed paths) let all_paths: Vec<PathBuf> = user_paths .iter() .chain(tool_paths.iter()) .cloned() .collect(); diff.path.clone_from(&all_paths); // update __MISE_DIFF with the new paths for the next run // Get shell aliases from config let new_aliases: indexmap::IndexMap<String, String> = config .shell_aliases .iter() .map(|(k, (v, _))| (k.clone(), v.clone())) .collect(); patches.extend(self.build_path_operations(&user_paths, &tool_paths, &__MISE_DIFF.path)?); patches.push(self.build_diff_operation(&diff)?); patches.push( self.build_session_operation(&config, ts, mise_env, new_aliases.clone(), watch_files) .await?, ); // Clear the precmd run flag after running once from precmd if self.reason == Some(HookReason::Precmd) && !*env::__MISE_ZSH_PRECMD_RUN { patches.push(EnvDiffOperation::Add( "__MISE_ZSH_PRECMD_RUN".into(), "1".into(), )); } let output = hook_env::build_env_commands(&*shell, &patches); miseprint!("{output}")?; // Build and output alias commands let alias_output = hook_env::build_alias_commands(&*shell, &PREV_SESSION.aliases, &new_aliases); miseprint!("{alias_output}")?; hooks::run_all_hooks(&config, ts, &*shell).await; watch_files::execute_runs(&config, ts).await; Ok(()) } async fn display_status( &self, config: &Arc<Config>, ts: &Toolset, cur_env: &EnvMap, ) -> Result<()> { if self.status || Settings::get().status.show_tools { let prev = &PREV_SESSION.loaded_tools; let cur = ts .list_current_installed_versions(config) .into_iter() .rev() .map(|(_, tv)| format!("{}@{}", tv.short(), tv.version)) .collect::<IndexSet<_>>(); let removed = prev.difference(&cur).collect::<IndexSet<_>>(); let new = cur.difference(prev).collect::<IndexSet<_>>(); if !new.is_empty() { let status = new.into_iter().map(|t| format!("+{t}")).rev().join(" "); info!("{}", format_status(&status)); } if !removed.is_empty() { let status = removed.into_iter().map(|t| format!("-{t}")).rev().join(" "); info!("{}", format_status(&status)); } } if self.status || Settings::get().status.show_env { let mut env_diff = EnvDiff::new(&PREV_SESSION.env, cur_env.clone()).to_patches(); // TODO: this logic should be in EnvDiff let removed_keys = PREV_SESSION .env .keys() .collect::<IndexSet<_>>() .difference(&cur_env.keys().collect::<IndexSet<_>>()) .map(|k| EnvDiffOperation::Remove(k.to_string())) .collect_vec(); env_diff.extend(removed_keys); if !env_diff.is_empty() { let env_diff = env_diff.into_iter().map(patch_to_status).join(" "); info!("{}", truncate_str(&env_diff, TERM_WIDTH.max(60) - 5, "…")); } let new_paths: IndexSet<PathBuf> = config .path_dirs() .await .map(|p| p.iter().cloned().collect()) .unwrap_or_default(); let old_paths = &PREV_SESSION.config_paths; let removed_paths = old_paths.difference(&new_paths).collect::<IndexSet<_>>(); let added_paths = new_paths.difference(old_paths).collect::<IndexSet<_>>(); if !added_paths.is_empty() { let status = added_paths .iter() .map(|p| format!("+{}", display_rel_path(p))) .join(" "); info!("{}", format_status(&status)); } if !removed_paths.is_empty() { let status = removed_paths .iter() .map(|p| format!("-{}", display_rel_path(p))) .join(" "); info!("{}", format_status(&status)); } } ts.notify_if_versions_missing(config).await; crate::prepare::notify_if_stale(config); Ok(()) } /// modifies the PATH and optionally DIRENV_DIFF env var if it exists /// user_paths are paths from env._.path config that are prepended (filtered only against user manual additions) /// tool_paths are paths from tool installations that should be filtered if already in original PATH fn build_path_operations( &self, user_paths: &[PathBuf], tool_paths: &[PathBuf], to_remove: &[PathBuf], ) -> Result<Vec<EnvDiffOperation>> { let full = join_paths(&*env::PATH)?.to_string_lossy().to_string(); let current_paths: Vec<PathBuf> = split_paths(&full).collect(); let (pre, post) = match &*env::__MISE_ORIG_PATH { Some(orig_path) if !Settings::get().activate_aggressive => { let orig_paths: Vec<PathBuf> = split_paths(orig_path).collect(); let orig_set: HashSet<_> = orig_paths.iter().collect(); // Get all mise-managed paths from the previous session // to_remove contains ALL paths that mise added (tool installs, config paths, etc.) let mise_paths_set: HashSet<_> = to_remove.iter().collect(); // Find paths in current that are not in original and not mise-managed // These are genuine user additions after mise activation. let mut pre = Vec::new(); for path in &current_paths { // Skip if in original PATH if orig_set.contains(path) { continue; } // Skip if it's a mise-managed path from previous session if mise_paths_set.contains(path) { continue; } // This is a genuine user addition pre.push(path.clone()); } // Use the original PATH directly as "post" to ensure it's preserved exactly (pre, orig_paths) } _ => (vec![], current_paths), }; // Filter out tool paths that are already in the original PATH (post) or // in the pre paths (user additions). This prevents mise from claiming ownership // of paths that were in the user's original PATH before mise activation, and also // prevents duplicates when paths from previous mise activations are in the current // PATH. When a tool is deactivated, these paths will remain accessible since they're // preserved in the `post` section or `pre` section. // This fixes the issue where system tools (e.g., rustup) become unavailable // after leaving a mise project that uses the same tool. // // IMPORTANT: Only filter tool_paths against __MISE_ORIG_PATH (post). // User-configured paths are filtered separately (only against user manual additions) // to preserve user's intended ordering while avoiding duplicates. // // Use canonicalized paths for comparison to handle symlinks, relative paths, // and other path variants that refer to the same filesystem location. let post_canonical: HashSet<PathBuf> = post.iter().filter_map(|p| p.canonicalize().ok()).collect(); let pre_set: HashSet<_> = pre.iter().collect(); let pre_canonical: HashSet<PathBuf> = pre.iter().filter_map(|p| p.canonicalize().ok()).collect(); let tool_paths_filtered: Vec<PathBuf> = tool_paths .iter() .filter(|p| { // Check both the original path and its canonical form // This handles cases where the path doesn't exist yet (can't canonicalize) // or where the canonical form differs from the string representation // Filter against post (original PATH) if post.contains(p) { return false; } if let Ok(canonical) = p.canonicalize() && post_canonical.contains(&canonical) { return false; } // Also filter against pre (user additions) to avoid duplicates if pre_set.contains(p) { return false; } if let Ok(canonical) = p.canonicalize() && pre_canonical.contains(&canonical) { return false; } true }) .cloned() .collect(); // Filter user_paths against pre (user manual additions) to avoid duplicates // when users manually add paths after mise activation. // IMPORTANT: Do NOT filter against post (__MISE_ORIG_PATH) - this would break // the intended behavior where user-configured paths should take precedence // even if they already exist in the original PATH. let pre_set: HashSet<_> = pre.iter().collect(); let pre_canonical: HashSet<PathBuf> = pre.iter().filter_map(|p| p.canonicalize().ok()).collect(); let user_paths_filtered: Vec<PathBuf> = user_paths .iter() .filter(|p| { // Filter against pre only (user manual additions after mise activation) if pre_set.contains(p) { return false; } if let Ok(canonical) = p.canonicalize() && pre_canonical.contains(&canonical) { return false; } true }) .cloned() .collect(); // Combine paths in the correct order: // pre (user shell additions) -> user_paths (from config, filtered against pre) -> tool_paths (filtered) -> post (original PATH) let new_path = join_paths( pre.iter() .chain(user_paths_filtered.iter()) .chain(tool_paths_filtered.iter()) .chain(post.iter()), )? .to_string_lossy() .into_owned(); let mut ops = vec![EnvDiffOperation::Add(PATH_KEY.to_string(), new_path)]; // For DIRENV_DIFF, we need to include both filtered user_paths and filtered tool_paths let all_installs: Vec<PathBuf> = user_paths_filtered .iter() .chain(tool_paths_filtered.iter()) .cloned() .collect(); if let Some(input) = env::DIRENV_DIFF.deref() { match self.update_direnv_diff(input, &all_installs, to_remove) { Ok(Some(op)) => { ops.push(op); } Err(err) => warn!("failed to update DIRENV_DIFF: {:#}", err), _ => {} } } Ok(ops) } /// inserts install path to DIRENV_DIFF both for old and new /// this makes direnv think that these paths were added before it ran /// that way direnv will not remove the path when it runs the next time fn update_direnv_diff( &self, input: &str, installs: &[PathBuf], to_remove: &[PathBuf], ) -> Result<Option<EnvDiffOperation>> { let mut diff = DirenvDiff::parse(input)?; if diff.new_path().is_empty() { return Ok(None); } for path in to_remove { diff.remove_path_from_old_and_new(path)?; } for install in installs { diff.add_path_to_old_and_new(install)?; } Ok(Some(EnvDiffOperation::Change( "DIRENV_DIFF".into(), diff.dump()?, ))) } fn build_diff_operation(&self, diff: &EnvDiff) -> Result<EnvDiffOperation> { Ok(EnvDiffOperation::Add( "__MISE_DIFF".into(), diff.serialize()?, )) } async fn build_session_operation( &self, config: &Arc<Config>, ts: &Toolset, env: EnvMap, aliases: indexmap::IndexMap<String, String>, watch_files: BTreeSet<WatchFilePattern>, ) -> Result<EnvDiffOperation> { let loaded_tools = if self.status || Settings::get().status.show_tools { ts.list_current_versions() .into_iter() .map(|(_, tv)| format!("{}@{}", tv.short(), tv.version)) .collect() } else { Default::default() }; let session = hook_env::build_session(config, env, aliases, loaded_tools, watch_files).await?; Ok(EnvDiffOperation::Add( "__MISE_SESSION".into(), hook_env::serialize(&session)?, )) } } fn patch_to_status(patch: EnvDiffOperation) -> String { match patch { EnvDiffOperation::Add(k, _) => format!("+{k}"), EnvDiffOperation::Change(k, _) => format!("~{k}"), EnvDiffOperation::Remove(k) => format!("-{k}"), } } fn format_status(status: &str) -> Cow<'_, str> { if Settings::get().status.truncate { truncate_str(status, TERM_WIDTH.max(60) - 5, "…") } else { status.into() } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/fmt.rs
src/cli/fmt.rs
use crate::Result; use crate::config::ALL_TOML_CONFIG_FILES; use crate::{config, dirs, file}; use eyre::bail; use std::io::{self, Read, Write}; use taplo::formatter::Options; /// Formats mise.toml /// /// Sorts keys and cleans up whitespace in mise.toml #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Fmt { /// Format all files from the current directory #[clap(short, long)] pub all: bool, /// Check if the configs are formatted, no formatting is done #[clap(short, long)] pub check: bool, /// Read config from stdin and write its formatted version into /// stdout #[clap(short, long)] pub stdin: bool, } impl Fmt { pub fn run(self) -> eyre::Result<()> { if self.stdin { let mut toml = String::new(); io::stdin().read_to_string(&mut toml)?; let toml = sort(toml)?; let toml = format(toml)?; let mut stdout = io::stdout(); write!(stdout, "{toml}")?; return Ok(()); } let cwd = dirs::CWD.clone().unwrap_or_default(); let configs = if self.all { ALL_TOML_CONFIG_FILES.clone() } else { config::config_files_in_dir(&cwd) }; if configs.is_empty() { bail!("No config file found in current directory"); } let mut errors = Vec::new(); for p in configs { if !p .file_name() .is_some_and(|f| f.to_string_lossy().ends_with("toml")) { continue; } let source = file::read_to_string(&p)?; let toml = source.clone(); let toml = sort(toml)?; let toml = format(toml)?; if self.check { if source != toml { errors.push(p.display().to_string()); } continue; } file::write(&p, &toml)?; } if !errors.is_empty() { bail!( "Following config files are not properly formatted:\n{}", errors.join("\n") ); } Ok(()) } } fn sort(toml: String) -> Result<String> { let mut doc: toml_edit::DocumentMut = toml.parse()?; let order = |k: String| match k.as_str() { "min_version" => 0, "env_file" => 1, "env_path" => 2, "_" => 3, "env" => 4, "vars" => 5, "hooks" => 6, "watch_files" => 7, "tools" => 8, "tasks" => 10, "task_config" => 11, "redactions" => 12, "alias" => 13, "plugins" => 14, "settings" => 15, _ => 9, }; doc.sort_values_by(|a, _, b, _| order(a.to_string()).cmp(&order(b.to_string()))); Ok(doc.to_string()) } fn format(toml: String) -> Result<String> { let tmp = taplo::formatter::format( &toml, Options { align_comments: true, align_entries: false, align_single_comments: true, allowed_blank_lines: 2, array_auto_collapse: true, array_auto_expand: true, array_trailing_comma: true, column_width: 80, compact_arrays: true, compact_entries: false, compact_inline_tables: false, crlf: false, indent_entries: false, indent_string: " ".to_string(), indent_tables: false, inline_table_expand: true, reorder_arrays: false, reorder_keys: false, reorder_inline_tables: false, trailing_newline: true, }, ); Ok(tmp) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise fmt</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/usage.rs
src/cli/usage.rs
use crate::cli::Cli; use clap::CommandFactory; use clap::builder::Resettable; use eyre::Result; /// Generate a usage CLI spec /// /// See https://usage.jdx.dev for more information on this specification. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, hide = true)] pub struct Usage {} impl Usage { pub fn run(self) -> Result<()> { let cli = Cli::command().version(Resettable::Reset); let mut spec: usage::Spec = cli.into(); // Enable "naked" task completions: `mise foo` completes like `mise run foo` spec.default_subcommand = Some("run".to_string()); let run = spec.cmd.subcommands.get_mut("run").unwrap(); run.args = vec![]; run.mounts.push(usage::SpecMount { run: "mise tasks --usage".to_string(), }); // Enable completions after ::: separator for multi-task invocations run.restart_token = Some(":::".to_string()); let tasks = spec.cmd.subcommands.get_mut("tasks").unwrap(); let tasks_run = tasks.subcommands.get_mut("run").unwrap(); tasks_run.mounts.push(usage::SpecMount { run: "mise tasks --usage".to_string(), }); tasks_run.restart_token = Some(":::".to_string()); let min_version = r#"min_usage_version "2.11""#; let extra = include_str!("../assets/mise-extra.usage.kdl").trim(); println!("{min_version}\n{}\n{extra}", spec.to_string().trim()); Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/render_help.rs
src/cli/render_help.rs
use crate::cli::Cli; use crate::file; use clap::CommandFactory; use eyre::Result; use indoc::formatdoc; use itertools::Itertools; /// internal command to generate markdown from help #[derive(Debug, clap::Args)] #[clap(hide = true)] pub struct RenderHelp {} impl RenderHelp { pub fn run(self) -> Result<()> { xx::file::mkdirp("docs/.vitepress")?; file::write("docs/.vitepress/cli_commands.ts", render_command_ts())?; if cfg!(windows) { cmd!("prettier.cmd", "--write", "docs/.vitepress/cli_commands.ts").run()?; } else { cmd!("prettier", "--write", "docs/.vitepress/cli_commands.ts").run()?; } Ok(()) } } fn render_command_ts() -> String { let mut doc = String::new(); doc.push_str(&formatdoc! {r#" // This file is generated by `mise render-help` // Do not edit this file directly export type Command = {{ hide: boolean, subcommands?: {{ [key: string]: Command, }}, }}; "#}); doc.push_str("export const commands: { [key: string]: Command } = {\n"); let mut cli = Cli::command() .term_width(80) .max_term_width(80) .disable_help_subcommand(true) .disable_help_flag(true); for command in cli .get_subcommands_mut() .sorted_by_cached_key(|c| c.get_name().to_string()) { match command.has_subcommands() { true => { let name = command.get_name().to_string(); doc.push_str(&format!( " \"{}\": {{\n hide: {},\n subcommands: {{\n", name, command.is_hide_set() )); for subcommand in command.get_subcommands_mut() { let output = format!( " \"{}\": {{\n hide: {},\n }},\n", subcommand.get_name(), subcommand.is_hide_set() ); doc.push_str(&output); } doc.push_str(" },\n },\n"); } false => { let output = format!( " \"{}\": {{\n hide: {},\n }},\n", command.get_name(), command.is_hide_set() ); doc.push_str(&output); } } } doc.push_str("};\n"); doc }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/ls.rs
src/cli/tasks/ls.rs
use std::sync::Arc; use crate::config::Config; use crate::file::display_rel_path; use crate::task::Task; use crate::ui::table::MiseTable; use comfy_table::{Attribute, Cell, Row}; use eyre::Result; use itertools::Itertools; use serde_json::json; /// List available tasks to execute /// These may be included from the config file or from the project's .mise/tasks directory /// mise will merge all tasks from all parent directories into this list. /// /// So if you have global tasks in `~/.config/mise/tasks/*` and project-specific tasks in /// ~/myproject/.mise/tasks/*, then they'll both be available but the project-specific /// tasks will override the global ones if they have the same name. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksLs { /// Only show global tasks #[clap( short, long, global = true, overrides_with = "local", verbatim_doc_comment )] pub global: bool, /// Output in JSON format #[clap(short = 'J', global = true, long, verbatim_doc_comment)] pub json: bool, /// Only show non-global tasks #[clap( short, long, global = true, overrides_with = "global", verbatim_doc_comment )] pub local: bool, /// Show all columns #[clap(short = 'x', long, global = true, verbatim_doc_comment)] pub extended: bool, /// Load all tasks from the entire monorepo, including sibling directories. /// By default, only tasks from the current directory hierarchy are loaded. #[clap(long, global = true, verbatim_doc_comment)] pub all: bool, /// Display tasks for usage completion #[clap(long, hide = true)] pub complete: bool, /// Show hidden tasks #[clap(long, global = true, verbatim_doc_comment)] pub hidden: bool, /// Do not print table header #[clap(long, alias = "no-headers", global = true, verbatim_doc_comment)] pub no_header: bool, /// Sort by column. Default is name. #[clap(long, global = true, value_name = "COLUMN", verbatim_doc_comment)] pub sort: Option<SortColumn>, /// Sort order. Default is asc. #[clap(long, global = true, verbatim_doc_comment)] pub sort_order: Option<SortOrder>, #[clap(long, global = true, hide = true)] pub usage: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum SortColumn { Name, Alias, Description, Source, } #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum SortOrder { Asc, Desc, } impl TasksLs { pub async fn run(self) -> Result<()> { use crate::task::TaskLoadContext; let config = Config::get().await?; // Create context based on --all flag or when generating completions/usage specs // to ensure monorepo tasks (e.g., `//app:task`) are available for autocomplete. let ctx = if self.all || self.complete || self.usage { Some(TaskLoadContext::all()) } else { None }; let tasks = config .tasks_with_context(ctx.as_ref()) .await? .values() .filter(|t| self.hidden || !t.hide) .filter(|t| !self.local || !t.global) .filter(|t| !self.global || t.global) .cloned() .sorted_by(|a, b| self.sort(a, b)) .collect::<Vec<Task>>(); if self.complete { return self.complete(tasks); } else if self.usage { self.display_usage(&config, tasks).await?; } else if self.json { self.display_json(tasks)?; } else { self.display(tasks)?; } Ok(()) } fn complete(&self, tasks: Vec<Task>) -> Result<()> { for t in tasks { let name = t.display_name.replace(":", "\\:"); let description = t.description.replace(":", "\\:"); println!("{name}:{description}",); } Ok(()) } fn display(&self, tasks: Vec<Task>) -> Result<()> { let mut table = MiseTable::new( self.no_header, if self.extended { &["Name", "Aliases", "Source", "Description"] } else { &["Name", "Description"] }, ); for task in tasks { table.add_row(self.task_to_row(&task)); } table.print() } async fn display_usage(&self, config: &Arc<Config>, tasks: Vec<Task>) -> Result<()> { let mut usage = usage::Spec::default(); for task in tasks { let mut task_spec = task.parse_usage_spec_for_display(config).await?; for (name, complete) in task_spec.complete { task_spec.cmd.complete.insert(name, complete); } usage .cmd .subcommands .insert(task.display_name.clone(), task_spec.cmd); } miseprintln!("{}", usage.to_string()); Ok(()) } fn display_json(&self, tasks: Vec<Task>) -> Result<()> { let array_items = tasks .into_iter() .map(|task| { json!({ "name": task.display_name, "aliases": task.aliases, "description": task.description, "source": task.config_source, "depends": task.depends, "depends_post": task.depends_post, "wait_for": task.wait_for, "env": task.env.0.iter().map(|d| d.to_string()).collect::<Vec<_>>(), "dir": task.dir, "hide": task.hide, "global": task.global, "raw": task.raw, "sources": task.sources, "outputs": task.outputs, "shell": task.shell, "quiet": task.quiet, "silent": task.silent, "tools": task.tools, "usage": task.usage, "timeout": task.timeout, "run": task.run_script_strings(), "args": task.args, "file": task.file }) }) .collect::<serde_json::Value>(); miseprintln!("{}", serde_json::to_string_pretty(&array_items)?); Ok(()) } fn sort(&self, a: &Task, b: &Task) -> std::cmp::Ordering { let cmp = match self.sort.unwrap_or(SortColumn::Name) { SortColumn::Alias => a.aliases.join(", ").cmp(&b.aliases.join(", ")), SortColumn::Description => a.description.cmp(&b.description), SortColumn::Source => a.config_source.cmp(&b.config_source), _ => a.name.cmp(&b.name), }; match self.sort_order.unwrap_or(SortOrder::Asc) { SortOrder::Desc => cmp.reverse(), _ => cmp, } } fn task_to_row(&self, task: &Task) -> Row { let mut row = vec![Cell::new(&task.display_name).add_attribute(Attribute::Bold)]; if self.extended { row.push(Cell::new(task.aliases.join(", "))); row.push(Cell::new(display_rel_path(&task.config_source))); } row.push(Cell::new(&task.description).add_attribute(Attribute::Dim)); row.into() } } // TODO: fill this out static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tasks ls</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/info.rs
src/cli/tasks/info.rs
use std::sync::Arc; use eyre::{Result, bail}; use itertools::Itertools; use serde_json::json; use crate::config::Config; use crate::file::display_path; use crate::task::Task; use crate::ui::info; /// Get information about a task #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksInfo { /// Name of the task to get information about #[clap(verbatim_doc_comment)] pub task: String, /// Output in JSON format #[clap(short = 'J', long, verbatim_doc_comment)] pub json: bool, } impl TasksInfo { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let task_name = crate::task::expand_colon_task_syntax(&self.task, &config)?; let tasks = if task_name.starts_with("//") { let ctx = crate::task::TaskLoadContext::from_pattern(&task_name); config.tasks_with_context(Some(&ctx)).await? } else { config.tasks().await? }; let tasks_with_aliases = crate::task::build_task_ref_map(tasks.iter()); use crate::task::GetMatchingExt; let matching = tasks_with_aliases.get_matching(&task_name).ok(); let task = matching.and_then(|m| m.first().cloned().cloned()); if let Some(task) = task { if self.json { self.display_json(&config, task).await?; } else { self.display(&config, task).await?; } } else { bail!( "Task not found: {}, use `mise tasks ls --all --hidden` to list all tasks", self.task ); } Ok(()) } async fn display(&self, config: &Arc<Config>, task: &Task) -> Result<()> { info::inline_section("Task", &task.display_name)?; if !task.aliases.is_empty() { info::inline_section("Aliases", task.aliases.join(", "))?; } info::inline_section("Description", &task.description)?; info::inline_section("Source", display_path(&task.config_source))?; let mut properties = vec![]; if task.hide { properties.push("hide"); } if task.raw { properties.push("raw"); } if !properties.is_empty() { info::inline_section("Properties", properties.join(", "))?; } if !task.depends.is_empty() { info::inline_section("Depends on", task.depends.iter().join(", "))?; } if !task.depends_post.is_empty() { info::inline_section("Depends post", task.depends_post.iter().join(", "))?; } if let Some(dir) = &task.dir { info::inline_section("Directory", display_path(dir))?; } if !task.sources.is_empty() { info::inline_section("Sources", task.sources.join(", "))?; } let outputs = task.outputs.paths(task); if !outputs.is_empty() { info::inline_section("Outputs", outputs.join(", "))?; } if let Some(file) = &task.file { info::inline_section("File", display_path(file))?; } let run = task.run(); if !run.is_empty() { info::section("Run", run.iter().map(|e| e.to_string()).join("\n"))?; } if !task.env.is_empty() { let env_display = task .env .0 .iter() .map(|directive| directive.to_string()) .collect::<Vec<_>>() .join("\n"); info::section("Environment Variables", env_display)?; } let spec = task.parse_usage_spec_for_display(config).await?; if !spec.is_empty() { info::section("Usage Spec", &spec)?; } Ok(()) } async fn display_json(&self, config: &Arc<Config>, task: &Task) -> Result<()> { let spec = task.parse_usage_spec_for_display(config).await?; let o = json!({ "name": task.display_name, "aliases": task.aliases, "description": task.description, "source": task.config_source, "depends": task.depends, "depends_post": task.depends_post, "wait_for": task.wait_for, "env": task.env.0.iter().map(|d| d.to_string()).collect::<Vec<_>>(), "dir": task.dir, "hide": task.hide, "raw": task.raw, "sources": task.sources, "outputs": task.outputs, "shell": task.shell, "quiet": task.quiet, "silent": task.silent, "tools": task.tools, "run": task.run(), "file": task.file, "usage_spec": spec, }); miseprintln!("{}", serde_json::to_string_pretty(&o)?); Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tasks info</bold> Name: test Aliases: t Description: Test the application Source: ~/src/myproj/mise.toml $ <bold>mise tasks info test --json</bold> { "name": "test", "aliases": "t", "description": "Test the application", "source": "~/src/myproj/mise.toml", "depends": [], "env": {}, "dir": null, "hide": false, "raw": false, "sources": [], "outputs": [], "run": [ "echo \"testing!\"" ], "file": null, "usage_spec": {} } "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/deps.rs
src/cli/tasks/deps.rs
use std::sync::Arc; use crate::config::Config; use crate::task::{Deps, Task}; use crate::ui::style::{self}; use crate::ui::tree::print_tree; use console::style; use eyre::{Result, eyre}; use itertools::Itertools; use petgraph::dot::Dot; /// Display a tree visualization of a dependency graph #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksDeps { /// Tasks to show dependencies for /// Can specify multiple tasks by separating with spaces /// e.g.: mise tasks deps lint test check #[clap(verbatim_doc_comment)] pub tasks: Option<Vec<String>>, /// Display dependencies in DOT format #[clap(long, alias = "dot", verbatim_doc_comment)] pub dot: bool, /// Show hidden tasks #[clap(long, verbatim_doc_comment)] pub hidden: bool, } impl TasksDeps { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let tasks = if self.tasks.is_none() { self.get_all_tasks(&config).await? } else { self.get_task_lists(&config).await? }; if self.dot { self.print_deps_dot(&config, tasks).await?; } else { self.print_deps_tree(&config, tasks).await?; } Ok(()) } async fn get_all_tasks(&self, config: &Arc<Config>) -> Result<Vec<Task>> { Ok(config .tasks() .await? .values() .filter(|t| self.hidden || !t.hide) .cloned() .collect()) } async fn get_task_lists(&self, config: &Arc<Config>) -> Result<Vec<Task>> { let all_tasks = config.tasks().await?; let mut tasks = vec![]; for task in self.tasks.as_ref().unwrap_or(&vec![]) { match all_tasks .get(task) .or_else(|| all_tasks.values().find(|t| &t.display_name == task)) .cloned() { Some(task) => { tasks.push(task); } None => { return Err(self.err_no_task(config, task).await); } } } Ok(tasks) } /// /// Print dependencies as a tree /// /// Example: /// ``` /// task1 /// ├─ task2 /// │ └─ task3 /// └─ task4 /// task5 /// ``` /// async fn print_deps_tree(&self, config: &Arc<Config>, tasks: Vec<Task>) -> Result<()> { let deps = Deps::new(config, tasks.clone()).await?; // filter out nodes that are not selected let start_indexes = deps.graph.node_indices().filter(|&idx| { let task = &deps.graph[idx]; tasks.iter().any(|t| t.name == task.name) }); // iterate over selected graph nodes and print tree for idx in start_indexes { print_tree(&(&deps.graph, idx))?; } Ok(()) } /// /// Print dependencies in DOT format /// /// Example: /// ``` /// digraph { /// 1 [label = "task1"] /// 2 [label = "task2"] /// 3 [label = "task3"] /// 4 [label = "task4"] /// 5 [label = "task5"] /// 1 -> 2 [ ] /// 2 -> 3 [ ] /// 1 -> 4 [ ] /// } /// ``` // async fn print_deps_dot(&self, config: &Arc<Config>, tasks: Vec<Task>) -> Result<()> { let deps = Deps::new(config, tasks).await?; miseprintln!( "{:?}", Dot::with_attr_getters( &deps.graph, &[ petgraph::dot::Config::NodeNoLabel, petgraph::dot::Config::EdgeNoLabel ], &|_, _| String::new(), &|_, nr| format!("label = \"{}\"", nr.1.name), ), ); Ok(()) } async fn err_no_task(&self, config: &Arc<Config>, t: &str) -> eyre::Report { let tasks = config .tasks() .await .map(|t| { t.values() .map(|v| v.display_name.clone()) .collect::<Vec<_>>() }) .unwrap_or_default(); let task_names = tasks.into_iter().map(style::ecyan).join(", "); let t = style(&t).yellow().for_stderr(); eyre!("no tasks named `{t}` found. Available tasks: {task_names}") } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Show dependencies for all tasks $ <bold>mise tasks deps</bold> # Show dependencies for the "lint", "test" and "check" tasks $ <bold>mise tasks deps lint test check</bold> # Show dependencies in DOT format $ <bold>mise tasks deps --dot</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/mod.rs
src/cli/tasks/mod.rs
use clap::Subcommand; use eyre::Result; use crate::cli::run; mod add; mod deps; mod edit; mod info; mod ls; mod validate; /// Manage tasks #[derive(clap::Args)] #[clap(visible_alias = "t", alias = "task", verbatim_doc_comment)] pub struct Tasks { #[clap(subcommand)] command: Option<Commands>, /// Task name to get info of task: Option<String>, #[clap(flatten)] ls: ls::TasksLs, } #[derive(Subcommand)] enum Commands { Add(Box<add::TasksAdd>), Deps(deps::TasksDeps), Edit(edit::TasksEdit), Info(info::TasksInfo), Ls(ls::TasksLs), Run(Box<run::Run>), Validate(validate::TasksValidate), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Add(cmd) => (*cmd).run().await, Self::Deps(cmd) => cmd.run().await, Self::Edit(cmd) => cmd.run().await, Self::Info(cmd) => cmd.run().await, Self::Ls(cmd) => cmd.run().await, Self::Run(cmd) => (*cmd).run().await, Self::Validate(cmd) => cmd.run().await, } } } impl Tasks { pub async fn run(self) -> Result<()> { let cmd = self .command .or(self.task.map(|t| { Commands::Info(info::TasksInfo { task: t, json: self.ls.json, }) })) .unwrap_or(Commands::Ls(self.ls)); cmd.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/edit.rs
src/cli/tasks/edit.rs
use crate::config::Config; use crate::task::Task; use crate::{dirs, env, file}; use eyre::Result; use indoc::formatdoc; use std::path::MAIN_SEPARATOR_STR; /// Edit a task with $EDITOR /// /// The task will be created as a standalone script if it does not already exist. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksEdit { /// Task to edit #[clap()] task: String, /// Display the path to the task instead of editing it #[clap(long, short, verbatim_doc_comment)] path: bool, } impl TasksEdit { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let cwd = dirs::CWD.clone().unwrap_or_default(); let project_root = config.project_root.clone().unwrap_or(cwd); let path = Task::task_dir() .await .join(self.task.replace(':', MAIN_SEPARATOR_STR)); let task = if let Some(task) = config.tasks_with_aliases().await?.get(&self.task).cloned() { task } else { Task::from_path(&config, &path, path.parent().unwrap(), &project_root) .await .or_else(|_| Task::new(&path, path.parent().unwrap(), &project_root))? }; let file = &task.config_source; if !file.exists() { file::create_dir_all(file.parent().unwrap())?; file::write(file, default_task())?; file::make_executable(file)?; } if self.path { miseprintln!("{}", file.display()); } else { cmd!(&*env::EDITOR, &file).run()?; } Ok(()) } } fn default_task() -> String { formatdoc!( r#"#!/usr/bin/env bash set -euxo pipefail "# ) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tasks edit build</bold> $ <bold>mise tasks edit test</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/add.rs
src/cli/tasks/add.rs
use crate::config::config_file; use crate::task::Task; use crate::{config, file}; use eyre::Result; use std::path::MAIN_SEPARATOR_STR; use toml_edit::Item; /// Create a new task #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksAdd { /// Tasks name to add #[clap()] task: String, #[clap(last = true)] run: Vec<String>, /// Other names for the task #[clap(long, short)] alias: Vec<String>, /// Add dependencies to the task #[clap(long, short)] depends: Vec<String>, /// Run the task in a specific directory #[clap(long, short = 'D')] dir: Option<String>, /// Create a file task instead of a toml task #[clap(long, short)] file: bool, /// Hide the task from `mise tasks` and completions #[clap(long, short = 'H')] hide: bool, /// Do not print the command before running #[clap(long, short)] quiet: bool, /// Directly connect stdin/stdout/stderr #[clap(long, short)] raw: bool, /// Glob patterns of files this task uses as input #[clap(long, short)] sources: Vec<String>, /// Wait for these tasks to complete if they are to run #[clap(long, short)] wait_for: Vec<String>, /// Dependencies to run after the task runs #[clap(long)] depends_post: Vec<String>, /// Description of the task #[clap(long)] description: Option<String>, /// Glob patterns of files this task creates, to skip if they are not modified #[clap(long)] outputs: Vec<String>, /// Command to run on windows #[clap(long)] run_windows: Option<String>, /// Run the task in a specific shell #[clap(long)] shell: Option<String>, /// Do not print the command or its output #[clap(long)] silent: bool, // TODO // env: Vec<String>, // tools: Vec<String>, } impl TasksAdd { pub async fn run(self) -> Result<()> { if self.file { let mut path = Task::task_dir() .await .join(self.task.replace(':', MAIN_SEPARATOR_STR)); if path.is_dir() { path = path.join("_default"); } let mut lines = vec![format!( "#!/usr/bin/env {}", self.shell.clone().unwrap_or("bash".into()) )]; if !self.depends.is_empty() { lines.push("#MISE depends=[\"".to_string() + &self.depends.join("\", \"") + "\"]"); } if !self.depends_post.is_empty() { lines.push( "#MISE depends_post=[\"".to_string() + &self.depends_post.join("\", \"") + "\"]", ); } if !self.wait_for.is_empty() { lines .push("#MISE wait_for=[\"".to_string() + &self.wait_for.join("\", \"") + "\"]"); } if !self.alias.is_empty() { lines.push("#MISE alias=[\"".to_string() + &self.alias.join("\", \"") + "\"]"); } if let Some(description) = &self.description { lines.push("#MISE description=\"".to_string() + description + "\""); } if let Some(dir) = &self.dir { lines.push("#MISE dir=".to_string() + dir); } if self.hide { lines.push("#MISE hide=true".to_string()); } if self.raw { lines.push("#MISE raw=true".to_string()); } if !self.sources.is_empty() { lines.push("#MISE sources=[\"".to_string() + &self.sources.join("\", \"") + "\"]"); } if !self.outputs.is_empty() { lines.push("#MISE outputs=[\"".to_string() + &self.outputs.join("\", \"") + "\"]"); } if self.quiet { lines.push("#MISE quiet=true".to_string()); } if self.silent { lines.push("#MISE silent=true".to_string()); } lines.push("set -euxo pipefail".into()); lines.push("".into()); if !self.run.is_empty() { lines.push(self.run.join(" ")); lines.push("".into()); } file::create_dir_all(path.parent().unwrap())?; file::write(&path, lines.join("\n"))?; file::make_executable(&path)?; } else { let path = config::local_toml_config_path(); let mut doc: toml_edit::DocumentMut = file::read_to_string(&path).unwrap_or_default().parse()?; let tasks = doc .entry("tasks") .or_insert_with(|| { let mut table = toml_edit::Table::new(); table.set_implicit(true); Item::Table(table) }) .as_table_mut() .unwrap(); let mut task = toml_edit::Table::new(); if !self.depends.is_empty() { let mut depends = toml_edit::Array::new(); for dep in &self.depends { depends.push(dep); } task.insert("depends", Item::Value(depends.into())); } if !self.depends_post.is_empty() { let mut depends_post = toml_edit::Array::new(); for dep in &self.depends_post { depends_post.push(dep); } task.insert("depends_post", Item::Value(depends_post.into())); } if !self.wait_for.is_empty() { let mut wait_for = toml_edit::Array::new(); for dep in &self.wait_for { wait_for.push(dep); } task.insert("wait_for", Item::Value(wait_for.into())); } if let Some(description) = &self.description { task.insert("description", description.clone().into()); } if !self.alias.is_empty() { let mut alias = toml_edit::Array::new(); for a in &self.alias { alias.push(a); } task.insert("alias", Item::Value(alias.into())); } if let Some(dir) = &self.dir { task.insert("dir", dir.clone().into()); } if self.hide { task.insert("hide", true.into()); } if self.raw { task.insert("raw", true.into()); } if !self.sources.is_empty() { let mut sources = toml_edit::Array::new(); for source in &self.sources { sources.push(source); } task.insert("sources", Item::Value(sources.into())); } if !self.outputs.is_empty() { let mut outputs = toml_edit::Array::new(); for output in &self.outputs { outputs.push(output); } task.insert("outputs", Item::Value(outputs.into())); } if let Some(shell) = &self.shell { task.insert("shell", shell.clone().into()); } if self.quiet { task.insert("quiet", true.into()); } if self.silent { task.insert("silent", true.into()); } if !self.run.is_empty() { task.insert("run", shell_words::join(&self.run).into()); } tasks.insert(&self.task, Item::Table(task)); file::write(&path, doc.to_string())?; config_file::trust(&config_file::config_trust_root(&path))?; } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tasks add pre-commit --depends "test" --depends "render" -- echo pre-commit</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tasks/validate.rs
src/cli/tasks/validate.rs
use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use std::sync::Arc; use crate::config::Config; use crate::duration; use crate::file; use crate::task::Task; use crate::ui::style; use console::style as console_style; use eyre::{Result, eyre}; use indexmap::IndexMap; use itertools::Itertools; use serde::Serialize; /// Validate tasks for common errors and issues #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TasksValidate { /// Tasks to validate /// If not specified, validates all tasks #[clap(verbatim_doc_comment)] pub tasks: Option<Vec<String>>, /// Only show errors (skip warnings) #[clap(long, verbatim_doc_comment)] pub errors_only: bool, /// Output validation results in JSON format #[clap(long, verbatim_doc_comment)] pub json: bool, } #[derive(Debug, Clone, Serialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] enum Severity { Error, Warning, } #[derive(Debug, Clone, Serialize)] struct ValidationIssue { task: String, severity: Severity, category: String, message: String, #[serde(skip_serializing_if = "Option::is_none")] details: Option<String>, } #[derive(Debug, Serialize)] struct ValidationResults { tasks_validated: usize, errors: usize, warnings: usize, issues: Vec<ValidationIssue>, } impl TasksValidate { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let all_tasks = config.tasks().await?; // Filter tasks to validate let tasks = if let Some(ref task_names) = self.tasks { self.get_specific_tasks(&all_tasks, task_names).await? } else { self.get_all_tasks(&all_tasks) }; // Run validation let mut issues = Vec::new(); for task in &tasks { issues.extend(self.validate_task(task, &all_tasks, &config).await); } // Filter by severity if needed if self.errors_only { issues.retain(|i| i.severity == Severity::Error); } let results = ValidationResults { tasks_validated: tasks.len(), errors: issues .iter() .filter(|i| i.severity == Severity::Error) .count(), warnings: issues .iter() .filter(|i| i.severity == Severity::Warning) .count(), issues, }; // Output results if self.json { self.output_json(&results)?; } else { self.output_human(&results)?; } // Exit with error if there are errors if results.errors > 0 { return Err(eyre!("Validation failed with {} error(s)", results.errors)); } Ok(()) } fn get_all_tasks(&self, all_tasks: &BTreeMap<String, Task>) -> Vec<Task> { all_tasks.values().cloned().collect() } async fn get_specific_tasks( &self, all_tasks: &BTreeMap<String, Task>, task_names: &[String], ) -> Result<Vec<Task>> { let mut tasks = Vec::new(); for name in task_names { // Check if task exists by name, display_name, or alias match all_tasks .get(name) .or_else(|| all_tasks.values().find(|t| &t.display_name == name)) .or_else(|| { all_tasks .values() .find(|t| t.aliases.contains(&name.to_string())) }) .cloned() { Some(task) => tasks.push(task), None => { return Err(eyre!( "Task '{}' not found. Available tasks: {}", name, all_tasks.keys().map(style::ecyan).join(", ") )); } } } Ok(tasks) } async fn validate_task( &self, task: &Task, all_tasks: &BTreeMap<String, Task>, config: &Arc<Config>, ) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // 1. Validate circular dependencies issues.extend(self.validate_circular_dependencies(task, all_tasks)); // 2. Validate missing task references issues.extend(self.validate_missing_references(task, all_tasks)); // 3. Validate usage spec parsing issues.extend(self.validate_usage_spec(task, config).await); // 4. Validate timeout format issues.extend(self.validate_timeout(task)); // 5. Validate alias conflicts issues.extend(self.validate_aliases(task, all_tasks)); // 6. Validate file existence issues.extend(self.validate_file_existence(task)); // 7. Validate directory template issues.extend(self.validate_directory(task, config).await); // 8. Validate shell command issues.extend(self.validate_shell(task)); // 9. Validate source globs issues.extend(self.validate_source_patterns(task)); // 10. Validate output patterns issues.extend(self.validate_output_patterns(task)); // 11. Validate run entries issues.extend(self.validate_run_entries(task, all_tasks)); issues } fn validate_circular_dependencies( &self, task: &Task, all_tasks: &BTreeMap<String, Task>, ) -> Vec<ValidationIssue> { let mut issues = Vec::new(); match task.all_depends(all_tasks) { Ok(_) => {} Err(e) => { let err_msg = e.to_string(); if err_msg.contains("circular dependency") { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "circular-dependency".to_string(), message: "Circular dependency detected".to_string(), details: Some(err_msg), }); } } } issues } /// Check if a task exists by name, display_name, or alias fn task_exists(all_tasks: &BTreeMap<String, Task>, task_name: &str) -> bool { all_tasks.contains_key(task_name) || all_tasks.values().any(|t| t.display_name == task_name) || all_tasks .values() .any(|t| t.aliases.contains(&task_name.to_string())) } fn validate_missing_references( &self, task: &Task, all_tasks: &BTreeMap<String, Task>, ) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // Check all dependency types let all_deps = task .depends .iter() .map(|d| ("depends", &d.task)) .chain(task.depends_post.iter().map(|d| ("depends_post", &d.task))) .chain(task.wait_for.iter().map(|d| ("wait_for", &d.task))); for (dep_type, dep_name) in all_deps { // Skip pattern wildcards for now (they're resolved at runtime) if dep_name.contains('*') || dep_name.contains('?') { continue; } // Check if task exists if !Self::task_exists(all_tasks, dep_name) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "missing-dependency".to_string(), message: format!("Dependency '{}' not found", dep_name), details: Some(format!( "Referenced in '{}' but no matching task exists", dep_type )), }); } } issues } async fn validate_usage_spec(&self, task: &Task, config: &Arc<Config>) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // Try to parse the usage spec match task.parse_usage_spec_for_display(config).await { Ok(_spec) => { // Successfully parsed } Err(e) => { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "usage-parse-error".to_string(), message: "Failed to parse usage specification".to_string(), details: Some(format!("{:#}", e)), }); } } // If task has explicit usage field, validate it's not empty if !task.usage.is_empty() { // Check if usage contains common USAGE directive errors if task.usage.contains("#USAGE") || task.usage.contains("# USAGE") { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "usage-directive".to_string(), message: "Usage field contains directive markers".to_string(), details: Some( "The 'usage' field should contain the spec directly, not #USAGE directives" .to_string(), ), }); } } issues } fn validate_timeout(&self, task: &Task) -> Vec<ValidationIssue> { let mut issues = Vec::new(); if let Some(ref timeout) = task.timeout { // Try to parse as duration if let Err(e) = duration::parse_duration(timeout) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "invalid-timeout".to_string(), message: format!("Invalid timeout format: '{}'", timeout), details: Some(format!("Parse error: {}", e)), }); } } issues } fn validate_aliases( &self, task: &Task, all_tasks: &BTreeMap<String, Task>, ) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // Build a map of aliases to tasks let mut alias_map: HashMap<String, Vec<String>> = HashMap::new(); for t in all_tasks.values() { for alias in &t.aliases { alias_map .entry(alias.clone()) .or_default() .push(t.name.clone()); } } // Check for conflicts - only report once for the first task alphabetically for alias in &task.aliases { if let Some(tasks) = alias_map.get(alias) && tasks.len() > 1 { // Only report the conflict for the first task (alphabetically) to avoid duplicates let mut sorted_tasks = tasks.clone(); sorted_tasks.sort(); if sorted_tasks[0] == task.name { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "alias-conflict".to_string(), message: format!("Alias '{}' is used by multiple tasks", alias), details: Some(format!("Tasks: {}", tasks.join(", "))), }); } } // Check if alias conflicts with a task name if all_tasks.contains_key(alias) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "alias-conflict".to_string(), message: format!("Alias '{}' conflicts with task name", alias), details: Some(format!("A task named '{}' already exists", alias)), }); } } issues } fn validate_file_existence(&self, task: &Task) -> Vec<ValidationIssue> { let mut issues = Vec::new(); if let Some(ref file) = task.file { if !file.exists() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "missing-file".to_string(), message: format!("Task file not found: {}", file::display_path(file)), details: None, }); } else if !file::is_executable(file) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "not-executable".to_string(), message: format!("Task file is not executable: {}", file::display_path(file)), details: Some(format!("Run: chmod +x {}", file::display_path(file))), }); } } issues } async fn validate_directory(&self, task: &Task, config: &Arc<Config>) -> Vec<ValidationIssue> { let mut issues = Vec::new(); if let Some(ref dir) = task.dir { // Try to render the directory template if dir.contains("{{") || dir.contains("{%") { // Contains template syntax - try to render it match task.dir(config).await { Ok(rendered_dir) => { if let Some(rendered) = rendered_dir && !rendered.exists() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "missing-directory".to_string(), message: format!( "Task directory does not exist: {}", file::display_path(&rendered) ), details: Some(format!("Template: {}", dir)), }); } } Err(e) => { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "invalid-directory-template".to_string(), message: "Failed to render directory template".to_string(), details: Some(format!("Template: {}, Error: {:#}", dir, e)), }); } } } else { // Static path - check if it exists let dir_path = PathBuf::from(dir); if dir_path.is_absolute() && !dir_path.exists() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "missing-directory".to_string(), message: format!("Task directory does not exist: {}", dir), details: None, }); } } } issues } fn validate_shell(&self, task: &Task) -> Vec<ValidationIssue> { let mut issues = Vec::new(); if let Some(ref shell) = task.shell { // Parse shell command (could be "bash -c" or just "bash") let shell_parts: Vec<&str> = shell.split_whitespace().collect(); if let Some(shell_cmd) = shell_parts.first() { // Check if it's an absolute path let shell_path = PathBuf::from(shell_cmd); if shell_path.is_absolute() && !shell_path.exists() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "invalid-shell".to_string(), message: format!("Shell command not found: {}", shell_cmd), details: Some(format!("Full shell: {}", shell)), }); } } } issues } fn validate_source_patterns(&self, task: &Task) -> Vec<ValidationIssue> { let mut issues = Vec::new(); for source in &task.sources { // Try to compile as glob pattern if let Err(e) = globset::GlobBuilder::new(source).build() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "invalid-glob-pattern".to_string(), message: format!("Invalid source glob pattern: '{}'", source), details: Some(format!("{}", e)), }); } } issues } fn validate_output_patterns(&self, task: &Task) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // Validate output patterns if they exist let paths = task.outputs.paths(task); for path in paths { // Try to compile as glob pattern if let Err(e) = globset::GlobBuilder::new(&path).build() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "invalid-glob-pattern".to_string(), message: format!("Invalid output glob pattern: '{}'", path), details: Some(format!("{}", e)), }); } } issues } fn validate_run_entries( &self, task: &Task, all_tasks: &BTreeMap<String, Task>, ) -> Vec<ValidationIssue> { let mut issues = Vec::new(); // Validate run entries for entry in task.run() { match entry { crate::task::RunEntry::Script(script) => { // Check if script is empty if script.trim().is_empty() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Warning, category: "empty-script".to_string(), message: "Task contains empty script entry".to_string(), details: None, }); } } crate::task::RunEntry::SingleTask { task: task_name } => { // Check if referenced task exists (by name, display_name, or alias) if !Self::task_exists(all_tasks, task_name) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "missing-task-reference".to_string(), message: format!( "Task '{}' referenced in run entry not found", task_name ), details: None, }); } } crate::task::RunEntry::TaskGroup { tasks } => { // Check if all tasks in group exist (by name, display_name, or alias) for task_name in tasks { if !Self::task_exists(all_tasks, task_name) { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "missing-task-reference".to_string(), message: format!("Task '{}' in task group not found", task_name), details: Some("Referenced in parallel task group".to_string()), }); } } } } } // Check if task has no run entries and no file // Allow tasks with dependencies but no run entries (meta/group tasks) if task.run().is_empty() && task.file.is_none() && task.depends.is_empty() && task.depends_post.is_empty() { issues.push(ValidationIssue { task: task.name.clone(), severity: Severity::Error, category: "no-execution".to_string(), message: "Task has no executable content".to_string(), details: Some( "Task must have either 'run', 'run_windows', 'file', or 'depends' defined" .to_string(), ), }); } issues } fn output_json(&self, results: &ValidationResults) -> Result<()> { let json = serde_json::to_string_pretty(results)?; miseprintln!("{}", json); Ok(()) } fn output_human(&self, results: &ValidationResults) -> Result<()> { if results.issues.is_empty() { miseprintln!( "{}", console_style(format!( "✓ All {} task(s) validated successfully", results.tasks_validated )) .green() ); return Ok(()); } // Group issues by task let mut issues_by_task: IndexMap<String, Vec<&ValidationIssue>> = IndexMap::new(); for issue in &results.issues { issues_by_task .entry(issue.task.clone()) .or_insert_with(Vec::new) .push(issue); } // Print summary miseprintln!( "\n{} task(s) validated with {} issue(s):\n", console_style(results.tasks_validated).bold(), console_style(results.errors + results.warnings).bold() ); if results.errors > 0 { miseprintln!( " {} {}", console_style("✗").red().bold(), console_style(format!("{} error(s)", results.errors)) .red() .bold() ); } if results.warnings > 0 { miseprintln!( " {} {}", console_style("⚠").yellow().bold(), console_style(format!("{} warning(s)", results.warnings)) .yellow() .bold() ); } miseprintln!(); // Print issues grouped by task for (task_name, task_issues) in issues_by_task { miseprintln!( "{} {}", console_style("Task:").bold(), console_style(&task_name).cyan() ); for issue in task_issues { let severity_icon = match issue.severity { Severity::Error => console_style("✗").red().bold(), Severity::Warning => console_style("⚠").yellow().bold(), }; miseprintln!( " {} {} [{}]", severity_icon, console_style(&issue.message).bold(), console_style(&issue.category).dim() ); if let Some(ref details) = issue.details { for line in details.lines() { miseprintln!(" {}", console_style(line).dim()); } } } miseprintln!(); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # Validate all tasks $ <bold>mise tasks validate</bold> # Validate specific tasks $ <bold>mise tasks validate build test</bold> # Output results as JSON $ <bold>mise tasks validate --json</bold> # Only show errors (skip warnings) $ <bold>mise tasks validate --errors-only</bold> <bold><underline>Validation Checks:</underline></bold> The validate command performs the following checks: • <bold>Circular Dependencies</bold>: Detects dependency cycles • <bold>Missing References</bold>: Finds references to non-existent tasks • <bold>Usage Spec Parsing</bold>: Validates #USAGE directives and specs • <bold>Timeout Format</bold>: Checks timeout values are valid durations • <bold>Alias Conflicts</bold>: Detects duplicate aliases across tasks • <bold>File Existence</bold>: Verifies file-based tasks exist • <bold>Directory Templates</bold>: Validates directory paths and templates • <bold>Shell Commands</bold>: Checks shell executables exist • <bold>Glob Patterns</bold>: Validates source and output patterns • <bold>Run Entries</bold>: Ensures tasks reference valid dependencies "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/config.rs
src/cli/generate/config.rs
use crate::Result; use crate::cli::config::generate; /// [experimental] Generate a mise.toml file #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = generate::AFTER_LONG_HELP)] pub struct Config { #[clap(flatten)] generate: generate::ConfigGenerate, } impl Config { pub async fn run(self) -> Result<()> { self.generate.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/git_pre_commit.rs
src/cli/generate/git_pre_commit.rs
use xx::file::display_path; use crate::file; use crate::git::Git; /// Generate a git pre-commit hook /// /// This command generates a git pre-commit hook that runs a mise task like `mise run pre-commit` /// when you commit changes to your repository. /// /// Staged files are passed to the task as `STAGED`. /// /// For more advanced pre-commit functionality, see mise's sister project: https://hk.jdx.dev/ #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_alias = "pre-commit", after_long_help = AFTER_LONG_HELP)] pub struct GitPreCommit { /// The task to run when the pre-commit hook is triggered #[clap(long, short, default_value = "pre-commit")] task: String, /// write to .git/hooks/pre-commit and make it executable #[clap(long, short)] write: bool, /// Which hook to generate (saves to .git/hooks/$hook) #[clap(long, default_value = "pre-commit")] hook: String, } impl GitPreCommit { pub async fn run(self) -> eyre::Result<()> { let output = self.generate(); if self.write { let path = Git::get_root()?.join(".git/hooks").join(&self.hook); if path.exists() { let old_path = path.with_extension("old"); miseprintln!( "Moving existing hook to {:?}", old_path.file_name().unwrap() ); file::rename(&path, path.with_extension("old"))?; } file::write(&path, &output)?; file::make_executable(&path)?; miseprintln!("Wrote to {}", display_path(&path)); } else { miseprintln!("{output}"); } Ok(()) } fn generate(&self) -> String { let task = &self.task; format!( r#"#!/bin/sh STAGED="$(git diff-index --cached --name-only -z HEAD | xargs -0)" export STAGED export MISE_PRE_COMMIT=1 exec mise run {task} "# ) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise generate git-pre-commit --write --task=pre-commit</bold> $ <bold>git commit -m "feat: add new feature"</bold> <dim># runs `mise run pre-commit`</dim> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/github_action.rs
src/cli/generate/github_action.rs
use xx::file; use crate::file::display_path; use crate::git::Git; /// Generate a GitHub Action workflow file /// /// This command generates a GitHub Action workflow file that runs a mise task like `mise run ci` /// when you push changes to your repository. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct GithubAction { /// The task to run when the workflow is triggered #[clap(long, short, default_value = "ci")] task: String, /// write to .github/workflows/$name.yml #[clap(long, short)] write: bool, /// the name of the workflow to generate #[clap(long, default_value = "ci")] name: String, } impl GithubAction { pub async fn run(self) -> eyre::Result<()> { let output = self.generate()?; if self.write { let path = Git::get_root()? .join(".github/workflows") .join(format!("{}.yml", &self.name)); file::write(&path, &output)?; miseprintln!("Wrote to {}", display_path(&path)); } else { miseprintln!("{output}"); } Ok(()) } fn generate(&self) -> eyre::Result<String> { let branch = Git::new(Git::get_root()?).current_branch()?; let name = &self.name; let task = &self.task; Ok(format!( r#"name: {name} on: workflow_dispatch: pull_request: push: tags: ["*"] branches: ["{branch}"] concurrency: group: ${{{{ github.workflow }}}}-${{{{ github.ref }}}} cancel-in-progress: true env: MISE_EXPERIMENTAL: true jobs: {name}: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jdx/mise-action@v2 - run: mise run {task} "# )) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise generate github-action --write --task=ci</bold> $ <bold>git commit -m "feat: add new feature"</bold> $ <bold>git push</bold> <dim># runs `mise run ci` on GitHub</dim> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/devcontainer.rs
src/cli/generate/devcontainer.rs
use std::collections::HashMap; use crate::{ dirs, file::{self, display_path}, git::Git, }; use serde::Serialize; /// Generate a devcontainer to execute mise #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Devcontainer { /// The image to use for the devcontainer #[clap(long, short, verbatim_doc_comment)] image: Option<String>, /// Bind the mise-data-volume to the devcontainer #[clap(long, short, verbatim_doc_comment)] mount_mise_data: bool, /// The name of the devcontainer #[clap(long, short, verbatim_doc_comment)] name: Option<String>, /// write to .devcontainer/devcontainer.json #[clap(long, short)] write: bool, } #[derive(Serialize)] struct DevcontainerTemplate { name: String, image: String, features: HashMap<String, HashMap<String, String>>, customizations: HashMap<String, HashMap<String, Vec<String>>>, mounts: Vec<DevcontainerMount>, #[serde(rename = "containerEnv")] container_env: HashMap<String, String>, #[serde(rename = "remoteEnv")] remote_env: HashMap<String, String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "postCreateCommand")] post_create_command: Option<String>, } #[derive(Serialize)] struct DevcontainerMount { source: String, target: String, #[serde(rename = "type")] type_field: String, } impl Devcontainer { pub async fn run(self) -> eyre::Result<()> { let output = self.generate()?; if self.write { let path = match Git::get_root() { Ok(root) => root.join(".devcontainer/devcontainer.json"), Err(_) => dirs::CWD .as_ref() .unwrap() .join(".devcontainer/devcontainer.json"), }; file::create(&path)?; file::write(&path, &output)?; miseprintln!("Wrote to {}", display_path(&path)); } else { miseprintln!("{output}"); } Ok(()) } fn generate(&self) -> eyre::Result<String> { let name = self.name.as_deref().unwrap_or("mise"); let image = self .image .as_deref() .unwrap_or("mcr.microsoft.com/devcontainers/base:ubuntu"); let mut post_create_command: Option<String> = None; let mut mounts = vec![]; let mut container_env = HashMap::new(); let mut remote_env = HashMap::new(); if self.mount_mise_data { mounts.push(DevcontainerMount { source: "mise-data-volume".to_string(), target: "/mnt/mise-data".to_string(), type_field: "volume".to_string(), }); container_env.insert("MISE_DATA_DIR".to_string(), "/mnt/mise-data".to_string()); remote_env.insert( "PATH".to_string(), "${containerEnv:PATH}:/mnt/mise-data/shims".to_string(), ); post_create_command = Some("sudo chown -R vscode:vscode /mnt/mise-data".to_string()); } let mut features = HashMap::new(); features.insert( "ghcr.io/devcontainers-extra/features/mise:1".to_string(), HashMap::new(), ); let mut customizations = HashMap::new(); let mut extensions = HashMap::new(); extensions.insert( "extensions".to_string(), vec!["hverlin.mise-vscode".to_string()], ); customizations.insert("vscode".to_string(), extensions); let template = DevcontainerTemplate { name: name.to_string(), image: image.to_string(), features, customizations, mounts, container_env, remote_env, post_create_command, }; let output = serde_json::to_string_pretty(&template)?; Ok(output) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise generate devcontainer</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/mod.rs
src/cli/generate/mod.rs
use clap::Subcommand; mod bootstrap; mod config; mod devcontainer; mod git_pre_commit; mod github_action; mod task_docs; mod task_stubs; mod tool_stub; /// Generate files for various tools/services #[derive(Debug, clap::Args)] #[clap(visible_alias = "gen", alias = "g")] pub struct Generate { #[clap(subcommand)] command: Commands, } #[derive(Debug, Subcommand)] enum Commands { Bootstrap(bootstrap::Bootstrap), Config(config::Config), Devcontainer(devcontainer::Devcontainer), GitPreCommit(git_pre_commit::GitPreCommit), GithubAction(github_action::GithubAction), TaskDocs(task_docs::TaskDocs), TaskStubs(task_stubs::TaskStubs), ToolStub(tool_stub::ToolStub), } impl Commands { pub async fn run(self) -> eyre::Result<()> { match self { Self::Bootstrap(cmd) => cmd.run().await, Self::Config(cmd) => cmd.run().await, Self::Devcontainer(cmd) => cmd.run().await, Self::GitPreCommit(cmd) => cmd.run().await, Self::GithubAction(cmd) => cmd.run().await, Self::TaskDocs(cmd) => cmd.run().await, Self::TaskStubs(cmd) => cmd.run().await, Self::ToolStub(cmd) => cmd.run().await, } } } impl Generate { pub async fn run(self) -> eyre::Result<()> { self.command.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/task_stubs.rs
src/cli/generate/task_stubs.rs
use crate::Result; use crate::config::Config; use crate::file; use crate::task::Task; use clap::ValueHint; use std::path::PathBuf; use xx::file::display_path; /// Generates shims to run mise tasks /// /// By default, this will build shims like ./bin/<task>. These can be paired with `mise generate bootstrap` /// so contributors to a project can execute mise tasks without installing mise into their system. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TaskStubs { /// Directory to create task stubs inside of #[clap(long, short, verbatim_doc_comment, default_value="bin", value_hint=ValueHint::DirPath)] dir: PathBuf, /// Path to a mise bin to use when running the task stub. /// /// Use `--mise-bin=./bin/mise` to use a mise bin generated from `mise generate bootstrap` #[clap(long, short, verbatim_doc_comment, default_value = "mise")] mise_bin: PathBuf, } impl TaskStubs { pub async fn run(self) -> eyre::Result<()> { let config = Config::get().await?; for task in config.tasks().await?.values() { let bin = self.dir.join(task.name_to_path()); let output = self.generate(task)?; if let Some(parent) = bin.parent() { file::create_dir_all(parent)?; } file::write(&bin, &output)?; file::make_executable(&bin)?; miseprintln!("Wrote to {}", display_path(&bin)); } Ok(()) } fn generate(&self, task: &Task) -> Result<String> { let mise_bin = self.mise_bin.to_string_lossy(); let mise_bin = shell_words::quote(&mise_bin); let display_name = &task.display_name; let script = format!( r#" #!/bin/sh exec {mise_bin} run {display_name} "$@" "# ); Ok(script.trim().to_string()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tasks add test -- echo 'running tests'</bold> $ <bold>mise generate task-stubs</bold> $ <bold>./bin/test</bold> running tests "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/bootstrap.rs
src/cli/generate/bootstrap.rs
use crate::http::HTTP; use crate::ui::info; use crate::{Result, file, minisign}; use clap::ValueHint; use std::path::PathBuf; use xx::file::display_path; use xx::regex; /// Generate a script to download+execute mise /// /// This is designed to be used in a project where contributors may not have mise installed. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Bootstrap { /// Sandboxes mise internal directories like MISE_DATA_DIR and MISE_CACHE_DIR into a `.mise` directory in the project /// /// This is necessary if users may use a different version of mise outside the project. #[clap(long, short, verbatim_doc_comment)] localize: bool, /// Specify mise version to fetch #[clap(long, short = 'V', verbatim_doc_comment)] version: Option<String>, /// instead of outputting the script to stdout, write to a file and make it executable #[clap(long, short, verbatim_doc_comment, num_args=0..=1, default_missing_value = "./bin/mise")] write: Option<PathBuf>, /// Directory to put localized data into #[clap(long, verbatim_doc_comment, default_value=".mise", value_hint=ValueHint::DirPath)] localized_dir: PathBuf, } impl Bootstrap { pub async fn run(self) -> eyre::Result<()> { let output = self.generate().await?; if let Some(bin) = &self.write { if let Some(parent) = bin.parent() { file::create_dir_all(parent)?; } file::write(bin, &output)?; file::make_executable(bin)?; miseprintln!("Wrote to {}", display_path(bin)); } else { miseprintln!("{output}"); } Ok(()) } async fn generate(&self) -> Result<String> { let url = if let Some(v) = &self.version { format!("https://mise.jdx.dev/v{v}/install.sh") } else { "https://mise.jdx.dev/install.sh".into() }; let install = HTTP.get_text(&url).await?; let install_sig = HTTP.get_text(format!("{url}.minisig")).await?; minisign::verify(&minisign::MISE_PUB_KEY, install.as_bytes(), &install_sig)?; let install = info::indent_by(install, " "); let version = regex!(r#"version="\$\{MISE_VERSION:-v([0-9.]+)\}""#) .captures(&install) .unwrap() .get(1) .unwrap() .as_str(); let vars = if self.localize { // TODO: this will only work right if it is in the base directory, not an absolute path or has a subdirectory let localized_dir = self.localized_dir.to_string_lossy(); format!( r#" local project_dir=$( cd -- "$( dirname -- "${{BASH_SOURCE[0]}}" )" &> /dev/null && cd .. && pwd ) local localized_dir="$project_dir/{localized_dir}" export MISE_DATA_DIR="$localized_dir" export MISE_CONFIG_DIR="$localized_dir" export MISE_CACHE_DIR="$localized_dir/cache" export MISE_STATE_DIR="$localized_dir/state" export MISE_INSTALL_PATH="$localized_dir/mise-{version}" export MISE_TRUSTED_CONFIG_PATHS="$project_dir${{MISE_TRUSTED_CONFIG_PATHS:+:$MISE_TRUSTED_CONFIG_PATHS}}" export MISE_IGNORED_CONFIG_PATHS="$HOME/.config/mise${{MISE_IGNORED_CONFIG_PATHS:+:$MISE_IGNORED_CONFIG_PATHS}}" "# ) } else { format!( r#" local cache_home="${{XDG_CACHE_HOME:-$HOME/.cache}}/mise" export MISE_INSTALL_PATH="$cache_home/mise-{version}" "# ) }; let vars = info::indent_by(vars.trim(), " "); let script = format!( r#" #!/usr/bin/env bash set -eu __mise_bootstrap() {{ {vars} install() {{ local initial_working_dir="$PWD" {install} cd -- "$initial_working_dir" }} local MISE_INSTALL_HELP=0 test -f "$MISE_INSTALL_PATH" || install }} __mise_bootstrap exec "$MISE_INSTALL_PATH" "$@" "# ); Ok(script.trim().to_string()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise generate bootstrap >./bin/mise</bold> $ <bold>chmod +x ./bin/mise</bold> $ <bold>./bin/mise install</bold> – automatically downloads mise to .mise if not already installed "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/tool_stub.rs
src/cli/generate/tool_stub.rs
use crate::Result; use crate::backend::asset_matcher::detect_platform_from_url; use crate::backend::static_helpers::get_filename_from_url; use crate::file::{self, TarFormat, TarOptions}; use crate::http::HTTP; use crate::minisign; use crate::ui::info; use crate::ui::multi_progress_report::MultiProgressReport; use crate::ui::progress_report::SingleReport; use clap::ValueHint; use color_eyre::eyre::bail; use humansize::{BINARY, format_size}; use indexmap::IndexMap; use std::path::PathBuf; use toml_edit::DocumentMut; use xx::file::display_path; /// Generate a tool stub for HTTP-based tools /// /// This command generates tool stubs that can automatically download and execute /// tools from HTTP URLs. It can detect checksums, file sizes, and binary paths /// automatically by downloading and analyzing the tool. /// /// When generating stubs with platform-specific URLs, the command will append new /// platforms to existing stub files rather than overwriting them. This allows you /// to incrementally build cross-platform tool stubs. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct ToolStub { /// Output file path for the tool stub #[clap(value_hint = ValueHint::FilePath)] pub output: PathBuf, /// Binary path within the extracted archive /// /// If not specified and the archive is downloaded, will auto-detect the most likely binary #[clap(long, short)] pub bin: Option<String>, /// Wrap stub in a bootstrap script that installs mise if not already present /// /// When enabled, generates a bash script that: /// 1. Checks if mise is installed at the expected path /// 2. If not, downloads and installs mise using the embedded installer /// 3. Executes the tool stub using mise #[clap(long, verbatim_doc_comment)] pub bootstrap: bool, /// Specify mise version for the bootstrap script /// /// By default, uses the latest version from the install script. /// Use this to pin to a specific version (e.g., "2025.1.0"). #[clap(long, verbatim_doc_comment, requires = "bootstrap")] pub bootstrap_version: Option<String>, /// Fetch checksums and sizes for an existing tool stub file /// /// This reads an existing stub file and fills in any missing checksum/size fields /// by downloading the files. URLs must already be present in the stub. #[clap(long, conflicts_with_all = &["url", "platform_url", "version", "bin", "platform_bin", "skip_download"])] pub fetch: bool, /// HTTP backend type to use #[clap(long, default_value = "http")] pub http: String, /// Platform-specific binary paths in the format platform:path /// /// Examples: --platform-bin windows-x64:tool.exe --platform-bin linux-x64:bin/tool #[clap(long)] pub platform_bin: Vec<String>, /// Platform-specific URLs in the format platform:url or just url (auto-detect platform) /// /// When the output file already exists, new platforms will be appended to the existing /// platforms table. Existing platform URLs will be updated if specified again. /// /// If only a URL is provided (without platform:), the platform will be automatically /// detected from the URL filename. /// /// Examples: /// --platform-url linux-x64:https://... /// --platform-url https://nodejs.org/dist/v22.17.1/node-v22.17.1-darwin-arm64.tar.gz #[clap(long)] pub platform_url: Vec<String>, /// Skip downloading for checksum and binary path detection (faster but less informative) #[clap(long)] pub skip_download: bool, /// URL for downloading the tool /// /// Example: https://github.com/owner/repo/releases/download/v2.0.0/tool-linux-x64.tar.gz #[clap(long, short)] pub url: Option<String>, /// Version of the tool #[clap(long, default_value = "latest")] pub version: String, } impl ToolStub { pub async fn run(self) -> Result<()> { let stub_content = if self.fetch { self.fetch_checksums().await? } else { self.generate_stub().await? }; if let Some(parent) = self.output.parent() { file::create_dir_all(parent)?; } file::write(&self.output, &stub_content)?; file::make_executable(&self.output)?; if self.fetch { miseprintln!("Updated tool stub: {}", display_path(&self.output)); } else { miseprintln!("Generated tool stub: {}", display_path(&self.output)); } Ok(()) } fn get_tool_name(&self) -> String { self.output .file_name() .and_then(|name| name.to_str()) .unwrap_or("tool") .to_string() } async fn generate_stub(&self) -> Result<String> { // Validate that either URL or platform URLs are provided if self.url.is_none() && self.platform_url.is_empty() { bail!("Either --url or --platform-url must be specified"); } // Read existing file if it exists let (existing_content, mut doc) = if self.output.exists() { let content = file::read_to_string(&self.output)?; let toml_content = extract_toml_from_stub(&content); let document = toml_content.parse::<DocumentMut>()?; (Some(content), document) } else { (None, DocumentMut::new()) }; // If file exists but we're trying to set a different version, bail if existing_content.is_some() && doc.get("version").is_some() { let existing_version = doc.get("version").and_then(|v| v.as_str()).unwrap_or(""); if existing_version != self.version { bail!( "Cannot change version of existing tool stub from {} to {}", existing_version, self.version ); } } // Set or update version only if it's not "latest" (which should be the default) if self.version != "latest" { doc["version"] = toml_edit::value(&self.version); } // Get the stub filename (without path) let stub_filename = self .output .file_stem() .and_then(|s| s.to_str()) .unwrap_or(""); // Update bin if provided and different from stub filename if let Some(bin) = &self.bin && bin != stub_filename { doc["bin"] = toml_edit::value(bin); } // We use toml_edit directly to preserve existing content // Handle URL or platform-specific URLs if let Some(url) = &self.url { doc["url"] = toml_edit::value(url); // Auto-detect checksum and size if not skipped if !self.skip_download { let mpr = MultiProgressReport::get(); let (checksum, size, bin_path) = self.analyze_url(url, &mpr).await?; doc["checksum"] = toml_edit::value(&checksum); // Create size entry with human-readable comment let mut size_item = toml_edit::value(size as i64); if let Some(value) = size_item.as_value_mut() { let formatted_comment = format_size_comment(size); value.decor_mut().set_suffix(formatted_comment); } doc["size"] = size_item; if self.bin.is_none() && let Some(detected_bin) = bin_path.as_ref() { // Only set bin if it's different from the stub filename if detected_bin != stub_filename { doc["bin"] = toml_edit::value(detected_bin); } } } } if !self.platform_url.is_empty() { let mpr = MultiProgressReport::get(); // Ensure platforms table exists if doc.get("platforms").is_none() { let mut platforms_table = toml_edit::Table::new(); platforms_table.set_implicit(true); doc["platforms"] = toml_edit::Item::Table(platforms_table); } let platforms = doc["platforms"].as_table_mut().unwrap(); // Parse platform-specific bin paths let mut explicit_platform_bins = IndexMap::new(); for platform_bin_spec in &self.platform_bin { let (platform, bin_path) = self.parse_platform_bin_spec(platform_bin_spec)?; explicit_platform_bins.insert(platform, bin_path); } // Track detected bin paths to see if they're all the same let mut detected_bin_paths = Vec::new(); for platform_spec in &self.platform_url { let (platform, url) = self.parse_platform_spec(platform_spec)?; // Create or get platform table if platforms.get(&platform).is_none() { platforms[&platform] = toml_edit::table(); } let platform_table = platforms[&platform].as_table_mut().unwrap(); // Set URL platform_table["url"] = toml_edit::value(&url); // Set platform-specific bin path if explicitly provided and different from stub filename if let Some(explicit_bin) = explicit_platform_bins.get(&platform) && explicit_bin != stub_filename { platform_table["bin"] = toml_edit::value(explicit_bin); } // Auto-detect checksum, size, and bin path if not skipped if !self.skip_download { let (checksum, size, bin_path) = self.analyze_url(&url, &mpr).await?; platform_table["checksum"] = toml_edit::value(&checksum); // Create size entry with human-readable comment let mut size_item = toml_edit::value(size as i64); if let Some(value) = size_item.as_value_mut() { let formatted_comment = format_size_comment(size); value.decor_mut().set_suffix(formatted_comment); } platform_table["size"] = size_item; // Track detected bin paths if let Some(ref bp) = bin_path { detected_bin_paths.push(bp.clone()); } // Set bin path if not explicitly provided and we detected one different from stub filename if !explicit_platform_bins.contains_key(&platform) && self.bin.is_none() && let Some(detected_bin) = bin_path.as_ref() && detected_bin != stub_filename { platform_table["bin"] = toml_edit::value(detected_bin); } } } // Check if we should set a global bin let should_set_global_bin = if self.bin.is_none() && !detected_bin_paths.is_empty() { let first_bin = &detected_bin_paths[0]; detected_bin_paths.iter().all(|b| b == first_bin) } else { false }; if should_set_global_bin { let global_bin = detected_bin_paths[0].clone(); // Remove platform-specific bin entries since we'll have a global one for platform_spec in &self.platform_url { let (platform, _) = self.parse_platform_spec(platform_spec)?; if let Some(platform_table) = platforms.get_mut(&platform) && let Some(table) = platform_table.as_table_mut() && !explicit_platform_bins.contains_key(&platform) { table.remove("bin"); } } // Now set the global bin if different from stub filename if global_bin != stub_filename { doc["bin"] = toml_edit::value(&global_bin); } } } let toml_content = doc.to_string(); // Check if we should use bootstrap format: // 1. If --bootstrap flag is explicitly set // 2. If existing file was a bootstrap stub (preserve format when appending) let use_bootstrap = self.bootstrap || existing_content .as_ref() .map(|c| is_bootstrap_stub(c)) .unwrap_or(false); if use_bootstrap { self.wrap_with_bootstrap(&toml_content).await } else { let mut content = vec![ "#!/usr/bin/env -S mise tool-stub".to_string(), "".to_string(), ]; content.push(toml_content); Ok(content.join("\n")) } } async fn wrap_with_bootstrap(&self, toml_content: &str) -> Result<String> { // Fetch and verify install.sh (same approach as bootstrap.rs) // Use versioned URL if a specific version is requested let url = if let Some(v) = &self.bootstrap_version { format!("https://mise.jdx.dev/v{v}/install.sh") } else { "https://mise.jdx.dev/install.sh".to_string() }; let install = HTTP.get_text(&url).await?; let install_sig = HTTP.get_text(format!("{url}.minisig")).await?; minisign::verify(&minisign::MISE_PUB_KEY, install.as_bytes(), &install_sig)?; let install = info::indent_by(install, " "); // Store TOML in a comment block - mise tool-stub will parse this from the script let commented_toml = toml_content .lines() .map(|line| format!("# {line}")) .collect::<Vec<_>>() .join("\n"); Ok(format!( r##"#!/usr/bin/env bash set -eu # MISE_TOOL_STUB: {commented_toml} # :MISE_TOOL_STUB __mise_tool_stub_bootstrap() {{ # Check if mise is on PATH first if command -v mise &>/dev/null; then MISE_BIN="$(command -v mise)" return fi # Fall back to ~/.local/bin/mise MISE_BIN="$HOME/.local/bin/mise" if [ -f "$MISE_BIN" ]; then return fi # Install mise to ~/.local/bin install() {{ local initial_working_dir="$PWD" {install} cd -- "$initial_working_dir" }} local MISE_INSTALL_HELP=0 install }} __mise_tool_stub_bootstrap exec "$MISE_BIN" tool-stub "$0" "$@" "## )) } fn parse_platform_spec(&self, spec: &str) -> Result<(String, String)> { // Check if this is a URL first (auto-detect case) if spec.starts_with("http://") || spec.starts_with("https://") { // Format: url (auto-detect platform) let url = spec.to_string(); if let Some(detected_platform) = detect_platform_from_url(&url) { let platform = detected_platform.to_platform_string(); debug!("Auto-detected platform '{}' from URL: {}", platform, url); Ok((platform, url)) } else { bail!( "Could not auto-detect platform from URL: {}. Please specify explicitly using 'platform:url' format.", url ); } } else { // Format: platform:url let parts: Vec<&str> = spec.splitn(2, ':').collect(); if parts.len() != 2 { bail!( "Platform spec must be in format 'platform:url' or just 'url' (for auto-detection). Got: {}", spec ); } let platform = parts[0].to_string(); let url = parts[1].to_string(); Ok((platform, url)) } } fn parse_platform_bin_spec(&self, spec: &str) -> Result<(String, String)> { let parts: Vec<&str> = spec.splitn(2, ':').collect(); if parts.len() != 2 { bail!( "Platform bin spec must be in format 'platform:path', got: {}", spec ); } let platform = parts[0].to_string(); let bin_path = parts[1].to_string(); Ok((platform, bin_path)) } async fn analyze_url( &self, url: &str, mpr: &std::sync::Arc<crate::ui::multi_progress_report::MultiProgressReport>, ) -> Result<(String, u64, Option<String>)> { // Create a temporary directory for download and extraction let temp_dir = tempfile::tempdir()?; let filename = get_filename_from_url(url); let archive_path = temp_dir.path().join(&filename); // Create one progress reporter for the entire operation let pr = mpr.add(&format!("download {filename}")); // Download using mise's HTTP client HTTP.download_file(url, &archive_path, Some(pr.as_ref())) .await?; // Read the file to calculate checksum and size let bytes = file::read(&archive_path)?; let size = bytes.len() as u64; let checksum = format!("blake3:{}", blake3::hash(&bytes).to_hex()); // Detect binary path if this is an archive let bin_path = if self.is_archive_format(url) { // Update progress message for extraction and reuse the same progress reporter pr.set_message(format!("extract {filename}")); match self .extract_and_find_binary(&archive_path, &temp_dir, &filename, pr.as_ref()) .await { Ok(path) => { pr.finish(); Some(path) } Err(_) => { pr.finish(); None } } } else { // For single binary files, just use the tool name pr.finish(); Some(self.get_tool_name()) }; Ok((checksum, size, bin_path)) } async fn extract_and_find_binary( &self, archive_path: &std::path::Path, temp_dir: &tempfile::TempDir, _filename: &str, pr: &dyn SingleReport, ) -> Result<String> { // Try to extract and find executables let extracted_dir = temp_dir.path().join("extracted"); std::fs::create_dir_all(&extracted_dir)?; // Try extraction using mise's built-in extraction logic (reuse the passed progress reporter) let tar_opts = TarOptions { format: TarFormat::Auto, strip_components: 0, pr: Some(pr), ..Default::default() }; file::untar(archive_path, &extracted_dir, &tar_opts)?; // Check if strip_components would be applied during actual installation let format = TarFormat::from_ext( &archive_path .extension() .unwrap_or_default() .to_string_lossy(), ); let will_strip = file::should_strip_components(archive_path, format)?; // Find executable files let executables = self.find_executables(&extracted_dir)?; if executables.is_empty() { bail!("No executable files found in archive"); } // Look for exact filename match only let tool_name = self.get_tool_name(); let selected_exe = self.find_exact_binary_match(&executables, &tool_name)?; // If strip_components will be applied, remove the first path component if will_strip { let path = std::path::Path::new(&selected_exe); if let Ok(stripped) = path.strip_prefix(path.components().next().unwrap()) { let stripped_str = stripped.to_string_lossy().to_string(); // Don't return empty string if stripping removed everything if !stripped_str.is_empty() { return Ok(stripped_str); } } } Ok(selected_exe) } fn is_archive_format(&self, url: &str) -> bool { // Check if the URL appears to be an archive format that mise can extract url.ends_with(".tar.gz") || url.ends_with(".tgz") || url.ends_with(".tar.xz") || url.ends_with(".txz") || url.ends_with(".tar.bz2") || url.ends_with(".tbz2") || url.ends_with(".tar.zst") || url.ends_with(".tzst") || url.ends_with(".zip") || url.ends_with(".7z") } fn find_executables(&self, dir: &std::path::Path) -> Result<Vec<String>> { let mut executables = Vec::new(); for entry in walkdir::WalkDir::new(dir) { let entry = entry?; if entry.file_type().is_file() { let path = entry.path(); if file::is_executable(path) && let Ok(relative_path) = path.strip_prefix(dir) { executables.push(relative_path.to_string_lossy().to_string()); } } } Ok(executables) } fn find_exact_binary_match(&self, executables: &[String], tool_name: &str) -> Result<String> { if executables.is_empty() { bail!("No executable files found in archive"); } // Look for exact filename matches (with or without extensions) for exe in executables { let path = std::path::Path::new(exe); if let Some(filename) = path.file_name().and_then(|f| f.to_str()) { // Check exact filename match if filename == tool_name { return Ok(exe.clone()); } // Check filename without extension if let Some(stem) = path.file_stem().and_then(|f| f.to_str()) && stem == tool_name { return Ok(exe.clone()); } } } // No exact match found, try to find the most likely binary let selected_exe = self.find_best_binary_match(executables, tool_name)?; Ok(selected_exe) } fn find_best_binary_match(&self, executables: &[String], tool_name: &str) -> Result<String> { // Strategy 1: Look for executables in common bin directories let bin_executables: Vec<_> = executables .iter() .filter(|exe| { let path = std::path::Path::new(exe); path.parent() .and_then(|p| p.file_name()) .and_then(|n| n.to_str()) .map(|n| n == "bin" || n == "sbin") .unwrap_or(false) }) .collect(); // If there's exactly one executable in a bin directory, use it if bin_executables.len() == 1 { return Ok(bin_executables[0].clone()); } // Strategy 2: Look for executables that contain the tool name let name_matches: Vec<_> = executables .iter() .filter(|exe| { let path = std::path::Path::new(exe); path.file_name() .and_then(|f| f.to_str()) .map(|f| f.to_lowercase().contains(&tool_name.to_lowercase())) .unwrap_or(false) }) .collect(); // If there's exactly one match containing the tool name, use it if name_matches.len() == 1 { return Ok(name_matches[0].clone()); } // Strategy 3: If there's only one executable total, use it if executables.len() == 1 { return Ok(executables[0].clone()); } // No good match found, provide helpful error message let mut exe_list = executables.to_vec(); exe_list.sort(); bail!( "Could not determine which executable to use for '{}'. Available executables:\n {}\n\nUse --bin to specify the correct binary path.", tool_name, exe_list.join("\n ") ); } async fn fetch_checksums(&self) -> Result<String> { // Read the existing stub file if !self.output.exists() { bail!( "Tool stub file does not exist: {}", display_path(&self.output) ); } let content = file::read_to_string(&self.output)?; let toml_content = extract_toml_from_stub(&content); let mut doc = toml_content.parse::<DocumentMut>()?; let mpr = MultiProgressReport::get(); // Process top-level URL if present if let Some(url) = doc.get("url").and_then(|v| v.as_str()) { // Only fetch if checksum is missing if doc.get("checksum").is_none() { let (checksum, size, _) = self.analyze_url(url, &mpr).await?; doc["checksum"] = toml_edit::value(&checksum); // Create size entry with human-readable comment let mut size_item = toml_edit::value(size as i64); if let Some(value) = size_item.as_value_mut() { let formatted_comment = format_size_comment(size); value.decor_mut().set_suffix(formatted_comment); } doc["size"] = size_item; } } // Process platform-specific URLs if let Some(platforms) = doc.get_mut("platforms").and_then(|p| p.as_table_mut()) { for (platform_name, platform_value) in platforms.iter_mut() { if let Some(platform_table) = platform_value.as_table_mut() && let Some(url) = platform_table.get("url").and_then(|v| v.as_str()) { // Only fetch if checksum is missing for this platform if platform_table.get("checksum").is_none() { match self.analyze_url(url, &mpr).await { Ok((checksum, size, _)) => { platform_table["checksum"] = toml_edit::value(&checksum); // Create size entry with human-readable comment let mut size_item = toml_edit::value(size as i64); if let Some(value) = size_item.as_value_mut() { let formatted_comment = format_size_comment(size); value.decor_mut().set_suffix(formatted_comment); } platform_table["size"] = size_item; } Err(e) => { // Log error but continue with other platforms eprintln!( "Warning: Failed to fetch checksum for platform '{platform_name}': {e}" ); } } } } } } let toml_content = doc.to_string(); // Check if original was a bootstrap stub and preserve that format if is_bootstrap_stub(&content) { self.wrap_with_bootstrap(&toml_content).await } else { let mut output = vec![ "#!/usr/bin/env -S mise tool-stub".to_string(), "".to_string(), ]; output.push(toml_content); Ok(output.join("\n")) } } } /// Check if content is a bootstrap stub fn is_bootstrap_stub(content: &str) -> bool { content.contains("# MISE_TOOL_STUB:") && content.contains("# :MISE_TOOL_STUB") } fn format_size_comment(bytes: u64) -> String { format!(" # {}", format_size(bytes, BINARY)) } /// Extract TOML content from a stub file (handles both regular and bootstrap stubs) fn extract_toml_from_stub(content: &str) -> String { // Check if this is a bootstrap stub by looking for comment markers if is_bootstrap_stub(content) { // Bootstrap stub: extract TOML between comment markers let start_marker = "# MISE_TOOL_STUB:"; let end_marker = "# :MISE_TOOL_STUB"; if let (Some(start_pos), Some(end_pos)) = (content.find(start_marker), content.find(end_marker)) && start_pos < end_pos { let between = &content[start_pos + start_marker.len()..end_pos]; return between .lines() .map(|line| line.strip_prefix("# ").unwrap_or(line)) .collect::<Vec<_>>() .join("\n") .trim() .to_string(); } String::new() } else { // Regular stub: skip shebang and comments at the start content .lines() .skip_while(|line| line.starts_with('#') || line.trim().is_empty()) .collect::<Vec<_>>() .join("\n") } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> Generate a tool stub for a single URL: $ <bold>mise generate tool-stub ./bin/gh --url "https://github.com/cli/cli/releases/download/v2.336.0/gh_2.336.0_linux_amd64.tar.gz"</bold> Generate a tool stub with platform-specific URLs: $ <bold>mise generate tool-stub ./bin/rg \ --platform-url linux-x64:https://github.com/BurntSushi/ripgrep/releases/download/14.0.3/ripgrep-14.0.3-x86_64-unknown-linux-musl.tar.gz \ --platform-url darwin-arm64:https://github.com/BurntSushi/ripgrep/releases/download/14.0.3/ripgrep-14.0.3-aarch64-apple-darwin.tar.gz</bold> Append additional platforms to an existing stub: $ <bold>mise generate tool-stub ./bin/rg \ --platform-url linux-x64:https://example.com/rg-linux.tar.gz</bold> $ <bold>mise generate tool-stub ./bin/rg \ --platform-url darwin-arm64:https://example.com/rg-darwin.tar.gz</bold> # The stub now contains both platforms Use auto-detection for platform from URL: $ <bold>mise generate tool-stub ./bin/node \ --platform-url https://nodejs.org/dist/v22.17.1/node-v22.17.1-darwin-arm64.tar.gz</bold> # Platform 'macos-arm64' will be auto-detected from the URL Generate with platform-specific binary paths: $ <bold>mise generate tool-stub ./bin/tool \ --platform-url linux-x64:https://example.com/tool-linux.tar.gz \ --platform-url windows-x64:https://example.com/tool-windows.zip \ --platform-bin windows-x64:tool.exe</bold> Generate without downloading (faster): $ <bold>mise generate tool-stub ./bin/tool --url "https://example.com/tool.tar.gz" --skip-download</bold> Fetch checksums for an existing stub: $ <bold>mise generate tool-stub ./bin/jq --fetch</bold> # This will read the existing stub and download files to fill in any missing checksums/sizes Generate a bootstrap stub that installs mise if needed: $ <bold>mise generate tool-stub ./bin/tool --url "https://example.com/tool.tar.gz" --bootstrap</bold> # The stub will check for mise and install it automatically before running the tool Generate a bootstrap stub with a pinned mise version: $ <bold>mise generate tool-stub ./bin/tool --url "https://example.com/tool.tar.gz" --bootstrap --bootstrap-version 2025.1.0</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/generate/task_docs.rs
src/cli/generate/task_docs.rs
use crate::config::Config; use crate::{dirs, file}; use std::path::PathBuf; use crate::config; /// Generate documentation for tasks in a project #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct TaskDocs { /// inserts the documentation into an existing file /// /// This will look for a special comment, `<!-- mise-tasks -->`, and replace it with the generated documentation. /// It will replace everything between the comment and the next comment, `<!-- /mise-tasks -->` so it can be /// run multiple times on the same file to update the documentation. #[clap(long, short, verbatim_doc_comment)] inject: bool, /// write only an index of tasks, intended for use with `--multi` #[clap(long, short = 'I', verbatim_doc_comment)] index: bool, /// render each task as a separate document, requires `--output` to be a directory #[clap(long, short, verbatim_doc_comment)] multi: bool, /// writes the generated docs to a file/directory #[clap(long, short, verbatim_doc_comment)] output: Option<PathBuf>, /// root directory to search for tasks #[clap(long, short, verbatim_doc_comment, value_hint = clap::ValueHint::DirPath)] root: Option<PathBuf>, #[clap(long, short, verbatim_doc_comment, value_enum, default_value_t)] style: TaskDocsStyle, } #[derive(Debug, Default, Clone, clap::ValueEnum)] enum TaskDocsStyle { #[default] #[value()] Simple, #[value()] Detailed, } impl TaskDocs { pub async fn run(self) -> eyre::Result<()> { let config = Config::get().await?; let dir = dirs::CWD.as_ref().unwrap(); let tasks = config::load_tasks_in_dir(&config, dir, &config.config_files).await?; let mut out = vec![]; for task in tasks.iter().filter(|t| !t.hide) { out.push(task.render_markdown(&config).await?); } if let Some(output) = &self.output { if self.multi { if output.is_dir() { for (i, task) in tasks.iter().filter(|t| !t.hide).enumerate() { let path = output.join(format!("{i}.md")); file::write(&path, &task.render_markdown(&config).await?)?; } } else { return Err(eyre::eyre!( "`--output` must be a directory when `--multi` is set" )); } } else { let mut doc = String::new(); for task in out { doc.push_str(&task); doc.push_str("\n\n"); } if self.inject { doc = format!("\n{}\n", doc.trim()); let mut contents = file::read_to_string(output)?; let task_placeholder_start = "<!-- mise-tasks -->"; let task_placeholder_end = "<!-- /mise-tasks -->"; let start = contents.find(task_placeholder_start).unwrap_or(0); let end = contents[start..] .find(task_placeholder_end) .map(|e| e + start) .unwrap_or(contents.len()); contents.replace_range((start + task_placeholder_start.len())..end, &doc); file::write(output, &contents)?; } else { doc = format!("{}\n", doc.trim()); file::write(output, &doc)?; } } } else { miseprintln!("{}", out.join("\n\n").trim()); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise generate task-docs</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell_alias/ls.rs
src/cli/shell_alias/ls.rs
use eyre::Result; use tabled::Tabled; use crate::config::Config; use crate::ui::table; /// List shell aliases /// /// Shows the shell aliases that are set in the current directory. /// These are defined in `mise.toml` under the `[shell_alias]` section. #[derive(Debug, clap::Args)] #[clap(visible_alias = "list", after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ShellAliasLs { /// Don't show table header #[clap(long)] pub no_header: bool, } impl ShellAliasLs { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let rows = config .shell_aliases .iter() .map(|(name, (command, _path))| Row { alias: name.clone(), command: command.clone(), }) .collect::<Vec<_>>(); let mut table = tabled::Table::new(rows); table::default_style(&mut table, self.no_header); miseprintln!("{table}"); Ok(()) } } #[derive(Tabled)] struct Row { alias: String, command: String, } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise shell-alias ls</bold> alias command ll ls -la gs git status "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell_alias/mod.rs
src/cli/shell_alias/mod.rs
use clap::Subcommand; use eyre::Result; mod get; mod ls; mod set; mod unset; #[derive(Debug, clap::Args)] #[clap(name = "shell-alias", about = "Manage shell aliases.")] pub struct ShellAlias { #[clap(subcommand)] command: Option<Commands>, /// Don't show table header #[clap(long)] pub no_header: bool, } #[derive(Debug, Subcommand)] enum Commands { Get(get::ShellAliasGet), Ls(ls::ShellAliasLs), Set(set::ShellAliasSet), Unset(unset::ShellAliasUnset), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Get(cmd) => cmd.run().await, Self::Ls(cmd) => cmd.run().await, Self::Set(cmd) => cmd.run().await, Self::Unset(cmd) => cmd.run().await, } } } impl ShellAlias { pub async fn run(self) -> Result<()> { let cmd = self.command.unwrap_or(Commands::Ls(ls::ShellAliasLs { no_header: self.no_header, })); cmd.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell_alias/unset.rs
src/cli/shell_alias/unset.rs
use eyre::Result; use crate::config::Config; use crate::config::config_file::ConfigFile; /// Removes a shell alias /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["rm", "remove", "delete", "del"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ShellAliasUnset { /// The alias to remove #[clap(name = "shell_alias")] pub alias: String, } impl ShellAliasUnset { pub async fn run(self) -> Result<()> { let mut global_config = Config::get().await?.global_config()?; global_config.remove_shell_alias(&self.alias)?; global_config.save() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise shell-alias unset ll</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell_alias/set.rs
src/cli/shell_alias/set.rs
use eyre::Result; use crate::config::Config; use crate::config::config_file::ConfigFile; /// Add/update a shell alias /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["add", "create"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ShellAliasSet { /// The alias name #[clap(name = "shell_alias")] pub alias: String, /// The command to run pub command: String, } impl ShellAliasSet { pub async fn run(self) -> Result<()> { let mut global_config = Config::get().await?.global_config()?; global_config.set_shell_alias(&self.alias, &self.command)?; global_config.save() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise shell-alias set ll "ls -la"</bold> $ <bold>mise shell-alias set gs "git status"</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell_alias/get.rs
src/cli/shell_alias/get.rs
use color_eyre::eyre::{Result, eyre}; use crate::config::Config; /// Show the command for a shell alias #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ShellAliasGet { /// The alias to show #[clap(name = "shell_alias")] pub alias: String, } impl ShellAliasGet { pub async fn run(self) -> Result<()> { let config = Config::get().await?; match config.shell_aliases.get(&self.alias) { Some((command, _path)) => { miseprintln!("{command}"); Ok(()) } None => Err(eyre!("Unknown shell alias: {}", &self.alias)), } } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise shell-alias get ll</bold> ls -la "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/cache/prune.rs
src/cli/cache/prune.rs
use crate::cache; use crate::cache::{PruneOptions, PruneResults}; use crate::config::Settings; use crate::dirs::CACHE; use eyre::Result; use number_prefix::NumberPrefix; use std::time::Duration; /// Removes stale mise cache files /// /// By default, this command will remove files that have not been accessed in 30 days. /// Change this with the MISE_CACHE_PRUNE_AGE environment variable. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_alias = "p")] pub struct CachePrune { /// Plugin(s) to clear cache for /// e.g.: node, python plugin: Option<Vec<String>>, /// Show pruned files #[clap(long, short, action = clap::ArgAction::Count)] verbose: u8, /// Just show what would be pruned #[clap(long)] dry_run: bool, } impl CachePrune { pub fn run(self) -> Result<()> { let settings = Settings::get(); let cache_dirs = vec![CACHE.to_path_buf()]; let opts = PruneOptions { dry_run: self.dry_run, verbose: self.verbose > 0, age: settings .cache_prune_age_duration() .unwrap_or(Duration::from_secs(30 * 24 * 60 * 60)), }; let mut results = PruneResults { size: 0, count: 0 }; for p in &cache_dirs { let r = cache::prune(p, &opts)?; results.size += r.size; results.count += r.count; } let count = results.count; let size = bytes_str(results.size); info!("cache pruned {count} files, {size}"); Ok(()) } } fn bytes_str(bytes: u64) -> String { match NumberPrefix::binary(bytes as f64) { NumberPrefix::Standalone(bytes) => format!("{bytes} bytes"), NumberPrefix::Prefixed(prefix, n) => format!("{n:.1} {prefix}B"), } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/cache/path.rs
src/cli/cache/path.rs
use eyre::Result; use crate::env; /// Show the cache directory path #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_alias = "dir")] pub struct CachePath {} impl CachePath { pub fn run(self) -> Result<()> { miseprintln!("{}", env::MISE_CACHE_DIR.display()); Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/cache/clear.rs
src/cli/cache/clear.rs
use crate::dirs::CACHE; use crate::file::{display_path, remove_all}; use eyre::Result; use filetime::set_file_times; use walkdir::WalkDir; /// Deletes all cache files in mise #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_alias = "c", alias = "clean")] pub struct CacheClear { /// Plugin(s) to clear cache for /// e.g.: node, python plugin: Option<Vec<String>>, /// Mark all cache files as old #[clap(long, hide = true)] outdate: bool, } impl CacheClear { pub fn run(self) -> Result<()> { let cache_dirs = match &self.plugin { Some(plugins) => plugins.iter().map(|p| CACHE.join(p)).collect(), None => vec![CACHE.to_path_buf()], }; if self.outdate { for p in cache_dirs { if p.exists() { debug!("outdating cache from {}", display_path(&p)); let files = WalkDir::new(&p) .into_iter() .filter_map(|e| e.ok()) .filter(|e| e.file_type().is_file() || e.file_type().is_dir()); for e in files { set_file_times( e.path(), filetime::FileTime::zero(), filetime::FileTime::zero(), )?; } } } } else { for p in cache_dirs { if p.exists() { debug!("clearing cache from {}", display_path(&p)); remove_all(p)?; } } match &self.plugin { Some(plugins) => info!("cache cleared for {}", plugins.join(", ")), None => info!("cache cleared"), } } Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/cache/mod.rs
src/cli/cache/mod.rs
use clap::Subcommand; use eyre::Result; use crate::env; mod clear; mod path; mod prune; /// Manage the mise cache /// /// Run `mise cache` with no args to view the current cache directory. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment)] pub struct Cache { #[clap(subcommand)] command: Option<Commands>, } #[derive(Debug, Subcommand)] enum Commands { Clear(clear::CacheClear), Path(path::CachePath), Prune(prune::CachePrune), } impl Commands { pub fn run(self) -> Result<()> { match self { Self::Clear(cmd) => cmd.run(), Self::Path(cmd) => cmd.run(), Self::Prune(cmd) => cmd.run(), } } } impl Cache { pub fn run(self) -> Result<()> { match self.command { Some(cmd) => cmd.run(), None => { // just show the cache dir miseprintln!("{}", env::MISE_CACHE_DIR.display()); Ok(()) } } } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/ls.rs
src/cli/settings/ls.rs
use crate::config; use crate::config::settings::{SETTINGS_META, SettingsPartial, SettingsType}; use crate::config::{ALL_TOML_CONFIG_FILES, Settings}; use crate::file::display_path; use crate::ui::table; use eyre::Result; use std::path::{Path, PathBuf}; use tabled::{Table, Tabled}; /// Show current settings /// /// This is the contents of ~/.config/mise/config.toml /// /// Note that aliases are also stored in this file /// but managed separately with `mise aliases` #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct SettingsLs { /// Name of setting pub setting: Option<String>, /// List all settings #[clap(long, short)] all: bool, /// Output in JSON format #[clap(long, short = 'J', group = "output")] json: bool, /// Use the local config file instead of the global one #[clap(long, short, global = true)] pub local: bool, /// Output in TOML format #[clap(long, short = 'T', group = "output")] toml: bool, /// Print all settings with descriptions for shell completions #[clap(long, hide = true)] complete: bool, /// Output in JSON format with sources #[clap(long, group = "output")] json_extended: bool, } fn settings_type_to_string(st: &SettingsType) -> String { match st { SettingsType::Bool => "boolean".to_string(), SettingsType::String => "string".to_string(), SettingsType::Integer => "number".to_string(), SettingsType::Duration => "number".to_string(), SettingsType::Path => "string".to_string(), SettingsType::Url => "string".to_string(), SettingsType::ListString => "array".to_string(), SettingsType::ListPath => "array".to_string(), SettingsType::SetString => "array".to_string(), SettingsType::IndexMap => "object".to_string(), } } impl SettingsLs { pub fn run(self) -> Result<()> { if self.complete { return self.complete(); } let mut rows: Vec<Row> = if self.local { let source = config::local_toml_config_path(); let partial = Settings::parse_settings_file(&source).unwrap_or_default(); Row::from_partial(&partial, &source)? } else { let mut rows = vec![]; if self.all { for (k, v) in Settings::get().as_dict()? { rows.extend(Row::from_toml(k.to_string(), v, None)); } } rows.extend(ALL_TOML_CONFIG_FILES.iter().rev().flat_map(|source| { match Settings::parse_settings_file(source) { Ok(partial) => match Row::from_partial(&partial, source) { Ok(rows) => rows, Err(e) => { warn!("Error parsing {}: {}", display_path(source), e); vec![] } }, Err(e) => { warn!("Error parsing {}: {}", display_path(source), e); vec![] } } })); rows }; if let Some(key) = &self.setting { rows.retain(|r| &r.key == key || r.key.starts_with(&format!("{key}."))); } for k in Settings::hidden_configs() { rows.retain(|r| &r.key != k || r.key.starts_with(&format!("{k}."))); } if self.json { self.print_json(rows)?; } else if self.json_extended { self.print_json_extended(rows)?; } else if self.toml { self.print_toml(rows)?; } else { let mut table = Table::new(rows); table::default_style(&mut table, false); miseprintln!("{}", table.to_string()); } Ok(()) } fn complete(&self) -> Result<()> { for (k, sm) in SETTINGS_META.iter() { println!("{k}:{}", sm.description.replace(":", "\\:")); } Ok(()) } fn print_json(&self, rows: Vec<Row>) -> Result<()> { let mut table = serde_json::Map::new(); for row in rows { if let Some((key, subkey)) = row.key.split_once('.') { let subtable = table .entry(key) .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())); let subtable = subtable.as_object_mut().unwrap(); subtable.insert(subkey.to_string(), toml_value_to_json_value(row.toml_value)); } else { table.insert(row.key, toml_value_to_json_value(row.toml_value)); } } miseprintln!("{}", serde_json::to_string_pretty(&table)?); Ok(()) } fn print_json_extended(&self, rows: Vec<Row>) -> Result<()> { let mut table = serde_json::Map::new(); for row in rows { let mut entry = serde_json::Map::new(); entry.insert( "value".to_string(), toml_value_to_json_value(row.toml_value), ); entry.insert("type".to_string(), row.type_.into()); if let Some(description) = row.description { entry.insert("description".to_string(), description.into()); } if let Some(source) = row.source { entry.insert("source".to_string(), source.to_string_lossy().into()); } if let Some((key, subkey)) = row.key.split_once('.') { let subtable = table .entry(key) .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())); let subtable = subtable.as_object_mut().unwrap(); subtable.insert(subkey.to_string(), entry.into()); } else { table.insert(row.key, entry.into()); } } miseprintln!("{}", serde_json::to_string_pretty(&table)?); Ok(()) } fn print_toml(&self, rows: Vec<Row>) -> Result<()> { let mut table = toml::Table::new(); for row in rows { if let Some((key, subkey)) = row.key.split_once('.') { let subtable = table .entry(key) .or_insert_with(|| toml::Value::Table(toml::Table::new())); let subtable = subtable.as_table_mut().unwrap(); subtable.insert(subkey.to_string(), row.toml_value); continue; } else { table.insert(row.key, row.toml_value); } } miseprintln!("{}", toml::to_string(&table)?); Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise settings ls</bold> idiomatic_version_file = false ... $ <bold>mise settings ls python</bold> default_packages_file = "~/.default-python-packages" ... "# ); #[derive(Debug, Tabled)] #[tabled(rename_all = "PascalCase")] struct Row { key: String, value: String, #[tabled(display = "Self::display_option_path")] source: Option<PathBuf>, #[tabled(skip)] toml_value: toml::Value, #[tabled(skip)] description: Option<String>, #[tabled(skip)] type_: String, } impl Row { fn display_option_path(o: &Option<PathBuf>) -> String { o.as_ref().map(display_path).unwrap_or_default() } fn from_partial(p: &SettingsPartial, source: &Path) -> Result<Vec<Self>> { let rows = Settings::partial_as_dict(p)? .into_iter() .flat_map(|(k, v)| Self::from_toml(k.to_string(), v, Some(source.to_path_buf()))) .collect(); Ok(rows) } fn from_toml(k: String, v: toml::Value, source: Option<PathBuf>) -> Vec<Self> { let mut rows = vec![]; if let Some(table) = v.as_table() { if !table.is_empty() { rows.reserve(table.len()); let meta = SETTINGS_META.get(k.as_str()); let desc = meta.map(|sm| sm.description.to_string()); let type_str = meta .map(|sm| settings_type_to_string(&sm.type_)) .unwrap_or_default(); for (subkey, subvalue) in table { rows.push(Row { key: format!("{k}.{subkey}"), value: subvalue.to_string(), type_: type_str.clone(), source: source.clone(), toml_value: subvalue.clone(), description: desc.clone(), }); } } } else { let meta = SETTINGS_META.get(k.as_str()); rows.push(Row { key: k.clone(), value: v.to_string(), type_: meta .map(|sm| settings_type_to_string(&sm.type_)) .unwrap_or_default(), source, toml_value: v, description: meta.map(|sm| sm.description.to_string()), }); } rows } } fn toml_value_to_json_value(v: toml::Value) -> serde_json::Value { match v { toml::Value::String(s) => s.into(), toml::Value::Integer(i) => i.into(), toml::Value::Boolean(b) => b.into(), toml::Value::Float(f) => f.into(), toml::Value::Table(t) => { let mut table = serde_json::Map::new(); for (k, v) in t { table.insert(k, toml_value_to_json_value(v)); } table.into() } toml::Value::Array(a) => a.into_iter().map(toml_value_to_json_value).collect(), v => v.to_string().into(), } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/mod.rs
src/cli/settings/mod.rs
use clap::Subcommand; use eyre::Result; mod add; mod get; mod ls; mod set; mod unset; #[derive(Debug, clap::Args)] #[clap(about = "Manage settings", after_long_help = AFTER_LONG_HELP)] pub struct Settings { #[clap(subcommand)] command: Option<Commands>, #[clap(flatten)] ls: ls::SettingsLs, /// Setting value to set #[clap(conflicts_with = "all")] value: Option<String>, } #[derive(Debug, Subcommand)] enum Commands { Add(add::SettingsAdd), Get(get::SettingsGet), #[clap(visible_alias = "list")] Ls(ls::SettingsLs), Set(set::SettingsSet), Unset(unset::SettingsUnset), } impl Commands { pub fn run(self) -> Result<()> { match self { Self::Add(cmd) => cmd.run(), Self::Get(cmd) => cmd.run(), Self::Ls(cmd) => cmd.run(), Self::Set(cmd) => cmd.run(), Self::Unset(cmd) => cmd.run(), } } } impl Settings { pub async fn run(self) -> Result<()> { let cmd = self.command.unwrap_or_else(|| { if let Some(value) = self.value { Commands::Set(set::SettingsSet { setting: self.ls.setting.unwrap(), value, local: self.ls.local, }) } else if let Some(setting) = self.ls.setting { if let Some((setting, value)) = setting.split_once('=') { Commands::Set(set::SettingsSet { setting: setting.to_string(), value: value.to_string(), local: self.ls.local, }) } else { Commands::Get(get::SettingsGet { setting, local: self.ls.local, }) } } else { Commands::Ls(self.ls) } }); cmd.run() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # list all settings $ <bold>mise settings</bold> # get the value of the setting "always_keep_download" $ <bold>mise settings always_keep_download</bold> # set the value of the setting "always_keep_download" to "true" $ <bold>mise settings always_keep_download=true</bold> # set the value of the setting "node.mirror_url" to "https://npm.taobao.org/mirrors/node" $ <bold>mise settings node.mirror_url https://npm.taobao.org/mirrors/node</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/unset.rs
src/cli/settings/unset.rs
use eyre::Result; use toml_edit::DocumentMut; use crate::config::settings::SettingsFile; use crate::{config, file}; /// Clears a setting /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["rm", "remove", "delete", "del"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct SettingsUnset { /// The setting to remove pub key: String, /// Use the local config file instead of the global one #[clap(long, short)] pub local: bool, } impl SettingsUnset { pub fn run(self) -> Result<()> { unset(&self.key, self.local) } } pub fn unset(mut key: &str, local: bool) -> Result<()> { let path = if local { config::local_toml_config_path() } else { config::global_config_path() }; let raw = file::read_to_string(&path)?; let mut config: DocumentMut = raw.parse()?; if let Some(mut settings) = config["settings"].as_table_mut() { if let Some((parent_key, child_key)) = key.split_once('.') { key = child_key; settings = settings .entry(parent_key) .or_insert({ let mut t = toml_edit::Table::new(); t.set_implicit(true); toml_edit::Item::Table(t) }) .as_table_mut() .unwrap(); } settings.remove(key); // validate let _: SettingsFile = toml::from_str(&config.to_string())?; file::write(&path, config.to_string())?; } Ok(()) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise settings unset idiomatic_version_file</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/add.rs
src/cli/settings/add.rs
use eyre::Result; use crate::cli::settings::set::set; /// Adds a setting to the configuration file /// /// Used with an array setting, this will append the value to the array. /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct SettingsAdd { /// The setting to set #[clap()] pub setting: String, /// The value to set pub value: String, /// Use the local config file instead of the global one #[clap(long, short)] pub local: bool, } impl SettingsAdd { pub fn run(self) -> Result<()> { set(&self.setting, &self.value, true, self.local) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise settings add disable_hints python_multi</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/set.rs
src/cli/settings/set.rs
use eyre::{Result, bail, eyre}; use toml_edit::DocumentMut; use crate::config::settings::{SETTINGS_META, SettingsFile, SettingsType, parse_url_replacements}; use crate::toml::dedup_toml_array; use crate::{config, duration, file}; /// Add/update a setting /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["create"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct SettingsSet { /// The setting to set #[clap()] pub setting: String, /// The value to set pub value: String, /// Use the local config file instead of the global one #[clap(long, short)] pub local: bool, } impl SettingsSet { pub fn run(self) -> Result<()> { set(&self.setting, &self.value, false, self.local) } } pub fn set(mut key: &str, value: &str, add: bool, local: bool) -> Result<()> { let meta = match SETTINGS_META.get(key) { Some(meta) => meta, None => { bail!("Unknown setting: {}", key); } }; let value = match meta.type_ { SettingsType::Bool => parse_bool(value)?, SettingsType::Integer => parse_i64(value)?, SettingsType::Duration => parse_duration(value)?, SettingsType::Url | SettingsType::Path | SettingsType::String => value.into(), SettingsType::ListString => parse_list_by_comma(value)?, SettingsType::ListPath => parse_list_by_colon(value)?, SettingsType::SetString => parse_set_by_comma(value)?, SettingsType::IndexMap => parse_indexmap_by_json(value)?, }; let path = if local { config::local_toml_config_path() } else { config::global_config_path() }; file::create_dir_all(path.parent().unwrap())?; let raw = file::read_to_string(&path).unwrap_or_default(); let mut config: DocumentMut = raw.parse()?; if !config.contains_key("settings") { config["settings"] = toml_edit::Item::Table(toml_edit::Table::new()); } if let Some(mut settings) = config["settings"].as_table_mut() { if let Some((parent_key, child_key)) = key.split_once('.') { key = child_key; settings = settings .entry(parent_key) .or_insert({ let mut t = toml_edit::Table::new(); t.set_implicit(true); toml_edit::Item::Table(t) }) .as_table_mut() .unwrap(); } let value = match settings.get(key).map(|c| c.as_array()) { Some(Some(array)) if add => { let mut new_array = array.clone(); new_array.extend(value.as_array().unwrap().iter().cloned()); match meta.type_ { SettingsType::SetString => dedup_toml_array(&new_array).into(), _ => new_array.into(), } } _ => value, }; settings.insert(key, value.into()); // validate let _: SettingsFile = toml::from_str(&config.to_string())?; file::write(path, config.to_string())?; } Ok(()) } fn parse_list_by_comma(value: &str) -> Result<toml_edit::Value> { if value.is_empty() || value == "[]" { return Ok(toml_edit::Array::new().into()); } Ok(value.split(',').map(|s| s.trim().to_string()).collect()) } fn parse_list_by_colon(value: &str) -> Result<toml_edit::Value> { if value.is_empty() || value == "[]" { return Ok(toml_edit::Array::new().into()); } Ok(value.split(':').map(|s| s.trim().to_string()).collect()) } fn parse_set_by_comma(value: &str) -> Result<toml_edit::Value> { if value.is_empty() || value == "[]" { return Ok(toml_edit::Array::new().into()); } let array: toml_edit::Array = value.split(',').map(|s| s.trim().to_string()).collect(); Ok(dedup_toml_array(&array).into()) } fn parse_bool(value: &str) -> Result<toml_edit::Value> { match value.to_lowercase().as_str() { "1" | "true" | "yes" | "y" => Ok(true.into()), "0" | "false" | "no" | "n" => Ok(false.into()), _ => Err(eyre!("{} must be true or false", value)), } } fn parse_i64(value: &str) -> Result<toml_edit::Value> { match value.parse::<i64>() { Ok(value) => Ok(value.into()), Err(_) => Err(eyre!("{} must be a number", value)), } } fn parse_duration(value: &str) -> Result<toml_edit::Value> { duration::parse_duration(value)?; Ok(value.into()) } fn parse_indexmap_by_json(value: &str) -> Result<toml_edit::Value> { let index_map = parse_url_replacements(value) .map_err(|e| eyre!("Failed to parse JSON for IndexMap: {}", e))?; Ok(toml_edit::Value::InlineTable({ let mut table = toml_edit::InlineTable::new(); for (k, v) in index_map { table.insert(&k, toml_edit::Value::String(toml_edit::Formatted::new(v))); } table })) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise settings idiomatic_version_file=true</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/settings/get.rs
src/cli/settings/get.rs
use crate::config; use crate::config::Settings; use eyre::bail; /// Show a current setting /// /// This is the contents of a single entry in ~/.config/mise/config.toml /// /// Note that aliases are also stored in this file /// but managed separately with `mise aliases get` #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct SettingsGet { /// The setting to show pub setting: String, /// Use the local config file instead of the global one #[clap(long, short)] pub local: bool, } impl SettingsGet { pub fn run(self) -> eyre::Result<()> { let settings = if self.local { let partial = Settings::parse_settings_file(&config::local_toml_config_path()) .unwrap_or_default(); Settings::partial_as_dict(&partial)? } else { Settings::get().as_dict()? }; let mut value = toml::Value::Table(settings); let mut key = Some(self.setting.as_str()); while let Some(k) = key { let k = k .split_once('.') .map(|(a, b)| (a, Some(b))) .unwrap_or((k, None)); if let Some(v) = value.as_table().and_then(|t| t.get(k.0)) { key = k.1; value = v.clone() } else { bail!("Unknown setting: {}", self.setting); } } match value { toml::Value::String(s) => miseprintln!("{s}"), value => miseprintln!("{value}"), } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise settings get idiomatic_version_file</bold> true "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/doctor/path.rs
src/cli/doctor/path.rs
use crate::Result; use crate::config::Config; use std::env; /// Print the current PATH entries mise is providing #[derive(Debug, clap::Args)] #[clap(alias="paths", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Path { /// Print all entries including those not provided by mise #[clap(long, short, verbatim_doc_comment)] full: bool, } impl Path { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let ts = config.get_toolset().await?; let paths = if self.full { let env = ts.env_with_path(&config).await?; let path = env.get("PATH").cloned().unwrap_or_default(); env::split_paths(&path).collect() } else { let (_env, env_results) = ts.final_env(&config).await?; ts.list_final_paths(&config, env_results).await? }; for path in paths { println!("{}", path.display()); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> Get the current PATH entries mise is providing $ mise path /home/user/.local/share/mise/installs/node/24.0.0/bin /home/user/.local/share/mise/installs/rust/1.90.0/bin /home/user/.local/share/mise/installs/python/3.10.0/bin "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/doctor/mod.rs
src/cli/doctor/mod.rs
mod path; use crate::{exit, plugins::PluginEnum}; use std::{collections::BTreeMap, sync::Arc}; use crate::backend::backend_type::BackendType; use crate::build_time::built_info; use crate::cli::self_update::SelfUpdate; use crate::cli::version; use crate::cli::version::VERSION; use crate::config::{Config, IGNORED_CONFIG_FILES}; use crate::env::PATH_KEY; use crate::file::display_path; use crate::git::Git; use crate::plugins::PluginType; use crate::plugins::core::CORE_PLUGINS; use crate::toolset::{ToolVersion, Toolset, ToolsetBuilder}; use crate::ui::{info, style}; use crate::{backend, dirs, duration, env, file, shims}; use console::{Alignment, pad_str, style}; use heck::ToSnakeCase; use indexmap::IndexMap; use indoc::formatdoc; use itertools::Itertools; use std::env::split_paths; use std::path::{Path, PathBuf}; use strum::IntoEnumIterator; /// Check mise installation for possible problems #[derive(Debug, clap::Args)] #[clap(visible_alias = "dr", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct Doctor { #[clap(subcommand)] subcommand: Option<Commands>, #[clap(skip)] errors: Vec<String>, #[clap(skip)] warnings: Vec<String>, #[clap(long, short = 'J')] json: bool, } #[derive(Debug, clap::Subcommand)] pub enum Commands { Path(path::Path), } impl Doctor { pub async fn run(self) -> eyre::Result<()> { if let Some(cmd) = self.subcommand { match cmd { Commands::Path(cmd) => cmd.run().await, } } else if self.json { self.doctor_json().await } else { self.doctor().await } } async fn doctor_json(mut self) -> crate::Result<()> { let mut data: BTreeMap<String, _> = BTreeMap::new(); data.insert( "version".into(), serde_json::Value::String(VERSION.to_string()), ); data.insert("activated".into(), env::is_activated().into()); data.insert("shims_on_path".into(), shims_on_path().into()); data.insert( "self_update_available".into(), SelfUpdate::is_available().into(), ); if env::is_activated() && shims_on_path() { self.errors.push("shims are on PATH and mise is also activated. You should only use one of these methods.".to_string()); } data.insert( "build_info".into(), build_info() .into_iter() .map(|(k, v)| (k.to_snake_case(), v)) .collect(), ); let shell = shell(); let mut shell_lines = shell.lines(); let mut shell = serde_json::Map::new(); if let Some(name) = shell_lines.next() { shell.insert("name".into(), name.into()); } if let Some(version) = shell_lines.next() { shell.insert("version".into(), version.into()); } data.insert("shell".into(), shell.into()); data.insert( "dirs".into(), mise_dirs() .into_iter() .map(|(k, p)| (k, p.to_string_lossy().to_string())) .collect(), ); let mut aqua = serde_json::Map::new(); aqua.insert( "baked_in_registry_tools".into(), aqua_registry_count().into(), ); data.insert("aqua".into(), aqua.into()); data.insert("env_vars".into(), mise_env_vars().into_iter().collect()); data.insert( "settings".into(), serde_json::from_str(&cmd!(&*env::MISE_BIN, "settings", "-J").read()?)?, ); let config = Config::get().await?; let ts = config.get_toolset().await?; self.analyze_shims(&config, ts).await; self.analyze_plugins(); data.insert( "paths".into(), self.paths(ts) .await? .into_iter() .map(|p| p.to_string_lossy().to_string()) .collect(), ); data.insert( "config_files".into(), config .config_files .keys() .map(|p| p.to_string_lossy().to_string()) .collect(), ); data.insert( "ignored_config_files".into(), IGNORED_CONFIG_FILES .iter() .map(|p| p.to_string_lossy().to_string()) .collect(), ); let tools = ts.list_versions_by_plugin().into_iter().map(|(f, tv)| { let versions: serde_json::Value = tv .iter() .filter(|tv| tv.request.is_os_supported()) .map(|tv: &ToolVersion| { let mut tool = serde_json::Map::new(); match f.is_version_installed(&config, tv, true) { true => { tool.insert("version".into(), tv.version.to_string().into()); } false => { tool.insert("version".into(), tv.version.to_string().into()); tool.insert("missing".into(), true.into()); self.errors.push(format!( "tool {tv} is not installed, install with `mise install`" )); } } serde_json::Value::from(tool) }) .collect(); (f.ba().to_string(), versions) }); data.insert("toolset".into(), tools.collect()); if !self.errors.is_empty() { data.insert("errors".into(), self.errors.clone().into_iter().collect()); } if !self.warnings.is_empty() { data.insert( "warnings".into(), self.warnings.clone().into_iter().collect(), ); } let out = serde_json::to_string_pretty(&data)?; println!("{out}"); if !self.errors.is_empty() { exit(1); } Ok(()) } async fn doctor(mut self) -> eyre::Result<()> { info::inline_section("version", &*VERSION)?; #[cfg(unix)] info::inline_section("activated", yn(env::is_activated()))?; info::inline_section("shims_on_path", yn(shims_on_path()))?; info::inline_section("self_update_available", yn(SelfUpdate::is_available()))?; if !SelfUpdate::is_available() && let Some(instructions) = crate::cli::self_update::upgrade_instructions_text() { info::section("self_update_instructions", instructions)?; } if env::is_activated() && shims_on_path() { self.errors.push("shims are on PATH and mise is also activated. You should only use one of these methods.".to_string()); } let build_info = build_info() .into_iter() .map(|(k, v)| format!("{k}: {v}")) .join("\n"); info::section("build_info", build_info)?; info::section("shell", shell())?; info::section("aqua", aqua_registry_count_str())?; let mise_dirs = mise_dirs() .into_iter() .map(|(k, p)| format!("{k}: {}", display_path(p))) .join("\n"); info::section("dirs", mise_dirs)?; match Config::get().await { Ok(config) => self.analyze_config(&config).await?, Err(err) => self.errors.push(format!("failed to load config: {err}")), } self.analyze_plugins(); let env_vars = mise_env_vars() .into_iter() .map(|(k, v)| format!("{k}={v}")) .join("\n"); if env_vars.is_empty() { info::section("env_vars", "(none)")?; } else { info::section("env_vars", env_vars)?; } self.analyze_settings()?; if let Some(latest) = version::check_for_new_version(duration::HOURLY).await { version::show_latest().await; self.warnings.push(format!( "new mise version {latest} available, currently on {}", *version::V )); } miseprintln!(); if !self.warnings.is_empty() { let warnings_plural = if self.warnings.len() == 1 { "" } else { "s" }; let warning_summary = format!("{} warning{warnings_plural} found:", self.warnings.len()); miseprintln!("{}\n", style(warning_summary).yellow().bold()); for (i, check) in self.warnings.iter().enumerate() { let num = style::nyellow(format!("{}.", i + 1)); miseprintln!("{num} {}\n", info::indent_by(check, " ").trim_start()); } } if self.errors.is_empty() { miseprintln!("No problems found"); } else { let errors_plural = if self.errors.len() == 1 { "" } else { "s" }; let error_summary = format!("{} problem{errors_plural} found:", self.errors.len()); miseprintln!("{}\n", style(error_summary).red().bold()); for (i, check) in self.errors.iter().enumerate() { let num = style::nred(format!("{}.", i + 1)); miseprintln!("{num} {}\n", info::indent_by(check, " ").trim_start()); } exit(1); } Ok(()) } fn analyze_settings(&mut self) -> eyre::Result<()> { match cmd!("mise", "settings").read() { Ok(settings) => { info::section("settings", settings)?; } Err(err) => self.errors.push(format!("failed to load settings: {err}")), } Ok(()) } async fn analyze_config(&mut self, config: &Arc<Config>) -> eyre::Result<()> { info::section("config_files", render_config_files(config))?; if IGNORED_CONFIG_FILES.is_empty() { println!(); info::inline_section("ignored_config_files", "(none)")?; } else { info::section( "ignored_config_files", IGNORED_CONFIG_FILES.iter().map(display_path).join("\n"), )?; } info::section("backends", render_backends())?; info::section("plugins", render_plugins())?; for backend in backend::list() { if let Some(plugin) = backend.plugin() && !plugin.is_installed() { self.errors .push(format!("plugin {} is not installed", &plugin.name())); continue; } } if !env::is_activated() && !shims_on_path() { let shims = style::ncyan(display_path(*dirs::SHIMS)); if cfg!(windows) { self.errors.push(formatdoc!( r#"mise shims are not on PATH Add this directory to PATH: {shims}"# )); } else { let cmd = style::nyellow("mise help activate"); let url = style::nunderline("https://mise.jdx.dev"); self.errors.push(formatdoc!( r#"mise is not activated, run {cmd} or read documentation at {url} for activation instructions. Alternatively, add the shims directory {shims} to PATH. Using the shims directory is preferred for non-interactive setups."# )); } } match ToolsetBuilder::new().build(config).await { Ok(ts) => { self.analyze_shims(config, &ts).await; self.analyze_toolset(&ts).await?; self.analyze_paths(&ts).await?; } Err(err) => self.errors.push(format!("failed to load toolset: {err}")), } Ok(()) } async fn analyze_toolset(&mut self, ts: &Toolset) -> eyre::Result<()> { let config = Config::get().await?; let tools = ts .list_current_versions() .into_iter() .map(|(f, tv)| match f.is_version_installed(&config, &tv, true) { true => (tv.to_string(), style::nstyle("")), false => { self.errors.push(format!( "tool {tv} is not installed, install with `mise install`" )); (tv.to_string(), style::ndim("(missing)")) } }) .collect_vec(); let max_tool_len = tools .iter() .map(|(t, _)| t.len()) .max() .unwrap_or(0) .min(20); let tools = tools .into_iter() .map(|(t, s)| format!("{} {s}", pad_str(&t, max_tool_len, Alignment::Left, None))) .sorted() .collect::<Vec<_>>() .join("\n"); info::section("toolset", tools)?; Ok(()) } async fn analyze_shims(&mut self, config: &Arc<Config>, toolset: &Toolset) { let mise_bin = file::which("mise").unwrap_or(env::MISE_BIN.clone()); if let Ok((missing, extra)) = shims::get_shim_diffs(config, mise_bin, toolset).await { let cmd = style::nyellow("mise reshim"); if !missing.is_empty() { self.errors.push(formatdoc!( "shims are missing, run {cmd} to create them Missing shims: {missing}", missing = missing.into_iter().join(", ") )); } if !extra.is_empty() { self.errors.push(formatdoc!( "unused shims are present, run {cmd} to remove them Unused shims: {extra}", extra = extra.into_iter().join(", ") )); } } time!("doctor::analyze_shims"); } fn analyze_plugins(&mut self) { for plugin in backend::list() { let is_core = CORE_PLUGINS.contains_key(plugin.id()); let plugin_type = plugin.get_plugin_type(); if is_core && matches!(plugin_type, Some(PluginType::Asdf | PluginType::Vfox)) { self.warnings .push(format!("plugin {} overrides a core plugin", &plugin.id())); } } } async fn paths(&mut self, ts: &Toolset) -> eyre::Result<Vec<PathBuf>> { let config = Config::get().await?; let env = ts.full_env(&config).await?; let path = env .get(&*PATH_KEY) .ok_or_else(|| eyre::eyre!("Path not found"))?; Ok(split_paths(path).collect()) } async fn analyze_paths(&mut self, ts: &Toolset) -> eyre::Result<()> { let paths = self .paths(ts) .await? .into_iter() .map(display_path) .join("\n"); info::section("path", paths)?; Ok(()) } } fn shims_on_path() -> bool { env::PATH.contains(&dirs::SHIMS.to_path_buf()) } fn yn(b: bool) -> String { if b { style("yes").green().to_string() } else { style("no").red().to_string() } } fn mise_dirs() -> Vec<(String, &'static Path)> { [ ("cache", &*dirs::CACHE), ("config", &*dirs::CONFIG), ("data", &*dirs::DATA), ("shims", &*dirs::SHIMS), ("state", &*dirs::STATE), ] .iter() .map(|(k, v)| (k.to_string(), **v)) .collect() } fn mise_env_vars() -> Vec<(String, String)> { const REDACT_KEYS: &[&str] = &[ "MISE_GITHUB_TOKEN", "MISE_GITLAB_TOKEN", "MISE_GITHUB_ENTERPRISE_TOKEN", "MISE_GITLAB_ENTERPRISE_TOKEN", ]; env::vars_safe() .filter(|(k, _)| k.starts_with("MISE_")) .map(|(k, v)| { let v = if REDACT_KEYS.contains(&k.as_str()) { style::ndim("REDACTED").to_string() } else { v }; (k, v) }) .collect() } fn render_config_files(config: &Config) -> String { config .config_files .keys() .rev() .map(display_path) .join("\n") } fn render_backends() -> String { let mut s = vec![]; for b in BackendType::iter().filter(|b| b != &BackendType::Unknown) { s.push(format!("{b}")); } s.join("\n") } fn render_plugins() -> String { let plugins = backend::list() .into_iter() .filter(|b| { b.plugin() .is_some_and(|p| p.is_installed() && b.get_type() == BackendType::Asdf) }) .collect::<Vec<_>>(); let max_plugin_name_len = plugins .iter() .map(|p| p.id().len()) .max() .unwrap_or(0) .min(40); plugins .into_iter() .filter(|b| b.plugin().is_some()) .map(|p| { let p = p.plugin().unwrap(); let padded_name = pad_str(p.name(), max_plugin_name_len, Alignment::Left, None); let extra = match p { PluginEnum::Asdf(_) | PluginEnum::Vfox(_) | PluginEnum::VfoxBackend(_) => { let git = Git::new(dirs::PLUGINS.join(p.name())); match git.get_remote_url() { Some(url) => { let sha = git .current_sha_short() .unwrap_or_else(|_| "(unknown)".to_string()); format!("{url}#{sha}") } None => "".to_string(), } } // TODO: PluginType::Core => "(core)".to_string(), }; format!("{padded_name} {}", style::ndim(extra)) }) .collect::<Vec<_>>() .join("\n") } fn build_info() -> IndexMap<String, &'static str> { let mut s = IndexMap::new(); s.insert("Target".into(), built_info::TARGET); s.insert("Features".into(), built_info::FEATURES_STR); s.insert("Built".into(), built_info::BUILT_TIME_UTC); s.insert("Rust Version".into(), built_info::RUSTC_VERSION); s.insert("Profile".into(), built_info::PROFILE); s } fn shell() -> String { match env::MISE_SHELL.map(|s| s.to_string()) { Some(shell) => { let shell_cmd = if env::SHELL.ends_with(shell.as_str()) { &*env::SHELL } else { &shell }; let version = cmd!(shell_cmd, "--version") .read() .unwrap_or_else(|e| format!("failed to get shell version: {e}")); format!("{shell_cmd}\n{version}") } None => "(unknown)".to_string(), } } fn aqua_registry_count() -> usize { aqua_registry::AQUA_STANDARD_REGISTRY_FILES.len() } fn aqua_registry_count_str() -> String { format!("baked in registry tools: {}", aqua_registry_count()) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise doctor</bold> [WARN] plugin node is not installed "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/uninstall.rs
src/cli/plugins/uninstall.rs
use eyre::Result; use crate::backend::unalias_backend; use crate::toolset::install_state; use crate::ui::multi_progress_report::MultiProgressReport; use crate::ui::style; use crate::{backend, plugins}; /// Removes a plugin #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_aliases = ["remove", "rm"], after_long_help = AFTER_LONG_HELP)] pub struct PluginsUninstall { /// Plugin(s) to remove #[clap(verbatim_doc_comment)] plugin: Vec<String>, /// Remove all plugins #[clap(long, short, verbatim_doc_comment, conflicts_with = "plugin")] all: bool, /// Also remove the plugin's installs, downloads, and cache #[clap(long, short, verbatim_doc_comment)] purge: bool, } impl PluginsUninstall { pub async fn run(self) -> Result<()> { let mpr = MultiProgressReport::get(); let plugins = match self.all { true => install_state::list_plugins().keys().cloned().collect(), false => self.plugin.clone(), }; for plugin_name in plugins { let plugin_name = unalias_backend(&plugin_name); self.uninstall_one(plugin_name, &mpr).await?; } Ok(()) } async fn uninstall_one(&self, plugin_name: &str, mpr: &MultiProgressReport) -> Result<()> { if let Ok(plugin) = plugins::get(plugin_name) { if plugin.is_installed() { let prefix = format!("plugin:{}", style::eblue(&plugin.name())); let pr = mpr.add(&prefix); plugin.uninstall(pr.as_ref()).await?; if self.purge { let backend = backend::get(&plugin_name.into()).unwrap(); backend.purge(pr.as_ref())?; } pr.finish_with_message("uninstalled".into()); } else { warn!("{} is not installed", style::eblue(plugin_name)); } } else { warn!("{} is not installed", style::eblue(plugin_name)); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise uninstall node</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/link.rs
src/cli/plugins/link.rs
use std::path::{Path, PathBuf}; use clap::ValueHint; use color_eyre::eyre::{Result, eyre}; use console::style; use path_absolutize::Absolutize; use crate::backend::unalias_backend; use crate::file::{make_symlink, remove_all}; use crate::{dirs, file}; /// Symlinks a plugin into mise /// /// This is used for developing a plugin. #[derive(Debug, clap::Args)] #[clap(visible_alias = "ln", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct PluginsLink { /// The name of the plugin /// e.g.: node, ruby #[clap(verbatim_doc_comment)] name: String, /// The local path to the plugin /// e.g.: ./mise-node #[clap(value_hint = ValueHint::DirPath, verbatim_doc_comment)] dir: Option<PathBuf>, /// Overwrite existing plugin #[clap(long, short = 'f')] force: bool, } impl PluginsLink { pub async fn run(self) -> Result<()> { let (name, path) = match self.dir { Some(path) => (self.name, path), None => { let path = PathBuf::from(PathBuf::from(&self.name).absolutize()?); let name = get_name_from_path(&path); (name, path) } }; let name = unalias_backend(&name); let path = path.absolutize()?; let symlink = dirs::PLUGINS.join(name); if symlink.exists() { if self.force { remove_all(&symlink)?; } else { return Err(eyre!( "plugin {} already exists, use --force to overwrite", style(&name).blue().for_stderr() )); } } file::create_dir_all(*dirs::PLUGINS)?; make_symlink(&path, &symlink)?; Ok(()) } } fn get_name_from_path(path: &Path) -> String { let name = path.file_name().unwrap().to_str().unwrap(); let name = name.strip_prefix("asdf-").unwrap_or(name); let name = name.strip_prefix("rtx-").unwrap_or(name); let name = name.strip_prefix("mise-").unwrap_or(name); unalias_backend(name).to_string() } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # essentially just `ln -s ./mise-node ~/.local/share/mise/plugins/node` $ <bold>mise plugins link node ./mise-node</bold> # infer plugin name as "node" $ <bold>mise plugins link ./mise-node</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/ls.rs
src/cli/plugins/ls.rs
use eyre::Result; use std::collections::BTreeMap; use tabled::{Table, Tabled}; use crate::config::Config; use crate::plugins::PluginType; use crate::plugins::core::CORE_PLUGINS; use crate::registry::full_to_url; use crate::toolset::install_state; use crate::ui::table; /// List installed plugins /// /// Can also show remotely available plugins to install. #[derive(Debug, clap::Args)] #[clap(visible_alias = "list", after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct PluginsLs { /// List all available remote plugins /// Same as `mise plugins ls-remote` #[clap(short, long, hide = true, verbatim_doc_comment)] pub all: bool, /// The built-in plugins only /// Normally these are not shown #[clap(short, long, verbatim_doc_comment, conflicts_with = "all", hide = true)] pub core: bool, /// Show the git url for each plugin /// e.g.: https://github.com/asdf-vm/asdf-nodejs.git #[clap(short, long, alias = "url", verbatim_doc_comment)] pub urls: bool, /// Show the git refs for each plugin /// e.g.: main 1234abc #[clap(long, hide = true, verbatim_doc_comment)] pub refs: bool, /// List installed plugins #[clap(long, verbatim_doc_comment, conflicts_with = "all", hide = true)] pub user: bool, } impl PluginsLs { pub async fn run(self, config: &Config) -> Result<()> { let mut plugins: BTreeMap<_, _> = install_state::list_plugins() .iter() .map(|(k, p)| (k.clone(), (*p, None))) .collect(); if self.core { for p in CORE_PLUGINS.keys() { miseprintln!("{p}"); } return Ok(()); } if self.all { for (name, backends) in &config.shorthands { for full in backends { let plugin_type = PluginType::from_full(full)?; plugins.insert(name.clone(), (plugin_type, Some(full_to_url(full)))); } } } let plugins = plugins .into_iter() .map(|(short, (pt, url))| { let plugin = pt.plugin(short.clone()); if let Some(url) = url { plugin.set_remote_url(url); } (short, plugin) }) .collect::<BTreeMap<_, _>>(); if self.urls || self.refs { let data = plugins .into_iter() .map(|(name, p)| { let remote_url = p.get_remote_url().unwrap_or_else(|e| { warn!("{name}: {e:?}"); None }); let abbrev_ref = p.current_abbrev_ref().unwrap_or_else(|e| { warn!("{name}: {e:?}"); None }); let sha_short = p.current_sha_short().unwrap_or_else(|e| { warn!("{name}: {e:?}"); None }); let mut row = Row { plugin: name, url: remote_url.unwrap_or_default(), ref_: String::new(), sha: String::new(), }; if p.is_installed() { row.ref_ = abbrev_ref.unwrap_or_default(); row.sha = sha_short.unwrap_or_default(); } row }) .collect::<Vec<_>>(); let mut table = Table::new(data); table::default_style(&mut table, false); miseprintln!("{table}"); } else { hint!("registry", "see available plugins with", "mise registry"); for tool in plugins.values() { miseprintln!("{tool}"); } } Ok(()) } } #[derive(Tabled)] #[tabled(rename_all = "PascalCase")] struct Row { plugin: String, url: String, ref_: String, sha: String, } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise plugins ls</bold> node ruby $ <bold>mise plugins ls --urls</bold> node https://github.com/asdf-vm/asdf-nodejs.git ruby https://github.com/asdf-vm/asdf-ruby.git "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/update.rs
src/cli/plugins/update.rs
use std::sync::Arc; use console::style; use eyre::{Result, WrapErr, eyre}; use tokio::{sync::Semaphore, task::JoinSet}; use crate::config::Settings; use crate::plugins; use crate::toolset::install_state; use crate::ui::multi_progress_report::MultiProgressReport; /// Updates a plugin to the latest version /// /// note: this updates the plugin itself, not the runtime versions #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, visible_aliases = ["up", "upgrade"], after_long_help = AFTER_LONG_HELP)] pub struct Update { /// Plugin(s) to update #[clap()] plugin: Option<Vec<String>>, /// Number of jobs to run in parallel /// Default: 4 #[clap(long, short, verbatim_doc_comment)] jobs: Option<usize>, } impl Update { pub async fn run(self) -> Result<()> { let plugins: Vec<_> = match self.plugin { Some(plugins) => plugins .into_iter() .map(|p| match p.split_once('#') { Some((p, ref_)) => (p.to_string(), Some(ref_.to_string())), None => (p, None), }) .collect(), None => install_state::list_plugins() .keys() .map(|p| (p.clone(), None)) .collect::<Vec<_>>(), }; let settings = Settings::try_get()?; let mut jset: JoinSet<Result<()>> = JoinSet::new(); let semaphore = Arc::new(Semaphore::new(self.jobs.unwrap_or(settings.jobs))); for (short, ref_) in plugins { let permit = semaphore.clone().acquire_owned().await?; jset.spawn(async move { let _permit = permit; let plugin = plugins::get(&short)?; let prefix = format!("plugin:{}", style(plugin.name()).blue().for_stderr()); let mpr = MultiProgressReport::get(); let pr = mpr.add(&prefix); plugin .update(pr.as_ref(), ref_) .await .wrap_err_with(|| format!("[{plugin}] plugin update"))?; Ok(()) }); } while let Some(result) = jset.join_next().await { match result { Ok(Ok(())) => {} Ok(Err(e)) => { return Err(e); } Err(e) => { return Err(eyre!(e)); } } } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise plugins update</bold> # update all plugins $ <bold>mise plugins update node</bold> # update only node $ <bold>mise plugins update node#beta</bold> # specify a ref "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/ls_remote.rs
src/cli/plugins/ls_remote.rs
use console::{Alignment, measure_text_width, pad_str}; use eyre::Result; use itertools::Itertools; use crate::config::Config; use crate::toolset::install_state; /// List all available remote plugins #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["list-remote", "list-all"], long_about = LONG_ABOUT, verbatim_doc_comment)] pub struct PluginsLsRemote { /// Show the git url for each plugin /// e.g.: https://github.com/mise-plugins/mise-poetry.git #[clap(short, long)] pub urls: bool, /// Only show the name of each plugin /// by default it will show a "*" next to installed plugins #[clap(long)] pub only_names: bool, } impl PluginsLsRemote { pub async fn run(self, config: &Config) -> Result<()> { let installed_plugins = install_state::list_plugins(); let shorthands = config.shorthands.iter().sorted().collect_vec(); let max_plugin_len = shorthands .iter() .map(|(plugin, _)| measure_text_width(plugin)) .max() .unwrap_or(0); if shorthands.is_empty() { warn!("default shorthands are disabled"); } for (plugin, backends) in shorthands { for repo in backends { let installed = if !self.only_names && installed_plugins.contains_key(plugin.as_str()) { "*" } else { " " }; let url = if self.urls { repo } else { "" }; let plugin = pad_str(plugin, max_plugin_len, Alignment::Left, None); miseprintln!("{} {}{}", plugin, installed, url); } } Ok(()) } } const LONG_ABOUT: &str = r#" List all available remote plugins The full list is here: https://github.com/jdx/mise/blob/main/registry.toml Examples: $ mise plugins ls-remote "#;
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/install.rs
src/cli/plugins/install.rs
use std::sync::Arc; use color_eyre::eyre::{Result, bail, eyre}; use contracts::ensures; use heck::ToKebabCase; use tokio::{sync::Semaphore, task::JoinSet}; use url::Url; use crate::config::Config; use crate::dirs; use crate::plugins::Plugin; use crate::plugins::asdf_plugin::AsdfPlugin; use crate::plugins::core::CORE_PLUGINS; use crate::toolset::ToolsetBuilder; use crate::ui::multi_progress_report::MultiProgressReport; use crate::ui::style; use crate::{backend::unalias_backend, config::Settings}; /// Install a plugin /// /// note that mise automatically can install plugins when you install a tool /// e.g.: `mise install node@20` will autoinstall the node plugin /// /// This behavior can be modified in ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["i", "a", "add"], verbatim_doc_comment, after_long_help = AFTER_LONG_HELP )] pub struct PluginsInstall { /// The name of the plugin to install /// e.g.: node, ruby /// Can specify multiple plugins: `mise plugins install node ruby python` #[clap(required_unless_present = "all", verbatim_doc_comment)] new_plugin: Option<String>, /// The git url of the plugin /// e.g.: https://github.com/asdf-vm/asdf-nodejs.git #[clap(help = "The git url of the plugin", value_hint = clap::ValueHint::Url, verbatim_doc_comment )] git_url: Option<String>, #[clap(hide = true)] rest: Vec<String>, /// Install all missing plugins /// This will only install plugins that have matching shorthands. /// i.e.: they don't need the full git repo url #[clap(short, long, conflicts_with_all = ["new_plugin", "force"], verbatim_doc_comment)] all: bool, /// Reinstall even if plugin exists #[clap(short, long, verbatim_doc_comment)] force: bool, /// Number of jobs to run in parallel #[clap(long, short, verbatim_doc_comment)] jobs: Option<usize>, /// Show installation output #[clap(long, short, action = clap::ArgAction::Count, verbatim_doc_comment)] verbose: u8, } impl PluginsInstall { pub async fn run(self, config: &Arc<Config>) -> Result<()> { let this = Arc::new(self); if this.all { return this.install_all_missing_plugins(config).await; } let (name, git_url) = get_name_and_url(&this.new_plugin.clone().unwrap(), &this.git_url)?; if git_url.is_some() { this.install_one(config, name, git_url).await?; } else { let is_core = CORE_PLUGINS.contains_key(&name); if is_core { let name = style::eblue(name); bail!("{name} is a core plugin and does not need to be installed"); } let mut plugins: Vec<String> = vec![name]; if let Some(second) = this.git_url.clone() { plugins.push(second); }; plugins.extend(this.rest.clone()); this.install_many(config, plugins).await?; } Ok(()) } async fn install_all_missing_plugins(self: Arc<Self>, config: &Arc<Config>) -> Result<()> { let ts = ToolsetBuilder::new().build(config).await?; let missing_plugins = ts.list_missing_plugins(); if missing_plugins.is_empty() { warn!("all plugins already installed"); } self.install_many(config, missing_plugins).await?; Ok(()) } async fn install_many( self: Arc<Self>, config: &Arc<Config>, plugins: Vec<String>, ) -> Result<()> { let mut jset: JoinSet<Result<()>> = JoinSet::new(); let semaphore = Arc::new(Semaphore::new(self.jobs.unwrap_or(Settings::get().jobs))); for plugin in plugins { let this = self.clone(); let config = config.clone(); let permit = semaphore.clone().acquire_owned().await?; jset.spawn(async move { let _permit = permit; println!("installing {plugin}"); this.install_one(&config, plugin, None).await }); } while let Some(result) = jset.join_next().await { match result { Ok(Ok(())) => {} Ok(Err(e)) => { return Err(e); } Err(e) => { return Err(eyre!(e)); } } } Ok(()) } async fn install_one( self: Arc<Self>, config: &Arc<Config>, name: String, git_url: Option<String>, ) -> Result<()> { let path = dirs::PLUGINS.join(name.to_kebab_case()); let plugin = AsdfPlugin::new(name.clone(), path); if let Some(url) = git_url { plugin.set_remote_url(url); } if !self.force && plugin.is_installed() { warn!("Plugin {name} already installed"); warn!("Use --force to install anyway"); } else { let mpr = MultiProgressReport::get(); plugin .ensure_installed(config, &mpr, self.force, false) .await?; } Ok(()) } } #[ensures(!ret.as_ref().is_ok_and(|(r, _)| r.is_empty()), "plugin name is empty")] fn get_name_and_url(name: &str, git_url: &Option<String>) -> Result<(String, Option<String>)> { let name = unalias_backend(name); Ok(match git_url { Some(url) => match url.contains(':') { true => (name.to_string(), Some(url.clone())), false => (name.to_string(), None), }, None => match name.contains(':') { true => (get_name_from_url(name)?, Some(name.to_string())), false => (name.to_string(), None), }, }) } fn get_name_from_url(url: &str) -> Result<String> { let url = url.strip_prefix("git@").unwrap_or(url); let url = url.strip_suffix(".git").unwrap_or(url); let url = url.strip_suffix("/").unwrap_or(url); let name = if let Ok(Some(name)) = Url::parse(url).map(|u| { u.path_segments() .and_then(|mut s| s.next_back().map(|s| s.to_string())) }) { name } else if let Some(name) = url.split('/').next_back().map(|s| s.to_string()) { name } else { return Err(eyre!("could not infer plugin name from url: {}", url)); }; let name = name.strip_prefix("asdf-").unwrap_or(&name); let name = name.strip_prefix("rtx-").unwrap_or(name); let name = name.strip_prefix("mise-").unwrap_or(name); Ok(unalias_backend(name).to_string()) } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> # install the poetry via shorthand $ <bold>mise plugins install poetry</bold> # install the poetry plugin using a specific git url $ <bold>mise plugins install poetry https://github.com/mise-plugins/mise-poetry.git</bold> # install the poetry plugin using the git url only # (poetry is inferred from the url) $ <bold>mise plugins install https://github.com/mise-plugins/mise-poetry.git</bold> # install the poetry plugin using a specific ref $ <bold>mise plugins install poetry https://github.com/mise-plugins/mise-poetry.git#11d0c1e</bold> "# ); #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_str_eq; #[test] fn test_get_name_from_url() { let get_name = |url| get_name_from_url(url).unwrap(); assert_str_eq!(get_name("nodejs"), "node"); assert_str_eq!( get_name("https://github.com/mise-plugins/mise-nodejs.git"), "node" ); assert_str_eq!( get_name("https://github.com/mise-plugins/asdf-nodejs.git"), "node" ); assert_str_eq!( get_name("https://github.com/mise-plugins/asdf-nodejs/"), "node" ); assert_str_eq!( get_name("git@github.com:mise-plugins/asdf-nodejs.git"), "node" ); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/plugins/mod.rs
src/cli/plugins/mod.rs
use std::sync::Arc; use clap::Subcommand; use eyre::Result; use crate::config::Config; mod install; mod link; mod ls; mod ls_remote; mod uninstall; mod update; #[derive(Debug, clap::Args)] #[clap(about = "Manage plugins", visible_alias = "p", aliases = ["plugin", "plugin-list"])] pub struct Plugins { #[clap(subcommand)] command: Option<Commands>, /// list all available remote plugins /// /// same as `mise plugins ls-remote` #[clap(short, long, hide = true)] pub all: bool, /// The built-in plugins only /// Normally these are not shown #[clap(short, long, verbatim_doc_comment, conflicts_with = "all")] pub core: bool, /// Show the git url for each plugin /// e.g.: https://github.com/asdf-vm/asdf-nodejs.git #[clap(short, long, alias = "url", verbatim_doc_comment)] pub urls: bool, /// Show the git refs for each plugin /// e.g.: main 1234abc #[clap(long, hide = true, verbatim_doc_comment)] pub refs: bool, /// List installed plugins /// /// This is the default behavior but can be used with --core /// to show core and user plugins #[clap(long, verbatim_doc_comment, conflicts_with = "all")] pub user: bool, } #[derive(Debug, Subcommand)] enum Commands { Install(install::PluginsInstall), Link(link::PluginsLink), Ls(ls::PluginsLs), LsRemote(ls_remote::PluginsLsRemote), Uninstall(uninstall::PluginsUninstall), Update(update::Update), } impl Commands { pub async fn run(self, config: &Arc<Config>) -> Result<()> { match self { Self::Install(cmd) => cmd.run(config).await, Self::Link(cmd) => cmd.run().await, Self::Ls(cmd) => cmd.run(config).await, Self::LsRemote(cmd) => cmd.run(config).await, Self::Uninstall(cmd) => cmd.run().await, Self::Update(cmd) => cmd.run().await, } } } impl Plugins { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let cmd = self.command.unwrap_or(Commands::Ls(ls::PluginsLs { all: self.all, core: self.core, refs: self.refs, urls: self.urls, user: self.user, })); cmd.run(&config).await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/backends/ls.rs
src/cli/backends/ls.rs
use crate::backend::backend_type::BackendType; use eyre::Result; use strum::IntoEnumIterator; /// List built-in backends #[derive(Debug, clap::Args)] #[clap(visible_alias = "list", after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct BackendsLs {} impl BackendsLs { pub fn run(self) -> Result<()> { let mut backends = BackendType::iter().collect::<Vec<BackendType>>(); backends.retain(|f| !matches!(f, BackendType::Unknown)); for backend in backends { miseprintln!("{}", backend); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise backends ls</bold> aqua asdf cargo core dotnet gem go npm pipx spm ubi vfox "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/backends/mod.rs
src/cli/backends/mod.rs
use clap::Subcommand; use eyre::Result; mod ls; #[derive(Debug, clap::Args)] #[clap(about = "Manage backends", visible_alias = "b", aliases = ["backend", "backend-list"])] pub struct Backends { #[clap(subcommand)] command: Option<Commands>, } #[derive(Debug, Subcommand)] enum Commands { Ls(ls::BackendsLs), } impl Commands { pub fn run(self) -> Result<()> { match self { Self::Ls(cmd) => cmd.run(), } } } impl Backends { pub async fn run(self) -> Result<()> { let cmd = self.command.unwrap_or(Commands::Ls(ls::BackendsLs {})); cmd.run() } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/config/ls.rs
src/cli/config/ls.rs
use crate::config::Config; use crate::config::config_file::ConfigFile; use crate::config::tracking::Tracker; use crate::file::display_path; use crate::ui::table::MiseTable; use comfy_table::{Attribute, Cell}; use eyre::Result; use itertools::Itertools; /// List config files currently in use #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct ConfigLs { /// Output in JSON format #[clap(short = 'J', long, verbatim_doc_comment)] pub json: bool, /// Do not print table header #[clap(long, alias = "no-headers", verbatim_doc_comment)] pub no_header: bool, /// List all tracked config files #[clap(long, verbatim_doc_comment)] pub tracked_configs: bool, } impl ConfigLs { pub async fn run(self) -> Result<()> { if self.tracked_configs { self.display_tracked_configs().await?; } else if self.json { self.display_json().await?; } else { self.display().await?; } Ok(()) } async fn display(&self) -> Result<()> { let config = Config::get().await?; let configs = config .config_files .values() .rev() .map(|cf| cf.as_ref()) .collect_vec(); let mut table = MiseTable::new(self.no_header, &["Path", "Tools"]); for cfg in configs { let ts = cfg.to_tool_request_set().unwrap(); let tools = ts.list_tools().into_iter().join(", "); let tools = if tools.is_empty() { Cell::new("(none)") .add_attribute(Attribute::Italic) .add_attribute(Attribute::Dim) } else { Cell::new(tools).add_attribute(Attribute::Dim) }; table.add_row(vec![Cell::new(display_path(cfg.get_path())), tools]); } table.truncate(true).print() } async fn display_json(&self) -> Result<()> { let array_items = Config::get() .await? .config_files .values() .map(|cf| { let c: &dyn ConfigFile = cf.as_ref(); let mut item = serde_json::Map::new(); item.insert( "path".to_string(), serde_json::Value::String(c.get_path().to_string_lossy().to_string()), ); let plugins = c .to_tool_request_set() .unwrap() .list_tools() .into_iter() .map(|s| serde_json::Value::String(s.to_string())) .collect::<Vec<serde_json::Value>>(); item.insert("tools".to_string(), serde_json::Value::Array(plugins)); item }) .collect::<serde_json::Value>(); miseprintln!("{}", serde_json::to_string_pretty(&array_items)?); Ok(()) } async fn display_tracked_configs(&self) -> Result<()> { let tracked_configs = Tracker::list_all()?.into_iter().unique().sorted(); for path in tracked_configs { println!("{}", path.display()); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise config ls</bold> Path Tools ~/.config/mise/config.toml pitchfork ~/src/mise/mise.toml actionlint, bun, cargo-binstall, cargo:cargo-edit, cargo:cargo-insta "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/config/mod.rs
src/cli/config/mod.rs
use clap::Subcommand; use eyre::Result; pub(crate) mod generate; mod get; mod ls; mod set; /// Manage config files #[derive(Debug, clap::Args)] #[clap(visible_alias = "cfg", alias = "toml")] pub struct Config { #[clap(subcommand)] command: Option<Commands>, #[clap(flatten)] pub ls: ls::ConfigLs, } #[derive(Debug, Subcommand)] enum Commands { Generate(generate::ConfigGenerate), Get(get::ConfigGet), #[clap(visible_alias = "list")] Ls(ls::ConfigLs), Set(set::ConfigSet), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Generate(cmd) => cmd.run().await, Self::Get(cmd) => cmd.run(), Self::Ls(cmd) => cmd.run().await, Self::Set(cmd) => cmd.run(), } } } impl Config { pub async fn run(self) -> Result<()> { let cmd = self.command.unwrap_or(Commands::Ls(self.ls)); cmd.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/config/generate.rs
src/cli/config/generate.rs
use std::path::{Path, PathBuf}; use clap::ValueHint; use eyre::Result; use crate::config::config_file; use crate::file::display_path; use crate::{env, file}; /// Generate a mise.toml file #[derive(Debug, clap::Args)] #[clap(visible_alias = "g", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct ConfigGenerate { /// Output to file instead of stdout #[clap(long, short, verbatim_doc_comment, value_hint = ValueHint::FilePath)] output: Option<PathBuf>, /// Path to a .tool-versions file to import tools from #[clap(long, short, verbatim_doc_comment, value_hint = ValueHint::FilePath)] tool_versions: Option<PathBuf>, } impl ConfigGenerate { pub async fn run(self) -> Result<()> { let doc = if let Some(tool_versions) = &self.tool_versions { self.tool_versions(tool_versions).await? } else { self.default() }; if let Some(output) = &self.output { info!("writing to {}", display_path(output)); file::write(output, doc)?; } else { miseprintln!("{doc}"); } Ok(()) } async fn tool_versions(&self, tool_versions: &Path) -> Result<String> { let to = config_file::parse_or_init(&PathBuf::from(&*env::MISE_DEFAULT_CONFIG_FILENAME)).await?; let from = config_file::parse(tool_versions).await?; let tools = from.to_tool_request_set()?.tools; for (ba, tools) in tools { to.replace_versions(&ba, tools)?; } to.dump() } fn default(&self) -> String { r#" # # mise config files are hierarchical. mise will find all of the config files # # in all parent directories and merge them together. # # You might have a structure like: # # * ~/work/project/mise.toml # a config file for a specific work project # * ~/work/mise.toml # a config file for projects related to work # * ~/.config/mise/config.toml # the global config file # * /etc/mise/config.toml # the system config file # # # This setup allows you to define default versions and configuration across # # all projects but override them for specific projects. # # # set arbitrary env vars to be used whenever in this project or subprojects # [env] # NODE_ENV = "development" # NPM_CONFIG_PREFIX = "~/.npm-global" # EDITOR = "code --wait" # # mise.file = ".env" # load vars from a dotenv file # mise.path = "./node_modules/.bin" # add a directory to PATH # # [tools] # terraform = '1.0.0' # specify a single version # erlang = '26' # specify a major version only # node = 'ref:master' # build from a git ref # node = 'path:~/.nodes/14' # BYO – specify a non-mise managed installation # # # newest with this prefix (typically exact matches don't use the prefix) # go = 'prefix:1.16' # # # multiple versions will all go into PATH in the order specified # # this is helpful for making `python311` and `python310` available # # even when `python` and `python3` point to a different version # python = ['3.12', '3.11', '3.10'] # # # some plugins can take options like python's virtualenv activation # # with these, mise will automatically setup and activate vevs when entering # # the project directory # python = {version='3.12', virtualenv='.venv'} # poetry = {version='1.7.1', pyproject='pyproject.toml'} # # [plugins] # # specify a custom repo url so you can install with `mise plugin add <name>` # # note this will only be used if the plugin is not already installed # python = 'https://github.com/asdf-community/asdf-python' # # [alias.node.versions] # # setup a custom alias so you can run `mise use -g node@work` for node-16.x # work = '16' "# .to_string() } } // TODO: fill this out pub static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise cf generate > mise.toml</bold> $ <bold>mise cf generate --output=mise.toml</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/config/set.rs
src/cli/config/set.rs
use crate::config::config_file::mise_toml::MiseToml; use crate::config::settings::{SETTINGS_META, SettingsType}; use crate::config::top_toml_config; use crate::toml::dedup_toml_array; use clap::ValueEnum; use eyre::bail; use std::path::PathBuf; /// Set the value of a setting in a mise.toml file #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ConfigSet { /// The path of the config to display pub key: String, /// The value to set the key to pub value: String, /// The path to the mise.toml file to edit /// /// If not provided, the nearest mise.toml file will be used #[clap(short, long)] pub file: Option<PathBuf>, #[clap(value_enum, short, long, default_value_t)] pub type_: TomlValueTypes, } #[derive(ValueEnum, Default, Clone, Debug)] pub enum TomlValueTypes { #[default] Infer, #[value()] String, #[value()] Integer, #[value()] Float, #[value()] Bool, #[value()] List, #[value()] Set, } impl ConfigSet { pub fn run(self) -> eyre::Result<()> { let mut file = self.file; if file.is_none() { file = top_toml_config(); } let Some(file) = file else { bail!("No mise.toml file found"); }; let mut config: toml_edit::DocumentMut = std::fs::read_to_string(&file)?.parse()?; let mut container = config.as_item_mut(); let parts = self.key.split('.').collect::<Vec<&str>>(); let last_key = parts.last().unwrap(); for (idx, key) in parts.iter().take(parts.len() - 1).enumerate() { container = container .as_table_like_mut() .unwrap() .entry(key) .or_insert({ let mut t = toml_edit::Table::new(); t.set_implicit(true); toml_edit::Item::Table(t) }); // if the key is a tool with a simple value, we want to convert it to a inline table preserving the version let is_simple_tool_version = self.key.starts_with("tools.") && idx == 1 && !container.is_table_like(); if is_simple_tool_version { let mut inline_table = toml_edit::InlineTable::new(); inline_table.insert("version", container.as_value().unwrap().clone()); *container = toml_edit::Item::Value(toml_edit::Value::InlineTable(inline_table)); } } let type_to_use = match self.type_ { TomlValueTypes::Infer => { let expected_type = if !self.key.starts_with("settings.") { None } else { SETTINGS_META.get(*last_key) }; match expected_type { Some(meta) => match meta.type_ { SettingsType::Bool => TomlValueTypes::Bool, SettingsType::String => TomlValueTypes::String, SettingsType::Integer => TomlValueTypes::Integer, SettingsType::Duration => TomlValueTypes::String, SettingsType::Path => TomlValueTypes::String, SettingsType::Url => TomlValueTypes::String, SettingsType::ListString => TomlValueTypes::List, SettingsType::ListPath => TomlValueTypes::List, SettingsType::SetString => TomlValueTypes::Set, SettingsType::IndexMap => TomlValueTypes::String, }, None => match self.value.as_str() { "true" | "false" => TomlValueTypes::Bool, _ => TomlValueTypes::String, }, } } _ => self.type_, }; let value = match type_to_use { TomlValueTypes::String => toml_edit::value(self.value), TomlValueTypes::Integer => toml_edit::value(self.value.parse::<i64>()?), TomlValueTypes::Float => toml_edit::value(self.value.parse::<f64>()?), TomlValueTypes::Bool => toml_edit::value(self.value.parse::<bool>()?), TomlValueTypes::List => { let mut list = toml_edit::Array::new(); for item in self.value.split(',').map(|s| s.trim()) { list.push(item); } toml_edit::Item::Value(toml_edit::Value::Array(list)) } TomlValueTypes::Set => { let set = toml_edit::Array::new(); toml_edit::Item::Value(toml_edit::Value::Array(dedup_toml_array(&set))) } TomlValueTypes::Infer => bail!("Type not found"), }; let mut t = toml_edit::Table::new(); t.set_implicit(true); let mut table = toml_edit::Item::Table(t); container .as_table_like_mut() .unwrap_or_else(|| table.as_table_like_mut().unwrap()) .insert(last_key, value); let raw = config.to_string(); MiseToml::from_str(&raw, &file)?; std::fs::write(&file, raw)?; Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise config set tools.python 3.12</bold> $ <bold>mise config set settings.always_keep_download true</bold> $ <bold>mise config set env.TEST_ENV_VAR ABC</bold> $ <bold>mise config set settings.disable_tools --type list node,rust</bold> # Type for `settings` is inferred $ <bold>mise config set settings.jobs 4</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/config/get.rs
src/cli/config/get.rs
use crate::config::top_toml_config; use crate::file::display_path; use eyre::bail; use std::path::PathBuf; /// Display the value of a setting in a mise.toml file #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ConfigGet { /// The path of the config to display pub key: Option<String>, /// The path to the mise.toml file to edit /// /// If not provided, the nearest mise.toml file will be used #[clap(short, long)] pub file: Option<PathBuf>, } impl ConfigGet { pub fn run(self) -> eyre::Result<()> { let mut file = self.file; if file.is_none() { file = top_toml_config(); } if let Some(file) = file { let config: toml::Value = std::fs::read_to_string(&file)?.parse()?; let mut value = &config; if let Some(key) = &self.key { for k in key.split('.') { value = value.get(k).ok_or_else(|| { eyre::eyre!("Key not found: {} in {}", key, display_path(&file)) })?; } } match value { toml::Value::String(s) => miseprintln!("{}", s), toml::Value::Integer(i) => miseprintln!("{}", i), toml::Value::Boolean(b) => miseprintln!("{}", b), toml::Value::Float(f) => miseprintln!("{}", f), toml::Value::Datetime(d) => miseprintln!("{}", d), toml::Value::Array(a) => { // seems that the toml crate does not have a way to serialize an array directly? // workaround which only handle non-nested arrays let elements: Vec<String> = a .iter() .map(|v| match v { toml::Value::String(s) => format!("\"{s}\""), toml::Value::Integer(i) => i.to_string(), toml::Value::Boolean(b) => b.to_string(), toml::Value::Float(f) => f.to_string(), toml::Value::Datetime(d) => d.to_string(), toml::Value::Array(_) => "[...]".to_string(), toml::Value::Table(_) => "{...}".to_string(), }) .collect(); miseprintln!("[{}]", elements.join(", ")); } toml::Value::Table(t) => { miseprintln!("{}", toml::to_string(t)?); } } } else { bail!("No mise.toml file found"); } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise toml get tools.python</bold> 3.12 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_alias/ls.rs
src/cli/tool_alias/ls.rs
use eyre::Result; use itertools::Itertools; use tabled::Tabled; use crate::cli::args::BackendArg; use crate::config::Config; use crate::ui::table; /// List tool version aliases /// Shows the aliases that can be specified. /// These can come from user config or from plugins in `bin/list-aliases`. /// /// For user config, aliases are defined like the following in `~/.config/mise/config.toml`: /// /// [tool_alias.node.versions] /// lts = "22.0.0" #[derive(Debug, clap::Args)] #[clap(visible_alias = "list", after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ToolAliasLs { /// Show aliases for <TOOL> #[clap()] pub tool: Option<BackendArg>, /// Don't show table header #[clap(long)] pub no_header: bool, } impl ToolAliasLs { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let rows = config .all_aliases .iter() .filter(|(short, _)| { self.tool.is_none() || self.tool.as_ref().is_some_and(|f| &f.short == *short) }) .sorted_by(|(a, _), (b, _)| a.cmp(b)) .flat_map(|(short, aliases)| { aliases .versions .iter() .filter(|(from, _to)| short != "node" || !from.starts_with("lts/")) .map(|(from, to)| Row { tool: short.clone(), alias: from.clone(), version: to.clone(), }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); let mut table = tabled::Table::new(rows); table::default_style(&mut table, self.no_header); miseprintln!("{table}"); Ok(()) } } #[derive(Tabled)] struct Row { tool: String, alias: String, version: String, } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tool-alias ls</bold> node lts-jod 22 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_alias/mod.rs
src/cli/tool_alias/mod.rs
use clap::Subcommand; use eyre::Result; use crate::cli::args::BackendArg; mod get; mod ls; mod set; mod unset; #[derive(Debug, clap::Args)] #[clap( name = "tool-alias", about = "Manage tool version aliases.", alias = "alias", alias = "aliases" )] pub struct ToolAlias { #[clap(subcommand)] command: Option<Commands>, /// filter aliases by plugin #[clap(short, long)] pub plugin: Option<BackendArg>, /// Don't show table header #[clap(long)] pub no_header: bool, } #[derive(Debug, Subcommand)] enum Commands { Get(get::ToolAliasGet), Ls(ls::ToolAliasLs), Set(set::ToolAliasSet), Unset(unset::ToolAliasUnset), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Get(cmd) => cmd.run().await, Self::Ls(cmd) => cmd.run().await, Self::Set(cmd) => cmd.run().await, Self::Unset(cmd) => cmd.run().await, } } } impl ToolAlias { pub async fn run(self) -> Result<()> { let cmd = self.command.unwrap_or(Commands::Ls(ls::ToolAliasLs { tool: self.plugin, no_header: self.no_header, })); cmd.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_alias/unset.rs
src/cli/tool_alias/unset.rs
use eyre::Result; use crate::cli::args::BackendArg; use crate::config::Config; use crate::config::config_file::ConfigFile; /// Clears an alias for a backend/plugin /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["rm", "remove", "delete", "del"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ToolAliasUnset { /// The backend/plugin to remove the alias from pub plugin: BackendArg, /// The alias to remove pub alias: Option<String>, } impl ToolAliasUnset { pub async fn run(self) -> Result<()> { let mut global_config = Config::get().await?.global_config()?; match self.alias { None => { global_config.remove_backend_alias(&self.plugin)?; } Some(ref alias) => { global_config.remove_alias(&self.plugin, alias)?; } } global_config.save() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tool-alias unset maven</bold> $ <bold>mise tool-alias unset node lts-jod</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_alias/set.rs
src/cli/tool_alias/set.rs
use eyre::Result; use crate::cli::args::BackendArg; use crate::config::Config; use crate::config::config_file::ConfigFile; /// Add/update an alias for a backend/plugin /// /// This modifies the contents of ~/.config/mise/config.toml #[derive(Debug, clap::Args)] #[clap(visible_aliases = ["add", "create"], after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ToolAliasSet { /// The backend/plugin to set the alias for pub plugin: BackendArg, /// The alias to set pub alias: String, /// The value to set the alias to pub value: Option<String>, } impl ToolAliasSet { pub async fn run(self) -> Result<()> { let mut global_config = Config::get().await?.global_config()?; match &self.value { None => global_config.set_backend_alias(&self.plugin, &self.alias)?, Some(val) => global_config.set_alias(&self.plugin, &self.alias, val)?, } global_config.save() } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tool-alias set maven asdf:mise-plugins/mise-maven</bold> $ <bold>mise tool-alias set node lts-jod 22.0.0</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/tool_alias/get.rs
src/cli/tool_alias/get.rs
use color_eyre::eyre::{Result, eyre}; use crate::cli::args::BackendArg; use crate::config::Config; /// Show an alias for a plugin /// /// This is the contents of a tool_alias.<PLUGIN> entry in ~/.config/mise/config.toml /// #[derive(Debug, clap::Args)] #[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)] pub struct ToolAliasGet { /// The plugin to show the alias for pub plugin: BackendArg, /// The alias to show pub alias: String, } impl ToolAliasGet { pub async fn run(self) -> Result<()> { let config = Config::get().await?; match config.all_aliases.get(&self.plugin.short) { Some(alias) => match alias.versions.get(&self.alias) { Some(alias) => { miseprintln!("{alias}"); Ok(()) } None => Err(eyre!("Unknown alias: {}", &self.alias)), }, None => Err(eyre!("Unknown plugin: {}", &self.plugin)), } } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise tool-alias get node lts-hydrogen</bold> 20.0.0 "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/direnv/envrc.rs
src/cli/direnv/envrc.rs
use std::io::Write; use std::{fs::File, sync::Arc}; use eyre::Result; use xx::file; use crate::config::Config; use crate::env; use crate::env::PATH_KEY; use crate::hash::hash_to_str; use crate::toolset::ToolsetBuilder; /// [internal] This is an internal command that writes an envrc file /// for direnv to consume. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, hide = true)] pub struct Envrc {} impl Envrc { pub async fn run(self, config: &Arc<Config>) -> Result<()> { let ts = ToolsetBuilder::new().build(config).await?; let envrc_path = env::MISE_TMP_DIR .join("direnv") .join(hash_to_str(&env::current_dir()?) + ".envrc"); // TODO: exit early if envrc_path exists and is up to date file::mkdirp(envrc_path.parent().unwrap())?; let mut file = File::create(&envrc_path)?; writeln!( file, "### Do not edit. This was autogenerated by 'asdf direnv envrc' ###" )?; for cf in config.config_files.keys() { writeln!(file, "watch_file {}", cf.to_string_lossy())?; } let (env, env_results) = ts.final_env(config).await?; for (k, v) in env { if k == *PATH_KEY { writeln!(file, "PATH_add {v}")?; } else { writeln!( file, "export {}={}", shell_escape::unix::escape(k.into()), shell_escape::unix::escape(v.into()), )?; } } for path in ts .list_final_paths(config, env_results) .await? .into_iter() .rev() { writeln!(file, "PATH_add {}", path.to_string_lossy())?; } miseprintln!("{}", envrc_path.to_string_lossy()); Ok(()) } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/direnv/mod.rs
src/cli/direnv/mod.rs
use std::sync::Arc; use clap::Subcommand; use eyre::Result; use crate::config::Config; mod activate; mod envrc; mod exec; /// Output direnv function to use mise inside direnv /// /// See https://mise.jdx.dev/direnv.html for more information /// /// Because this generates the idiomatic files based on currently installed plugins, /// you should run this command after installing new plugins. Otherwise /// direnv may not know to update environment variables when idiomatic file versions change. #[derive(Debug, clap::Args)] #[clap(hide = true, verbatim_doc_comment)] pub struct Direnv { #[clap(subcommand)] command: Option<Commands>, } #[derive(Debug, Subcommand)] enum Commands { Activate(activate::DirenvActivate), Envrc(envrc::Envrc), Exec(exec::DirenvExec), } impl Commands { pub async fn run(self, config: &Arc<Config>) -> Result<()> { match self { Self::Activate(cmd) => cmd.run().await, Self::Envrc(cmd) => cmd.run(config).await, Self::Exec(cmd) => cmd.run(config).await, } } } impl Direnv { pub async fn run(self) -> Result<()> { let config = Config::get().await?; let cmd = self .command .unwrap_or(Commands::Activate(activate::DirenvActivate {})); cmd.run(&config).await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/direnv/activate.rs
src/cli/direnv/activate.rs
use eyre::Result; use indoc::indoc; /// Output direnv function to use mise inside direnv /// /// See https://mise.jdx.dev/direnv.html for more information /// /// Because this generates the idiomatic files based on currently installed plugins, /// you should run this command after installing new plugins. Otherwise /// direnv may not know to update environment variables when idiomatic file versions change. #[derive(Debug, clap::Args)] #[clap(hide=true, verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct DirenvActivate {} impl DirenvActivate { pub async fn run(self) -> Result<()> { miseprintln!( // source_env "$(mise direnv envrc "$@")" indoc! {r#" ### Do not edit. This was autogenerated by 'mise direnv' ### use_mise() {{ direnv_load mise direnv exec }} "#} ); Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>mise direnv activate > ~/.config/direnv/lib/use_mise.sh</bold> $ <bold>echo 'use mise' > .envrc</bold> $ <bold>direnv allow</bold> "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/direnv/exec.rs
src/cli/direnv/exec.rs
use std::sync::Arc; use duct::Expression; use eyre::{Result, WrapErr}; use serde_derive::Deserialize; use crate::config::Config; use crate::toolset::ToolsetBuilder; /// [internal] This is an internal command that writes an envrc file /// for direnv to consume. #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, hide = true)] pub struct DirenvExec {} #[derive(Debug, Default, Deserialize)] struct DirenvWatches { #[serde(rename(deserialize = "DIRENV_WATCHES"))] watches: String, } impl DirenvExec { pub async fn run(self, config: &Arc<Config>) -> Result<()> { let ts = ToolsetBuilder::new().build(config).await?; let mut cmd = env_cmd(); for (k, v) in ts.env_with_path(config).await? { cmd = cmd.env(k, v); } let json = cmd!("direnv", "watch", "json", ".tool-versions") .read() .wrap_err("error running direnv watch")?; let w: DirenvWatches = serde_json::from_str(&json)?; cmd = cmd.env("DIRENV_WATCHES", w.watches); miseprint!("{}", cmd.read()?)?; Ok(()) } } #[cfg(test)] fn env_cmd() -> Expression { cmd!("env") } #[cfg(not(test))] fn env_cmd() -> Expression { cmd!("direnv", "dump") }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/sync/ruby.rs
src/cli/sync/ruby.rs
use std::path::PathBuf; use eyre::Result; use itertools::sorted; use crate::{ backend, config::{self, Config}, dirs, file, }; /// Symlinks all ruby tool versions from an external tool into mise #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct SyncRuby { #[clap(flatten)] _type: SyncRubyType, } #[derive(Debug, clap::Args)] #[group(required = true, multiple = true)] pub struct SyncRubyType { /// Get tool versions from Homebrew #[clap(long)] brew: bool, } impl SyncRuby { pub async fn run(self) -> Result<()> { if self._type.brew { self.run_brew().await?; } let config = Config::reset().await?; let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?; Ok(()) } async fn run_brew(&self) -> Result<()> { let ruby = backend::get(&"ruby".into()).unwrap(); let brew_prefix = PathBuf::from(cmd!("brew", "--prefix").read()?).join("opt"); let installed_versions_path = dirs::INSTALLS.join("ruby"); file::remove_symlinks_with_target_prefix(&installed_versions_path, &brew_prefix)?; let subdirs = file::dir_subdirs(&brew_prefix)?; for entry in sorted(subdirs) { if entry.starts_with(".") { continue; } if !entry.starts_with("ruby@") { continue; } let v = entry.trim_start_matches("ruby@"); if ruby.create_symlink(v, &brew_prefix.join(&entry))?.is_some() { miseprintln!("Synced ruby@{} from Homebrew", v); } } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>brew install ruby</bold> $ <bold>mise sync ruby --brew</bold> $ <bold>mise use -g ruby</bold> - Use the latest version of Ruby installed by Homebrew "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/sync/node.rs
src/cli/sync/node.rs
use std::path::PathBuf; use eyre::Result; use itertools::sorted; use crate::{backend, config, dirs, file}; use crate::{ config::Config, env::{NODENV_ROOT, NVM_DIR}, }; /// Symlinks all tool versions from an external tool into mise /// /// For example, use this to import all Homebrew node installs into mise /// /// This won't overwrite any existing installs but will overwrite any existing symlinks #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct SyncNode { #[clap(flatten)] _type: SyncNodeType, } #[derive(Debug, clap::Args)] #[group(required = true, multiple = true)] pub struct SyncNodeType { /// Get tool versions from Homebrew #[clap(long)] brew: bool, /// Get tool versions from nodenv #[clap(long)] nodenv: bool, /// Get tool versions from nvm #[clap(long)] nvm: bool, } impl SyncNode { pub async fn run(self) -> Result<()> { if self._type.brew { self.run_brew().await?; } if self._type.nvm { self.run_nvm().await?; } if self._type.nodenv { self.run_nodenv().await?; } let config = Config::reset().await?; let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?; Ok(()) } async fn run_brew(&self) -> Result<()> { let node = backend::get(&"node".into()).unwrap(); let brew_prefix = PathBuf::from(cmd!("brew", "--prefix").read()?).join("opt"); let installed_versions_path = dirs::INSTALLS.join("node"); file::remove_symlinks_with_target_prefix(&installed_versions_path, &brew_prefix)?; let subdirs = file::dir_subdirs(&brew_prefix)?; for entry in sorted(subdirs) { if entry.starts_with(".") { continue; } if !entry.starts_with("node@") { continue; } let v = entry.trim_start_matches("node@"); if node.create_symlink(v, &brew_prefix.join(&entry))?.is_some() { miseprintln!("Synced node@{} from Homebrew", v); } } Ok(()) } async fn run_nvm(&self) -> Result<()> { let node = backend::get(&"node".into()).unwrap(); let nvm_versions_path = NVM_DIR.join("versions").join("node"); let installed_versions_path = dirs::INSTALLS.join("node"); let removed = file::remove_symlinks_with_target_prefix(&installed_versions_path, &nvm_versions_path)?; if !removed.is_empty() { debug!("Removed symlinks: {removed:?}"); } let mut created = vec![]; let subdirs = file::dir_subdirs(&nvm_versions_path)?; for entry in sorted(subdirs) { if entry.starts_with(".") { continue; } let v = entry.trim_start_matches('v'); let symlink = node.create_symlink(v, &nvm_versions_path.join(&entry))?; if let Some(symlink) = symlink { created.push(symlink); miseprintln!("Synced node@{} from nvm", v); } else { info!("Skipping node@{v} from nvm because it already exists in mise"); } } if !created.is_empty() { debug!("Created symlinks: {created:?}"); } Ok(()) } async fn run_nodenv(&self) -> Result<()> { let node = backend::get(&"node".into()).unwrap(); let nodenv_versions_path = NODENV_ROOT.join("versions"); let installed_versions_path = dirs::INSTALLS.join("node"); file::remove_symlinks_with_target_prefix(&installed_versions_path, &nodenv_versions_path)?; let subdirs = file::dir_subdirs(&nodenv_versions_path)?; for v in sorted(subdirs) { if v.starts_with(".") { continue; } if node .create_symlink(&v, &nodenv_versions_path.join(&v))? .is_some() { miseprintln!("Synced node@{} from nodenv", v); } } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>brew install node@18 node@20</bold> $ <bold>mise sync node --brew</bold> $ <bold>mise use -g node@18</bold> - uses Homebrew-provided node "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/sync/python.rs
src/cli/sync/python.rs
use eyre::Result; use itertools::sorted; use std::env::consts::{ARCH, OS}; use crate::{backend, config, dirs, env, file}; use crate::{config::Config, env::PYENV_ROOT}; /// Symlinks all tool versions from an external tool into mise /// /// For example, use this to import all pyenv installs into mise /// /// This won't overwrite any existing installs but will overwrite any existing symlinks #[derive(Debug, clap::Args)] #[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)] pub struct SyncPython { /// Get tool versions from pyenv #[clap(long)] pyenv: bool, /// Sync tool versions with uv (2-way sync) #[clap(long)] uv: bool, } impl SyncPython { pub async fn run(self) -> Result<()> { if self.pyenv { self.pyenv().await?; } if self.uv { self.uv().await?; } let config = Config::get().await?; let ts = config.get_toolset().await?; config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?; Ok(()) } async fn pyenv(&self) -> Result<()> { let python = backend::get(&"python".into()).unwrap(); let pyenv_versions_path = PYENV_ROOT.join("versions"); let installed_python_versions_path = dirs::INSTALLS.join("python"); file::remove_symlinks_with_target_prefix( &installed_python_versions_path, &pyenv_versions_path, )?; let subdirs = file::dir_subdirs(&pyenv_versions_path)?; for v in sorted(subdirs) { if v.starts_with(".") { continue; } python.create_symlink(&v, &pyenv_versions_path.join(&v))?; miseprintln!("Synced python@{} from pyenv", v); } Ok(()) } async fn uv(&self) -> Result<()> { let python = backend::get(&"python".into()).unwrap(); let uv_versions_path = &*env::UV_PYTHON_INSTALL_DIR; let installed_python_versions_path = dirs::INSTALLS.join("python"); file::remove_symlinks_with_target_prefix( &installed_python_versions_path, uv_versions_path, )?; let subdirs = file::dir_subdirs(uv_versions_path)?; for name in sorted(subdirs) { if name.starts_with(".") { continue; } // name is like cpython-3.13.1-macos-aarch64-none let v = name.split('-').nth(1).unwrap(); if python .create_symlink(v, &uv_versions_path.join(&name))? .is_some() { miseprintln!("Synced python@{v} from uv to mise"); } } let subdirs = file::dir_subdirs(&installed_python_versions_path)?; for v in sorted(subdirs) { if v.starts_with(".") { continue; } let src = installed_python_versions_path.join(&v); if src.is_symlink() { continue; } // ~/.local/share/uv/python/cpython-3.10.16-macos-aarch64-none // ~/.local/share/uv/python/cpython-3.13.0-linux-x86_64-gnu let os = OS; let arch = if cfg!(target_arch = "x86_64") { "x86_64-gnu" } else if cfg!(target_arch = "aarch64") { "aarch64-none" } else { ARCH }; let dst = uv_versions_path.join(format!("cpython-{v}-{os}-{arch}")); if !dst.exists() { if !uv_versions_path.exists() { file::create_dir_all(uv_versions_path)?; } // TODO: uv doesn't support symlinked dirs // https://github.com/astral-sh/uv/blob/e65a273f1b6b7c3ab129d902e93adeda4da20636/crates/uv-python/src/managed.rs#L196 file::clone_dir(&src, &dst)?; miseprintln!("Synced python@{v} from mise to uv"); } } Ok(()) } } static AFTER_LONG_HELP: &str = color_print::cstr!( r#"<bold><underline>Examples:</underline></bold> $ <bold>pyenv install 3.11.0</bold> $ <bold>mise sync python --pyenv</bold> $ <bold>mise use -g python@3.11.0</bold> - uses pyenv-provided python $ <bold>uv python install 3.11.0</bold> $ <bold>mise install python@3.10.0</bold> $ <bold>mise sync python --uv</bold> $ <bold>mise x python@3.11.0 -- python -V</bold> - uses uv-provided python $ <bold>uv run -p 3.10.0 -- python -V</bold> - uses mise-provided python "# );
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/sync/mod.rs
src/cli/sync/mod.rs
use clap::Subcommand; use eyre::Result; mod node; mod python; mod ruby; #[derive(Debug, clap::Args)] #[clap(about = "Synchronize tools from other version managers with mise")] pub struct Sync { #[clap(subcommand)] command: Commands, } #[derive(Debug, Subcommand)] enum Commands { Node(node::SyncNode), Python(python::SyncPython), Ruby(ruby::SyncRuby), } impl Commands { pub async fn run(self) -> Result<()> { match self { Self::Node(cmd) => cmd.run().await, Self::Python(cmd) => cmd.run().await, Self::Ruby(cmd) => cmd.run().await, } } } impl Sync { pub async fn run(self) -> Result<()> { self.command.run().await } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/args/env_var_arg.rs
src/cli/args/env_var_arg.rs
use std::str::FromStr; #[derive(Debug, Clone, Eq, PartialEq)] pub struct EnvVarArg { pub key: String, pub value: Option<String>, } impl FromStr for EnvVarArg { type Err = eyre::Error; fn from_str(input: &str) -> eyre::Result<Self> { let ev = match input.split_once('=') { Some((k, v)) => Self { key: k.to_string(), value: Some(v.to_string()), }, None => Self { key: input.to_string(), value: None, }, }; Ok(ev) } } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use test_log::test; use super::EnvVarArg; #[test] fn valid_values() { let values = [ ("FOO", new_arg("FOO", None)), ("FOO=", new_arg("FOO", Some(""))), ("FOO=bar", new_arg("FOO", Some("bar"))), ]; for (input, want) in values { let got: EnvVarArg = input.parse().unwrap(); assert_eq!(got, want); } } fn new_arg(key: &str, value: Option<&str>) -> EnvVarArg { EnvVarArg { key: key.to_string(), value: value.map(|s| s.to_string()), } } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/args/tool_arg.rs
src/cli/args/tool_arg.rs
use std::path::PathBuf; use std::str::FromStr; use std::{fmt::Display, sync::Arc}; use crate::cli::args::BackendArg; use crate::toolset::{ToolRequest, ToolSource}; use crate::ui::style; use console::style; use eyre::bail; use xx::regex; #[derive(Debug, Clone, Eq, PartialEq)] pub struct ToolArg { pub short: String, pub ba: Arc<BackendArg>, pub version: Option<String>, pub version_type: ToolVersionType, pub tvr: Option<ToolRequest>, } #[derive(Debug, Clone, Eq, PartialEq)] pub enum ToolVersionType { Path(PathBuf), Prefix(String), Ref(String, String), Sub { sub: String, orig_version: String }, System, Version(String), } impl FromStr for ToolArg { type Err = eyre::Error; fn from_str(input: &str) -> eyre::Result<Self> { let (backend_input, version) = parse_input(input); let ba: Arc<BackendArg> = Arc::new(backend_input.into()); let version_type = match version.as_ref() { Some(version) => version.parse()?, None => ToolVersionType::Version(String::from("latest")), }; let tvr = version .as_ref() .map(|v| ToolRequest::new(ba.clone(), v, ToolSource::Argument)) .transpose()?; Ok(Self { short: ba.short.clone(), tvr, version: version.map(|v| v.to_string()), version_type, ba, }) } } impl FromStr for ToolVersionType { type Err = eyre::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { trace!("parsing ToolVersionType from: {}", s); Ok(match s.split_once(':') { Some((ref_type @ ("ref" | "tag" | "branch" | "rev"), r)) => { Self::Ref(ref_type.to_string(), r.to_string()) } Some(("prefix", p)) => Self::Prefix(p.to_string()), Some(("path", p)) => Self::Path(PathBuf::from(p)), Some((p, v)) if p.starts_with("sub-") => Self::Sub { sub: p.split_once('-').unwrap().1.to_string(), orig_version: v.to_string(), }, Some((p, _)) => bail!("invalid prefix: {}", style::ered(p)), None if s == "system" => Self::System, None => Self::Version(s.to_string()), }) } } impl Display for ToolVersionType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Path(p) => write!(f, "path:{}", p.to_string_lossy()), Self::Prefix(p) => write!(f, "prefix:{p}"), Self::Ref(rt, r) => write!(f, "{rt}:{r}"), Self::Sub { sub, orig_version } => write!(f, "sub-{sub}:{orig_version}"), Self::System => write!(f, "system"), Self::Version(v) => write!(f, "{v}"), } } } impl ToolArg { /// this handles the case where the user typed in: /// mise local node 20.0.0 /// instead of /// mise local node@20.0.0 /// /// We can detect this, and we know what they meant, so make it work the way /// they expected. pub fn double_tool_condition(tools: &[ToolArg]) -> eyre::Result<Vec<ToolArg>> { let mut tools = tools.to_vec(); if tools.len() == 2 { let re = regex!(r"^\d+(\.\d+)*$"); let a = tools[0].clone(); let b = tools[1].clone(); if a.tvr.is_none() && b.tvr.is_none() && re.is_match(&b.ba.tool_name) { tools[1].short = a.short.clone(); tools[1].tvr = Some(ToolRequest::new( a.ba.clone(), &b.ba.tool_name, ToolSource::Argument, )?); tools[1].ba = a.ba; tools[1].version_type = b.ba.tool_name.parse()?; tools[1].version = Some(b.ba.tool_name.clone()); tools.remove(0); } } Ok(tools) } pub fn with_version(self, version: &str) -> Self { Self { tvr: Some(ToolRequest::new(self.ba.clone(), version, ToolSource::Argument).unwrap()), version: Some(version.into()), version_type: version.parse().unwrap(), ..self } } pub fn style(&self) -> String { let version = self .tvr .as_ref() .map(|t| t.version()) .unwrap_or(String::from("latest")); format!( "{}{}", style(&self.short).blue().for_stderr(), style(&format!("@{version}")).for_stderr() ) } } impl Display for ToolArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.tvr { Some(tvr) => write!(f, "{tvr}"), _ => write!(f, "{}", self.ba.tool_name), } } } fn parse_input(s: &str) -> (&str, Option<&str>) { let Some((left, right)) = s.split_once('@') else { return (s, None); }; if left.ends_with(':') { // Backend format: try to find version in the remaining part return right .split_once('@') .map(|(tool, version)| { ( &s[..left.len() + tool.len() + 1], if version.is_empty() { None } else { Some(version) }, ) }) .unwrap_or((s, None)); } // Simple "tool@version" format (left, if right.is_empty() { None } else { Some(right) }) } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use crate::config::Config; use super::*; #[tokio::test] async fn test_tool_arg() { let _config = Config::get().await.unwrap(); let tool = ToolArg::from_str("node").unwrap(); assert_eq!( tool, ToolArg { short: "node".into(), ba: Arc::new("node".into()), version: None, version_type: ToolVersionType::Version("latest".into()), tvr: None, } ); } #[tokio::test] async fn test_tool_arg_with_version() { let _config = Config::get().await.unwrap(); let tool = ToolArg::from_str("node@20").unwrap(); assert_eq!( tool, ToolArg { short: "node".into(), ba: Arc::new("node".into()), version: Some("20".into()), version_type: ToolVersionType::Version("20".into()), tvr: Some( ToolRequest::new(Arc::new("node".into()), "20", ToolSource::Argument).unwrap() ), } ); } #[tokio::test] async fn test_tool_arg_with_version_and_alias() { let _config = Config::get().await.unwrap(); let tool = ToolArg::from_str("nodejs@lts").unwrap(); assert_eq!( tool, ToolArg { short: "node".into(), ba: Arc::new("node".into()), version: Some("lts".into()), version_type: ToolVersionType::Version("lts".into()), tvr: Some( ToolRequest::new(Arc::new("node".into()), "lts", ToolSource::Argument).unwrap() ), } ); } #[tokio::test] async fn test_tool_arg_parse_input() { let _config = Config::get().await.unwrap(); let t = |input, f, v| { let (backend, version) = parse_input(input); assert_eq!(backend, f); assert_eq!(version, v); }; t("erlang", "erlang", None); t("erlang@", "erlang", None); t("erlang@27.2", "erlang", Some("27.2")); t("npm:@antfu/ni", "npm:@antfu/ni", None); t("npm:@antfu/ni@", "npm:@antfu/ni", None); t("npm:@antfu/ni@1.0.0", "npm:@antfu/ni", Some("1.0.0")); t("npm:@antfu/ni@1.0.0@1", "npm:@antfu/ni", Some("1.0.0@1")); t("npm:", "npm:", None); t("npm:prettier", "npm:prettier", None); t("npm:prettier@1.0.0", "npm:prettier", Some("1.0.0")); t( "ubi:BurntSushi/ripgrep[exe=rg]", "ubi:BurntSushi/ripgrep[exe=rg]", None, ); t( "ubi:BurntSushi/ripgrep[exe=rg,match=musl]", "ubi:BurntSushi/ripgrep[exe=rg,match=musl]", None, ); t( "ubi:BurntSushi/ripgrep[exe=rg,match=musl]@1.0.0", "ubi:BurntSushi/ripgrep[exe=rg,match=musl]", Some("1.0.0"), ); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/args/mod.rs
src/cli/args/mod.rs
pub use backend_arg::BackendArg; pub use env_var_arg::EnvVarArg; pub use tool_arg::{ToolArg, ToolVersionType}; mod backend_arg; mod env_var_arg; mod tool_arg;
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/args/backend_arg.rs
src/cli/args/backend_arg.rs
use crate::backend::backend_type::BackendType; use crate::backend::{ABackend, unalias_backend}; use crate::config::Config; use crate::plugins::PluginType; use crate::registry::REGISTRY; use crate::toolset::install_state::InstallStateTool; use crate::toolset::{ToolVersionOptions, install_state, parse_tool_options}; use crate::{backend, config, dirs, lockfile, registry}; use contracts::requires; use eyre::{Result, bail}; use heck::{ToKebabCase, ToShoutySnakeCase}; use std::collections::HashSet; use std::env; use std::fmt::{Debug, Display}; use std::hash::Hash; use std::path::PathBuf; use xx::regex; #[derive(Clone)] pub struct BackendArg { /// short or full identifier (what the user specified), "node", "prettier", "npm:prettier", "cargo:eza" pub short: String, /// full identifier, "core:node", "npm:prettier", "cargo:eza", "vfox:version-fox/vfox-nodejs" full: Option<String>, /// the name of the tool within the backend, e.g.: "node", "prettier", "eza", "vfox-nodejs" pub tool_name: String, /// ~/.local/share/mise/cache/<THIS> pub cache_path: PathBuf, /// ~/.local/share/mise/installs/<THIS> pub installs_path: PathBuf, /// ~/.local/share/mise/downloads/<THIS> pub downloads_path: PathBuf, pub opts: Option<ToolVersionOptions>, // TODO: make this not a hash key anymore to use this // backend: OnceCell<ABackend>, } impl<A: AsRef<str>> From<A> for BackendArg { fn from(s: A) -> Self { let short = unalias_backend(s.as_ref()).to_string(); Self::new(short, None) } } impl From<InstallStateTool> for BackendArg { fn from(ist: InstallStateTool) -> Self { Self::new(ist.short, ist.full) } } impl BackendArg { #[requires(!short.is_empty())] pub fn new(short: String, full: Option<String>) -> Self { let short = unalias_backend(&short).to_string(); let (_backend, mut tool_name) = full .as_ref() .unwrap_or(&short) .split_once(':') .unwrap_or(("", full.as_ref().unwrap_or(&short))); let short = regex!(r#"\[.+\]$"#).replace_all(&short, "").to_string(); let mut opts = None; if let Some(c) = regex!(r"^(.+)\[(.+)\]$").captures(tool_name) { tool_name = c.get(1).unwrap().as_str(); opts = Some(parse_tool_options(c.get(2).unwrap().as_str())); } Self::new_raw(short.clone(), full.clone(), tool_name.to_string(), opts) } pub fn new_raw( short: String, full: Option<String>, tool_name: String, opts: Option<ToolVersionOptions>, ) -> Self { let pathname = short.to_kebab_case(); Self { tool_name, short, full, cache_path: dirs::CACHE.join(&pathname), installs_path: dirs::INSTALLS.join(&pathname), downloads_path: dirs::DOWNLOADS.join(&pathname), opts, // backend: Default::default(), } } pub fn backend(&self) -> Result<ABackend> { // TODO: see above about hash key // let backend = self.backend.get_or_try_init(|| { // if let Some(backend) = backend::get(self) { // Ok(backend) // } else { // bail!("{self} not found in mise tool registry"); // } // })?; // Ok(backend.clone()) if let Some(backend) = backend::get(self) { Ok(backend) } else if let Some((plugin_name, tool_name)) = self.short.split_once(':') { // Check if the plugin exists first if let Some(plugin_type) = install_state::get_plugin_type(plugin_name) { // Plugin exists, but the backend couldn't be created // This could be due to the tool not being available or plugin not properly installed match plugin_type { PluginType::Asdf => { bail!( "asdf plugin '{plugin_name}' exists but '{tool_name}' is not available or the plugin is not properly installed" ); } PluginType::Vfox => { bail!( "vfox plugin '{plugin_name}' exists but '{tool_name}' is not available or the plugin is not properly installed" ); } PluginType::VfoxBackend => { bail!( "vfox-backend plugin '{plugin_name}' exists but '{tool_name}' is not available or the plugin is not properly installed" ); } } } else { // Plugin doesn't exist bail!("{plugin_name} is not a valid plugin name"); } } else { bail!("{self} not found in mise tool registry"); } } pub fn backend_type(&self) -> BackendType { // Check if this is a valid backend:tool format first if let Some((backend_prefix, _tool_name)) = self.short.split_once(':') && let Ok(backend_type) = backend_prefix.parse::<BackendType>() { return backend_type; } // Then check if this is a vfox plugin:tool format if let Some((plugin_name, _tool_name)) = self.short.split_once(':') { // we cannot reliably determine backend type within install state so we check config first if config::is_loaded() && Config::get_().get_repo_url(plugin_name).is_some() { return BackendType::VfoxBackend(plugin_name.to_string()); } if let Some(plugin_type) = install_state::get_plugin_type(plugin_name) { return match plugin_type { PluginType::Vfox => BackendType::Vfox, PluginType::VfoxBackend => BackendType::VfoxBackend(plugin_name.to_string()), PluginType::Asdf => BackendType::Asdf, }; } } // Only check install state for non-plugin:tool format entries if !self.short.contains(':') && let Ok(Some(backend_type)) = install_state::backend_type(&self.short) { return backend_type; } let full = self.full(); let backend = full.split(':').next().unwrap(); if let Ok(backend_type) = backend.parse() { return backend_type; } if config::is_loaded() && let Some(repo_url) = Config::get_().get_repo_url(&self.short) { return if repo_url.contains("vfox-") { BackendType::Vfox } else { // TODO: maybe something more intelligent? BackendType::Asdf }; } BackendType::Unknown } pub fn full(&self) -> String { let short = unalias_backend(&self.short); // Check for environment variable override first // e.g., MISE_BACKENDS_MYTOOLS='github:myorg/mytools' let env_key = format!("MISE_BACKENDS_{}", short.to_shouty_snake_case()); if let Ok(env_value) = env::var(&env_key) { return env_value; } if config::is_loaded() { if let Some(full) = Config::get_() .all_aliases .get(short) .and_then(|a| a.backend.clone()) { return full; } if let Some(url) = Config::get_().repo_urls.get(short) { return format!("asdf:{url}"); } let config = Config::get_(); if let Some(backend) = lockfile::get_locked_backend(&config, short) { return backend; } } if let Some(full) = &self.full { full.clone() } else if let Some(full) = install_state::get_tool_full(short) { full } else if let Some((plugin_name, _tool_name)) = short.split_once(':') { // Check if this is a plugin:tool format if BackendType::guess(short) != BackendType::Unknown { // Handle built-in backends short.to_string() } else if let Some(pt) = install_state::get_plugin_type(plugin_name) { match pt { PluginType::Asdf => { // For asdf plugins, plugin:tool format is invalid // Return just the plugin name since asdf doesn't support plugin:tool structure plugin_name.to_string() } // For vfox plugins, when already in plugin:tool format, return as-is // because the plugin itself is the backend specification PluginType::Vfox => short.to_string(), PluginType::VfoxBackend => short.to_string(), } } else if plugin_name.starts_with("asdf-") { // Handle asdf plugin:tool format even if not installed plugin_name.to_string() } else { short.to_string() } } else if let Some(pt) = install_state::get_plugin_type(short) { match pt { PluginType::Asdf => format!("asdf:{short}"), PluginType::Vfox => format!("vfox:{short}"), PluginType::VfoxBackend => short.to_string(), } } else if let Some(full) = REGISTRY .get(short) .and_then(|rt| rt.backends().first().cloned()) { full.to_string() } else { short.to_string() } } pub fn full_with_opts(&self) -> String { let full = self.full(); if regex!(r"^(.+)\[(.+)\]$").is_match(&full) { return full; } if let Some(opts) = &self.opts { let opts_str = opts .opts .iter() // filter out global options that are only relevant for initial installation .filter(|(k, _)| !["postinstall", "install_env"].contains(&k.as_str())) .map(|(k, v)| format!("{k}={v}")) .collect::<Vec<_>>() .join(","); if !full.contains(['[', ']']) && !opts_str.is_empty() { return format!("{full}[{opts_str}]"); } } full } pub fn full_without_opts(&self) -> String { let full = self.full(); if let Some(c) = regex!(r"^(.+)\[(.+)\]$").captures(&full) { return c.get(1).unwrap().as_str().to_string(); } full } pub fn opts(&self) -> ToolVersionOptions { // Start with registry options as base (if available) // Use backend_options to get options specific to the backend being used let full = self.full(); let mut opts = REGISTRY .get(self.short.as_str()) .map(|rt| rt.backend_options(&full)) .unwrap_or_default(); // Get user-provided options (from self.opts or from full string) let user_opts = self.opts.clone().unwrap_or_else(|| { if let Some(c) = regex!(r"^(.+)\[(.+)\]$").captures(&full) { parse_tool_options(c.get(2).unwrap().as_str()) } else { ToolVersionOptions::default() } }); // Merge user options on top (user options take precedence) for (k, v) in user_opts.opts { opts.opts.insert(k, v); } for (k, v) in user_opts.install_env { opts.install_env.insert(k, v); } if user_opts.os.is_some() { opts.os = user_opts.os; } opts } pub fn set_opts(&mut self, opts: Option<ToolVersionOptions>) { self.opts = opts; } pub fn tool_name(&self) -> String { let full = self.full(); let (_backend, tool_name) = full.split_once(':').unwrap_or(("", &full)); let tool_name = regex!(r#"\[.+\]$"#).replace_all(tool_name, "").to_string(); tool_name.to_string() } /// maps something like cargo:cargo-binstall to cargo-binstall and ubi:cargo-binstall, etc pub fn all_fulls(&self) -> HashSet<String> { let full = self.full(); let mut all = HashSet::new(); for short in registry::shorts_for_full(&full) { let rt = REGISTRY.get(short).unwrap(); let backends = rt.backends(); if backends.contains(&full.as_str()) { all.insert(rt.short.to_string()); all.extend(backends.into_iter().map(|s| s.to_string())); } } all.insert(full); all.insert(self.short.to_string()); all } pub fn is_os_supported(&self) -> bool { if self.uses_plugin() { return true; } if let Some(rt) = REGISTRY.get(self.short.as_str()) { return rt.is_supported_os(); } true } pub fn uses_plugin(&self) -> bool { install_state::get_plugin_type(&self.short).is_some() } } impl Display for BackendArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.short) } } impl Debug for BackendArg { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(full) = &self.full { write!(f, r#"BackendArg({} -> {})"#, self.short, full) } else { write!(f, r#"BackendArg({})"#, self.short) } } } impl PartialEq for BackendArg { fn eq(&self, other: &Self) -> bool { self.short == other.short } } impl Eq for BackendArg {} impl PartialOrd for BackendArg { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for BackendArg { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.short.cmp(&other.short) } } impl Hash for BackendArg { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.short.hash(state); } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::{assert_eq, assert_str_eq}; #[tokio::test] async fn test_backend_arg() { let _config = Config::get().await.unwrap(); let t = |s: &str, full, tool_name, t| { let fa: BackendArg = s.into(); assert_str_eq!(full, fa.full()); assert_str_eq!(tool_name, fa.tool_name); assert_eq!(t, fa.backend_type()); }; #[cfg(unix)] let asdf = |s, full, name| t(s, full, name, BackendType::Asdf); let cargo = |s, full, name| t(s, full, name, BackendType::Cargo); // let core = |s, full, name| t(s, full, name, BackendType::Core); let npm = |s, full, name| t(s, full, name, BackendType::Npm); let vfox = |s, full, name| t(s, full, name, BackendType::Vfox); #[cfg(unix)] { asdf("asdf:clojure", "asdf:clojure", "clojure"); asdf("clojure", "asdf:mise-plugins/mise-clojure", "clojure"); } cargo("cargo:eza", "cargo:eza", "eza"); // core("node", "node", "node"); npm("npm:@antfu/ni", "npm:@antfu/ni", "@antfu/ni"); npm("npm:prettier", "npm:prettier", "prettier"); vfox( "vfox:version-fox/vfox-nodejs", "vfox:version-fox/vfox-nodejs", "version-fox/vfox-nodejs", ); } #[tokio::test] async fn test_backend_arg_pathname() { let _config = Config::get().await.unwrap(); let t = |s: &str, expected| { let fa: BackendArg = s.into(); let actual = fa.installs_path.to_string_lossy(); let expected = dirs::INSTALLS.join(expected); assert_str_eq!(actual, expected.to_string_lossy()); }; t("asdf:node", "asdf-node"); t("node", "node"); t("cargo:eza", "cargo-eza"); t("npm:@antfu/ni", "npm-antfu-ni"); t("npm:prettier", "npm-prettier"); t( "vfox:version-fox/vfox-nodejs", "vfox-version-fox-vfox-nodejs", ); t("vfox:version-fox/nodejs", "vfox-version-fox-nodejs"); } #[tokio::test] async fn test_backend_arg_bug_fixes() { let _config = Config::get().await.unwrap(); // Test that asdf plugins in plugin:tool format return just the plugin name // (asdf doesn't support plugin:tool structure) let fa: BackendArg = "asdf-plugin:tool".into(); assert_str_eq!("asdf-plugin", fa.full()); // Test that vfox plugins in plugin:tool format return as-is let fa: BackendArg = "vfox-plugin:tool".into(); assert_str_eq!("vfox-plugin:tool", fa.full()); } #[tokio::test] async fn test_backend_arg_improved_error_messages() { let _config = Config::get().await.unwrap(); // Test that when a plugin exists but the tool is not available, // we get a more specific error message instead of "not a valid backend name" let fa: BackendArg = "nonexistent-plugin:some-tool".into(); let result = fa.backend(); assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!( error_msg.contains("is not a valid plugin name"), "Expected error to mention invalid plugin name, got: {error_msg}" ); // Note: We can't easily test the case where a plugin exists but the tool doesn't // because that would require setting up actual plugins in the test environment. // The logic has been improved to check plugin existence first and provide // more specific error messages based on the plugin type. } #[tokio::test] async fn test_full_with_opts_appends_and_filters() { let _config = Config::get().await.unwrap(); // start with a normal full like "npm:prettier" and attach opts via set_opts let mut fa: BackendArg = "npm:prettier".into(); fa.set_opts(Some(parse_tool_options("a=1,install_env=ignored,b=2"))); // install_env should be filtered out, remaining order preserved assert_str_eq!("npm:prettier[a=1,b=2]", fa.full_with_opts()); fa = "http:hello-lock".into(); fa.set_opts(Some(parse_tool_options("url=https://mise.jdx.dev/test-fixtures/hello-world-1.0.0.tar.gz,bin_path=hello-world-1.0.0/bin"))); // install_env should be filtered out, remaining order preserved assert_str_eq!( "http:hello-lock[url=https://mise.jdx.dev/test-fixtures/hello-world-1.0.0.tar.gz,bin_path=hello-world-1.0.0/bin]", fa.full_with_opts() ); } #[tokio::test] async fn test_full_with_opts_preserves_existing_brackets() { let _config = Config::get().await.unwrap(); // when the full already contains options brackets, full_with_opts should return it unchanged let mut fa = BackendArg::new_raw( "node".to_string(), Some("node[foo=bar]".to_string()), "node".to_string(), None, ); assert_str_eq!("node[foo=bar]", fa.full_with_opts()); fa = BackendArg::new_raw( "gitlab:jdxcode/mise-test-fixtures".to_string(), Some("gitlab:jdxcode/mise-test-fixtures[asset_pattern=hello-world-1.0.0.tar.gz,bin_path=hello-world-1.0.0/bin]".to_string()), "gitlab:jdxcode/mise-test-fixtures".to_string(), None, ); assert_str_eq!( "gitlab:jdxcode/mise-test-fixtures[asset_pattern=hello-world-1.0.0.tar.gz,bin_path=hello-world-1.0.0/bin]", fa.full_with_opts() ); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_load_context.rs
src/task/task_load_context.rs
use eyre::bail; /// Context for loading tasks with optional filtering hints #[derive(Debug, Clone, Default, Hash, Eq, PartialEq)] pub struct TaskLoadContext { /// Specific paths to load tasks from /// e.g., ["foo/bar", "baz/qux"] from patterns "//foo/bar:task" and "//baz/qux:task" pub path_hints: Vec<String>, /// If true, load all tasks from the entire monorepo (for `mise tasks ls --all`) /// If false (default), only load tasks from current directory hierarchy pub load_all: bool, } impl TaskLoadContext { /// Create a new context that loads all tasks pub fn all() -> Self { Self { path_hints: vec![], load_all: true, } } /// Create a context from a task pattern like "//foo/bar:task" or "//foo/bar/..." pub fn from_pattern(pattern: &str) -> Self { // Extract path hint from pattern let path_hints = if let Some(hint) = Self::extract_path_hint(pattern) { vec![hint] } else { vec![] }; Self { path_hints, load_all: false, } } /// Create a context from multiple patterns, merging their path hints pub fn from_patterns<'a>(patterns: impl Iterator<Item = &'a str>) -> Self { use std::collections::HashSet; let mut path_hints_set = HashSet::new(); let mut load_all = false; for pattern in patterns { if let Some(hint) = Self::extract_path_hint(pattern) { path_hints_set.insert(hint); } else { // If any pattern has no hint, we need to load all load_all = true; } } Self { path_hints: path_hints_set.into_iter().collect(), load_all, } } /// Extract path hint from a monorepo pattern /// Returns None if the pattern doesn't provide useful filtering information fn extract_path_hint(pattern: &str) -> Option<String> { const MONOREPO_PREFIX: &str = "//"; const TASK_SEPARATOR: &str = ":"; const ELLIPSIS: &str = "..."; if !pattern.starts_with(MONOREPO_PREFIX) { return None; } // Remove the // prefix let without_prefix = pattern.strip_prefix(MONOREPO_PREFIX)?; // Split on : to separate path from task name let parts: Vec<&str> = without_prefix.splitn(2, TASK_SEPARATOR).collect(); let path_part = parts.first()?; // If it's just "//..." or "//" we need everything if path_part.is_empty() || *path_part == ELLIPSIS { return None; } // Remove trailing ellipsis if present (e.g., "foo/bar/...") let path_part = path_part.strip_suffix('/').unwrap_or(path_part); let path_part = path_part.strip_suffix(ELLIPSIS).unwrap_or(path_part); let path_part = path_part.strip_suffix('/').unwrap_or(path_part); // If the path still contains "..." anywhere, it's a wildcard pattern // that could match many paths, so we can't use it as a specific hint // e.g., ".../graph" or "foo/.../bar" should load all subdirectories if path_part.contains(ELLIPSIS) { return None; } // If we have a non-empty path hint, return it if !path_part.is_empty() { Some(path_part.to_string()) } else { None } } /// Check if a subdirectory should be loaded based on the context pub fn should_load_subdir(&self, subdir: &str, _monorepo_root: &str) -> bool { use std::path::Path; // If load_all is true, load everything if self.load_all { return true; } // If no path hints, don't load anything (unless load_all is true) if self.path_hints.is_empty() { return false; } // Use Path APIs for more robust path comparison let subdir_path = Path::new(subdir); // Check if subdir matches or is a parent/child of any hint for hint in &self.path_hints { let hint_path = Path::new(hint); // Check if subdir matches or is a parent/child of this hint // e.g., hint "foo/bar" should match: // - "foo/bar" (exact match) // - "foo/bar/baz" (child - subdir starts with hint) // - "foo" (parent - hint starts with subdir, might contain the target) if subdir_path == hint_path || subdir_path.starts_with(hint_path) || hint_path.starts_with(subdir_path) { return true; } } false } } /// Expands :task syntax to //path:task based on current directory relative to monorepo root /// /// This function handles the special `:task` syntax that refers to tasks in the current /// config_root within a monorepo. It converts `:build` to either `//:build` (if at monorepo root) /// or `//project:build` (if in a subdirectory). /// /// # Arguments /// * `task` - The task pattern to expand (e.g., ":build") /// * `config` - The configuration containing monorepo information /// /// # Returns /// * `Ok(String)` - The expanded task pattern (e.g., "//project:build") /// * `Err` - If monorepo is not configured or current directory is outside monorepo root pub fn expand_colon_task_syntax( task: &str, config: &crate::config::Config, ) -> eyre::Result<String> { // Skip expansion for absolute monorepo paths or explicit global tasks if task.starts_with("//") || task.starts_with("::") { return Ok(task.to_string()); } // Check if this is a colon pattern or a bare name let is_colon_pattern = task.starts_with(':'); // Reject patterns that look like monorepo paths with wrong syntax (have / and : but don't start with // or :) if !is_colon_pattern && task.contains('/') && task.contains(':') { bail!( "relative path syntax '{}' is not supported, use '//{}' or ':task' for current directory", task, task ); } // Get the monorepo root (the config file with experimental_monorepo_root = true) let monorepo_root = config .config_files .values() .find(|cf| cf.experimental_monorepo_root() == Some(true)) .and_then(|cf| cf.project_root()); // If not in monorepo context, only expand if it's a colon pattern (error), otherwise return as-is if monorepo_root.is_none() { if is_colon_pattern { bail!("Cannot use :task syntax without a monorepo root"); } return Ok(task.to_string()); } // We're in a monorepo context let monorepo_root = monorepo_root.unwrap(); // Determine the current directory relative to monorepo root if let Some(cwd) = &*crate::dirs::CWD { if let Ok(rel_path) = cwd.strip_prefix(monorepo_root) { // For bare task names, only expand if we're actually in the monorepo // For colon patterns, always expand (and error if outside monorepo) // Convert relative path to monorepo path format let path_str = rel_path .to_string_lossy() .replace(std::path::MAIN_SEPARATOR, "/"); if path_str.is_empty() { // We're at the root if is_colon_pattern { // :task -> //:task (task already has colon) Ok(format!("//{}", task)) } else { // bare task -> //:task (add colon) Ok(format!("//:{}", task)) } } else { // We're in a subdirectory if is_colon_pattern { // :task -> //path:task Ok(format!("//{}{}", path_str, task)) } else { // bare name -> //path:task Ok(format!("//{}:{}", path_str, task)) } } } else { if is_colon_pattern { bail!("Cannot use :task syntax outside of monorepo root directory"); } // Bare name outside monorepo - return as-is for global matching Ok(task.to_string()) } } else { if is_colon_pattern { bail!("Cannot use :task syntax without a current working directory"); } Ok(task.to_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_extract_path_hint() { assert_eq!( TaskLoadContext::extract_path_hint("//foo/bar:task"), Some("foo/bar".to_string()) ); assert_eq!( TaskLoadContext::extract_path_hint("//foo/bar/...:task"), Some("foo/bar".to_string()) ); assert_eq!( TaskLoadContext::extract_path_hint("//foo:task"), Some("foo".to_string()) ); assert_eq!(TaskLoadContext::extract_path_hint("//:task"), None); assert_eq!(TaskLoadContext::extract_path_hint("//...:task"), None); assert_eq!(TaskLoadContext::extract_path_hint("foo:task"), None); // Test patterns with ... in different positions (wildcard patterns) // ... at the START of path assert_eq!( TaskLoadContext::extract_path_hint("//.../api:task"), None, "Pattern with ... at start should load all subdirs" ); assert_eq!( TaskLoadContext::extract_path_hint("//.../services/api:task"), None, "Pattern with ... at start and more path should load all subdirs" ); // ... in the MIDDLE of path assert_eq!( TaskLoadContext::extract_path_hint("//projects/.../api:task"), None, "Pattern with ... in middle should load all subdirs" ); assert_eq!( TaskLoadContext::extract_path_hint("//libs/.../utils:task"), None, "Pattern with ... in middle should load all subdirs" ); // Multiple ... in path assert_eq!( TaskLoadContext::extract_path_hint("//projects/.../api/...:task"), None, "Pattern with multiple ... should load all subdirs" ); assert_eq!( TaskLoadContext::extract_path_hint("//.../foo/.../bar:task"), None, "Pattern with ... at start and middle should load all subdirs" ); } #[test] fn test_should_load_subdir() { let ctx = TaskLoadContext::from_pattern("//foo/bar:task"); // Should load exact match assert!(ctx.should_load_subdir("foo/bar", "/root")); // Should load children assert!(ctx.should_load_subdir("foo/bar/baz", "/root")); // Should load parent (might contain target) assert!(ctx.should_load_subdir("foo", "/root")); // Should not load unrelated paths assert!(!ctx.should_load_subdir("baz/qux", "/root")); } #[test] fn test_should_load_subdir_multiple_hints() { let ctx = TaskLoadContext::from_patterns(["//foo/bar:task", "//baz/qux:task"].iter().copied()); // Should load exact matches for both hints assert!(ctx.should_load_subdir("foo/bar", "/root")); assert!(ctx.should_load_subdir("baz/qux", "/root")); // Should load children of both hints assert!(ctx.should_load_subdir("foo/bar/child", "/root")); assert!(ctx.should_load_subdir("baz/qux/child", "/root")); // Should load parents of both hints assert!(ctx.should_load_subdir("foo", "/root")); assert!(ctx.should_load_subdir("baz", "/root")); // Should not load unrelated paths assert!(!ctx.should_load_subdir("other/path", "/root")); } #[test] fn test_load_all_context() { let ctx = TaskLoadContext::all(); assert!(ctx.load_all); assert!(ctx.should_load_subdir("any/path", "/root")); } #[test] fn test_expand_colon_task_syntax() { // Note: This is a basic structure test. Full integration testing is done in e2e tests // because it requires a real config with monorepo root setup and CWD manipulation. // Test that non-colon patterns are returned as-is // We can't easily test the full expansion here without setting up a real config // and manipulating CWD, so we just verify the function signature and basic behavior let task = "regular-task"; // For non-colon tasks, this should work even with empty config // The actual expansion logic is tested via e2e tests assert!(!task.starts_with(':')); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_scheduler.rs
src/task/task_scheduler.rs
use crate::cmd::CmdLineRunner; use crate::config::Config; use crate::task::{Deps, Task}; use eyre::Result; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::{Mutex, Semaphore, mpsc}; use tokio::task::JoinSet; #[cfg(unix)] use nix::sys::signal::SIGTERM; pub type SchedMsg = (Task, Arc<Mutex<Deps>>); /// Schedules and executes tasks with concurrency control pub struct Scheduler { pub semaphore: Arc<Semaphore>, pub jset: Arc<Mutex<JoinSet<Result<()>>>>, pub sched_tx: Arc<mpsc::UnboundedSender<SchedMsg>>, pub sched_rx: Option<mpsc::UnboundedReceiver<SchedMsg>>, pub in_flight: Arc<AtomicUsize>, } impl Scheduler { pub fn new(jobs: usize) -> Self { let (sched_tx, sched_rx) = mpsc::unbounded_channel::<SchedMsg>(); Self { semaphore: Arc::new(Semaphore::new(jobs)), jset: Arc::new(Mutex::new(JoinSet::new())), sched_tx: Arc::new(sched_tx), sched_rx: Some(sched_rx), in_flight: Arc::new(AtomicUsize::new(0)), } } /// Take ownership of the receiver (can only be called once) pub fn take_receiver(&mut self) -> Option<mpsc::UnboundedReceiver<SchedMsg>> { self.sched_rx.take() } /// Wait for all spawned tasks to complete pub async fn join_all(&self, continue_on_error: bool) -> Result<()> { while let Some(result) = self.jset.lock().await.join_next().await { if result.is_ok() || continue_on_error { continue; } #[cfg(unix)] CmdLineRunner::kill_all(SIGTERM); #[cfg(windows)] CmdLineRunner::kill_all(); break; } Ok(()) } /// Create a spawn context pub fn spawn_context(&self, config: Arc<Config>) -> SpawnContext { SpawnContext { semaphore: self.semaphore.clone(), config, sched_tx: self.sched_tx.clone(), jset: self.jset.clone(), in_flight: self.in_flight.clone(), } } /// Get the in-flight task count pub fn in_flight_count(&self) -> usize { self.in_flight.load(Ordering::SeqCst) } /// Pump dependency graph leaves into the scheduler /// /// Forwards initial leaves synchronously, then spawns an async task to forward /// remaining leaves as they become available. Returns a watch receiver that signals /// when all dependencies are complete. pub async fn pump_deps(&self, deps: Arc<Mutex<Deps>>) -> tokio::sync::watch::Receiver<bool> { let (main_done_tx, main_done_rx) = tokio::sync::watch::channel(false); let sched_tx = self.sched_tx.clone(); let deps_clone = deps.clone(); // Forward initial leaves synchronously { let mut rx = deps_clone.lock().await.subscribe(); loop { match rx.try_recv() { Ok(Some(task)) => { trace!( "main deps initial leaf: {} {}", task.name, task.args.join(" ") ); let _ = sched_tx.send((task, deps_clone.clone())); } Ok(None) => { trace!("main deps initial done"); break; } Err(mpsc::error::TryRecvError::Empty) => { break; } Err(mpsc::error::TryRecvError::Disconnected) => { break; } } } } // Forward remaining leaves asynchronously tokio::spawn(async move { let mut rx = deps_clone.lock().await.subscribe(); while let Some(msg) = rx.recv().await { match msg { Some(task) => { trace!( "main deps leaf scheduled: {} {}", task.name, task.args.join(" ") ); let _ = sched_tx.send((task, deps_clone.clone())); } None => { trace!("main deps completed"); let _ = main_done_tx.send(true); break; } } } }); main_done_rx } /// Run the scheduler loop, draining tasks and spawning them via the callback /// /// The loop continues until: /// - main_done signal is received AND /// - no tasks are in-flight AND /// - no tasks were recently drained /// /// Or if should_stop returns true (for early exit due to failures) pub async fn run_loop<F, Fut>( &mut self, main_done_rx: &mut tokio::sync::watch::Receiver<bool>, main_deps: Arc<Mutex<Deps>>, should_stop: impl Fn() -> bool, continue_on_error: bool, mut spawn_job: F, ) -> Result<()> where F: FnMut(Task, Arc<Mutex<Deps>>) -> Fut, Fut: std::future::Future<Output = Result<()>>, { let mut sched_rx = self.take_receiver().expect("receiver already taken"); loop { // Drain ready tasks without awaiting let mut drained_any = false; loop { match sched_rx.try_recv() { Ok((task, deps_for_remove)) => { drained_any = true; trace!("scheduler received: {} {}", task.name, task.args.join(" ")); if should_stop() && !continue_on_error { break; } spawn_job(task, deps_for_remove).await?; } Err(mpsc::error::TryRecvError::Empty) => break, Err(mpsc::error::TryRecvError::Disconnected) => break, } } // Check if we should stop early due to failure if should_stop() && !continue_on_error { trace!("scheduler: stopping early due to failure, cleaning up main deps"); // Clean up the dependency graph to ensure the main_done signal is sent let mut deps = main_deps.lock().await; let tasks_to_remove: Vec<Task> = deps.all().cloned().collect(); for task in tasks_to_remove { deps.remove(&task); } drop(deps); break; } // Exit if main deps finished and nothing is running/queued if *main_done_rx.borrow() && self.in_flight_count() == 0 && !drained_any { trace!("scheduler drain complete; exiting loop"); break; } // Await either new work or main_done change tokio::select! { m = sched_rx.recv() => { if let Some((task, deps_for_remove)) = m { trace!("scheduler received: {} {}", task.name, task.args.join(" ")); if should_stop() && !continue_on_error { break; } spawn_job(task, deps_for_remove).await?; } else { // channel closed; rely on main_done/in_flight to exit soon } } _ = main_done_rx.changed() => { trace!("main_done changed: {}", *main_done_rx.borrow()); } } } Ok(()) } } /// Context passed to spawned tasks #[derive(Clone)] pub struct SpawnContext { pub semaphore: Arc<Semaphore>, pub config: Arc<Config>, pub sched_tx: Arc<mpsc::UnboundedSender<SchedMsg>>, pub jset: Arc<Mutex<JoinSet<Result<()>>>>, pub in_flight: Arc<AtomicUsize>, } #[cfg(test)] mod tests { use super::*; #[test] fn test_scheduler_new() { let scheduler = Scheduler::new(4); // Verify basic initialization assert_eq!( scheduler.in_flight_count(), 0, "in_flight should start at 0" ); } #[tokio::test] async fn test_spawn_context_clone() { let scheduler = Scheduler::new(4); let config = Config::get().await.unwrap(); let ctx = scheduler.spawn_context(config.clone()); let ctx2 = ctx.clone(); // Verify cloning works assert!(Arc::ptr_eq(&ctx.config, &ctx2.config)); } #[tokio::test] async fn test_scheduler_receiver_take() { let mut scheduler = Scheduler::new(4); let rx = scheduler.take_receiver(); assert!(rx.is_some(), "should be able to take receiver once"); let rx2 = scheduler.take_receiver(); assert!(rx2.is_none(), "should not be able to take receiver twice"); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_script_parser.rs
src/task/task_script_parser.rs
use crate::cli::version::V; use crate::config::{Config, Settings}; use crate::env_diff::EnvMap; use crate::exit::exit; use crate::shell::ShellType; use crate::task::Task; use crate::tera::get_tera; use eyre::{Context, Result}; use heck::ToSnakeCase; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::iter::once; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use versions::Versioning; type TeraSpecParsingResult = ( tera::Tera, Arc<Mutex<HashMap<String, usize>>>, Arc<Mutex<Vec<usage::SpecArg>>>, Arc<Mutex<Vec<usage::SpecFlag>>>, ); pub struct TaskScriptParser { dir: Option<PathBuf>, } impl TaskScriptParser { pub fn new(dir: Option<PathBuf>) -> Self { TaskScriptParser { dir } } fn get_tera(&self) -> tera::Tera { get_tera(self.dir.as_deref()) } fn render_script_with_context( tera: &mut tera::Tera, script: &str, ctx: &tera::Context, ) -> Result<String> { tera.render_str(script.trim(), ctx) .with_context(|| format!("Failed to render task script: {}", script)) } fn render_usage_with_context( tera: &mut tera::Tera, usage: &str, ctx: &tera::Context, ) -> Result<String> { tera.render_str(usage.trim(), ctx) .with_context(|| format!("Failed to render task usage: {}", usage)) } fn check_tera_args_deprecation( task_name: &str, args: &[usage::SpecArg], flags: &[usage::SpecFlag], ) { // Check if any args or flags were defined via Tera templates if args.is_empty() && flags.is_empty() { return; } // Debug assertion to ensure we remove this functionality after 2026.11.0 let removal_version = Versioning::new("2026.11.0").unwrap(); debug_assert!( *V < removal_version, "Tera template task arguments (arg/option/flag functions) should have been removed in version 2026.11.0. \ Please remove this deprecated functionality from task_script_parser.rs" ); // Show deprecation warning for versions >= 2026.5.0 let deprecation_version = Versioning::new("2026.5.0").unwrap(); if *V >= deprecation_version { deprecated!( "tera_template_task_args", "Task '{}' uses deprecated Tera template functions (arg(), option(), flag()) in run scripts. \ This will be removed in mise 2026.11.0. The template functions require two-pass parsing which \ causes unexpected behavior - they return empty strings during spec collection and have complex \ escaping rules. The 'usage' field is cleaner, works consistently between TOML/file tasks, and \ provides all the same functionality. See migration guide: https://mise.jdx.dev/tasks/task-arguments/#tera-templates", task_name ); } } // Helper functions for tera error handling fn expect_string(value: &tera::Value, param_name: &str) -> tera::Result<String> { value.as_str().map(|s| s.to_string()).ok_or_else(|| { tera::Error::msg(format!( "expected string for '{}', got {:?}", param_name, value )) }) } fn expect_opt_string( value: Option<&tera::Value>, param_name: &str, ) -> tera::Result<Option<String>> { value .map(|v| Self::expect_string(v, param_name)) .transpose() } fn expect_opt_bool( value: Option<&tera::Value>, param_name: &str, ) -> tera::Result<Option<bool>> { value.map(|v| Self::expect_bool(v, param_name)).transpose() } fn expect_bool(value: &tera::Value, param_name: &str) -> tera::Result<bool> { value.as_bool().ok_or_else(|| { tera::Error::msg(format!( "expected boolean for '{}', got {:?}", param_name, value )) }) } fn expect_i64(value: &tera::Value, param_name: &str) -> tera::Result<i64> { value.as_i64().ok_or_else(|| { tera::Error::msg(format!( "expected integer for '{}', got {:?}", param_name, value )) }) } fn expect_opt_i64(value: Option<&tera::Value>, param_name: &str) -> tera::Result<Option<i64>> { value.map(|v| Self::expect_i64(v, param_name)).transpose() } fn expect_array<'a>( value: &'a tera::Value, param_name: &str, ) -> tera::Result<&'a Vec<tera::Value>> { value.as_array().ok_or_else(|| { tera::Error::msg(format!( "expected array for '{}', got {:?}", param_name, value )) }) } fn expect_opt_array<'a>( value: Option<&'a tera::Value>, param_name: &str, ) -> tera::Result<Option<&'a Vec<tera::Value>>> { value.map(|v| Self::expect_array(v, param_name)).transpose() } fn lock_error(e: impl std::fmt::Display) -> tera::Error { tera::Error::msg(format!("failed to lock: {}", e)) } fn setup_tera_for_spec_parsing(&self, task: &Task) -> TeraSpecParsingResult { let mut tera = self.get_tera(); let arg_order = Arc::new(Mutex::new(HashMap::new())); let input_args = Arc::new(Mutex::new(vec![])); let input_flags = Arc::new(Mutex::new(vec![])); // override throw function to do nothing tera.register_function("throw", { move |_args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { Ok(tera::Value::Null) } }); // render args, options, and flags as null // these functions are only used to collect the spec tera.register_function("arg", { let input_args = input_args.clone(); let arg_order = arg_order.clone(); move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { let i = Self::expect_i64( args.get("i").unwrap_or(&tera::Value::from( input_args.lock().map_err(Self::lock_error)?.len(), )), "i", )? as usize; let required = Self::expect_opt_bool(args.get("required"), "required")?.unwrap_or(true); let var = Self::expect_opt_bool(args.get("var"), "var")?.unwrap_or(false); let name = Self::expect_opt_string(args.get("name"), "name")?.unwrap_or(i.to_string()); let mut arg_order = arg_order.lock().map_err(Self::lock_error)?; if arg_order.contains_key(&name) { trace!("already seen {name}"); return Ok(tera::Value::String("".to_string())); } arg_order.insert(name.clone(), i); let usage = Self::expect_opt_string(args.get("usage"), "usage")?.unwrap_or_default(); let help = Self::expect_opt_string(args.get("help"), "help")?; let help_long = Self::expect_opt_string(args.get("help_long"), "help_long")?; let help_md = Self::expect_opt_string(args.get("help_md"), "help_md")?; let var_min = Self::expect_opt_i64(args.get("var_min"), "var_min")?.map(|v| v as usize); let var_max = Self::expect_opt_i64(args.get("var_max"), "var_max")?.map(|v| v as usize); let hide = Self::expect_opt_bool(args.get("hide"), "hide")?.unwrap_or(false); let default = Self::expect_opt_string(args.get("default"), "default")? .map(|s| vec![s]) .unwrap_or_default(); let choices = Self::expect_opt_array(args.get("choices"), "choices")? .map(|array| { tera::Result::Ok(usage::SpecChoices { choices: array .iter() .map(|v| Self::expect_string(v, "choice")) .collect::<Result<Vec<String>, tera::Error>>()?, }) }) .transpose()?; let env = Self::expect_opt_string(args.get("env"), "env")?; let help_first_line = match &help { Some(h) => { if h.is_empty() { None } else { h.lines().next().map(|line| line.to_string()) } } None => None, }; let mut arg = usage::SpecArg { name: name.clone(), usage, help_first_line, help, help_long, help_md, required, var, var_min, var_max, hide, default, choices, env, ..Default::default() }; arg.usage = arg.usage(); input_args.lock().map_err(Self::lock_error)?.push(arg); Ok(tera::Value::String("".to_string())) } }); tera.register_function("option", { let input_flags = input_flags.clone(); move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { let name = match args.get("name") { Some(n) => Self::expect_string(n, "name")?, None => return Err(tera::Error::msg("missing required 'name' parameter")), }; let short = args .get("short") .map(|s| s.to_string().chars().collect()) .unwrap_or_default(); let long = match args.get("long") { Some(l) => { let s = Self::expect_string(l, "long")?; s.split_whitespace().map(|s| s.to_string()).collect() } None => vec![name.clone()], }; let default = Self::expect_opt_string(args.get("default"), "default")? .map(|s| vec![s]) .unwrap_or_default(); let var = Self::expect_opt_bool(args.get("var"), "var")?.unwrap_or(false); let deprecated = Self::expect_opt_string(args.get("deprecated"), "deprecated")?; let help = Self::expect_opt_string(args.get("help"), "help")?; let help_long = Self::expect_opt_string(args.get("help_long"), "help_long")?; let help_md = Self::expect_opt_string(args.get("help_md"), "help_md")?; let hide = Self::expect_opt_bool(args.get("hide"), "hide")?.unwrap_or(false); let global = Self::expect_opt_bool(args.get("global"), "global")?.unwrap_or(false); let count = Self::expect_opt_bool(args.get("count"), "count")?.unwrap_or(false); let usage = Self::expect_opt_string(args.get("usage"), "usage")?.unwrap_or_default(); let required = Self::expect_opt_bool(args.get("required"), "required")?.unwrap_or(false); let negate = Self::expect_opt_string(args.get("negate"), "negate")?; let choices = match args.get("choices") { Some(c) => { let array = Self::expect_array(c, "choices")?; let mut choices_vec = Vec::new(); for choice in array { let s = Self::expect_string(choice, "choice")?; choices_vec.push(s); } Some(usage::SpecChoices { choices: choices_vec, }) } None => None, }; let env = Self::expect_opt_string(args.get("env"), "env")?; let help_first_line = match &help { Some(h) => { if h.is_empty() { None } else { h.lines().next().map(|line| line.to_string()) } } None => None, }; let mut flag = usage::SpecFlag { name: name.clone(), short, long, default, var, var_min: None, var_max: None, hide, global, count, deprecated, help_first_line, help, usage, help_long, help_md, required, negate, env: env.clone(), arg: Some(usage::SpecArg { name: name.clone(), var, choices, env, ..Default::default() }), }; flag.usage = flag.usage(); input_flags.lock().map_err(Self::lock_error)?.push(flag); Ok(tera::Value::String("".to_string())) } }); tera.register_function("flag", { let input_flags = input_flags.clone(); move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { let name = match args.get("name") { Some(n) => Self::expect_string(n, "name")?, None => return Err(tera::Error::msg("missing required 'name' parameter")), }; let short = args .get("short") .map(|s| s.to_string().chars().collect()) .unwrap_or_default(); let long = match args.get("long") { Some(l) => { let s = Self::expect_string(l, "long")?; s.split_whitespace().map(|s| s.to_string()).collect() } None => vec![name.clone()], }; let default = Self::expect_opt_string(args.get("default"), "default")? .map(|s| vec![s]) .unwrap_or_default(); let var = Self::expect_opt_bool(args.get("var"), "var")?.unwrap_or(false); let deprecated = Self::expect_opt_string(args.get("deprecated"), "deprecated")?; let help = Self::expect_opt_string(args.get("help"), "help")?; let help_long = Self::expect_opt_string(args.get("help_long"), "help_long")?; let help_md = Self::expect_opt_string(args.get("help_md"), "help_md")?; let hide = Self::expect_opt_bool(args.get("hide"), "hide")?.unwrap_or(false); let global = Self::expect_opt_bool(args.get("global"), "global")?.unwrap_or(false); let count = Self::expect_opt_bool(args.get("count"), "count")?.unwrap_or(false); let usage = Self::expect_opt_string(args.get("usage"), "usage")?.unwrap_or_default(); let required = Self::expect_opt_bool(args.get("required"), "required")?.unwrap_or(false); let negate = Self::expect_opt_string(args.get("negate"), "negate")?; let choices = match args.get("choices") { Some(c) => { let array = Self::expect_array(c, "choices")?; let mut choices_vec = Vec::new(); for choice in array { let s = Self::expect_string(choice, "choice")?; choices_vec.push(s); } Some(usage::SpecChoices { choices: choices_vec, }) } None => None, }; let env = Self::expect_opt_string(args.get("env"), "env")?; let help_first_line = match &help { Some(h) => { if h.is_empty() { None } else { h.lines().next().map(|line| line.to_string()) } } None => None, }; // Create SpecArg when any arg-level properties are set (choices, env) // This matches the behavior of option() which always creates SpecArg let arg = if choices.is_some() || env.is_some() { Some(usage::SpecArg { name: name.clone(), var, choices, env: env.clone(), ..Default::default() }) } else { None }; let mut flag = usage::SpecFlag { name: name.clone(), short, long, default, var, var_min: None, var_max: None, hide, global, count, deprecated, help_first_line, help, usage, help_long, help_md, required, negate, env, arg, }; flag.usage = flag.usage(); input_flags.lock().map_err(Self::lock_error)?.push(flag); Ok(tera::Value::String("".to_string())) } }); tera.register_function("task_source_files", { let sources = Arc::new(task.sources.clone()); move |_: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { if sources.is_empty() { trace!("tera::render::resolve_task_sources `task_source_files` called in task with empty sources array"); return Ok(tera::Value::Array(Default::default())); }; let mut resolved = Vec::with_capacity(sources.len()); for pattern in sources.iter() { // pattern is considered a tera template string if it contains opening tags: // - "{#" for comments // - "{{" for expressions // - "{%" for statements if pattern.contains("{#") || pattern.contains("{{") || pattern.contains("{%") { trace!( "tera::render::resolve_task_sources including tera template string in resolved task sources: {pattern}" ); resolved.push(tera::Value::String(pattern.clone())); continue; } match glob::glob_with( pattern, glob::MatchOptions { case_sensitive: false, require_literal_separator: false, require_literal_leading_dot: false, }, ) { Err(error) => { warn!( "tera::render::resolve_task_sources including '{pattern}' in resolved task sources, ignoring glob parsing error: {error:#?}" ); resolved.push(tera::Value::String(pattern.clone())); } Ok(expanded) => { let mut source_found = false; for path in expanded { source_found = true; match path { Ok(path) => { let source = path.display(); trace!( "tera::render::resolve_task_sources resolved source from pattern '{pattern}': {source}" ); resolved.push(tera::Value::String(source.to_string())); } Err(error) => { let source = error.path().display(); warn!( "tera::render::resolve_task_sources omitting '{source}' from resolved task sources due to: {:#?}", error.error() ); } } } if !source_found { warn!( "tera::render::resolve_task_sources no source file(s) resolved for pattern: '{pattern}'" ); } } } } Ok(tera::Value::Array(resolved)) } }); (tera, arg_order, input_args, input_flags) } pub async fn parse_run_scripts_for_spec_only( &self, config: &Arc<Config>, task: &Task, scripts: &[String], ) -> Result<usage::Spec> { let (mut tera, arg_order, input_args, input_flags) = self.setup_tera_for_spec_parsing(task); let mut tera_ctx = task.tera_ctx(config).await?; // First render the usage field to collect the spec let rendered_usage = Self::render_usage_with_context(&mut tera, &task.usage, &tera_ctx)?; let spec_from_field: usage::Spec = rendered_usage.parse()?; if Settings::get().task.disable_spec_from_run_scripts { return Ok(spec_from_field); } // Make the arg/flag names available as snake_case in the template context, using // default values from the spec (or sensible fallbacks when no default is provided). let usage_ctx = Self::make_usage_ctx_from_spec_defaults(&spec_from_field); tera_ctx.insert("usage", &usage_ctx); // Don't insert env for spec-only parsing to avoid expensive environment rendering // Render scripts to trigger spec collection via Tera template functions // (arg/option/flag), but discard the results for script in scripts { Self::render_script_with_context(&mut tera, script, &tera_ctx)?; } let mut cmd = usage::SpecCommand::default(); // TODO: ensure no gaps in args, e.g.: 1,2,3,4,5 let arg_order = arg_order.lock().unwrap(); cmd.args = input_args .lock() .unwrap() .iter() .cloned() .sorted_by_key(|arg| { arg_order .get(&arg.name) .unwrap_or_else(|| panic!("missing arg order for {}", arg.name.as_str())) }) .collect(); cmd.flags = input_flags.lock().unwrap().clone(); // Check for deprecated Tera template args usage Self::check_tera_args_deprecation(&task.name, &cmd.args, &cmd.flags); let mut spec = usage::Spec { cmd, ..Default::default() }; spec.merge(spec_from_field); Ok(spec) } pub async fn parse_run_scripts( &self, config: &Arc<Config>, task: &Task, scripts: &[String], env: &EnvMap, ) -> Result<(Vec<String>, usage::Spec)> { let (mut tera, arg_order, input_args, input_flags) = self.setup_tera_for_spec_parsing(task); let mut tera_ctx = task.tera_ctx(config).await?; tera_ctx.insert("env", &env); // First render the usage field to collect the spec and build a default // usage map, so that `{{ usage.* }}` references in run scripts do not // fail during this initial parsing phase (e.g. for inline tasks). let rendered_usage = Self::render_usage_with_context(&mut tera, &task.usage, &tera_ctx)?; let spec_from_field: usage::Spec = rendered_usage.parse()?; let usage_ctx = Self::make_usage_ctx_from_spec_defaults(&spec_from_field); tera_ctx.insert("usage", &usage_ctx); let scripts = scripts .iter() .map(|s| Self::render_script_with_context(&mut tera, s, &tera_ctx)) .collect::<Result<Vec<String>>>()?; let mut cmd = usage::SpecCommand::default(); // TODO: ensure no gaps in args, e.g.: 1,2,3,4,5 let arg_order = arg_order.lock().unwrap(); cmd.args = input_args .lock() .unwrap() .iter() .cloned() .sorted_by_key(|arg| { arg_order .get(&arg.name) .unwrap_or_else(|| panic!("missing arg order for {}", arg.name.as_str())) }) .collect(); cmd.flags = input_flags.lock().unwrap().clone(); // Check for deprecated Tera template args usage Self::check_tera_args_deprecation(&task.name, &cmd.args, &cmd.flags); let mut spec = usage::Spec { cmd, ..Default::default() }; spec.merge(spec_from_field); Ok((scripts, spec)) } pub async fn parse_run_scripts_with_args( &self, config: &Arc<Config>, task: &Task, scripts: &[String], env: &EnvMap, args: &[String], spec: &usage::Spec, ) -> Result<Vec<String>> { let args = vec!["".to_string()] .into_iter() .chain(args.iter().cloned()) .collect::<Vec<_>>(); let m = match usage::parse(spec, &args) { Ok(m) => m, Err(e) => { // just print exactly what usage returns so the error output isn't double-wrapped // this could be displaying help or a parse error eprintln!("{}", format!("{e}").trim_end()); exit(1); } }; let mut out: Vec<String> = vec![]; for script in scripts { let shell_type = shell_from_shebang(script) .or(task.shell()) .unwrap_or(Settings::get().default_inline_shell()?)[0] .parse() .ok(); let escape = { move |v: &usage::parse::ParseValue| match v { usage::parse::ParseValue::MultiString(_) => { // these are already escaped v.to_string() } _ => match shell_type { Some(ShellType::Zsh | ShellType::Bash | ShellType::Fish) => { shell_words::quote(&v.to_string()).to_string() } _ => v.to_string(), }, } }; let mut tera = self.get_tera(); tera.register_function("arg", { { let usage_args = m.args.clone(); move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { let seen_args = Arc::new(Mutex::new(HashSet::new())); { let mut seen_args = seen_args.lock().unwrap(); let i = args .get("i") .map(|i| i.as_i64().unwrap() as usize) .unwrap_or_else(|| seen_args.len()); let name = args .get("name") .map(|n| n.as_str().unwrap().to_string()) .unwrap_or(i.to_string()); seen_args.insert(name.clone()); Ok(tera::Value::String( usage_args .iter() .find(|(arg, _)| arg.name == name) .map(|(_, value)| escape(value)) .unwrap_or("".to_string()), )) } } } }); let flag_func = { |default_value: String| { let usage_flags = m.flags.clone(); move |args: &HashMap<String, tera::Value>| -> tera::Result<tera::Value> { let name = args .get("name") .map(|n| n.as_str().unwrap().to_string()) .unwrap(); Ok(tera::Value::String( usage_flags .iter() .find(|(flag, _)| flag.name == name) .map(|(_, value)| escape(value)) .unwrap_or(default_value.clone()), )) } } }; tera.register_function("option", flag_func("".to_string())); tera.register_function("flag", flag_func(false.to_string())); let mut tera_ctx = task.tera_ctx(config).await?; tera_ctx.insert("env", &env); tera_ctx.insert("usage", &Self::make_usage_ctx(&m)); out.push(Self::render_script_with_context( &mut tera, script, &tera_ctx, )?); } Ok(out) } fn make_usage_ctx(usage: &usage::parse::ParseOutput) -> HashMap<String, tera::Value> { let mut usage_ctx: HashMap<String, tera::Value> = HashMap::new(); // These values are not escaped or shell-quoted. let to_tera_value = |val: &usage::parse::ParseValue| -> tera::Value { use tera::Value; use usage::parse::ParseValue::*; match val { MultiBool(v) => Value::Array(v.iter().map(|b| Value::Bool(*b)).collect()), MultiString(v) => { Value::Array(v.iter().map(|s| Value::String(s.clone())).collect()) } Bool(v) => Value::Bool(*v), String(v) => Value::String(v.clone()), } }; // The names are converted to snake_case (hyphens become underscores). // For example, a flag like "--dry-run" becomes accessible as {{ usage.dry_run }}. for (arg, val) in &usage.args { let tera_val = to_tera_value(val); usage_ctx.insert(arg.name.to_snake_case(), tera_val); } for (flag, val) in &usage.flags { let tera_val = to_tera_value(val); usage_ctx.insert(flag.name.to_snake_case(), tera_val); } usage_ctx } /// Build a usage context hashmap from a `usage::Spec`, using default values /// defined in the spec or sensible fallbacks when no defaults are provided. /// Only needed for deprecated parsing of run scripts for collecting the spec. /// /// - Args: /// - Non-var args use an empty string. /// - Var args use an empty array. /// - Flags: /// - Value flags (`var = true`) use an empty array. /// - Count flags (`count = true`) use a `Vec<bool>` whose length is /// derived from the default (parsed as a usize) or an empty array. /// - Simple flags use `false`. fn make_usage_ctx_from_spec_defaults(spec: &usage::Spec) -> HashMap<String, tera::Value> { let mut usage_ctx: HashMap<String, tera::Value> = HashMap::new(); // Args
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
true
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_helpers.rs
src/task/task_helpers.rs
use crate::task::Task; use std::path::{Path, PathBuf}; /// Check if a task needs a permit from the semaphore /// Only shell/script tasks execute external commands and need a concurrency slot. /// Orchestrator-only tasks (pure groups of sub-tasks) do not. pub fn task_needs_permit(task: &Task) -> bool { task.file.is_some() || !task.run_script_strings().is_empty() } /// Canonicalize a path for use as cache key /// Falls back to original path if canonicalization fails pub fn canonicalize_path(path: &Path) -> PathBuf { path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_context_builder.rs
src/task/task_context_builder.rs
use crate::cli::args::ToolArg; use crate::config::Config; use crate::config::config_file::ConfigFile; use crate::config::env_directive::EnvDirective; use crate::env; use crate::task::Task; use crate::task::task_helpers::canonicalize_path; use crate::toolset::{Toolset, ToolsetBuilder}; use eyre::Result; use indexmap::IndexMap; use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::{Arc, RwLock}; type EnvResolutionResult = (BTreeMap<String, String>, Vec<(String, String)>); /// Builds toolset and environment context for task execution /// /// Handles: /// - Toolset caching for monorepo tasks /// - Environment resolution with config file contexts /// - Tool request set caching pub struct TaskContextBuilder { toolset_cache: RwLock<IndexMap<PathBuf, Arc<Toolset>>>, tool_request_set_cache: RwLock<IndexMap<PathBuf, Arc<crate::toolset::ToolRequestSet>>>, env_resolution_cache: RwLock<IndexMap<PathBuf, EnvResolutionResult>>, } impl Clone for TaskContextBuilder { fn clone(&self) -> Self { // Clone by creating a new instance with the same cache contents Self { toolset_cache: RwLock::new(self.toolset_cache.read().unwrap().clone()), tool_request_set_cache: RwLock::new( self.tool_request_set_cache.read().unwrap().clone(), ), env_resolution_cache: RwLock::new(self.env_resolution_cache.read().unwrap().clone()), } } } impl TaskContextBuilder { pub fn new() -> Self { Self { toolset_cache: RwLock::new(IndexMap::new()), tool_request_set_cache: RwLock::new(IndexMap::new()), env_resolution_cache: RwLock::new(IndexMap::new()), } } /// Build toolset for a task, with caching for monorepo tasks pub async fn build_toolset_for_task( &self, config: &Arc<Config>, task: &Task, task_cf: Option<&Arc<dyn ConfigFile>>, tools: &[ToolArg], ) -> Result<Toolset> { // Only use task-specific config file context for monorepo tasks // (tasks with self.cf set, not just those with a config_source) if let (Some(task_cf), Some(_)) = (task_cf, &task.cf) { let config_path = canonicalize_path(task_cf.get_path()); trace!( "task {} using monorepo config file context from {}", task.name, config_path.display() ); // Check cache first if no task-specific tools or CLI args if tools.is_empty() && task.tools.is_empty() { let cache = self .toolset_cache .read() .expect("toolset_cache RwLock poisoned"); if let Some(cached_ts) = cache.get(&config_path) { trace!( "task {} using cached toolset from {}", task.name, config_path.display() ); // Clone Arc, not the entire Toolset return Ok(Arc::unwrap_or_clone(Arc::clone(cached_ts))); } } // Build a toolset from all config files in the hierarchy // This ensures tools are inherited from parent configs // Start by building a toolset from all global config files // This includes parent configs but NOT the subdirectory config let mut task_ts = ToolsetBuilder::new().build(config).await?; trace!( "task {} base toolset from global configs: {:?}", task.name, task_ts ); // Then merge the subdirectory's config file tools on top // This allows subdirectories to override parent tools let subdir_toolset = task_cf.to_toolset()?; trace!( "task {} merging subdirectory tools from {}: {:?}", task.name, task_cf.get_path().display(), subdir_toolset ); task_ts.merge(subdir_toolset); trace!("task {} final merged toolset: {:?}", task.name, task_ts); // Add task-specific tools and CLI args if !tools.is_empty() { let arg_toolset = ToolsetBuilder::new().with_args(tools).build(config).await?; // Merge task-specific tools into the config file's toolset task_ts.merge(arg_toolset); } // Resolve the final toolset task_ts.resolve(config).await?; // Cache the toolset if no task-specific tools or CLI args if tools.is_empty() && task.tools.is_empty() { let mut cache = self .toolset_cache .write() .expect("toolset_cache RwLock poisoned"); cache.insert(config_path.clone(), Arc::new(task_ts.clone())); trace!( "task {} cached toolset to {}", task.name, config_path.display() ); } Ok(task_ts) } else { trace!("task {} using standard toolset build", task.name); // Standard toolset build - includes all config files ToolsetBuilder::new().with_args(tools).build(config).await } } /// Resolve environment variables for a task using its config file context /// This is used for monorepo tasks to load env vars from subdirectory mise.toml files pub async fn resolve_task_env_with_config( &self, config: &Arc<Config>, task: &Task, task_cf: &Arc<dyn ConfigFile>, ts: &Toolset, ) -> Result<(BTreeMap<String, String>, Vec<(String, String)>)> { // Determine if this is a monorepo task (task config differs from current project root) let is_monorepo_task = task_cf.project_root() != config.project_root; // Check if task runs in the current working directory let task_runs_in_cwd = task .dir(config) .await? .and_then(|dir| config.project_root.as_ref().map(|pr| dir == *pr)) .unwrap_or(false); // Get env entries - load the FULL config hierarchy for monorepo tasks let all_config_env_entries: Vec<(crate::config::env_directive::EnvDirective, PathBuf)> = if is_monorepo_task && !task_runs_in_cwd { // For monorepo tasks that DON'T run in cwd: Load config hierarchy from the task's directory // This includes parent configs AND MISE_ENV-specific configs let task_dir = task_cf.get_path().parent().unwrap_or(task_cf.get_path()); trace!( "Loading config hierarchy for monorepo task {} from {}", task.name, task_dir.display() ); // Load all config files in the hierarchy let config_paths = crate::config::load_config_hierarchy_from_dir(task_dir)?; trace!("Found {} config files in hierarchy", config_paths.len()); let task_config_files = crate::config::load_config_files_from_paths(&config_paths).await?; // Extract env entries from all config files task_config_files .iter() .rev() .filter_map(|(source, cf)| { cf.env_entries() .ok() .map(|entries| entries.into_iter().map(move |e| (e, source.clone()))) }) .flatten() .collect() } else { // For regular tasks OR monorepo tasks that run in cwd: // Use ALL config files from the current project (including MISE_ENV-specific ones) // This fixes env inheritance for tasks with dir="{{cwd}}" config .config_files .iter() .rev() .filter_map(|(source, cf)| { cf.env_entries() .ok() .map(|entries| entries.into_iter().map(move |e| (e, source.clone()))) }) .flatten() .collect() }; // Early return if no special context needed // Check using task_cf entries for compatibility with existing logic let task_cf_env_entries = task_cf.env_entries()?; if self.should_use_standard_env_resolution(task, task_cf, config, &task_cf_env_entries) { return task.render_env(config, ts).await; } let config_path = canonicalize_path(task_cf.get_path()); // Check cache first if task has no task-specific env directives if task.env.0.is_empty() { let cache = self .env_resolution_cache .read() .expect("env_resolution_cache RwLock poisoned"); if let Some(cached_env) = cache.get(&config_path) { trace!( "task {} using cached env resolution from {}", task.name, config_path.display() ); return Ok(cached_env.clone()); } } let mut env = ts.full_env(config).await?; let tera_ctx = self.build_tera_context(task_cf, ts, config).await?; // Resolve config-level env from ALL config files, not just task_cf let config_env_results = self .resolve_env_directives(config, &tera_ctx, &env, all_config_env_entries) .await?; Self::apply_env_results(&mut env, &config_env_results); let task_env_directives = self.build_task_env_directives(task); let task_env_results = self .resolve_env_directives(config, &tera_ctx, &env, task_env_directives) .await?; let task_env = self.extract_task_env(&task_env_results); Self::apply_env_results(&mut env, &task_env_results); // Cache the result if no task-specific env directives if task.env.0.is_empty() { let mut cache = self .env_resolution_cache .write() .expect("env_resolution_cache RwLock poisoned"); // Double-check: another thread may have populated while we were resolving cache.entry(config_path.clone()).or_insert_with(|| { trace!( "task {} cached env resolution to {}", task.name, config_path.display() ); (env.clone(), task_env.clone()) }); } Ok((env, task_env)) } /// Check if standard env resolution should be used instead of special context fn should_use_standard_env_resolution( &self, task: &Task, task_cf: &Arc<dyn ConfigFile>, config: &Arc<Config>, config_env_entries: &[EnvDirective], ) -> bool { if let (Some(task_config_root), Some(current_config_root)) = (task_cf.project_root(), config.project_root.as_ref()) && task_config_root == *current_config_root && config_env_entries.is_empty() { trace!( "task {} config root matches current and no config env, using standard env resolution", task.name ); return true; } false } /// Build tera context with config_root for monorepo tasks async fn build_tera_context( &self, task_cf: &Arc<dyn ConfigFile>, ts: &Toolset, config: &Arc<Config>, ) -> Result<tera::Context> { let mut tera_ctx = ts.tera_ctx(config).await?.clone(); if let Some(root) = task_cf.project_root() { tera_ctx.insert("config_root", &root); } Ok(tera_ctx) } /// Build env directives from task-specific env fn build_task_env_directives(&self, task: &Task) -> Vec<(EnvDirective, PathBuf)> { task.env .0 .iter() .map(|directive| (directive.clone(), task.config_source.clone())) .collect() } /// Resolve env directives using EnvResults async fn resolve_env_directives( &self, config: &Arc<Config>, tera_ctx: &tera::Context, env: &BTreeMap<String, String>, directives: Vec<(EnvDirective, PathBuf)>, ) -> Result<crate::config::env_directive::EnvResults> { use crate::config::env_directive::{EnvResolveOptions, EnvResults, ToolsFilter}; EnvResults::resolve( config, tera_ctx.clone(), env, directives, EnvResolveOptions { vars: false, tools: ToolsFilter::Both, warn_on_missing_required: false, }, ) .await } /// Extract task env from EnvResults (only task-specific directives) fn extract_task_env( &self, task_env_results: &crate::config::env_directive::EnvResults, ) -> Vec<(String, String)> { task_env_results .env .iter() .map(|(k, (v, _))| (k.clone(), v.clone())) .collect() } /// Apply EnvResults to an environment map /// Handles env vars, env_remove, and env_paths (PATH modifications) fn apply_env_results( env: &mut BTreeMap<String, String>, results: &crate::config::env_directive::EnvResults, ) { // Apply environment variables for (k, (v, _)) in &results.env { env.insert(k.clone(), v.clone()); } // Remove explicitly unset variables for key in &results.env_remove { env.remove(key); } // Apply path additions if !results.env_paths.is_empty() { use crate::path_env::PathEnv; let mut path_env = PathEnv::from_iter(env::split_paths( &env.get(&*env::PATH_KEY).cloned().unwrap_or_default(), )); for path in &results.env_paths { path_env.add(path.clone()); } env.insert(env::PATH_KEY.to_string(), path_env.to_string()); } } /// Get access to the tool request set cache for collecting tools pub fn tool_request_set_cache( &self, ) -> &RwLock<IndexMap<PathBuf, Arc<crate::toolset::ToolRequestSet>>> { &self.tool_request_set_cache } } impl Default for TaskContextBuilder { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_task_context_builder_new() { let builder = TaskContextBuilder::new(); assert!(builder.toolset_cache.read().unwrap().is_empty()); assert!(builder.tool_request_set_cache.read().unwrap().is_empty()); assert!(builder.env_resolution_cache.read().unwrap().is_empty()); } #[test] fn test_apply_env_results_basic() { let mut env = BTreeMap::new(); env.insert("EXISTING".to_string(), "value".to_string()); let mut results = crate::config::env_directive::EnvResults::default(); results.env.insert( "NEW_VAR".to_string(), ("new_value".to_string(), PathBuf::from("/test")), ); TaskContextBuilder::apply_env_results(&mut env, &results); assert_eq!(env.get("EXISTING"), Some(&"value".to_string())); assert_eq!(env.get("NEW_VAR"), Some(&"new_value".to_string())); } #[test] fn test_apply_env_results_removes_vars() { let mut env = BTreeMap::new(); env.insert("TO_REMOVE".to_string(), "value".to_string()); env.insert("TO_KEEP".to_string(), "value".to_string()); let mut results = crate::config::env_directive::EnvResults::default(); results.env_remove.insert("TO_REMOVE".to_string()); TaskContextBuilder::apply_env_results(&mut env, &results); assert_eq!(env.get("TO_REMOVE"), None); assert_eq!(env.get("TO_KEEP"), Some(&"value".to_string())); } #[test] fn test_apply_env_results_path_handling() { let mut env = BTreeMap::new(); env.insert(env::PATH_KEY.to_string(), "/existing/path".to_string()); let mut results = crate::config::env_directive::EnvResults::default(); results .env_paths .push(PathBuf::from("/new/path").to_path_buf()); TaskContextBuilder::apply_env_results(&mut env, &results); let path = env.get(&*env::PATH_KEY).unwrap(); assert!(path.contains("/new/path")); } #[test] fn test_extract_task_env() { let builder = TaskContextBuilder::new(); let mut results = crate::config::env_directive::EnvResults::default(); results.env.insert( "VAR1".to_string(), ("value1".to_string(), PathBuf::from("/test")), ); results.env.insert( "VAR2".to_string(), ("value2".to_string(), PathBuf::from("/test")), ); let task_env = builder.extract_task_env(&results); assert_eq!(task_env.len(), 2); assert!(task_env.contains(&("VAR1".to_string(), "value1".to_string()))); assert!(task_env.contains(&("VAR2".to_string(), "value2".to_string()))); } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_list.rs
src/task/task_list.rs
use crate::config::{self, Config, Settings}; use crate::file::display_path; use crate::task::{ GetMatchingExt, Task, TaskLoadContext, extract_monorepo_path, resolve_task_pattern, }; use crate::ui::ctrlc; use crate::ui::{prompt, style}; use crate::{dirs, file}; use console::Term; use demand::{DemandOption, Select}; use eyre::{Result, bail, ensure, eyre}; use fuzzy_matcher::{FuzzyMatcher, skim::SkimMatcherV2}; use itertools::Itertools; use std::collections::HashSet; use std::iter::once; use std::path::PathBuf; use std::sync::Arc; /// Split a task spec into name and args /// e.g., "task arg1 arg2" -> ("task", vec!["arg1", "arg2"]) pub fn split_task_spec(spec: &str) -> (&str, Vec<String>) { let mut parts = spec.split_whitespace(); let name = parts.next().unwrap_or(""); let args = parts.map(|s| s.to_string()).collect_vec(); (name, args) } /// Validate that monorepo features are properly configured fn validate_monorepo_setup(config: &Arc<Config>) -> Result<()> { // Check if experimental mode is enabled if !Settings::get().experimental { bail!( "Monorepo task paths (like `//path:task` or `:task`) require experimental mode.\n\ \n\ To enable experimental features, set:\n\ {}\n\ \n\ Or run with: {}", style::eyellow(" export MISE_EXPERIMENTAL=true"), style::eyellow("MISE_EXPERIMENTAL=1 mise run ...") ); } // Check if a monorepo root is configured if !config.is_monorepo() { bail!( "Monorepo task paths (like `//path:task` or `:task`) require a monorepo root configuration.\n\ \n\ To set up monorepo support, add this to your root mise.toml:\n\ {}\n\ \n\ Then create task files in subdirectories that will be automatically discovered.\n\ See {} for more information.", style::eyellow(" experimental_monorepo_root = true"), style::eunderline( "https://mise.jdx.dev/tasks/task-configuration.html#monorepo-support" ) ); } Ok(()) } /// Show an error when a task is not found, with helpful suggestions async fn err_no_task(config: &Config, name: &str) -> Result<()> { if config.tasks().await.is_ok_and(|t| t.is_empty()) { // Check if there are any untrusted config files in the current directory // that might contain tasks if let Some(cwd) = &*dirs::CWD { use crate::config::config_file::{config_trust_root, is_trusted}; use crate::config::config_files_in_dir; let config_files = config_files_in_dir(cwd); let untrusted_configs: Vec<_> = config_files .iter() .filter(|p| !is_trusted(&config_trust_root(p)) && !is_trusted(p)) .collect(); if !untrusted_configs.is_empty() { let paths = untrusted_configs .iter() .map(display_path) .collect::<Vec<_>>() .join(", "); bail!( "Config file(s) in {} are not trusted: {}\nTrust them with `mise trust`. See https://mise.jdx.dev/cli/trust.html for more information.", display_path(cwd), paths ); } } bail!( "no tasks defined in {}. Are you in a project directory?", display_path(dirs::CWD.clone().unwrap_or_default()) ); } if let Some(cwd) = &*dirs::CWD { let includes = config::task_includes_for_dir(cwd, &config.config_files); let path = includes .iter() .map(|d| d.join(name)) .find(|d| d.is_file() && !file::is_executable(d)); if let Some(path) = path && !cfg!(windows) { warn!( "no task {} found, but a non-executable file exists at {}", style::ered(name), display_path(&path) ); let yn = prompt::confirm("Mark this file as executable to allow it to be run as a task?")?; if yn { file::make_executable(&path)?; info!("marked as executable, try running this task again"); } } } // Suggest similar tasks using fuzzy matching for monorepo tasks let mut err_msg = format!("no task {} found", style::ered(name)); if name.starts_with("//") { // Load ALL monorepo tasks for suggestions if let Ok(tasks) = config .tasks_with_context(Some(&TaskLoadContext::all())) .await { let matcher = SkimMatcherV2::default().use_cache(true).smart_case(); let similar: Vec<String> = tasks .keys() .filter(|k| k.starts_with("//")) .filter_map(|k| { matcher .fuzzy_match(&k.to_lowercase(), &name.to_lowercase()) .map(|score| (score, k.clone())) }) .sorted_by_key(|(score, _)| -1 * *score) .take(5) .map(|(_, k)| k) .collect(); if !similar.is_empty() { err_msg.push_str("\n\nDid you mean one of these?"); for task_name in similar { err_msg.push_str(&format!("\n - {}", task_name)); } } } } bail!(err_msg); } /// Prompt the user to select a task interactively async fn prompt_for_task() -> Result<Task> { let config = Config::get().await?; let tasks = config.tasks().await?; ensure!( !tasks.is_empty(), "no tasks defined. see {url}", url = style::eunderline("https://mise.jdx.dev/tasks/") ); let theme = crate::ui::theme::get_theme(); let mut s = Select::new("Tasks") .description("Select a task to run") .filtering(true) .filterable(true) .theme(&theme); for t in tasks.values().filter(|t| !t.hide) { // Truncate description to first line only, like tasks ls does let desc = t.description.lines().next().unwrap_or_default(); s = s.option( DemandOption::new(&t.name) .label(&t.display_name) .description(desc), ); } ctrlc::show_cursor_after_ctrl_c(); match s.run() { Ok(name) => match tasks.get(name) { Some(task) => Ok(task.clone()), None => bail!("no tasks {} found", style::ered(name)), }, Err(err) => { Term::stderr().show_cursor()?; Err(eyre!(err)) } } } /// Get a list of tasks to run from command-line arguments /// Handles task patterns, monorepo paths, and interactive selection pub async fn get_task_lists( config: &Arc<Config>, args: &[String], prompt: bool, only: bool, ) -> Result<Vec<Task>> { let args = args .iter() .map(|s| vec![s.to_string()]) .coalesce(|a, b| { if b == vec![":::".to_string()] { Err((a, b)) } else if a == vec![":::".to_string()] { Ok(b) } else { Ok(a.into_iter().chain(b).collect_vec()) } }) .flat_map(|args| args.split_first().map(|(t, a)| (t.clone(), a.to_vec()))) .collect::<Vec<_>>(); // Determine the appropriate task loading context based on patterns // For monorepo patterns, we need to load tasks from the relevant parts of the monorepo let task_context = if args.is_empty() { None } else { // Collect all monorepo patterns let monorepo_patterns: Vec<&str> = args .iter() .filter_map(|(t, _)| { if t.starts_with("//") || t.contains("...") || t.starts_with(':') { Some(t.as_str()) } else { None } }) .collect(); if monorepo_patterns.is_empty() { None } else { // Validate monorepo setup before attempting to load tasks validate_monorepo_setup(config)?; // Merge all path hints from the patterns into a single context Some(TaskLoadContext::from_patterns( monorepo_patterns.into_iter(), )) } }; let mut tasks = vec![]; let arg_re = xx::regex!(r#"^((\.*|~)(/|\\)|\w:\\)"#); for (t, args) in args { // Expand :task pattern to match tasks in current directory's config root let t = crate::task::expand_colon_task_syntax(&t, config)?; // can be any of the following: // - ./path/to/script // - ~/path/to/script // - /path/to/script // - ../path/to/script // - C:\path\to\script // - .\path\to\script if arg_re.is_match(&t) { let path = PathBuf::from(&t); if path.exists() { let config_root = config .project_root .clone() .or_else(|| dirs::CWD.clone()) .unwrap_or_default(); let task = Task::from_path(config, &path, &PathBuf::new(), &config_root).await?; return Ok(vec![task.with_args(args)]); } } // Load tasks with the appropriate context let all_tasks = if let Some(ref ctx) = task_context { config.tasks_with_context(Some(ctx)).await? } else { config.tasks().await? }; let tasks_with_aliases = crate::task::build_task_ref_map(all_tasks.iter()); let cur_tasks = tasks_with_aliases .get_matching(&t)? .into_iter() .cloned() .collect_vec(); if cur_tasks.is_empty() { // Check if this is a "default" task (either plain "default" or monorepo syntax like "//:default") // For monorepo tasks, ensure it starts with "//" and has exactly one ":" before "default" // This matches "//:default" and "//subfolder:default" but not "//subfolder:task-group:default" let is_default_task = t == "default" || { t.starts_with("//") && t.ends_with(":default") && t[2..].matches(':').count() == 1 }; if !is_default_task || !prompt || !console::user_attended_stderr() { err_no_task(config, &t).await?; } tasks.push(prompt_for_task().await?); } else { cur_tasks .into_iter() .map(|t| t.clone().with_args(args.to_vec())) .for_each(|t| tasks.push(t)); } } if only { for task in &mut tasks { task.depends.clear(); task.depends_post.clear(); task.wait_for.clear(); } } Ok(tasks) } /// Resolve all dependencies for a list of tasks /// Iteratively discovers path hints by loading tasks and their dependencies pub async fn resolve_depends(config: &Arc<Config>, tasks: Vec<Task>) -> Result<Vec<Task>> { // Iteratively discover all path hints by loading tasks and their dependencies // This handles chains like: //A:B -> :C -> :D -> //E:F where we need to discover E let mut all_path_hints = HashSet::new(); let mut tasks_to_process: Vec<Task> = tasks.clone(); let mut processed_tasks = HashSet::new(); // Iteratively discover paths until no new paths are found while !tasks_to_process.is_empty() { // Extract path hints from current batch of tasks let new_hints: Vec<String> = tasks_to_process .iter() .filter_map(|t| extract_monorepo_path(&t.name)) .chain(tasks_to_process.iter().flat_map(|t| { t.depends .iter() .chain(t.wait_for.iter()) .chain(t.depends_post.iter()) .map(|td| resolve_task_pattern(&td.task, Some(t))) .filter_map(|resolved| extract_monorepo_path(&resolved)) })) .collect(); // Check if we found any new paths let had_new_hints = new_hints.iter().any(|h| all_path_hints.insert(h.clone())); if !had_new_hints { break; } // Load tasks with current path hints to discover dependencies let ctx = Some(TaskLoadContext { path_hints: all_path_hints.iter().cloned().collect(), load_all: false, }); let loaded_tasks = config.tasks_with_context(ctx.as_ref()).await?; // Find new tasks that haven't been processed yet tasks_to_process = loaded_tasks .values() .filter(|t| processed_tasks.insert(t.name.clone())) .cloned() .collect(); } // Now load all tasks with the complete set of path hints let ctx = if !all_path_hints.is_empty() { Some(TaskLoadContext { path_hints: all_path_hints.into_iter().collect(), load_all: false, }) } else { None }; let all_tasks = config.tasks_with_context(ctx.as_ref()).await?; tasks .into_iter() .map(|t| { let depends = t.all_depends(&all_tasks)?; Ok(once(t).chain(depends).collect::<Vec<_>>()) }) .flatten_ok() .collect() }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_source_checker.rs
src/task/task_source_checker.rs
use crate::config::Config; use crate::dirs; use crate::file::{self, display_path}; use crate::hash; use crate::task::Task; use eyre::{Result, eyre}; use glob::glob; use itertools::Itertools; use std::collections::BTreeMap; use std::fs; use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::SystemTime; /// Check if a path is a glob pattern pub fn is_glob_pattern(path: &str) -> bool { // This is the character set used for glob detection by glob let glob_chars = ['*', '{', '}']; path.chars().any(|c| glob_chars.contains(&c)) } /// Get the last modified time from a list of paths pub(crate) fn last_modified_path(root: &Path, paths: &[&String]) -> Result<Option<SystemTime>> { let files = paths.iter().map(|p| { let base = Path::new(p); if base.is_relative() { Path::new(&root).join(base) } else { base.to_path_buf() } }); last_modified_file(files) } /// Get the last modified time from files matching glob patterns pub(crate) fn last_modified_glob_match( root: impl AsRef<Path>, patterns: &[&String], ) -> Result<Option<SystemTime>> { if patterns.is_empty() { return Ok(None); } let files = patterns .iter() .flat_map(|pattern| { glob( root.as_ref() .join(pattern) .to_str() .expect("Conversion to string path failed"), ) .unwrap() }) .filter_map(|e| e.ok()) .filter(|e| { e.metadata() .expect("Metadata call failed") .file_type() .is_file() }); last_modified_file(files) } /// Get the last modified time from an iterator of file paths pub(crate) fn last_modified_file( files: impl IntoIterator<Item = PathBuf>, ) -> Result<Option<SystemTime>> { Ok(files .into_iter() .unique() .filter(|p| p.exists()) .map(|p| { p.metadata() .map_err(|err| eyre!("{}: {}", display_path(p), err)) }) .collect::<Result<Vec<_>>>()? .into_iter() .map(|m| m.modified().map_err(|err| eyre!(err))) .collect::<Result<Vec<_>>>()? .into_iter() .max()) } /// Get the working directory for a task pub async fn task_cwd(task: &Task, config: &Arc<Config>) -> Result<PathBuf> { if let Some(d) = task.dir(config).await? { Ok(d) } else { Ok(config .project_root .clone() .or_else(|| dirs::CWD.clone()) .unwrap_or_default()) } } /// Check if task sources are up to date (fresher than outputs) pub async fn sources_are_fresh(task: &Task, config: &Arc<Config>) -> Result<bool> { if task.sources.is_empty() { return Ok(false); } // TODO: We should benchmark this and find out if it might be possible to do some caching around this or something // perhaps using some manifest in a state directory or something, maybe leveraging atime? let run = async || -> Result<bool> { let root = task_cwd(task, config).await?; let mut sources = task.sources.clone(); sources.push(task.config_source.to_string_lossy().to_string()); let source_metadatas = get_file_metadatas(&root, &sources)?; let source_metadata_hash = file_metadatas_to_hash(&source_metadatas); let source_metadata_hash_path = sources_hash_path(task); if let Some(dir) = source_metadata_hash_path.parent() { file::create_dir_all(dir)?; } if source_metadata_existing_hash(task).is_some_and(|h| h != source_metadata_hash) { debug!( "source metadata hash mismatch in {}", source_metadata_hash_path.display() ); file::write(&source_metadata_hash_path, &source_metadata_hash)?; return Ok(false); } let sources = get_last_modified_from_metadatas(&source_metadatas); let outputs = get_last_modified(&root, &task.outputs.paths(task))?; file::write(&source_metadata_hash_path, &source_metadata_hash)?; trace!("sources: {sources:?}, outputs: {outputs:?}"); match (sources, outputs) { (Some(sources), Some(outputs)) => Ok(sources < outputs), _ => Ok(false), } }; Ok(run().await.unwrap_or_else(|err| { warn!("sources_are_fresh: {err:?}"); false })) } /// Save a checksum file after a task completes successfully pub fn save_checksum(task: &Task) -> Result<()> { if task.sources.is_empty() { return Ok(()); } if task.outputs.is_auto() { for p in task.outputs.paths(task) { debug!("touching auto output file: {p}"); file::touch_file(&PathBuf::from(&p))?; } } Ok(()) } /// Get the path to store source hashes for a task fn sources_hash_path(task: &Task) -> PathBuf { let mut hasher = DefaultHasher::new(); task.hash(&mut hasher); task.config_source.hash(&mut hasher); let hash = format!("{:x}", hasher.finish()); dirs::STATE.join("task-sources").join(&hash) } /// Get the existing source hash for a task, if it exists fn source_metadata_existing_hash(task: &Task) -> Option<String> { let path = sources_hash_path(task); if path.exists() { Some(file::read_to_string(&path).unwrap_or_default()) } else { None } } /// Get file metadata for a list of patterns or paths fn get_file_metadatas( root: &Path, patterns_or_paths: &[String], ) -> Result<Vec<(PathBuf, fs::Metadata)>> { if patterns_or_paths.is_empty() { return Ok(vec![]); } let (patterns, paths): (Vec<&String>, Vec<&String>) = patterns_or_paths.iter().partition(|p| is_glob_pattern(p)); let mut metadatas = BTreeMap::new(); for pattern in patterns { let files = glob(root.join(pattern).to_str().unwrap())?; for file in files.flatten() { if let Ok(metadata) = file.metadata() { metadatas.insert(file, metadata); } } } for path in paths { let file = root.join(path); if let Ok(metadata) = file.metadata() { metadatas.insert(file, metadata); } } let metadatas = metadatas .into_iter() .filter(|(_, m)| m.is_file()) .collect_vec(); Ok(metadatas) } /// Convert file metadata to a hash string for comparison fn file_metadatas_to_hash(metadatas: &[(PathBuf, fs::Metadata)]) -> String { let paths: Vec<_> = metadatas.iter().map(|(p, _)| p).collect(); hash::hash_to_str(&paths) } /// Get the last modified time from file metadata fn get_last_modified_from_metadatas(metadatas: &[(PathBuf, fs::Metadata)]) -> Option<SystemTime> { metadatas.iter().flat_map(|(_, m)| m.modified()).max() } /// Get the last modified time from a list of patterns or paths fn get_last_modified(root: &Path, patterns_or_paths: &[String]) -> Result<Option<SystemTime>> { if patterns_or_paths.is_empty() { return Ok(None); } let (patterns, paths): (Vec<&String>, Vec<&String>) = patterns_or_paths.iter().partition(|p| is_glob_pattern(p)); let last_mod = std::cmp::max( last_modified_glob_match(root, &patterns)?, last_modified_path(root, &paths)?, ); trace!( "last_modified of {}: {last_mod:?}", patterns_or_paths.iter().join(" ") ); Ok(last_mod) }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_output_handler.rs
src/task/task_output_handler.rs
use crate::config::Settings; use crate::task::Task; use crate::task::task_output::TaskOutput; use crate::ui::multi_progress_report::MultiProgressReport; use crate::ui::progress_report::SingleReport; use indexmap::IndexMap; use std::sync::{Arc, Mutex}; use std::time::SystemTime; type KeepOrderOutputs = (Vec<(String, String)>, Vec<(String, String)>); /// Configuration for OutputHandler pub struct OutputHandlerConfig { pub prefix: bool, pub interleave: bool, pub output: Option<TaskOutput>, pub silent: bool, pub quiet: bool, pub raw: bool, pub is_linear: bool, pub jobs: Option<usize>, } /// Handles task output routing, formatting, and display pub struct OutputHandler { pub keep_order_output: Arc<Mutex<IndexMap<Task, KeepOrderOutputs>>>, pub task_prs: IndexMap<Task, Arc<Box<dyn SingleReport>>>, pub timed_outputs: Arc<Mutex<IndexMap<String, (SystemTime, String)>>>, // Configuration from CLI args prefix: bool, interleave: bool, output: Option<TaskOutput>, silent: bool, quiet: bool, raw: bool, is_linear: bool, jobs: Option<usize>, } impl Clone for OutputHandler { fn clone(&self) -> Self { Self { keep_order_output: self.keep_order_output.clone(), task_prs: self.task_prs.clone(), timed_outputs: self.timed_outputs.clone(), prefix: self.prefix, interleave: self.interleave, output: self.output, silent: self.silent, quiet: self.quiet, raw: self.raw, is_linear: self.is_linear, jobs: self.jobs, } } } impl OutputHandler { pub fn new(config: OutputHandlerConfig) -> Self { Self { keep_order_output: Arc::new(Mutex::new(IndexMap::new())), task_prs: IndexMap::new(), timed_outputs: Arc::new(Mutex::new(IndexMap::new())), prefix: config.prefix, interleave: config.interleave, output: config.output, silent: config.silent, quiet: config.quiet, raw: config.raw, is_linear: config.is_linear, jobs: config.jobs, } } /// Initialize output handling for a task pub fn init_task(&mut self, task: &Task) { match self.output(Some(task)) { TaskOutput::KeepOrder => { self.keep_order_output .lock() .unwrap() .insert(task.clone(), Default::default()); } TaskOutput::Replacing => { let pr = MultiProgressReport::get().add(&task.estyled_prefix()); self.task_prs.insert(task.clone(), Arc::new(pr)); } _ => {} } } /// Determine the output mode for a task pub fn output(&self, task: Option<&Task>) -> TaskOutput { // Check for full silent mode (both streams) // Only Silent::Bool(true) means completely silent, not Silent::Stdout or Silent::Stderr if let Some(task_ref) = task && matches!(task_ref.silent, crate::task::Silent::Bool(true)) { return TaskOutput::Silent; } // Check global output settings if let Some(o) = self.output { return o; } else if let Some(task_ref) = task { // Fall through to other checks if silent is Off if self.silent_bool() { return TaskOutput::Silent; } if self.quiet(Some(task_ref)) { return TaskOutput::Quiet; } } else if self.silent_bool() { return TaskOutput::Silent; } else if self.quiet(task) { return TaskOutput::Quiet; } // CLI flags (--prefix, --interleave) override config settings if self.prefix { TaskOutput::Prefix } else if self.interleave { TaskOutput::Interleave } else if let Some(output) = Settings::get().task_output { // Silent/quiet from config override raw (output suppression takes precedence) // Other modes (prefix, etc.) allow raw to take precedence for stdin/stdout if output.is_silent() || output.is_quiet() { output } else if self.raw(task) { TaskOutput::Interleave } else { output } } else if self.raw(task) || self.jobs() == 1 || self.is_linear { TaskOutput::Interleave } else { TaskOutput::Prefix } } /// Print error message for a task pub fn eprint(&self, task: &Task, prefix: &str, line: &str) { match self.output(Some(task)) { TaskOutput::Replacing => { let pr = self.task_prs.get(task).unwrap().clone(); pr.set_message(format!("{prefix} {line}")); } _ => { prefix_eprintln!(prefix, "{line}"); } } } fn silent_bool(&self) -> bool { self.silent || Settings::get().silent || self.output.is_some_and(|o| o.is_silent()) } pub fn silent(&self, task: Option<&Task>) -> bool { self.silent_bool() || task.is_some_and(|t| t.silent.is_silent()) } pub fn quiet(&self, task: Option<&Task>) -> bool { self.quiet || Settings::get().quiet || self.output.is_some_and(|o| o.is_quiet()) || task.is_some_and(|t| t.quiet) || self.silent(task) } pub fn raw(&self, task: Option<&Task>) -> bool { self.raw || Settings::get().raw || task.is_some_and(|t| t.raw) } pub fn jobs(&self) -> usize { if self.raw { 1 } else { self.jobs.unwrap_or(Settings::get().jobs) } } }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false
jdx/mise
https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/task/task_output.rs
src/task/task_output.rs
use crate::config::Settings; use crate::env; use console; #[derive( Debug, Default, Clone, Copy, PartialEq, strum::Display, strum::EnumString, strum::EnumIs, serde::Serialize, serde::Deserialize, )] #[serde(rename_all = "kebab-case")] #[strum(serialize_all = "kebab-case")] pub enum TaskOutput { Interleave, KeepOrder, #[default] Prefix, Replacing, Timed, Quiet, Silent, } /// Returns the first line of a message for display unless task_show_full_cmd is true /// In CI mode, returns the full first line without truncation /// Otherwise, truncates to terminal width with ellipsis pub fn trunc(prefix: &str, msg: &str) -> String { let settings = Settings::get(); // Skip width truncation when explicitly disabled if settings.task_show_full_cmd { return msg.to_string(); } let msg = msg.lines().next().unwrap_or_default(); if settings.ci { return msg.to_string(); } let prefix_len = console::measure_text_width(prefix); // Ensure we have at least 20 characters for the message, even with very long prefixes let available_width = (*env::TERM_WIDTH).saturating_sub(prefix_len + 1); let max_width = available_width.max(20); // Always show at least 20 chars of message console::truncate_str(msg, max_width, "…").to_string() }
rust
MIT
3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb
2026-01-04T15:39:11.175160Z
false