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/toolset/builder.rs | src/toolset/builder.rs | use std::sync::Arc;
use eyre::Result;
use itertools::Itertools;
use crate::cli::args::{BackendArg, ToolArg};
use crate::config::Config;
use crate::env_diff::EnvMap;
use crate::errors::Error;
use crate::toolset::{ResolveOptions, ToolRequest, ToolSource, Toolset};
use crate::{config, env};
#[derive(Debug, Default)]
pub struct ToolsetBuilder {
args: Vec<ToolArg>,
global_only: bool,
default_to_latest: bool,
resolve_options: ResolveOptions,
}
impl ToolsetBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn with_args(mut self, args: &[ToolArg]) -> Self {
self.args = args.to_vec();
self
}
pub fn with_default_to_latest(mut self, default_to_latest: bool) -> Self {
self.default_to_latest = default_to_latest;
self
}
pub fn with_global_only(mut self, global_only: bool) -> Self {
self.global_only = global_only;
self
}
pub fn with_resolve_options(mut self, resolve_options: ResolveOptions) -> Self {
self.resolve_options = resolve_options;
self
}
pub async fn build(self, config: &Arc<Config>) -> Result<Toolset> {
let mut toolset = Toolset {
..Default::default()
};
measure!("toolset_builder::build::load_config_files", {
self.load_config_files(config, &mut toolset)?;
});
measure!("toolset_builder::build::load_runtime_env", {
self.load_runtime_env(&mut toolset, env::vars_safe().collect())?;
});
measure!("toolset_builder::build::load_runtime_args", {
self.load_runtime_args(&mut toolset)?;
});
measure!("toolset_builder::build::resolve", {
if let Err(err) = toolset
.resolve_with_opts(config, &self.resolve_options)
.await
{
if Error::is_argument_err(&err) {
return Err(err);
}
warn!("failed to resolve toolset: {err}");
}
});
time!("toolset::builder::build");
Ok(toolset)
}
fn load_config_files(&self, config: &Arc<Config>, ts: &mut Toolset) -> eyre::Result<()> {
for cf in config.config_files.values().rev() {
if self.global_only && !config::is_global_config(cf.get_path()) {
continue;
}
ts.merge(cf.to_toolset()?);
}
Ok(())
}
fn load_runtime_env(&self, ts: &mut Toolset, env: EnvMap) -> eyre::Result<()> {
for (k, v) in env {
if k.starts_with("MISE_") && k.ends_with("_VERSION") && k != "MISE_VERSION" {
let plugin_name = k
.trim_start_matches("MISE_")
.trim_end_matches("_VERSION")
.to_lowercase();
if plugin_name == "install" {
// ignore MISE_INSTALL_VERSION
continue;
}
let ba: Arc<BackendArg> = Arc::new(plugin_name.as_str().into());
let source = ToolSource::Environment(k, v.clone());
let mut env_ts = Toolset::new(source.clone());
for v in v.split_whitespace() {
let tvr = ToolRequest::new(ba.clone(), v, source.clone())?;
env_ts.add_version(tvr);
}
ts.merge(env_ts);
}
}
Ok(())
}
fn load_runtime_args(&self, ts: &mut Toolset) -> eyre::Result<()> {
for (_, args) in self.args.iter().into_group_map_by(|arg| arg.ba.clone()) {
let mut arg_ts = Toolset::new(ToolSource::Argument);
for arg in args {
if let Some(tvr) = &arg.tvr {
arg_ts.add_version(tvr.clone());
} else if self.default_to_latest {
// this logic is required for `mise x` because with that specific command mise
// should default to installing the "latest" version if no version is specified
// in mise.toml
// determine if we already have some active version in config
let current_active = ts
.list_current_requests()
.into_iter()
.find(|tvr| tvr.ba() == &arg.ba);
if let Some(current_active) = current_active {
// active version, so don't set "latest"
arg_ts.add_version(ToolRequest::new(
arg.ba.clone(),
¤t_active.version(),
ToolSource::Argument,
)?);
} else {
// no active version, so use "latest"
arg_ts.add_version(ToolRequest::new(
arg.ba.clone(),
"latest",
ToolSource::Argument,
)?);
}
}
}
ts.merge(arg_ts);
}
Ok(())
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_source.rs | src/toolset/tool_source.rs | use serde::ser::{Serialize, SerializeStruct, Serializer};
use std::fmt::{Display, Formatter};
use std::path::{Path, PathBuf};
use indexmap::{IndexMap, indexmap};
use crate::file::display_path;
/// where a tool version came from (e.g.: .tool-versions)
#[derive(Debug, Default, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, strum::EnumIs)]
pub enum ToolSource {
ToolVersions(PathBuf),
MiseToml(PathBuf),
IdiomaticVersionFile(PathBuf),
ToolStub(PathBuf),
Argument,
Environment(String, String),
#[default]
Unknown,
}
impl Display for ToolSource {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
ToolSource::ToolVersions(path) => write!(f, "{}", display_path(path)),
ToolSource::MiseToml(path) => write!(f, "{}", display_path(path)),
ToolSource::IdiomaticVersionFile(path) => write!(f, "{}", display_path(path)),
ToolSource::ToolStub(path) => write!(f, "{}", display_path(path)),
ToolSource::Argument => write!(f, "--runtime"),
ToolSource::Environment(k, v) => write!(f, "{k}={v}"),
ToolSource::Unknown => write!(f, "unknown"),
}
}
}
impl ToolSource {
pub fn path(&self) -> Option<&Path> {
match self {
ToolSource::ToolVersions(path) => Some(path),
ToolSource::MiseToml(path) => Some(path),
ToolSource::IdiomaticVersionFile(path) => Some(path),
ToolSource::ToolStub(path) => Some(path),
_ => None,
}
}
pub fn as_json(&self) -> IndexMap<String, String> {
match self {
ToolSource::ToolVersions(path) => indexmap! {
"type".to_string() => ".tool-versions".to_string(),
"path".to_string() => path.to_string_lossy().to_string(),
},
ToolSource::MiseToml(path) => indexmap! {
"type".to_string() => "mise.toml".to_string(),
"path".to_string() => path.to_string_lossy().to_string(),
},
ToolSource::IdiomaticVersionFile(path) => indexmap! {
"type".to_string() => "idiomatic-version-file".to_string(),
"path".to_string() => path.to_string_lossy().to_string(),
},
ToolSource::ToolStub(path) => indexmap! {
"type".to_string() => "tool-stub".to_string(),
"path".to_string() => path.to_string_lossy().to_string(),
},
ToolSource::Argument => indexmap! {
"type".to_string() => "argument".to_string(),
},
ToolSource::Environment(key, value) => indexmap! {
"type".to_string() => "environment".to_string(),
"key".to_string() => key.to_string(),
"value".to_string() => value.to_string(),
},
ToolSource::Unknown => indexmap! {
"type".to_string() => "unknown".to_string(),
},
}
}
}
impl Serialize for ToolSource {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("ToolSource", 3)?;
match self {
ToolSource::ToolVersions(path) => {
s.serialize_field("type", ".tool-versions")?;
s.serialize_field("path", path)?;
}
ToolSource::MiseToml(path) => {
s.serialize_field("type", "mise.toml")?;
s.serialize_field("path", path)?;
}
ToolSource::IdiomaticVersionFile(path) => {
s.serialize_field("type", "idiomatic-version-file")?;
s.serialize_field("path", path)?;
}
ToolSource::ToolStub(path) => {
s.serialize_field("type", "tool-stub")?;
s.serialize_field("path", path)?;
}
ToolSource::Argument => {
s.serialize_field("type", "argument")?;
}
ToolSource::Environment(key, value) => {
s.serialize_field("type", "environment")?;
s.serialize_field("key", key)?;
s.serialize_field("value", value)?;
}
ToolSource::Unknown => {
s.serialize_field("type", "unknown")?;
}
}
s.end()
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::{assert_eq, assert_str_eq};
use super::*;
#[test]
fn test_tool_source_display() {
let path = PathBuf::from("/home/user/.test-tool-versions");
let ts = ToolSource::ToolVersions(path);
assert_str_eq!(ts.to_string(), "/home/user/.test-tool-versions");
let ts = ToolSource::MiseToml(PathBuf::from("/home/user/.mise.toml"));
assert_str_eq!(ts.to_string(), "/home/user/.mise.toml");
let ts = ToolSource::IdiomaticVersionFile(PathBuf::from("/home/user/.node-version"));
assert_str_eq!(ts.to_string(), "/home/user/.node-version");
let ts = ToolSource::Argument;
assert_str_eq!(ts.to_string(), "--runtime");
let ts = ToolSource::Environment("MISE_NODE_VERSION".to_string(), "18".to_string());
assert_str_eq!(ts.to_string(), "MISE_NODE_VERSION=18");
}
#[test]
fn test_tool_source_as_json() {
let ts = ToolSource::ToolVersions(PathBuf::from("/home/user/.test-tool-versions"));
assert_eq!(
ts.as_json(),
indexmap! {
"type".to_string() => ".tool-versions".to_string(),
"path".to_string() => "/home/user/.test-tool-versions".to_string(),
}
);
let ts = ToolSource::MiseToml(PathBuf::from("/home/user/.mise.toml"));
assert_eq!(
ts.as_json(),
indexmap! {
"type".to_string() => "mise.toml".to_string(),
"path".to_string() => "/home/user/.mise.toml".to_string(),
}
);
let ts = ToolSource::IdiomaticVersionFile(PathBuf::from("/home/user/.node-version"));
assert_eq!(
ts.as_json(),
indexmap! {
"type".to_string() => "idiomatic-version-file".to_string(),
"path".to_string() => "/home/user/.node-version".to_string(),
}
);
let ts = ToolSource::Argument;
assert_eq!(
ts.as_json(),
indexmap! {
"type".to_string() => "argument".to_string(),
}
);
let ts = ToolSource::Environment("MISE_NODE_VERSION".to_string(), "18".to_string());
assert_eq!(
ts.as_json(),
indexmap! {
"type".to_string() => "environment".to_string(),
"key".to_string() => "MISE_NODE_VERSION".to_string(),
"value".to_string() => "18".to_string(),
}
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/install_options.rs | src/toolset/install_options.rs | use crate::config::settings::Settings;
use crate::toolset::tool_version::ResolveOptions;
#[derive(Debug, Clone)]
pub struct InstallOptions {
pub reason: String,
pub force: bool,
pub jobs: Option<usize>,
pub raw: bool,
/// only install missing tools if passed as arguments
pub missing_args_only: bool,
/// completely disable auto-installation when auto_install setting is false
pub skip_auto_install: bool,
pub auto_install_disable_tools: Option<Vec<String>>,
pub resolve_options: ResolveOptions,
pub dry_run: bool,
/// require lockfile URLs to be present; fail if not
pub locked: bool,
}
impl Default for InstallOptions {
fn default() -> Self {
InstallOptions {
jobs: Some(Settings::get().jobs),
raw: Settings::get().raw,
reason: "install".to_string(),
force: false,
missing_args_only: true,
skip_auto_install: false,
auto_install_disable_tools: Settings::get().auto_install_disable_tools.clone(),
resolve_options: Default::default(),
dry_run: false,
locked: Settings::get().locked,
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_request_set.rs | src/toolset/tool_request_set.rs | use std::fmt::{Debug, Display};
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
sync::Arc,
};
use crate::backend::backend_type::BackendType;
use crate::cli::args::{BackendArg, ToolArg};
use crate::config::{Config, Settings};
use crate::env;
use crate::registry::{REGISTRY, tool_enabled};
use crate::toolset::{ToolRequest, ToolSource, Toolset};
use indexmap::IndexMap;
use itertools::Itertools;
#[derive(Debug, Default, Clone)]
pub struct ToolRequestSet {
pub tools: IndexMap<Arc<BackendArg>, Vec<ToolRequest>>,
pub sources: BTreeMap<Arc<BackendArg>, ToolSource>,
/// Tools that were filtered out because they don't exist in the registry (BackendType::Unknown)
pub unknown_tools: Vec<Arc<BackendArg>>,
}
impl ToolRequestSet {
pub fn new() -> Self {
Self::default()
}
// pub fn tools_with_sources(&self) -> Vec<(&BackendArg, &Vec<ToolRequest>, &ToolSource)> {
// self.tools
// .iter()
// .map(|(backend, tvr)| (backend, tvr, self.sources.get(backend).unwrap()))
// .collect()
// }
// pub fn installed_tools(&self) -> eyre::Result<Vec<&ToolRequest>> {
// self.tools
// .values()
// .flatten()
// .map(|tvr| match tvr.is_installed()? {
// true => Ok(Some(tvr)),
// false => Ok(None),
// })
// .flatten_ok()
// .collect()
// }
pub async fn missing_tools(&self, config: &Arc<Config>) -> Vec<&ToolRequest> {
let mut tools = vec![];
for tr in self.tools.values().flatten() {
if tr.is_os_supported() && !tr.is_installed(config).await {
tools.push(tr);
}
}
tools
}
pub fn list_tools(&self) -> Vec<&Arc<BackendArg>> {
self.tools.keys().collect()
}
pub fn add_version(&mut self, tr: ToolRequest, source: &ToolSource) {
let fa = tr.ba();
if !self.tools.contains_key(fa) {
self.sources.insert(fa.clone(), source.clone());
}
let list = self.tools.entry(tr.ba().clone()).or_default();
list.push(tr);
}
pub fn iter(&self) -> impl Iterator<Item = (&Arc<BackendArg>, &Vec<ToolRequest>, &ToolSource)> {
self.tools
.iter()
.map(|(backend, tvr)| (backend, tvr, self.sources.get(backend).unwrap()))
}
pub fn into_iter(
self,
) -> impl Iterator<Item = (Arc<BackendArg>, Vec<ToolRequest>, ToolSource)> {
self.tools.into_iter().map(move |(ba, tvr)| {
let source = self.sources.get(&ba).unwrap().clone();
(ba, tvr, source)
})
}
pub fn filter_by_tool(&self, mut tools: HashSet<String>) -> ToolRequestSet {
// add in the full names so something like cargo:cargo-binstall can be used in place of cargo-binstall
for short in tools.clone().iter() {
if let Some(rt) = REGISTRY.get(short.as_str()) {
tools.extend(rt.backends().iter().map(|s| s.to_string()));
}
}
self.iter()
.filter(|(ba, ..)| tools.contains(&ba.short) || tools.contains(&ba.full()))
.map(|(ba, trl, ts)| (ba.clone(), trl.clone(), ts.clone()))
.collect::<ToolRequestSet>()
}
pub fn into_toolset(self) -> Toolset {
self.into()
}
}
impl Display for ToolRequestSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let versions = self.tools.values().flatten().join(" ");
if versions.is_empty() {
write!(f, "ToolRequestSet: <empty>")?;
} else {
write!(f, "ToolRequestSet: {versions}")?;
}
Ok(())
}
}
impl FromIterator<(Arc<BackendArg>, Vec<ToolRequest>, ToolSource)> for ToolRequestSet {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = (Arc<BackendArg>, Vec<ToolRequest>, ToolSource)>,
{
let mut trs = ToolRequestSet::new();
for (_ba, tvr, source) in iter {
for tr in tvr {
trs.add_version(tr.clone(), &source);
}
}
trs
}
}
#[derive(Debug, Default)]
pub struct ToolRequestSetBuilder {
/// cli tool args
args: Vec<ToolArg>,
/// default to latest version if no version is specified (for `mise x`)
default_to_latest: bool,
/// tools which will be disabled
disable_tools: BTreeSet<BackendArg>,
/// tools which will be enabled
enable_tools: BTreeSet<BackendArg>,
}
impl ToolRequestSetBuilder {
pub fn new() -> Self {
let settings = Settings::get();
Self {
disable_tools: settings.disable_tools().iter().map(|s| s.into()).collect(),
enable_tools: settings.enable_tools().iter().map(|s| s.into()).collect(),
..Default::default()
}
}
// pub fn add_arg(mut self, arg: ToolArg) -> Self {
// self.args.push(arg);
// self
// }
//
// pub fn default_to_latest(mut self) -> Self {
// self.default_to_latest = true;
// self
// }
//
pub async fn build(&self, config: &Config) -> eyre::Result<ToolRequestSet> {
let mut trs = ToolRequestSet::default();
trs = self.load_config_files(config, trs).await?;
trs = self.load_runtime_env(trs)?;
trs = self.load_runtime_args(trs)?;
for ba in trs.tools.keys().cloned().collect_vec() {
if self.is_disabled(&ba) {
// Track tools that don't exist in the registry
if ba.backend_type() == BackendType::Unknown {
trs.unknown_tools.push(ba.clone());
}
trs.tools.shift_remove(&ba);
trs.sources.remove(&ba);
}
}
time!("tool_request_set::build");
Ok(trs)
}
fn is_disabled(&self, ba: &BackendArg) -> bool {
let backend_type = ba.backend_type();
backend_type == BackendType::Unknown
|| (cfg!(windows) && backend_type == BackendType::Asdf)
|| !ba.is_os_supported()
|| !tool_enabled(&self.enable_tools, &self.disable_tools, ba)
}
async fn load_config_files(
&self,
config: &Config,
mut trs: ToolRequestSet,
) -> eyre::Result<ToolRequestSet> {
for cf in config.config_files.values().rev() {
trs = merge(trs, cf.to_tool_request_set()?);
}
Ok(trs)
}
fn load_runtime_env(&self, mut trs: ToolRequestSet) -> eyre::Result<ToolRequestSet> {
for (k, v) in env::vars_safe() {
if k.starts_with("MISE_") && k.ends_with("_VERSION") && k != "MISE_VERSION" {
let plugin_name = k
.trim_start_matches("MISE_")
.trim_end_matches("_VERSION")
.to_lowercase();
if plugin_name == "install" {
// ignore MISE_INSTALL_VERSION
continue;
}
let ba: Arc<BackendArg> = Arc::new(plugin_name.as_str().into());
let source = ToolSource::Environment(k, v.clone());
let mut env_ts = ToolRequestSet::new();
for v in v.split_whitespace() {
let tvr = ToolRequest::new(ba.clone(), v, source.clone())?;
env_ts.add_version(tvr, &source);
}
trs = merge(trs, env_ts);
}
}
Ok(trs)
}
fn load_runtime_args(&self, mut trs: ToolRequestSet) -> eyre::Result<ToolRequestSet> {
for (_, args) in self.args.iter().into_group_map_by(|arg| arg.ba.clone()) {
let mut arg_ts = ToolRequestSet::new();
for arg in args {
if let Some(tvr) = &arg.tvr {
arg_ts.add_version(tvr.clone(), &ToolSource::Argument);
} else if self.default_to_latest {
// this logic is required for `mise x` because with that specific command mise
// should default to installing the "latest" version if no version is specified
// in mise.toml
if !trs.tools.contains_key(&arg.ba) {
// no active version, so use "latest"
let tr = ToolRequest::new(arg.ba.clone(), "latest", ToolSource::Argument)?;
arg_ts.add_version(tr, &ToolSource::Argument);
}
}
}
trs = merge(trs, arg_ts);
}
let tool_args = env::TOOL_ARGS.read().unwrap();
let mut arg_trs = ToolRequestSet::new();
for arg in tool_args.iter() {
if let Some(tvr) = &arg.tvr {
arg_trs.add_version(tvr.clone(), &ToolSource::Argument);
} else if !trs.tools.contains_key(&arg.ba) {
// no active version, so use "latest"
let tr = ToolRequest::new(arg.ba.clone(), "latest", ToolSource::Argument)?;
arg_trs.add_version(tr, &ToolSource::Argument);
}
}
trs = merge(trs, arg_trs);
Ok(trs)
}
}
fn merge(mut a: ToolRequestSet, mut b: ToolRequestSet) -> ToolRequestSet {
// move things around such that the tools are in the config order
a.tools.retain(|ba, _| !b.tools.contains_key(ba));
a.sources.retain(|ba, _| !b.sources.contains_key(ba));
b.tools.extend(a.tools);
b.sources.extend(a.sources);
b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_load_runtime_env_with_valid_utf8() {
// This test verifies that valid UTF-8 MISE_*_VERSION variables work correctly
unsafe {
std::env::set_var("MISE_NODE_VERSION", "20.0.0");
std::env::set_var("MISE_PYTHON_VERSION", "3.11");
}
let builder = ToolRequestSetBuilder::new();
let trs = builder.load_runtime_env(ToolRequestSet::new());
// Should not panic and should successfully load the versions
assert!(trs.is_ok());
let trs = trs.unwrap();
assert!(trs.tools.len() >= 2 || trs.tools.is_empty()); // May be empty if backends are disabled
unsafe {
std::env::remove_var("MISE_NODE_VERSION");
std::env::remove_var("MISE_PYTHON_VERSION");
}
}
#[test]
fn test_load_runtime_env_ignores_non_mise_vars() {
// Non-MISE variables should be ignored, even with special characters
unsafe {
std::env::set_var("HOMEBREW_INSTALL_BADGE", "✅");
std::env::set_var("SOME_OTHER_VAR", "value");
}
let builder = ToolRequestSetBuilder::new();
let result = builder.load_runtime_env(ToolRequestSet::new());
// Should not panic when non-MISE vars are present
assert!(result.is_ok());
unsafe {
std::env::remove_var("HOMEBREW_INSTALL_BADGE");
std::env::remove_var("SOME_OTHER_VAR");
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_request.rs | src/toolset/tool_request.rs | use std::collections::BTreeMap;
use std::path::PathBuf;
use std::{
fmt::{Display, Formatter},
sync::Arc,
};
use eyre::{Result, bail};
use versions::{Chunk, Version};
use xx::file;
use crate::backend::platform_target::PlatformTarget;
use crate::cli::args::BackendArg;
use crate::lockfile::LockfileTool;
use crate::runtime_symlinks::is_runtime_symlink;
use crate::toolset::tool_version::ResolveOptions;
use crate::toolset::{ToolSource, ToolVersion, ToolVersionOptions};
use crate::{backend, lockfile};
use crate::{backend::ABackend, config::Config};
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ToolRequest {
Version {
backend: Arc<BackendArg>,
version: String,
options: ToolVersionOptions,
source: ToolSource,
},
Prefix {
backend: Arc<BackendArg>,
prefix: String,
options: ToolVersionOptions,
source: ToolSource,
},
Ref {
backend: Arc<BackendArg>,
ref_: String,
ref_type: String,
options: ToolVersionOptions,
source: ToolSource,
},
Sub {
backend: Arc<BackendArg>,
sub: String,
orig_version: String,
options: ToolVersionOptions,
source: ToolSource,
},
Path {
backend: Arc<BackendArg>,
path: PathBuf,
options: ToolVersionOptions,
source: ToolSource,
},
System {
backend: Arc<BackendArg>,
source: ToolSource,
options: ToolVersionOptions,
},
}
impl ToolRequest {
pub fn new(backend: Arc<BackendArg>, s: &str, source: ToolSource) -> eyre::Result<Self> {
let s = match s.split_once('-') {
Some((ref_type @ ("ref" | "tag" | "branch" | "rev"), r)) => format!("{ref_type}:{r}"),
_ => s.to_string(),
};
Ok(match s.split_once(':') {
Some((ref_type @ ("ref" | "tag" | "branch" | "rev"), r)) => Self::Ref {
ref_: r.to_string(),
ref_type: ref_type.to_string(),
options: backend.opts(),
backend,
source,
},
Some(("prefix", p)) => Self::Prefix {
prefix: p.to_string(),
options: backend.opts(),
backend,
source,
},
Some(("path", p)) => Self::Path {
path: PathBuf::from(p),
options: backend.opts(),
backend,
source,
},
Some((p, v)) if p.starts_with("sub-") => Self::Sub {
sub: p.split_once('-').unwrap().1.to_string(),
options: backend.opts(),
orig_version: v.to_string(),
backend,
source,
},
None => {
if s == "system" {
Self::System {
options: backend.opts(),
backend,
source,
}
} else {
Self::Version {
version: s,
options: backend.opts(),
backend,
source,
}
}
}
_ => bail!("invalid tool version request: {s}"),
})
}
pub fn new_opts(
backend: Arc<BackendArg>,
s: &str,
options: ToolVersionOptions,
source: ToolSource,
) -> eyre::Result<Self> {
let mut tvr = Self::new(backend, s, source)?;
match &mut tvr {
Self::Version { options: o, .. }
| Self::Prefix { options: o, .. }
| Self::Ref { options: o, .. } => *o = options,
_ => Default::default(),
}
Ok(tvr)
}
pub fn set_source(&mut self, source: ToolSource) -> Self {
match self {
Self::Version { source: s, .. }
| Self::Prefix { source: s, .. }
| Self::Ref { source: s, .. }
| Self::Path { source: s, .. }
| Self::Sub { source: s, .. }
| Self::System { source: s, .. } => *s = source,
}
self.clone()
}
pub fn ba(&self) -> &Arc<BackendArg> {
match self {
Self::Version { backend, .. }
| Self::Prefix { backend, .. }
| Self::Ref { backend, .. }
| Self::Path { backend, .. }
| Self::Sub { backend, .. }
| Self::System { backend, .. } => backend,
}
}
pub fn backend(&self) -> Result<ABackend> {
self.ba().backend()
}
pub fn source(&self) -> &ToolSource {
match self {
Self::Version { source, .. }
| Self::Prefix { source, .. }
| Self::Ref { source, .. }
| Self::Path { source, .. }
| Self::Sub { source, .. }
| Self::System { source, .. } => source,
}
}
pub fn os(&self) -> &Option<Vec<String>> {
match self {
Self::Version { options, .. }
| Self::Prefix { options, .. }
| Self::Ref { options, .. }
| Self::Path { options, .. }
| Self::Sub { options, .. }
| Self::System { options, .. } => &options.os,
}
}
pub fn set_options(&mut self, options: ToolVersionOptions) -> &mut Self {
match self {
Self::Version { options: o, .. }
| Self::Prefix { options: o, .. }
| Self::Ref { options: o, .. }
| Self::Sub { options: o, .. }
| Self::Path { options: o, .. }
| Self::System { options: o, .. } => *o = options,
}
self
}
pub fn version(&self) -> String {
match self {
Self::Version { version: v, .. } => v.clone(),
Self::Prefix { prefix: p, .. } => format!("prefix:{p}"),
Self::Ref {
ref_: r, ref_type, ..
} => format!("{ref_type}:{r}"),
Self::Path { path: p, .. } => format!("path:{}", p.display()),
Self::Sub {
sub, orig_version, ..
} => format!("sub-{sub}:{orig_version}"),
Self::System { .. } => "system".to_string(),
}
}
pub fn options(&self) -> ToolVersionOptions {
match self {
Self::Version { options: o, .. }
| Self::Prefix { options: o, .. }
| Self::Ref { options: o, .. }
| Self::Sub { options: o, .. }
| Self::Path { options: o, .. }
| Self::System { options: o, .. } => o.clone(),
}
}
pub async fn is_installed(&self, config: &Arc<Config>) -> bool {
if let Some(backend) = backend::get(self.ba()) {
match self.resolve(config, &Default::default()).await {
Ok(tv) => backend.is_version_installed(config, &tv, false),
Err(e) => {
debug!("ToolRequest.is_installed: {e:#}");
false
}
}
} else {
false
}
}
pub fn install_path(&self, config: &Config) -> Option<PathBuf> {
match self {
Self::Version {
backend, version, ..
} => Some(backend.installs_path.join(version)),
Self::Ref {
backend,
ref_,
ref_type,
..
} => Some(backend.installs_path.join(format!("{ref_type}-{ref_}"))),
Self::Sub {
backend,
sub,
orig_version,
..
} => self
.local_resolve(config, orig_version)
.inspect_err(|e| warn!("ToolRequest.local_resolve: {e:#}"))
.unwrap_or_default()
.map(|v| backend.installs_path.join(version_sub(&v, sub.as_str()))),
Self::Prefix {
backend, prefix, ..
} => match file::ls(&backend.installs_path) {
Ok(installs) => installs
.iter()
.find(|p| {
!is_runtime_symlink(p)
&& p.file_name().unwrap().to_string_lossy().starts_with(prefix)
})
.cloned(),
Err(_) => None,
},
Self::Path { path, .. } => Some(path.clone()),
Self::System { .. } => None,
}
}
pub fn lockfile_resolve(&self, config: &Config) -> Result<Option<LockfileTool>> {
// Get the resolved lockfile options from the backend
let request_options = if let Ok(backend) = self.backend() {
let target = PlatformTarget::from_current();
backend.resolve_lockfile_options(self, &target)
} else {
BTreeMap::new()
};
match self.source() {
ToolSource::MiseToml(path) => lockfile::get_locked_version(
config,
Some(path),
&self.ba().short,
&self.version(),
&request_options,
),
_ => lockfile::get_locked_version(
config,
None,
&self.ba().short,
&self.version(),
&request_options,
),
}
}
pub fn local_resolve(&self, config: &Config, v: &str) -> eyre::Result<Option<String>> {
if let Some(lt) = self.lockfile_resolve(config)? {
return Ok(Some(lt.version));
}
if let Some(backend) = backend::get(self.ba()) {
let matches = backend.list_installed_versions_matching(v);
if matches.iter().any(|m| m == v) {
return Ok(Some(v.to_string()));
}
if let Some(v) = matches.last() {
return Ok(Some(v.to_string()));
}
}
Ok(None)
}
pub async fn resolve(
&self,
config: &Arc<Config>,
opts: &ResolveOptions,
) -> Result<ToolVersion> {
ToolVersion::resolve(config, self.clone(), opts).await
}
pub fn is_os_supported(&self) -> bool {
if let Some(os) = self.os()
&& !os.contains(&crate::cli::version::OS)
{
return false;
}
self.ba().is_os_supported()
}
}
/// subtracts sub from orig and removes suffix
/// e.g. version_sub("18.2.3", "2") -> "16"
/// e.g. version_sub("18.2.3", "0.1") -> "18.1"
/// e.g. version_sub("2.79.0", "0.0.1") -> "2.78" (underflow, returns prefix)
pub fn version_sub(orig: &str, sub: &str) -> String {
let mut orig = Version::new(orig).unwrap();
let sub = Version::new(sub).unwrap();
while orig.chunks.0.len() > sub.chunks.0.len() {
orig.chunks.0.pop();
}
for i in 0..orig.chunks.0.len() {
let m = sub.nth(i).unwrap();
let orig_val = orig.chunks.0[i].single_digit().unwrap();
if orig_val < m {
// Handle underflow with borrowing from higher digits
for j in (0..i).rev() {
let prev_val = orig.chunks.0[j].single_digit().unwrap();
if prev_val > 0 {
orig.chunks.0[j] = Chunk::Numeric(prev_val - 1);
orig.chunks.0.truncate(j + 1);
return orig.to_string();
}
}
return "0".to_string();
}
orig.chunks.0[i] = Chunk::Numeric(orig_val - m);
}
orig.to_string()
}
impl Display for ToolRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{}@{}", &self.ba(), self.version())
}
}
#[cfg(test)]
mod tests {
use super::version_sub;
use pretty_assertions::assert_str_eq;
use test_log::test;
#[test]
fn test_version_sub() {
assert_str_eq!(version_sub("18.2.3", "2"), "16");
assert_str_eq!(version_sub("18.2.3", "0.1"), "18.1");
assert_str_eq!(version_sub("18.2.3", "0.0.1"), "18.2.2");
}
#[test]
fn test_version_sub_underflow() {
// Test cases that would cause underflow return prefix for higher digit
assert_str_eq!(version_sub("2.0.0", "0.0.1"), "1");
assert_str_eq!(version_sub("2.79.0", "0.0.1"), "2.78");
assert_str_eq!(version_sub("1.0.0", "0.1.0"), "0");
assert_str_eq!(version_sub("0.1.0", "1"), "0");
assert_str_eq!(version_sub("1.2.3", "0.2.4"), "0");
assert_str_eq!(version_sub("1.3.3", "0.2.4"), "1.0");
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/helpers.rs | src/toolset/helpers.rs | use std::collections::HashSet;
use std::sync::Arc;
use eyre::Result;
use itertools::Itertools;
use crate::backend::Backend;
use crate::toolset::tool_request::ToolRequest;
use crate::toolset::tool_version::ToolVersion;
pub(super) type TVTuple = (Arc<dyn Backend>, ToolVersion);
pub(super) fn show_python_install_hint(versions: &[ToolRequest]) {
let num_python = versions
.iter()
.filter(|tr| tr.ba().tool_name == "python")
.count();
if num_python != 1 {
return;
}
hint!(
"python_multi",
"use multiple versions simultaneously with",
"mise use python@3.12 python@3.11"
);
}
pub(super) fn get_leaf_dependencies(requests: &[ToolRequest]) -> Result<Vec<ToolRequest>> {
// reverse maps potential shorts like "cargo-binstall" for "cargo:cargo-binstall"
let versions_hash = requests
.iter()
.flat_map(|tr| tr.ba().all_fulls())
.collect::<HashSet<_>>();
let leaves = requests
.iter()
.map(|tr| {
match tr.backend()?.get_all_dependencies(true)?.iter().all(|dep| {
// dep is a dependency of tr so if it is in versions_hash (meaning it's also being installed) then it is not a leaf node
!dep.all_fulls()
.iter()
.any(|full| versions_hash.contains(full))
}) {
true => Ok(Some(tr)),
false => Ok(None),
}
})
.flatten_ok()
.map_ok(|tr| tr.clone())
.collect::<Result<Vec<_>>>()?;
Ok(leaves)
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/install_state.rs | src/toolset/install_state.rs | use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::file::display_path;
use crate::git::Git;
use crate::plugins::PluginType;
use crate::{dirs, file, runtime_symlinks};
use eyre::{Ok, Result};
use heck::ToKebabCase;
use itertools::Itertools;
use std::collections::BTreeMap;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tokio::task::JoinSet;
use versions::Versioning;
/// Normalize a version string for sorting by stripping leading 'v' or 'V' prefix.
/// This ensures "v1.0.0" and "1.0.0" are sorted together correctly.
fn normalize_version_for_sort(v: &str) -> &str {
v.strip_prefix('v')
.or_else(|| v.strip_prefix('V'))
.unwrap_or(v)
}
type InstallStatePlugins = BTreeMap<String, PluginType>;
type InstallStateTools = BTreeMap<String, InstallStateTool>;
type MutexResult<T> = Result<Arc<T>>;
#[derive(Debug, Clone)]
pub struct InstallStateTool {
pub short: String,
pub full: Option<String>,
pub versions: Vec<String>,
}
static INSTALL_STATE_PLUGINS: Mutex<Option<Arc<InstallStatePlugins>>> = Mutex::new(None);
static INSTALL_STATE_TOOLS: Mutex<Option<Arc<InstallStateTools>>> = Mutex::new(None);
pub(crate) async fn init() -> Result<()> {
let (plugins, tools) = tokio::join!(
tokio::task::spawn(async { measure!("init_plugins", { init_plugins().await }) }),
tokio::task::spawn(async { measure!("init_tools", { init_tools().await }) }),
);
plugins??;
tools??;
Ok(())
}
async fn init_plugins() -> MutexResult<InstallStatePlugins> {
if let Some(plugins) = INSTALL_STATE_PLUGINS
.lock()
.expect("INSTALL_STATE_PLUGINS lock failed")
.clone()
{
return Ok(plugins);
}
let dirs = file::dir_subdirs(&dirs::PLUGINS)?;
let plugins: InstallStatePlugins = dirs
.into_iter()
.filter_map(|d| {
time!("init_plugins {d}");
let path = dirs::PLUGINS.join(&d);
if is_banned_plugin(&path) {
info!("removing banned plugin {d}");
let _ = file::remove_all(&path);
None
} else if path.join("metadata.lua").exists() {
if has_backend_methods(&path) {
Some((d, PluginType::VfoxBackend))
} else {
Some((d, PluginType::Vfox))
}
} else if path.join("bin").join("list-all").exists() {
Some((d, PluginType::Asdf))
} else {
None
}
})
.collect();
let plugins = Arc::new(plugins);
*INSTALL_STATE_PLUGINS
.lock()
.expect("INSTALL_STATE_PLUGINS lock failed") = Some(plugins.clone());
Ok(plugins)
}
async fn init_tools() -> MutexResult<InstallStateTools> {
if let Some(tools) = INSTALL_STATE_TOOLS
.lock()
.expect("INSTALL_STATE_TOOLS lock failed")
.clone()
{
return Ok(tools);
}
let mut jset = JoinSet::new();
for dir in file::dir_subdirs(&dirs::INSTALLS)? {
jset.spawn(async move {
let backend_meta = read_backend_meta(&dir).unwrap_or_default();
let short = backend_meta.first().unwrap_or(&dir).to_string();
let full = backend_meta.get(1).cloned();
let dir = dirs::INSTALLS.join(&dir);
let versions = file::dir_subdirs(&dir)
.unwrap_or_else(|err| {
warn!("reading versions in {} failed: {err:?}", display_path(&dir));
Default::default()
})
.into_iter()
.filter(|v| !v.starts_with('.'))
.filter(|v| !runtime_symlinks::is_runtime_symlink(&dir.join(v)))
.filter(|v| !dir.join(v).join("incomplete").exists())
.sorted_by_cached_key(|v| {
// Normalize version for sorting to handle mixed v-prefix versions
// e.g., "v2.0.51" and "2.0.35" should sort by numeric value
let normalized = normalize_version_for_sort(v);
(Versioning::new(normalized), v.to_string())
})
.collect();
let tool = InstallStateTool {
short: short.clone(),
full,
versions,
};
time!("init_tools {short}");
(short, tool)
});
}
let mut tools = jset
.join_all()
.await
.into_iter()
.filter(|(_, tool)| !tool.versions.is_empty())
.collect::<BTreeMap<_, _>>();
for (short, pt) in init_plugins().await?.iter() {
let full = match pt {
PluginType::Asdf => format!("asdf:{short}"),
PluginType::Vfox => format!("vfox:{short}"),
PluginType::VfoxBackend => short.clone(),
};
let tool = tools
.entry(short.clone())
.or_insert_with(|| InstallStateTool {
short: short.clone(),
full: Some(full.clone()),
versions: Default::default(),
});
tool.full = Some(full);
}
let tools = Arc::new(tools);
*INSTALL_STATE_TOOLS
.lock()
.expect("INSTALL_STATE_TOOLS lock failed") = Some(tools.clone());
Ok(tools)
}
pub fn list_plugins() -> Arc<BTreeMap<String, PluginType>> {
INSTALL_STATE_PLUGINS
.lock()
.expect("INSTALL_STATE_PLUGINS lock failed")
.as_ref()
.expect("INSTALL_STATE_PLUGINS is None")
.clone()
}
fn is_banned_plugin(path: &Path) -> bool {
if path.ends_with("gradle") {
let repo = Git::new(path);
if let Some(url) = repo.get_remote_url() {
return url == "https://github.com/rfrancis/asdf-gradle.git";
}
}
false
}
fn has_backend_methods(plugin_path: &Path) -> bool {
// to be a backend plugin, it must have a backend_install.lua file so we don't need to check for other files
plugin_path
.join("hooks")
.join("backend_install.lua")
.exists()
}
pub fn get_tool_full(short: &str) -> Option<String> {
list_tools().get(short).and_then(|t| t.full.clone())
}
pub fn get_plugin_type(short: &str) -> Option<PluginType> {
list_plugins().get(short).cloned()
}
pub fn list_tools() -> Arc<BTreeMap<String, InstallStateTool>> {
INSTALL_STATE_TOOLS
.lock()
.expect("INSTALL_STATE_TOOLS lock failed")
.as_ref()
.expect("INSTALL_STATE_TOOLS is None")
.clone()
}
pub fn backend_type(short: &str) -> Result<Option<BackendType>> {
let backend_type = list_tools()
.get(short)
.and_then(|ist| ist.full.as_ref())
.map(|full| BackendType::guess(full));
if let Some(BackendType::Unknown) = backend_type
&& let Some((plugin_name, _)) = short.split_once(':')
&& let Some(PluginType::VfoxBackend) = get_plugin_type(plugin_name)
{
return Ok(Some(BackendType::VfoxBackend(plugin_name.to_string())));
}
Ok(backend_type)
}
pub fn list_versions(short: &str) -> Vec<String> {
list_tools()
.get(short)
.map(|tool| tool.versions.clone())
.unwrap_or_default()
}
pub async fn add_plugin(short: &str, plugin_type: PluginType) -> Result<()> {
let mut plugins = init_plugins().await?.deref().clone();
plugins.insert(short.to_string(), plugin_type);
*INSTALL_STATE_PLUGINS
.lock()
.expect("INSTALL_STATE_PLUGINS lock failed") = Some(Arc::new(plugins));
Ok(())
}
fn backend_meta_path(short: &str) -> PathBuf {
dirs::INSTALLS
.join(short.to_kebab_case())
.join(".mise.backend")
}
fn migrate_backend_meta_json(dir: &str) {
let old = dirs::INSTALLS.join(dir).join(".mise.backend.json");
let migrate = || {
let json: serde_json::Value = serde_json::from_reader(file::open(&old)?)?;
if let Some(full) = json.get("id").and_then(|id| id.as_str()) {
let short = json
.get("short")
.and_then(|short| short.as_str())
.unwrap_or(dir);
let doc = format!("{short}\n{full}");
file::write(backend_meta_path(dir), doc.trim())?;
}
Ok(())
};
if old.exists() {
if let Err(err) = migrate() {
debug!("{err:#}");
}
if let Err(err) = file::remove_file(&old) {
debug!("{err:#}");
}
}
}
fn read_backend_meta(short: &str) -> Option<Vec<String>> {
migrate_backend_meta_json(short);
let path = backend_meta_path(short);
if path.exists() {
let body = file::read_to_string(&path)
.map_err(|err| {
warn!("{err:?}");
})
.unwrap_or_default();
Some(
body.lines()
.filter(|f| !f.is_empty())
.map(|f| f.to_string())
.collect(),
)
} else {
None
}
}
pub fn write_backend_meta(ba: &BackendArg) -> Result<()> {
let full = match ba.full() {
full if full.starts_with("core:") => ba.full(),
_ => ba.full_with_opts(),
};
let doc = format!("{}\n{}", ba.short, full);
file::write(backend_meta_path(&ba.short), doc.trim())?;
Ok(())
}
pub fn incomplete_file_path(short: &str, v: &str) -> PathBuf {
dirs::CACHE
.join(short.to_kebab_case())
.join(v)
.join("incomplete")
}
pub fn reset() {
*INSTALL_STATE_PLUGINS
.lock()
.expect("INSTALL_STATE_PLUGINS lock failed") = None;
*INSTALL_STATE_TOOLS
.lock()
.expect("INSTALL_STATE_TOOLS lock failed") = None;
}
#[cfg(test)]
mod tests {
use super::normalize_version_for_sort;
use itertools::Itertools;
use versions::Versioning;
#[test]
fn test_normalize_version_for_sort() {
assert_eq!(normalize_version_for_sort("v1.0.0"), "1.0.0");
assert_eq!(normalize_version_for_sort("V1.0.0"), "1.0.0");
assert_eq!(normalize_version_for_sort("1.0.0"), "1.0.0");
assert_eq!(normalize_version_for_sort("latest"), "latest");
}
#[test]
fn test_version_sorting_with_v_prefix() {
// Test that mixed v-prefix and non-v-prefix versions sort correctly
let versions = ["v2.0.51", "2.0.35", "2.0.52"];
// Without normalization - demonstrates the problem
let sorted_without_norm: Vec<_> = versions
.iter()
.sorted_by_cached_key(|v| (Versioning::new(v), v.to_string()))
.collect();
println!("Without normalization: {:?}", sorted_without_norm);
// With normalization - the fix
let sorted_with_norm: Vec<_> = versions
.iter()
.sorted_by_cached_key(|v| {
let normalized = normalize_version_for_sort(v);
(Versioning::new(normalized), v.to_string())
})
.collect();
println!("With normalization: {:?}", sorted_with_norm);
// With the fix, v2.0.51 should sort between 2.0.35 and 2.0.52
// The highest version should be 2.0.52
assert_eq!(**sorted_with_norm.last().unwrap(), "2.0.52");
// v2.0.51 should be second to last
assert_eq!(**sorted_with_norm.get(1).unwrap(), "v2.0.51");
// 2.0.35 should be first
assert_eq!(**sorted_with_norm.first().unwrap(), "2.0.35");
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/toolset_install.rs | src/toolset/toolset_install.rs | use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use eyre::Result;
use indexmap::IndexSet;
use itertools::Itertools;
use tokio::{sync::Semaphore, task::JoinSet};
use crate::config::Config;
use crate::config::settings::Settings;
use crate::errors::Error;
use crate::hooks::{Hooks, InstalledToolInfo};
use crate::install_context::InstallContext;
use crate::toolset::Toolset;
use crate::toolset::helpers::{get_leaf_dependencies, show_python_install_hint};
use crate::toolset::install_options::InstallOptions;
use crate::toolset::tool_request::ToolRequest;
use crate::toolset::tool_source::ToolSource;
use crate::toolset::tool_version::ToolVersion;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{config, hooks};
impl Toolset {
#[async_backtrace::framed]
pub async fn install_missing_versions(
&mut self,
config: &mut Arc<Config>,
opts: &InstallOptions,
) -> Result<Vec<ToolVersion>> {
// If auto-install is explicitly disabled, skip all automatic installation
if opts.skip_auto_install {
return Ok(vec![]);
}
let mut versions = self
.list_missing_versions(config)
.await
.into_iter()
.filter(|tv| {
!opts.missing_args_only
|| matches!(self.versions[tv.ba()].source, ToolSource::Argument)
})
.filter(|tv| {
if let Some(tools) = &opts.auto_install_disable_tools {
!tools.contains(&tv.ba().short)
} else {
true
}
})
.map(|tv| tv.request)
.collect_vec();
// Ensure options from toolset are preserved during auto-install
self.init_request_options(&mut versions);
let versions = self.install_all_versions(config, versions, opts).await?;
if !versions.is_empty() {
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(config, ts, &versions).await?;
}
Ok(versions)
}
/// sets the options on incoming requests to install to whatever is already in the toolset
/// this handles the use-case where you run `mise use ubi:cilium/cilium-cli` (without CLi options)
/// but this tool has options inside mise.toml
pub(super) fn init_request_options(&self, requests: &mut Vec<ToolRequest>) {
for tr in requests {
if let Some(tvl) = self.versions.get(tr.ba()) {
if tvl.requests.len() != 1 {
// TODO: handle this case with multiple versions
continue;
}
let options = tvl.backend.opts();
// TODO: tr.options() probably should be Option<ToolVersionOptions>
// to differentiate between no options and empty options
// without that it might not be possible to unset the options if they are set
if tr.options().is_empty() || tr.options() != options {
tr.set_options(options);
}
}
}
}
#[async_backtrace::framed]
pub async fn install_all_versions(
&mut self,
config: &mut Arc<Config>,
mut versions: Vec<ToolRequest>,
opts: &InstallOptions,
) -> Result<Vec<ToolVersion>> {
if versions.is_empty() {
return Ok(vec![]);
}
// Initialize a footer for the entire install session once (before batching)
let mpr = MultiProgressReport::get();
let footer_reason = if opts.dry_run {
format!("{} (dry-run)", opts.reason)
} else {
opts.reason.clone()
};
mpr.init_footer(opts.dry_run, &footer_reason, versions.len());
// Skip hooks in dry-run mode
if !opts.dry_run {
// Run pre-install hook
hooks::run_one_hook(config, self, Hooks::Preinstall, None).await;
}
self.init_request_options(&mut versions);
show_python_install_hint(&versions);
// Handle dependencies by installing in dependency order
let mut installed = vec![];
let mut leaf_deps = get_leaf_dependencies(&versions)?;
while !leaf_deps.is_empty() {
if leaf_deps.len() < versions.len() {
debug!("installing {} leaf tools first", leaf_deps.len());
}
versions.retain(|tr| !leaf_deps.contains(tr));
match self.install_some_versions(config, leaf_deps, opts).await {
Ok(leaf_versions) => installed.extend(leaf_versions),
Err(Error::InstallFailed {
successful_installations,
failed_installations,
}) => {
// Count both successes and failures toward footer progress
mpr.footer_inc(successful_installations.len() + failed_installations.len());
installed.extend(successful_installations);
return Err(Error::InstallFailed {
successful_installations: installed,
failed_installations,
}
.into());
}
Err(e) => return Err(e.into()),
}
leaf_deps = get_leaf_dependencies(&versions)?;
}
// Skip config reload and resolve in dry-run mode
if !opts.dry_run {
// Reload config and resolve (ignoring errors like the original does)
trace!("install: reloading config");
*config = Config::reset().await?;
trace!("install: resolving");
if let Err(err) = self.resolve(config).await {
debug!("error resolving versions after install: {err:#}");
}
}
// Debug logging for successful installations
if log::log_enabled!(log::Level::Debug) {
for tv in installed.iter() {
let backend = tv.backend()?;
let bin_paths = backend
.list_bin_paths(config, tv)
.await
.map_err(|e| {
warn!("Error listing bin paths for {tv}: {e:#}");
})
.unwrap_or_default();
debug!("[{tv}] list_bin_paths: {bin_paths:?}");
let env = backend
.exec_env(config, self, tv)
.await
.map_err(|e| {
warn!("Error running exec-env: {e:#}");
})
.unwrap_or_default();
if !env.is_empty() {
debug!("[{tv}] exec_env: {env:?}");
}
}
}
// Skip hooks in dry-run mode
if !opts.dry_run {
// Run post-install hook with installed tools info (ignoring errors)
let installed_tools: Vec<InstalledToolInfo> =
installed.iter().map(InstalledToolInfo::from).collect();
let _ = hooks::run_one_hook_with_context(
config,
self,
Hooks::Postinstall,
None,
Some(&installed_tools),
)
.await;
}
// Finish the global footer
if !opts.dry_run {
mpr.footer_finish();
}
Ok(installed)
}
pub(super) async fn install_some_versions(
&mut self,
config: &Arc<Config>,
versions: Vec<ToolRequest>,
opts: &InstallOptions,
) -> Result<Vec<ToolVersion>, Error> {
debug!("install_some_versions: {}", versions.iter().join(" "));
// Group versions by backend
let versions_clone = versions.clone();
let queue: Result<Vec<_>> = versions
.into_iter()
.rev()
.chunk_by(|v| v.ba().clone())
.into_iter()
.map(|(ba, v)| Ok((ba.backend()?, v.collect_vec())))
.collect();
let queue = match queue {
Ok(q) => q,
Err(e) => {
// If we can't build the queue, return error for all versions
let failed_installations: Vec<_> = versions_clone
.into_iter()
.map(|tr| (tr, eyre::eyre!("{}", e)))
.collect();
return Err(Error::InstallFailed {
successful_installations: vec![],
failed_installations,
});
}
};
// Don't initialize header here - it's already done in install_all_versions
// Track plugin installation errors to avoid early returns
let mut plugin_errors = Vec::new();
// Ensure plugins are installed
for (backend, trs) in &queue {
if let Some(plugin) = backend.plugin()
&& !plugin.is_installed()
{
let mpr = MultiProgressReport::get();
if let Err(e) = plugin
.ensure_installed(config, &mpr, false, opts.dry_run)
.await
.or_else(|err| {
if let Some(&Error::PluginNotInstalled(_)) = err.downcast_ref::<Error>() {
Ok(())
} else {
Err(err)
}
})
{
// Collect plugin installation errors instead of returning early
let plugin_name = backend.ba().short.clone();
for tr in trs {
plugin_errors.push((
tr.clone(),
eyre::eyre!("Plugin '{}' installation failed: {}", plugin_name, e),
));
}
}
}
}
let raw = opts.raw || Settings::get().raw;
let jobs = match raw {
true => 1,
false => opts.jobs.unwrap_or(Settings::get().jobs),
};
let semaphore = Arc::new(Semaphore::new(jobs));
let ts = Arc::new(self.clone());
let mut tset: JoinSet<Vec<(ToolRequest, Result<ToolVersion>)>> = JoinSet::new();
let opts = Arc::new(opts.clone());
// Track semaphore acquisition errors
let mut semaphore_errors = Vec::new();
// Track which tools are being processed by each task for better error reporting
// Use a HashMap to map task IDs to their tools
let mut task_tools: HashMap<usize, Vec<ToolRequest>> = HashMap::new();
// Track which tools already have plugin errors to avoid duplicate reporting
let mut tools_with_plugin_errors: HashSet<ToolRequest> = HashSet::new();
for (tr, _) in &plugin_errors {
tools_with_plugin_errors.insert(tr.clone());
}
for (ba, trs) in queue {
let ts = ts.clone();
let permit = match semaphore.clone().acquire_owned().await {
Ok(p) => p,
Err(e) => {
// Collect semaphore acquisition errors instead of returning early
for tr in trs {
semaphore_errors
.push((tr, eyre::eyre!("Failed to acquire semaphore: {}", e)));
}
continue;
}
};
let opts = opts.clone();
let ba = ba.clone();
let config = config.clone();
// Filter out tools that already have plugin errors
let filtered_trs: Vec<ToolRequest> = trs
.into_iter()
.filter(|tr| !tools_with_plugin_errors.contains(tr))
.collect();
// Skip spawning task if no tools remain after filtering
if filtered_trs.is_empty() {
continue;
}
// Track the tools for this task using the task ID
let task_id = tset.len();
task_tools.insert(task_id, filtered_trs.clone());
tset.spawn(async move {
let _permit = permit;
let mpr = MultiProgressReport::get();
let mut results = vec![];
for tr in filtered_trs {
let result = async {
let tv = tr.resolve(&config, &opts.resolve_options).await?;
let ctx = InstallContext {
config: config.clone(),
ts: ts.clone(),
pr: mpr.add_with_options(&tv.style(), opts.dry_run),
force: opts.force,
dry_run: opts.dry_run,
locked: opts.locked,
};
// Avoid wrapping the backend error here so the error location
// points to the backend implementation (more helpful for debugging).
ba.install_version(ctx, tv).await
}
.await;
results.push((tr, result));
// Bump footer for each completed tool
MultiProgressReport::get().footer_inc(1);
}
results
});
}
let mut task_results = vec![];
// Collect results from spawned tasks
while let Some(res) = tset.join_next().await {
match res {
Ok(results) => task_results.extend(results),
Err(e) => panic!("task join error: {e:#}"),
}
}
// Reverse task results to maintain original order (since we reversed when building queue)
task_results.reverse();
let mut all_results = vec![];
// Add plugin errors first (in original order)
all_results.extend(plugin_errors.into_iter().map(|(tr, e)| (tr, Err(e))));
// Add semaphore errors (in original order)
all_results.extend(semaphore_errors.into_iter().map(|(tr, e)| (tr, Err(e))));
// Add task results (already in correct order after reversal)
all_results.extend(task_results);
// Process results and separate successes from failures
let mut successful_installations = vec![];
let mut failed_installations = vec![];
for (tr, result) in all_results {
match result {
Ok(tv) => successful_installations.push(tv),
Err(e) => failed_installations.push((tr, e)),
}
}
// Return appropriate result
if failed_installations.is_empty() {
Ok(successful_installations)
} else {
Err(Error::InstallFailed {
successful_installations,
failed_installations,
})
}
}
pub async fn install_missing_bin(
&mut self,
config: &mut Arc<Config>,
bin_name: &str,
) -> Result<Option<Vec<ToolVersion>>> {
// Strategy: Find backends that could provide this bin by checking:
// 1. Any currently installed versions that provide the bin
// 2. Any requested backends with installed versions (even if not current)
let mut plugins = IndexSet::new();
// First check currently active installed versions
for (p, tv) in self.list_current_installed_versions(config) {
if let Ok(Some(_bin)) = p.which(config, &tv, bin_name).await {
plugins.insert(p);
}
}
// Also check backends that are requested but not currently active
// This handles the case where a user has tool@v1 globally and tool@v2 locally (not installed)
// When looking for a bin provided by the tool, we check if any installed version provides it
let all_installed = self.list_installed_versions(config).await?;
for (backend, _versions) in self.list_versions_by_plugin() {
// Skip if we already found this backend
if plugins.contains(&backend) {
continue;
}
// Check if this backend has ANY installed version that provides the bin
let backend_versions: Vec<_> = all_installed
.iter()
.filter(|(p, _)| p.ba() == backend.ba())
.collect();
for (_, tv) in backend_versions {
if let Ok(Some(_bin)) = backend.which(config, tv, bin_name).await {
plugins.insert(backend.clone());
break;
}
}
}
// Install missing versions for backends that provide this bin
for plugin in plugins {
let versions = self
.list_missing_versions(config)
.await
.into_iter()
.filter(|tv| tv.ba() == &**plugin.ba())
.filter(|tv| match &Settings::get().auto_install_disable_tools {
Some(disable_tools) => !disable_tools.contains(&tv.ba().short),
None => true,
})
.map(|tv| tv.request)
.collect_vec();
if !versions.is_empty() {
let versions = self
.install_all_versions(config, versions.clone(), &InstallOptions::default())
.await?;
if !versions.is_empty() {
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(config, ts, &versions).await?;
}
return Ok(Some(versions));
}
}
Ok(None)
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_version_options.rs | src/toolset/tool_version_options.rs | use indexmap::IndexMap;
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ToolVersionOptions {
pub os: Option<Vec<String>>,
pub install_env: IndexMap<String, String>,
#[serde(flatten)]
pub opts: IndexMap<String, String>,
}
// Implement Hash manually to ensure deterministic hashing across IndexMap
impl std::hash::Hash for ToolVersionOptions {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.os.hash(state);
// Hash install_env in sorted order for deterministic hashing
let mut install_env_sorted: Vec<_> = self.install_env.iter().collect();
install_env_sorted.sort_by_key(|(k, _)| *k);
install_env_sorted.hash(state);
// Hash opts in sorted order for deterministic hashing
let mut opts_sorted: Vec<_> = self.opts.iter().collect();
opts_sorted.sort_by_key(|(k, _)| *k);
opts_sorted.hash(state);
}
}
impl ToolVersionOptions {
pub fn is_empty(&self) -> bool {
self.install_env.is_empty() && self.opts.is_empty()
}
pub fn get(&self, key: &str) -> Option<&String> {
// First try direct lookup
if let Some(value) = self.opts.get(key) {
return Some(value);
}
// We can't return references to temporarily parsed TOML values,
// so nested lookup is not possible with this API.
// For nested values, users should access the raw opts and parse themselves.
None
}
pub fn merge(&mut self, other: &IndexMap<String, String>) {
for (key, value) in other {
self.opts
.entry(key.to_string())
.or_insert(value.to_string());
}
}
pub fn contains_key(&self, key: &str) -> bool {
if self.opts.contains_key(key) {
return true;
}
// Check if it's a nested key that exists
self.get_nested_value_exists(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
self.opts.iter()
}
// Check if a nested value exists without returning a reference
fn get_nested_value_exists(&self, key: &str) -> bool {
// Split the key by dots to navigate nested structure
let parts: Vec<&str> = key.split('.').collect();
if parts.len() < 2 {
return false;
}
let root_key = parts[0];
let nested_path = &parts[1..];
// Get the root value and try to parse it as TOML
if let Some(value) = self.opts.get(root_key) {
if let Ok(toml_value) = value.parse::<toml::Value>() {
return Self::value_exists_at_path(&toml_value, nested_path);
} else if value.trim().starts_with('{') && value.trim().ends_with('}') {
// Try to parse as inline TOML table
if let Ok(toml_value) = format!("value = {value}").parse::<toml::Value>()
&& let Some(table_value) = toml_value.get("value")
{
return Self::value_exists_at_path(table_value, nested_path);
}
}
}
false
}
fn value_exists_at_path(value: &toml::Value, path: &[&str]) -> bool {
if path.is_empty() {
return matches!(value, toml::Value::String(_));
}
match value {
toml::Value::Table(table) => {
if let Some(next_value) = table.get(path[0]) {
Self::value_exists_at_path(next_value, &path[1..])
} else {
false
}
}
_ => false,
}
}
// New method to get nested values as owned Strings
pub fn get_nested_string(&self, key: &str) -> Option<String> {
// Split the key by dots to navigate nested structure
let parts: Vec<&str> = key.split('.').collect();
if parts.len() < 2 {
return None;
}
let root_key = parts[0];
let nested_path = &parts[1..];
// Get the root value and try to parse it as TOML
if let Some(value) = self.opts.get(root_key) {
if let Ok(toml_value) = value.parse::<toml::Value>() {
return Self::get_string_at_path(&toml_value, nested_path);
} else if value.trim().starts_with('{') && value.trim().ends_with('}') {
// Try to parse as inline TOML table
if let Ok(toml_value) = format!("value = {value}").parse::<toml::Value>()
&& let Some(table_value) = toml_value.get("value")
{
return Self::get_string_at_path(table_value, nested_path);
}
}
}
None
}
fn get_string_at_path(value: &toml::Value, path: &[&str]) -> Option<String> {
if path.is_empty() {
return match value {
toml::Value::String(s) => Some(s.clone()),
toml::Value::Integer(i) => Some(i.to_string()),
toml::Value::Boolean(b) => Some(b.to_string()),
toml::Value::Float(f) => Some(f.to_string()),
_ => None,
};
}
match value {
toml::Value::Table(table) => {
if let Some(next_value) = table.get(path[0]) {
Self::get_string_at_path(next_value, &path[1..])
} else {
None
}
}
_ => None,
}
}
}
pub fn parse_tool_options(s: &str) -> ToolVersionOptions {
let mut tvo = ToolVersionOptions::default();
for opt in s.split(',') {
let (k, v) = opt.split_once('=').unwrap_or((opt, ""));
if k.is_empty() {
continue;
}
tvo.opts.insert(k.to_string(), v.to_string());
}
tvo
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use test_log::test;
#[test]
fn test_parse_tool_options() {
let t = |input, expected| {
let opts = parse_tool_options(input);
assert_eq!(opts, expected);
};
t("", ToolVersionOptions::default());
t(
"exe=rg",
ToolVersionOptions {
opts: [("exe".to_string(), "rg".to_string())]
.iter()
.cloned()
.collect(),
..Default::default()
},
);
t(
"exe=rg,match=musl",
ToolVersionOptions {
opts: [
("exe".to_string(), "rg".to_string()),
("match".to_string(), "musl".to_string()),
]
.iter()
.cloned()
.collect(),
..Default::default()
},
);
}
#[test]
fn test_nested_option_with_os_arch_dash() {
let mut opts = IndexMap::new();
opts.insert(
"platforms".to_string(),
r#"
[macos-x64]
url = "https://example.com/macos-x64.tar.gz"
checksum = "sha256:abc123"
[linux-x64]
url = "https://example.com/linux-x64.tar.gz"
checksum = "sha256:def456"
"#
.to_string(),
);
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
assert_eq!(
tool_opts.get_nested_string("platforms.macos-x64.url"),
Some("https://example.com/macos-x64.tar.gz".to_string())
);
assert_eq!(
tool_opts.get_nested_string("platforms.macos-x64.checksum"),
Some("sha256:abc123".to_string())
);
assert_eq!(
tool_opts.get_nested_string("platforms.linux-x64.url"),
Some("https://example.com/linux-x64.tar.gz".to_string())
);
assert_eq!(
tool_opts.get_nested_string("platforms.linux-x64.checksum"),
Some("sha256:def456".to_string())
);
}
#[test]
fn test_generic_nested_options() {
let mut opts = IndexMap::new();
opts.insert(
"config".to_string(),
r#"
[database]
host = "localhost"
port = 5432
[cache.redis]
host = "redis.example.com"
port = 6379
"#
.to_string(),
);
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
assert_eq!(
tool_opts.get_nested_string("config.database.host"),
Some("localhost".to_string())
);
assert_eq!(
tool_opts.get_nested_string("config.database.port"),
Some("5432".to_string())
);
assert_eq!(
tool_opts.get_nested_string("config.cache.redis.host"),
Some("redis.example.com".to_string())
);
assert_eq!(
tool_opts.get_nested_string("config.cache.redis.port"),
Some("6379".to_string())
);
}
#[test]
fn test_direct_and_nested_options() {
let mut opts = IndexMap::new();
opts.insert(
"platforms".to_string(),
r#"
[macos-x64]
url = "https://example.com/macos-x64.tar.gz"
"#
.to_string(),
);
opts.insert("simple_option".to_string(), "value".to_string());
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
// Test nested option
assert_eq!(
tool_opts.get_nested_string("platforms.macos-x64.url"),
Some("https://example.com/macos-x64.tar.gz".to_string())
);
// Test direct option
assert_eq!(tool_opts.get("simple_option"), Some(&"value".to_string()));
}
#[test]
fn test_contains_key_with_nested_options() {
let mut opts = IndexMap::new();
opts.insert(
"platforms".to_string(),
r#"
[macos-x64]
url = "https://example.com/macos-x64.tar.gz"
"#
.to_string(),
);
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
assert!(tool_opts.contains_key("platforms.macos-x64.url"));
assert!(!tool_opts.contains_key("platforms.linux-x64.url"));
assert!(!tool_opts.contains_key("nonexistent"));
}
#[test]
fn test_merge_functionality() {
let mut opts = IndexMap::new();
opts.insert(
"platforms".to_string(),
r#"
[macos-x64]
url = "https://example.com/macos-x64.tar.gz"
"#
.to_string(),
);
let mut tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
// Verify nested option access
assert!(tool_opts.contains_key("platforms.macos-x64.url"));
// Merge new options
let mut new_opts = IndexMap::new();
new_opts.insert("simple_option".to_string(), "value".to_string());
tool_opts.merge(&new_opts);
// Should be able to access both old and new options
assert!(tool_opts.contains_key("platforms.macos-x64.url"));
assert!(tool_opts.contains_key("simple_option"));
}
#[test]
fn test_non_existent_nested_paths() {
let mut opts = IndexMap::new();
opts.insert(
"platforms".to_string(),
r#"
[macos-x64]
url = "https://example.com/macos-x64.tar.gz"
"#
.to_string(),
);
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
// Test non-existent nested paths
assert_eq!(
tool_opts.get_nested_string("platforms.windows-x64.url"),
None
);
assert_eq!(
tool_opts.get_nested_string("platforms.macos-x64.checksum"),
None
);
assert_eq!(tool_opts.get_nested_string("config.database.host"), None);
}
#[test]
fn test_indexmap_preserves_order() {
let mut tvo = ToolVersionOptions::default();
// Insert options in a specific order
tvo.opts.insert("zebra".to_string(), "last".to_string());
tvo.opts.insert("alpha".to_string(), "first".to_string());
tvo.opts.insert("beta".to_string(), "second".to_string());
// Collect keys to verify order is preserved
let keys: Vec<_> = tvo.opts.keys().collect();
assert_eq!(keys, vec!["zebra", "alpha", "beta"]);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/mod.rs | src/toolset/mod.rs | use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::sync::Arc;
use crate::backend::Backend;
use crate::cli::args::BackendArg;
use crate::config::Config;
use crate::config::settings::{Settings, SettingsStatusMissingTools};
use crate::env::TERM_WIDTH;
use crate::registry::tool_enabled;
use crate::{backend, parallel};
pub use builder::ToolsetBuilder;
use console::truncate_str;
use eyre::Result;
use indexmap::IndexMap;
use itertools::Itertools;
use outdated_info::OutdatedInfo;
pub use outdated_info::is_outdated_version;
use tokio::sync::OnceCell;
pub use tool_request::ToolRequest;
pub use tool_request_set::{ToolRequestSet, ToolRequestSetBuilder};
pub use tool_source::ToolSource;
pub use tool_version::{ResolveOptions, ToolVersion};
pub use tool_version_list::ToolVersionList;
pub use tool_version_options::{ToolVersionOptions, parse_tool_options};
use helpers::TVTuple;
pub use install_options::InstallOptions;
mod builder;
mod helpers;
mod install_options;
pub(crate) mod install_state;
pub(crate) mod outdated_info;
pub(crate) mod tool_request;
mod tool_request_set;
mod tool_source;
mod tool_version;
mod tool_version_list;
mod tool_version_options;
mod toolset_env;
mod toolset_install;
mod toolset_paths;
/// a toolset is a collection of tools for various plugins
///
/// one example is a .tool-versions file
/// the idea is that we start with an empty toolset, then
/// merge in other toolsets from various sources
#[derive(Debug, Default, Clone)]
pub struct Toolset {
pub versions: IndexMap<Arc<BackendArg>, ToolVersionList>,
pub source: Option<ToolSource>,
tera_ctx: OnceCell<tera::Context>,
}
impl Toolset {
pub fn new(source: ToolSource) -> Self {
Self {
source: Some(source),
..Default::default()
}
}
pub fn add_version(&mut self, tvr: ToolRequest) {
let ba = tvr.ba();
if self.is_disabled(ba) {
return;
}
let tvl = self
.versions
.entry(tvr.ba().clone())
.or_insert_with(|| ToolVersionList::new(ba.clone(), self.source.clone().unwrap()));
tvl.requests.push(tvr);
}
pub fn merge(&mut self, other: Toolset) {
let mut versions = other.versions;
for (plugin, tvl) in self.versions.clone() {
if !versions.contains_key(&plugin) {
versions.insert(plugin, tvl);
}
}
versions.retain(|_, tvl| !self.is_disabled(&tvl.backend));
self.versions = versions;
self.source = other.source;
}
#[async_backtrace::framed]
pub async fn resolve(&mut self, config: &Arc<Config>) -> eyre::Result<()> {
self.resolve_with_opts(config, &Default::default()).await
}
#[async_backtrace::framed]
pub async fn resolve_with_opts(
&mut self,
config: &Arc<Config>,
opts: &ResolveOptions,
) -> eyre::Result<()> {
self.list_missing_plugins();
let versions = self
.versions
.clone()
.into_iter()
.map(|(ba, tvl)| (config.clone(), ba, tvl.clone(), opts.clone()))
.collect::<Vec<_>>();
let tvls = parallel::parallel(versions, |(config, ba, mut tvl, opts)| async move {
if let Err(err) = tvl.resolve(&config, &opts).await {
warn!("Failed to resolve tool version list for {ba}: {err}");
}
Ok((ba, tvl))
})
.await?;
self.versions = tvls.into_iter().collect();
Ok(())
}
pub fn list_missing_plugins(&self) -> Vec<String> {
self.versions
.iter()
.filter(|(_, tvl)| {
tvl.versions
.first()
.map(|tv| tv.request.is_os_supported())
.unwrap_or_default()
})
.map(|(ba, _)| ba)
.flat_map(|ba| ba.backend())
.filter(|b| b.plugin().is_some_and(|p| !p.is_installed()))
.map(|p| p.id().into())
.collect()
}
pub async fn list_missing_versions(&self, config: &Arc<Config>) -> Vec<ToolVersion> {
trace!("list_missing_versions");
measure!("toolset::list_missing_versions", {
self.list_current_versions()
.into_iter()
.filter(|(p, tv)| !p.is_version_installed(config, tv, true))
.map(|(_, tv)| tv)
.collect()
})
}
pub async fn list_installed_versions(&self, config: &Arc<Config>) -> Result<Vec<TVTuple>> {
let current_versions: HashMap<(String, String), TVTuple> = self
.list_current_versions()
.into_iter()
.map(|(p, tv)| ((p.id().into(), tv.version.clone()), (p.clone(), tv)))
.collect();
let current_versions = Arc::new(current_versions);
let mut versions = vec![];
for b in backend::list().into_iter() {
for v in b.list_installed_versions() {
if let Some((p, tv)) = current_versions.get(&(b.id().into(), v.clone())) {
versions.push((p.clone(), tv.clone()));
} else {
let tv = ToolRequest::new(b.ba().clone(), &v, ToolSource::Unknown)?
.resolve(config, &Default::default())
.await?;
versions.push((b.clone(), tv));
}
}
}
Ok(versions)
}
pub fn list_current_requests(&self) -> Vec<&ToolRequest> {
self.versions
.values()
.flat_map(|tvl| &tvl.requests)
.collect()
}
pub fn list_versions_by_plugin(&self) -> Vec<(Arc<dyn Backend>, &Vec<ToolVersion>)> {
self.versions
.iter()
.flat_map(|(ba, v)| eyre::Ok((ba.backend()?, &v.versions)))
.collect()
}
pub fn list_current_versions(&self) -> Vec<(Arc<dyn Backend>, ToolVersion)> {
trace!("list_current_versions");
self.list_versions_by_plugin()
.iter()
.flat_map(|(p, v)| {
v.iter().filter(|v| v.request.is_os_supported()).map(|v| {
// map cargo backend specific prefixes to ref
let tv = match v.version.split_once(':') {
Some((ref_type @ ("tag" | "branch" | "rev"), r)) => {
let request = ToolRequest::Ref {
backend: p.ba().clone(),
ref_: r.to_string(),
ref_type: ref_type.to_string(),
options: v.request.options().clone(),
source: v.request.source().clone(),
};
let version = format!("ref:{r}");
ToolVersion::new(request, version)
}
_ => v.clone(),
};
(p.clone(), tv)
})
})
.collect()
}
pub async fn list_all_versions(
&self,
config: &Arc<Config>,
) -> Result<Vec<(Arc<dyn Backend>, ToolVersion)>> {
use itertools::Itertools;
let versions = self
.list_current_versions()
.into_iter()
.chain(self.list_installed_versions(config).await?)
.unique_by(|(ba, tv)| (ba.clone(), tv.tv_pathname().to_string()))
.collect();
Ok(versions)
}
pub fn list_current_installed_versions(
&self,
config: &Arc<Config>,
) -> Vec<(Arc<dyn Backend>, ToolVersion)> {
self.list_current_versions()
.into_iter()
.filter(|(p, tv)| p.is_version_installed(config, tv, true))
.collect()
}
pub async fn list_outdated_versions(
&self,
config: &Arc<Config>,
bump: bool,
opts: &ResolveOptions,
) -> Vec<OutdatedInfo> {
self.list_outdated_versions_filtered(config, bump, opts, None)
.await
}
pub async fn list_outdated_versions_filtered(
&self,
config: &Arc<Config>,
bump: bool,
opts: &ResolveOptions,
filter_tools: Option<&[crate::cli::args::ToolArg]>,
) -> Vec<OutdatedInfo> {
let versions = self
.list_current_versions()
.into_iter()
// Filter to only check specified tools if provided
.filter(|(_, tv)| {
if let Some(tools) = filter_tools {
tools.iter().any(|t| t.ba.as_ref() == tv.ba())
} else {
true
}
})
.map(|(t, tv)| (config.clone(), t, tv, bump, opts.clone()))
.collect::<Vec<_>>();
let outdated = parallel::parallel(versions, |(config, t, tv, bump, opts)| async move {
let mut outdated = vec![];
match t.outdated_info(&config, &tv, bump, &opts).await {
Ok(Some(oi)) => outdated.push(oi),
Ok(None) => {}
Err(e) => {
warn!("Error getting outdated info for {tv}: {e:#}");
}
}
if t.symlink_path(&tv).is_some() {
trace!("skipping symlinked version {tv}");
// do not consider symlinked versions to be outdated
return Ok(outdated);
}
match OutdatedInfo::resolve(&config, tv.clone(), bump, &opts).await {
Ok(Some(oi)) => outdated.push(oi),
Ok(None) => {}
Err(e) => {
warn!("Error creating OutdatedInfo for {tv}: {e:#}");
}
}
Ok(outdated)
})
.await
.unwrap_or_else(|e| {
warn!("Error in parallel outdated version check: {e:#}");
vec![]
});
outdated.into_iter().flatten().collect()
}
pub async fn tera_ctx(&self, config: &Arc<Config>) -> Result<&tera::Context> {
self.tera_ctx
.get_or_try_init(async || {
let env = self.full_env(config).await?;
let mut ctx = config.tera_ctx.clone();
ctx.insert("env", &env);
Ok(ctx)
})
.await
}
pub async fn which(
&self,
config: &Arc<Config>,
bin_name: &str,
) -> Option<(Arc<dyn Backend>, ToolVersion)> {
for (p, tv) in self.list_current_installed_versions(config) {
match Box::pin(p.which(config, &tv, bin_name)).await {
Ok(Some(_bin)) => return Some((p, tv)),
Ok(None) => {}
Err(e) => {
debug!("Error running which: {:#}", e);
}
}
}
None
}
pub async fn which_bin(&self, config: &Arc<Config>, bin_name: &str) -> Option<PathBuf> {
for (p, tv) in self.list_current_installed_versions(config) {
if let Ok(Some(bin)) = Box::pin(p.which(config, &tv, bin_name)).await {
return Some(bin);
}
}
None
}
pub async fn list_rtvs_with_bin(
&self,
config: &Arc<Config>,
bin_name: &str,
) -> Result<Vec<ToolVersion>> {
let mut rtvs = vec![];
for (p, tv) in self.list_installed_versions(config).await? {
match p.which(config, &tv, bin_name).await {
Ok(Some(_bin)) => rtvs.push(tv),
Ok(None) => {}
Err(e) => {
warn!("Error running which: {:#}", e);
}
}
}
Ok(rtvs)
}
pub async fn notify_if_versions_missing(&self, config: &Arc<Config>) {
if Settings::get().status.missing_tools() == SettingsStatusMissingTools::Never {
return;
}
let mut missing = vec![];
let missing_versions = self.list_missing_versions(config).await;
for tv in missing_versions.into_iter() {
if Settings::get().status.missing_tools() == SettingsStatusMissingTools::Always {
missing.push(tv);
continue;
}
if let Ok(backend) = tv.backend() {
let installed = backend.list_installed_versions();
if !installed.is_empty() {
missing.push(tv);
}
}
}
if missing.is_empty() || *crate::env::__MISE_SHIM {
return;
}
let versions = missing
.iter()
.map(|tv| tv.style())
.collect::<Vec<_>>()
.join(" ");
warn!(
"missing: {}",
truncate_str(&versions, *TERM_WIDTH - 14, "…"),
);
}
fn is_disabled(&self, ba: &BackendArg) -> bool {
!ba.is_os_supported()
|| !tool_enabled(
&Settings::get().enable_tools(),
&Settings::get().disable_tools(),
&ba.short.to_string(),
)
}
}
impl Display for Toolset {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let plugins = &self
.versions
.iter()
.map(|(_, v)| v.requests.iter().map(|tvr| tvr.to_string()).join(" "))
.collect_vec();
write!(f, "{}", plugins.join(", "))
}
}
impl From<ToolRequestSet> for Toolset {
fn from(trs: ToolRequestSet) -> Self {
let mut ts = Toolset::default();
for (ba, versions, source) in trs.into_iter() {
ts.source = Some(source.clone());
let mut tvl = ToolVersionList::new(ba.clone(), source);
for tr in versions {
tvl.requests.push(tr);
}
ts.versions.insert(ba, tvl);
}
ts
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_version_list.rs | src/toolset/tool_version_list.rs | use std::sync::Arc;
use crate::errors::Error;
use crate::toolset::tool_request::ToolRequest;
use crate::toolset::tool_version::ResolveOptions;
use crate::toolset::{ToolSource, ToolVersion};
use crate::{cli::args::BackendArg, config::Config};
/// represents several versions of a tool for a particular plugin
#[derive(Debug, Clone)]
pub struct ToolVersionList {
pub backend: Arc<BackendArg>,
pub versions: Vec<ToolVersion>,
pub requests: Vec<ToolRequest>,
pub source: ToolSource,
}
impl ToolVersionList {
pub fn new(backend: Arc<BackendArg>, source: ToolSource) -> Self {
Self {
backend,
versions: Vec::new(),
requests: vec![],
source,
}
}
pub async fn resolve(
&mut self,
config: &Arc<Config>,
opts: &ResolveOptions,
) -> eyre::Result<()> {
self.versions.clear();
for tvr in &mut self.requests {
// Only use special options (latest_versions, skip lockfile) for requests that
// explicitly specify "latest". This ensures `mise x node@20 npm@latest` only
// fetches latest and skips the lockfile for npm, not node.
let request_opts = if tvr.version() == "latest" {
opts.clone()
} else {
ResolveOptions {
latest_versions: false,
use_locked_version: true,
..opts.clone()
}
};
match tvr.resolve(config, &request_opts).await {
Ok(v) => self.versions.push(v),
Err(err) => {
return Err(Error::FailedToResolveVersion {
tr: Box::new(tvr.clone()),
ts: self.source.clone(),
source: err,
}
.into());
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use crate::{dirs, env, file};
use super::*;
#[tokio::test]
#[cfg(unix)]
async fn test_tool_version_list() {
let config = Config::get().await.unwrap();
let ba: Arc<BackendArg> = Arc::new("tiny".into());
let mut tvl = ToolVersionList::new(ba.clone(), ToolSource::Argument);
tvl.requests
.push(ToolRequest::new(ba, "latest", ToolSource::Argument).unwrap());
tvl.resolve(
&config,
&ResolveOptions {
latest_versions: true,
use_locked_version: false,
..Default::default()
},
)
.await
.unwrap();
assert_eq!(tvl.versions.len(), 1);
}
#[tokio::test]
async fn test_tool_version_list_failure() {
env::set_var("MISE_FAILURE", "1");
file::remove_all(dirs::CACHE.join("dummy")).unwrap();
let config = Config::reset().await.unwrap();
let ba: Arc<BackendArg> = Arc::new("dummy".into());
let mut tvl = ToolVersionList::new(ba.clone(), ToolSource::Argument);
tvl.requests
.push(ToolRequest::new(ba, "latest", ToolSource::Argument).unwrap());
let _ = tvl
.resolve(
&config,
&ResolveOptions {
latest_versions: true,
use_locked_version: false,
..Default::default()
},
)
.await;
assert_eq!(tvl.versions.len(), 0);
env::remove_var("MISE_FAILURE");
Config::reset().await.unwrap();
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/tool_version.rs | src/toolset/tool_version.rs | use std::fmt::{Display, Formatter};
use std::fs;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::{cmp::Ordering, sync::LazyLock};
use std::{collections::BTreeMap, sync::Arc};
use crate::backend::ABackend;
use crate::cli::args::BackendArg;
use crate::config::Config;
#[cfg(windows)]
use crate::file;
use crate::hash::hash_to_str;
use crate::lockfile::PlatformInfo;
use crate::toolset::{ToolRequest, ToolVersionOptions, tool_request};
use console::style;
use dashmap::DashMap;
use eyre::Result;
use jiff::Timestamp;
#[cfg(windows)]
use path_absolutize::Absolutize;
/// represents a single version of a tool for a particular plugin
#[derive(Debug, Clone)]
pub struct ToolVersion {
pub request: ToolRequest,
pub version: String,
pub lock_platforms: BTreeMap<String, PlatformInfo>,
pub install_path: Option<PathBuf>,
}
impl ToolVersion {
pub fn new(request: ToolRequest, version: String) -> Self {
ToolVersion {
request,
version,
lock_platforms: Default::default(),
install_path: None,
}
}
pub async fn resolve(
config: &Arc<Config>,
request: ToolRequest,
opts: &ResolveOptions,
) -> Result<Self> {
trace!("resolving {} {}", &request, opts);
if opts.use_locked_version
&& let Some(lt) = request.lockfile_resolve(config)?
{
let mut tv = Self::new(request.clone(), lt.version);
tv.lock_platforms = lt.platforms;
return Ok(tv);
}
let backend = request.ba().backend()?;
if let Some(plugin) = backend.plugin()
&& !plugin.is_installed()
{
let tv = Self::new(request.clone(), request.version());
return Ok(tv);
}
let tv = match request.clone() {
ToolRequest::Version { version: v, .. } => {
Self::resolve_version(config, request, &v, opts).await?
}
ToolRequest::Prefix { prefix, .. } => {
Self::resolve_prefix(config, request, &prefix, opts).await?
}
ToolRequest::Sub {
sub, orig_version, ..
} => Self::resolve_sub(config, request, &sub, &orig_version, opts).await?,
_ => {
let version = request.version();
Self::new(request, version)
}
};
trace!("resolved: {tv}");
Ok(tv)
}
pub fn ba(&self) -> &BackendArg {
self.request.ba()
}
pub fn backend(&self) -> Result<ABackend> {
self.ba().backend()
}
pub fn short(&self) -> &str {
&self.ba().short
}
pub fn install_path(&self) -> PathBuf {
if let Some(p) = &self.install_path {
return p.clone();
}
static CACHE: LazyLock<DashMap<ToolVersion, PathBuf>> = LazyLock::new(DashMap::new);
if let Some(p) = CACHE.get(self) {
return p.clone();
}
let pathname = match &self.request {
ToolRequest::Path { path: p, .. } => p.to_string_lossy().to_string(),
_ => self.tv_pathname(),
};
let path = self.ba().installs_path.join(pathname);
// handle non-symlinks on windows
// TODO: make this a utility function in xx
#[cfg(windows)]
if path.is_file() {
if let Ok(p) = file::read_to_string(&path).map(PathBuf::from) {
let path = self.ba().installs_path.join(p);
if path.exists() {
return path
.absolutize()
.expect("failed to absolutize path")
.to_path_buf();
}
}
}
CACHE.insert(self.clone(), path.clone());
path
}
pub fn cache_path(&self) -> PathBuf {
self.ba().cache_path.join(self.tv_pathname())
}
pub fn download_path(&self) -> PathBuf {
self.request.ba().downloads_path.join(self.tv_pathname())
}
pub async fn latest_version(&self, config: &Arc<Config>) -> Result<String> {
self.latest_version_with_opts(config, &ResolveOptions::default())
.await
}
pub async fn latest_version_with_opts(
&self,
config: &Arc<Config>,
base_opts: &ResolveOptions,
) -> Result<String> {
// Note: We always use latest_versions=true and use_locked_version=false for latest version lookup,
// but we preserve before_date from base_opts to respect date-based filtering
let opts = ResolveOptions {
latest_versions: true,
use_locked_version: false,
before_date: base_opts.before_date,
};
let tv = self.request.resolve(config, &opts).await?;
// map cargo backend specific prefixes to ref
let version = match tv.request.version().split_once(':') {
Some((_ref_type @ ("tag" | "branch" | "rev"), r)) => {
format!("ref:{r}")
}
_ => tv.version,
};
Ok(version)
}
pub fn style(&self) -> String {
format!(
"{}{}",
style(&self.ba().short).blue().for_stderr(),
style(&format!("@{}", &self.version)).for_stderr()
)
}
pub fn tv_pathname(&self) -> String {
match &self.request {
ToolRequest::Version { .. } => self.version.to_string(),
ToolRequest::Prefix { .. } => self.version.to_string(),
ToolRequest::Sub { .. } => self.version.to_string(),
ToolRequest::Ref { ref_: r, .. } => format!("ref-{r}"),
ToolRequest::Path { path: p, .. } => format!("path-{}", hash_to_str(p)),
ToolRequest::System { .. } => {
// Only show deprecation warning if not from .tool-versions file
if !matches!(
self.request.source(),
crate::toolset::ToolSource::ToolVersions(_)
) {
deprecated!(
"system_tool_version",
"@system is deprecated, use MISE_DISABLE_TOOLS instead"
);
}
"system".to_string()
}
}
.replace([':', '/'], "-")
}
async fn resolve_version(
config: &Arc<Config>,
request: ToolRequest,
v: &str,
opts: &ResolveOptions,
) -> Result<ToolVersion> {
let backend = request.backend()?;
let v = config.resolve_alias(&backend, v).await?;
match v.split_once(':') {
Some((ref_type @ ("ref" | "tag" | "branch" | "rev"), r)) => {
return Ok(Self::resolve_ref(
r.to_string(),
ref_type.to_string(),
request.options(),
&request,
));
}
Some(("path", p)) => {
return Self::resolve_path(PathBuf::from(p), &request);
}
Some(("prefix", p)) => {
return Self::resolve_prefix(config, request, p, opts).await;
}
Some((part, v)) if part.starts_with("sub-") => {
let sub = part.split_once('-').unwrap().1;
return Self::resolve_sub(config, request, sub, v, opts).await;
}
_ => (),
}
let build = |v| Ok(Self::new(request.clone(), v));
if let Some(plugin) = backend.plugin()
&& !plugin.is_installed()
{
return build(v);
}
if v == "latest" {
if !opts.latest_versions
&& let Some(v) = backend.latest_installed_version(None)?
{
return build(v);
}
if let Some(v) = backend
.latest_version_with_opts(config, None, opts.before_date)
.await?
{
return build(v);
}
}
if !opts.latest_versions {
let matches = backend.list_installed_versions_matching(&v);
if matches.contains(&v) {
return build(v);
}
if let Some(v) = matches.last() {
return build(v.clone());
}
}
// First try with date filter (common case)
let matches = backend
.list_versions_matching_with_opts(config, &v, opts.before_date)
.await?;
if matches.contains(&v) {
return build(v);
}
// If date filter is active and exact version not found, check without filter.
// Explicit pinned versions like "22.5.0" should not be filtered by date.
if opts.before_date.is_some() {
let all_versions = backend.list_versions_matching(config, &v).await?;
if all_versions.contains(&v) {
// Exact match exists but was filtered by date - use it anyway
return build(v);
}
}
Self::resolve_prefix(config, request, &v, opts).await
}
/// resolve a version like `sub-1:12.0.0` which becomes `11.0.0`, `sub-0.1:12.1.0` becomes `12.0.0`
async fn resolve_sub(
config: &Arc<Config>,
request: ToolRequest,
sub: &str,
v: &str,
opts: &ResolveOptions,
) -> Result<Self> {
let backend = request.backend()?;
let v = match v {
"latest" => backend
.latest_version_with_opts(config, None, opts.before_date)
.await?
.ok_or_else(|| {
let msg = if opts.before_date.is_some() {
format!(
"no versions found for {} matching date filter",
backend.id()
)
} else {
format!("no versions found for {}", backend.id())
};
eyre::eyre!(msg)
})?,
_ => config.resolve_alias(&backend, v).await?,
};
let v = tool_request::version_sub(&v, sub);
Box::pin(Self::resolve_version(config, request, &v, opts)).await
}
async fn resolve_prefix(
config: &Arc<Config>,
request: ToolRequest,
prefix: &str,
opts: &ResolveOptions,
) -> Result<Self> {
let backend = request.backend()?;
if !opts.latest_versions
&& let Some(v) = backend.list_installed_versions_matching(prefix).last()
{
return Ok(Self::new(request, v.to_string()));
}
let matches = backend
.list_versions_matching_with_opts(config, prefix, opts.before_date)
.await?;
let v = match matches.last() {
Some(v) => v,
None => prefix,
// None => Err(VersionNotFound(plugin.name.clone(), prefix.to_string()))?,
};
Ok(Self::new(request, v.to_string()))
}
fn resolve_ref(
ref_: String,
ref_type: String,
opts: ToolVersionOptions,
tr: &ToolRequest,
) -> Self {
let request = ToolRequest::Ref {
backend: tr.ba().clone(),
ref_,
ref_type,
options: opts.clone(),
source: tr.source().clone(),
};
let version = request.version();
Self::new(request, version)
}
fn resolve_path(path: PathBuf, tr: &ToolRequest) -> Result<ToolVersion> {
let path = fs::canonicalize(path)?;
let request = ToolRequest::Path {
backend: tr.ba().clone(),
path,
source: tr.source().clone(),
options: tr.options().clone(),
};
let version = request.version();
Ok(Self::new(request, version))
}
}
impl Display for ToolVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{}@{}", &self.ba().full(), &self.version)
}
}
impl PartialEq for ToolVersion {
fn eq(&self, other: &Self) -> bool {
self.ba() == other.ba() && self.version == other.version
}
}
impl Eq for ToolVersion {}
impl PartialOrd for ToolVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for ToolVersion {
fn cmp(&self, other: &Self) -> Ordering {
match self.request.ba().as_ref().cmp(other.ba()) {
Ordering::Equal => self.version.cmp(&other.version),
o => o,
}
}
}
impl Hash for ToolVersion {
fn hash<H: Hasher>(&self, state: &mut H) {
self.ba().hash(state);
self.version.hash(state);
}
}
#[derive(Debug, Clone)]
pub struct ResolveOptions {
pub latest_versions: bool,
pub use_locked_version: bool,
/// Only consider versions released before this timestamp
pub before_date: Option<Timestamp>,
}
impl Default for ResolveOptions {
fn default() -> Self {
Self {
latest_versions: false,
use_locked_version: true,
before_date: None,
}
}
}
impl Display for ResolveOptions {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let mut opts = vec![];
if self.latest_versions {
opts.push("latest_versions".to_string());
}
if self.use_locked_version {
opts.push("use_locked_version".to_string());
}
if let Some(ts) = &self.before_date {
opts.push(format!("before_date={ts}"));
}
write!(f, "({})", opts.join(", "))
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/outdated_info.rs | src/toolset/outdated_info.rs | use crate::semver::{chunkify_version, split_version_prefix};
use crate::toolset;
use crate::toolset::{ResolveOptions, ToolRequest, ToolSource, ToolVersion};
use crate::{Result, config::Config};
use serde_derive::Serialize;
use std::{
fmt::{Display, Formatter},
sync::Arc,
};
use tabled::Tabled;
use versions::Version;
#[derive(Debug, Serialize, Clone, Tabled)]
pub struct OutdatedInfo {
pub name: String,
#[serde(skip)]
#[tabled(skip)]
pub tool_request: ToolRequest,
#[serde(skip)]
#[tabled(skip)]
pub tool_version: ToolVersion,
pub requested: String,
#[tabled(display("Self::display_current"))]
pub current: Option<String>,
#[tabled(display("Self::display_bump"))]
pub bump: Option<String>,
pub latest: String,
pub source: ToolSource,
}
impl OutdatedInfo {
pub fn new(config: &Arc<Config>, tv: ToolVersion, latest: String) -> Result<Self> {
let t = tv.backend()?;
let current = if t.is_version_installed(config, &tv, true) {
Some(tv.version.clone())
} else {
None
};
let oi = Self {
source: tv.request.source().clone(),
name: tv.ba().short.to_string(),
current,
requested: tv.request.version(),
tool_request: tv.request.clone(),
tool_version: tv,
bump: None,
latest,
};
Ok(oi)
}
pub async fn resolve(
config: &Arc<Config>,
tv: ToolVersion,
bump: bool,
opts: &ResolveOptions,
) -> eyre::Result<Option<Self>> {
let t = tv.backend()?;
// prefix is something like "temurin-" or "corretto-"
let (prefix, _) = split_version_prefix(&tv.request.version());
let latest_result = if bump {
// Note: Backend's latest_version_with_opts takes individual parameters,
// not a ResolveOptions struct like ToolVersion's method
t.latest_version_with_opts(
config,
Some(prefix.clone()).filter(|s| !s.is_empty()),
opts.before_date,
)
.await
} else {
tv.latest_version_with_opts(config, opts)
.await
.map(Option::from)
};
let latest = match latest_result {
Ok(Some(latest)) => latest,
Ok(None) => {
warn!("Error getting latest version for {t}: no latest version found");
return Ok(None);
}
Err(e) => {
warn!("Error getting latest version for {t}: {e:#}");
return Ok(None);
}
};
let mut oi = Self::new(config, tv, latest)?;
if oi
.current
.as_ref()
.is_some_and(|c| !toolset::is_outdated_version(c, &oi.latest))
{
trace!("skipping up-to-date version {}", oi.tool_version);
return Ok(None);
}
if bump {
let old = oi.tool_version.request.version();
let old = old.strip_prefix(&prefix).unwrap_or_default();
let new = oi.latest.strip_prefix(&prefix).unwrap_or_default();
if let Some(bumped_version) = check_semver_bump(old, new)
&& bumped_version != oi.tool_version.request.version()
{
oi.bump = match oi.tool_request.clone() {
ToolRequest::Version {
version: _version,
backend,
options,
source,
} => {
oi.tool_request = ToolRequest::Version {
backend,
options,
source,
version: format!("{prefix}{bumped_version}"),
};
Some(oi.tool_request.version())
}
ToolRequest::Prefix {
prefix: _prefix,
backend,
options,
source,
} => {
oi.tool_request = ToolRequest::Prefix {
backend,
options,
source,
prefix: format!("{prefix}{bumped_version}"),
};
Some(oi.tool_request.version())
}
_ => {
warn!("upgrading non-version tool requests");
None
}
}
}
}
Ok(Some(oi))
}
fn display_current(current: &Option<String>) -> String {
if let Some(current) = current {
current.to_string()
} else {
"[MISSING]".to_string()
}
}
fn display_bump(bump: &Option<String>) -> String {
if let Some(bump) = bump {
bump.to_string()
} else {
"[NONE]".to_string()
}
}
}
impl Display for OutdatedInfo {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:<20} ", self.name)?;
if let Some(current) = &self.current {
write!(f, "{current:<20} ")?;
} else {
write!(f, "{:<20} ", "MISSING")?;
}
write!(f, "-> {:<10} (", self.latest)?;
if let Some(bump) = &self.bump {
write!(f, "bump to {bump} in ")?;
}
write!(f, "{})", self.source)
}
}
/// check if the new version is a bump from the old version and return the new version
/// at the same specificity level as the old version
/// used with `mise outdated --bump` to determine what new semver range to use
/// given old: "20" and new: "21.2.3", return Some("21")
fn check_semver_bump(old: &str, new: &str) -> Option<String> {
if old == "latest" {
return Some("latest".to_string());
}
if let Some(("prefix", old_)) = old.split_once(':') {
return check_semver_bump(old_, new);
}
let old_chunks = chunkify_version(old);
let new_chunks = chunkify_version(new);
if !old_chunks.is_empty() && !new_chunks.is_empty() {
if old_chunks.len() > new_chunks.len() {
warn!(
"something weird happened with versioning, old: {old:?}, new: {new:?}",
old = old_chunks,
new = new_chunks,
);
}
let bump = new_chunks
.into_iter()
.take(old_chunks.len())
.collect::<Vec<_>>();
if bump == old_chunks {
None
} else {
Some(bump.join(""))
}
} else {
Some(new.to_string())
}
}
pub fn is_outdated_version(current: &str, latest: &str) -> bool {
if let (Some(c), Some(l)) = (Version::new(current), Version::new(latest)) {
c.lt(&l)
} else {
current != latest
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use test_log::test;
use super::{check_semver_bump, is_outdated_version};
#[test]
fn test_is_outdated_version() {
assert_eq!(is_outdated_version("1.10.0", "1.12.0"), true);
assert_eq!(is_outdated_version("1.12.0", "1.10.0"), false);
assert_eq!(
is_outdated_version("1.10.0-SNAPSHOT", "1.12.0-SNAPSHOT"),
true
);
assert_eq!(
is_outdated_version("1.12.0-SNAPSHOT", "1.10.0-SNAPSHOT"),
false
);
assert_eq!(
is_outdated_version("temurin-17.0.0", "temurin-17.0.1"),
true
);
assert_eq!(
is_outdated_version("temurin-17.0.1", "temurin-17.0.0"),
false
);
}
#[test]
fn test_check_semver_bump() {
std::assert_eq!(check_semver_bump("20", "20.0.0"), None);
std::assert_eq!(check_semver_bump("20.0", "20.0.0"), None);
std::assert_eq!(check_semver_bump("20.0.0", "20.0.0"), None);
std::assert_eq!(check_semver_bump("20", "21.0.0"), Some("21".to_string()));
std::assert_eq!(
check_semver_bump("20.0", "20.1.0"),
Some("20.1".to_string())
);
std::assert_eq!(
check_semver_bump("20.0.0", "20.0.1"),
Some("20.0.1".to_string())
);
std::assert_eq!(
check_semver_bump("20.0.1", "20.1"),
Some("20.1".to_string())
);
std::assert_eq!(
check_semver_bump("2024-09-16", "2024-10-21"),
Some("2024-10-21".to_string())
);
std::assert_eq!(
check_semver_bump("20.0a1", "20.0a2"),
Some("20.0a2".to_string())
);
std::assert_eq!(check_semver_bump("v20", "v20.0.0"), None);
std::assert_eq!(check_semver_bump("v20.0", "v20.0.0"), None);
std::assert_eq!(check_semver_bump("v20.0.0", "v20.0.0"), None);
std::assert_eq!(check_semver_bump("v20", "v21.0.0"), Some("v21".to_string()));
std::assert_eq!(
check_semver_bump("v20.0.0", "v20.0.1"),
Some("v20.0.1".to_string())
);
std::assert_eq!(
check_semver_bump("latest", "20.0.0"),
Some("latest".to_string())
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/toolset/toolset_env.rs | src/toolset/toolset_env.rs | use std::path::PathBuf;
use std::sync::Arc;
use eyre::Result;
use crate::config::Config;
use crate::config::env_directive::{EnvResolveOptions, EnvResults, ToolsFilter};
use crate::env::{PATH_KEY, WARN_ON_MISSING_REQUIRED_ENV};
use crate::env_diff::EnvMap;
use crate::path_env::PathEnv;
use crate::toolset::Toolset;
use crate::toolset::tool_request::ToolRequest;
use crate::{env, parallel, uv};
impl Toolset {
pub async fn full_env(&self, config: &Arc<Config>) -> Result<EnvMap> {
let mut env = env::PRISTINE_ENV.clone().into_iter().collect::<EnvMap>();
env.extend(self.env_with_path(config).await?.clone());
Ok(env)
}
/// the full mise environment including all tool paths
pub async fn env_with_path(&self, config: &Arc<Config>) -> Result<EnvMap> {
let (mut env, env_results) = self.final_env(config).await?;
let mut path_env = PathEnv::from_iter(env::PATH.clone());
for p in self.list_final_paths(config, env_results).await? {
path_env.add(p.clone());
}
env.insert(PATH_KEY.to_string(), path_env.to_string());
Ok(env)
}
pub async fn env_from_tools(&self, config: &Arc<Config>) -> Vec<(String, String, String)> {
let this = Arc::new(self.clone());
let items: Vec<_> = self
.list_current_installed_versions(config)
.into_iter()
.filter(|(_, tv)| !matches!(tv.request, ToolRequest::System { .. }))
.map(|(b, tv)| (config.clone(), this.clone(), b, tv))
.collect();
let envs = parallel::parallel(items, |(config, this, b, tv)| async move {
let backend_id = b.id().to_string();
match b.exec_env(&config, &this, &tv).await {
Ok(env) => Ok(env
.into_iter()
.map(|(k, v)| (k, v, backend_id.clone()))
.collect::<Vec<_>>()),
Err(e) => {
warn!("Error running exec-env: {:#}", e);
Ok(Vec::new())
}
}
})
.await
.unwrap_or_default();
envs.into_iter()
.flatten()
.filter(|(k, _, _)| k.to_uppercase() != "PATH")
.collect()
}
pub(super) async fn env(&self, config: &Arc<Config>) -> Result<(EnvMap, Vec<PathBuf>)> {
time!("env start");
let entries = self
.env_from_tools(config)
.await
.into_iter()
.map(|(k, v, _)| (k, v))
.collect::<Vec<(String, String)>>();
// Collect and process MISE_ADD_PATH values into paths
let paths_to_add: Vec<PathBuf> = entries
.iter()
.filter(|(k, _)| k == "MISE_ADD_PATH" || k == "RTX_ADD_PATH")
.flat_map(|(_, v)| env::split_paths(v))
.collect();
let mut env: EnvMap = entries
.into_iter()
.filter(|(k, _)| k != "RTX_ADD_PATH")
.filter(|(k, _)| k != "MISE_ADD_PATH")
.filter(|(k, _)| !k.starts_with("RTX_TOOL_OPTS__"))
.filter(|(k, _)| !k.starts_with("MISE_TOOL_OPTS__"))
.rev()
.collect();
env.extend(config.env().await?.clone());
if let Some(venv) = uv::uv_venv(config, self).await {
for (k, v) in venv.env.clone() {
env.insert(k, v);
}
}
time!("env end");
Ok((env, paths_to_add))
}
pub async fn final_env(&self, config: &Arc<Config>) -> Result<(EnvMap, EnvResults)> {
let (mut env, add_paths) = self.env(config).await?;
let mut tera_env = env::PRISTINE_ENV.clone().into_iter().collect::<EnvMap>();
tera_env.extend(env.clone());
let mut path_env = PathEnv::from_iter(env::PATH.clone());
for p in config.path_dirs().await?.clone() {
path_env.add(p);
}
for p in &add_paths {
path_env.add(p.clone());
}
for p in self.list_paths(config).await {
path_env.add(p);
}
tera_env.insert(PATH_KEY.to_string(), path_env.to_string());
let mut ctx = config.tera_ctx.clone();
ctx.insert("env", &tera_env);
let mut env_results = self.load_post_env(config, ctx, &tera_env).await?;
// Store add_paths separately to maintain consistent PATH ordering
env_results.tool_add_paths = add_paths;
env.extend(
env_results
.env
.iter()
.map(|(k, v)| (k.clone(), v.0.clone())),
);
Ok((env, env_results))
}
pub(super) async fn load_post_env(
&self,
config: &Arc<Config>,
ctx: tera::Context,
env: &EnvMap,
) -> Result<EnvResults> {
let entries = config
.config_files
.iter()
.rev()
.map(|(source, cf)| {
cf.env_entries()
.map(|ee| ee.into_iter().map(|e| (e, source.clone())))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
// trace!("load_env: entries: {:#?}", entries);
let env_results = EnvResults::resolve(
config,
ctx,
env,
entries,
EnvResolveOptions {
vars: false,
tools: ToolsFilter::ToolsOnly,
warn_on_missing_required: *WARN_ON_MISSING_REQUIRED_ENV,
},
)
.await?;
if log::log_enabled!(log::Level::Trace) {
trace!("{env_results:#?}");
} else if !env_results.is_empty() {
debug!("{env_results:?}");
}
Ok(env_results)
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/sysconfig/cursor.rs | src/sysconfig/cursor.rs | #![allow(dead_code)]
use std::str::Chars;
pub(super) const EOF_CHAR: char = '\0';
/// A cursor represents a pointer in the source code.
///
/// Based on [`rustc`'s `Cursor`](https://github.com/rust-lang/rust/blob/d1b7355d3d7b4ead564dbecb1d240fcc74fff21b/compiler/rustc_lexer/src/cursor.rs)
#[derive(Clone, Debug)]
pub(super) struct Cursor<'src> {
/// An iterator over the [`char`]'s of the source code.
chars: Chars<'src>,
/// Stores the previous character for debug assertions.
#[cfg(debug_assertions)]
prev_char: char,
}
impl<'src> Cursor<'src> {
pub(super) fn new(source: &'src str) -> Self {
Self {
chars: source.chars(),
#[cfg(debug_assertions)]
prev_char: EOF_CHAR,
}
}
/// Returns the previous character. Useful for debug assertions.
#[cfg(debug_assertions)]
pub(super) const fn previous(&self) -> char {
self.prev_char
}
/// Peeks the next character from the input stream without consuming it.
/// Returns [`EOF_CHAR`] if the position is past the end of the file.
pub(super) fn first(&self) -> char {
self.chars.clone().next().unwrap_or(EOF_CHAR)
}
/// Peeks the second character from the input stream without consuming it.
/// Returns [`EOF_CHAR`] if the position is past the end of the file.
pub(super) fn second(&self) -> char {
let mut chars = self.chars.clone();
chars.next();
chars.next().unwrap_or(EOF_CHAR)
}
/// Returns the remaining text to lex.
///
/// Use [`Cursor::text_len`] to get the length of the remaining text.
pub(super) fn rest(&self) -> &'src str {
self.chars.as_str()
}
/// Returns `true` if the cursor is at the end of file.
pub(super) fn is_eof(&self) -> bool {
self.chars.as_str().is_empty()
}
/// Moves the cursor to the next character, returning the previous character.
/// Returns [`None`] if there is no next character.
pub(super) fn bump(&mut self) -> Option<char> {
let prev = self.chars.next()?;
#[cfg(debug_assertions)]
{
self.prev_char = prev;
}
Some(prev)
}
pub(super) fn eat_char(&mut self, c: char) -> bool {
if self.first() == c {
self.bump();
true
} else {
false
}
}
pub(super) fn eat_char2(&mut self, c1: char, c2: char) -> bool {
let mut chars = self.chars.clone();
if chars.next() == Some(c1) && chars.next() == Some(c2) {
self.bump();
self.bump();
true
} else {
false
}
}
pub(super) fn eat_char3(&mut self, c1: char, c2: char, c3: char) -> bool {
let mut chars = self.chars.clone();
if chars.next() == Some(c1) && chars.next() == Some(c2) && chars.next() == Some(c3) {
self.bump();
self.bump();
self.bump();
true
} else {
false
}
}
pub(super) fn eat_if<F>(&mut self, mut predicate: F) -> Option<char>
where
F: FnMut(char) -> bool,
{
if predicate(self.first()) && !self.is_eof() {
self.bump()
} else {
None
}
}
/// Eats symbols while predicate returns true or until the end of file is reached.
#[inline]
pub(super) fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
// It was tried making optimized version of this for eg. line comments, but
// LLVM can inline all of this and compile it down to fast iteration over bytes.
while predicate(self.first()) && !self.is_eof() {
self.bump();
}
}
/// Skips the next `count` bytes.
///
/// ## Panics
/// - If `count` is larger than the remaining bytes in the input stream.
/// - If `count` indexes into a multi-byte character.
pub(super) fn skip_bytes(&mut self, count: usize) {
#[cfg(debug_assertions)]
{
self.prev_char = self.chars.as_str()[..count]
.chars()
.next_back()
.unwrap_or('\0');
}
self.chars = self.chars.as_str()[count..].chars();
}
/// Skips to the end of the input stream.
pub(super) fn skip_to_end(&mut self) {
self.chars = "".chars();
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/sysconfig/parser.rs | src/sysconfig/parser.rs | use std::collections::BTreeMap;
use std::str::FromStr;
use serde::Serialize;
use serde_json::ser::PrettyFormatter;
use crate::sysconfig::cursor::Cursor;
/// A value in the [`SysconfigData`] map.
///
/// Values are assumed to be either strings or integers.
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)]
#[serde(untagged)]
pub(super) enum Value {
String(String),
Int(i32),
}
/// The data extracted from a `_sysconfigdata_` file.
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)]
pub(super) struct SysconfigData(BTreeMap<String, Value>);
impl SysconfigData {
/// Returns an iterator over the key-value pairs in the map.
pub(super) fn iter_mut(&mut self) -> std::collections::btree_map::IterMut<'_, String, Value> {
self.0.iter_mut()
}
/// Inserts a key-value pair into the map.
pub(super) fn insert(&mut self, key: String, value: Value) -> Option<Value> {
self.0.insert(key, value)
}
/// Formats the `sysconfig` data as a pretty-printed string.
pub(super) fn to_string_pretty(&self) -> Result<String, serde_json::Error> {
let output = {
let mut buf = Vec::new();
let mut serializer = serde_json::Serializer::with_formatter(
&mut buf,
PrettyFormatter::with_indent(b" "),
);
self.0.serialize(&mut serializer)?;
String::from_utf8(buf).unwrap()
};
Ok(format!(
"# system configuration generated and used by the sysconfig module\nbuild_time_vars = {output}\n",
))
}
}
impl std::fmt::Display for SysconfigData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let output = {
let mut buf = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buf);
self.0.serialize(&mut serializer).unwrap();
String::from_utf8(buf).unwrap()
};
write!(f, "{output}",)
}
}
impl FromIterator<(String, Value)> for SysconfigData {
fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
/// Parse the `_sysconfigdata_` file (e.g., `{real_prefix}/lib/python3.12/_sysconfigdata__darwin_darwin.py"`
/// on macOS).
///
/// `_sysconfigdata_` is structured as follows:
///
/// 1. A comment on the first line (e.g., `# system configuration generated and used by the sysconfig module`).
/// 2. An assignment to `build_time_vars` (e.g., `build_time_vars = { ... }`).
///
/// The right-hand side of the assignment is a JSON object. The keys are strings, and the values
/// are strings or numbers.
impl FromStr for SysconfigData {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Read the first line of the file.
let Some(s) =
s.strip_prefix("# system configuration generated and used by the sysconfig module\n")
else {
return Err(Error::MissingHeader);
};
// Read the assignment to `build_time_vars`.
let Some(s) = s.strip_prefix("build_time_vars") else {
return Err(Error::MissingAssignment);
};
let mut cursor = Cursor::new(s);
cursor.eat_while(is_python_whitespace);
if !cursor.eat_char('=') {
return Err(Error::MissingAssignment);
}
cursor.eat_while(is_python_whitespace);
if !cursor.eat_char('{') {
return Err(Error::MissingOpenBrace);
}
let mut map = BTreeMap::new();
loop {
let Some(next) = cursor.bump() else {
return Err(Error::UnexpectedEof);
};
match next {
'\'' | '"' => {
// Parse key.
let key = parse_string(&mut cursor, next)?;
cursor.eat_while(is_python_whitespace);
cursor.eat_char(':');
cursor.eat_while(is_python_whitespace);
// Parse value
let value = match cursor.first() {
'\'' | '"' => Value::String(parse_concatenated_string(&mut cursor)?),
'-' => {
cursor.bump();
Value::Int(-parse_int(&mut cursor)?)
}
c if c.is_ascii_digit() => Value::Int(parse_int(&mut cursor)?),
c => return Err(Error::UnexpectedCharacter(c)),
};
// Insert into map.
map.insert(key, value);
// Skip optional comma.
cursor.eat_while(is_python_whitespace);
cursor.eat_char(',');
cursor.eat_while(is_python_whitespace);
}
// Skip whitespace.
' ' | '\n' | '\r' | '\t' => {}
// When we see a closing brace, we're done.
'}' => {
break;
}
c => return Err(Error::UnexpectedCharacter(c)),
}
}
Ok(Self(map))
}
}
/// Parse a Python string literal.
///
/// Expects the previous character to be the opening quote character.
fn parse_string(cursor: &mut Cursor, quote: char) -> Result<String, Error> {
let mut result = String::new();
loop {
let Some(c) = cursor.bump() else {
return Err(Error::UnexpectedEof);
};
match c {
'\\' => {
// Handle escaped quotes.
if cursor.first() == quote {
// Consume the backslash.
cursor.bump();
result.push(quote);
continue;
}
// Keep the backslash and following character.
result.push('\\');
result.push(cursor.first());
cursor.bump();
}
// Consume closing quote.
c if c == quote => {
break;
}
c => {
result.push(c);
}
}
}
Ok(result)
}
/// Parse a Python string, which may be a concatenation of multiple string literals.
///
/// Expects the cursor to start at an opening quote character.
fn parse_concatenated_string(cursor: &mut Cursor) -> Result<String, Error> {
let mut result = String::new();
loop {
let Some(c) = cursor.bump() else {
return Err(Error::UnexpectedEof);
};
match c {
'\'' | '"' => {
// Parse a new string fragment and append it.
result.push_str(&parse_string(cursor, c)?);
}
c if is_python_whitespace(c) => {
// Skip whitespace between fragments
}
c => return Err(Error::UnexpectedCharacter(c)),
}
// Lookahead to the end of the string.
if matches!(cursor.first(), ',' | '}') {
break;
}
}
Ok(result)
}
/// Parse an integer literal.
///
/// Expects the cursor to start at the first digit of the integer.
fn parse_int(cursor: &mut Cursor) -> Result<i32, std::num::ParseIntError> {
let mut result = String::new();
loop {
let c = cursor.first();
if !c.is_ascii_digit() {
break;
}
result.push(c);
cursor.bump();
}
result.parse()
}
/// Returns `true` for [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens)
/// characters.
const fn is_python_whitespace(c: char) -> bool {
matches!(
c,
// Space, tab, form-feed, newline, or carriage return
' ' | '\t' | '\x0C' | '\n' | '\r'
)
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Missing opening brace")]
MissingOpenBrace,
#[error("Unexpected character: {0}")]
UnexpectedCharacter(char),
#[error("Unexpected end of file")]
UnexpectedEof,
#[error("Failed to parse integer")]
ParseInt(#[from] std::num::ParseIntError),
#[error("`_sysconfigdata_` is missing a header comment")]
MissingHeader,
#[error("`_sysconfigdata_` is missing an assignment to `build_time_vars`")]
MissingAssignment,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_string() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value1",
"key2": 42,
"key3": "multi-part" " string"
}
"#
);
let result = input.parse::<SysconfigData>().expect("Parsing failed");
let snapshot = result.to_string_pretty().unwrap();
insta::assert_snapshot!(snapshot, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value1",
"key2": 42,
"key3": "multi-part string"
}
"###);
}
#[test]
fn test_parse_trailing_comma() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value1",
"key2": 42,
"key3": "multi-part" " string",
}
"#
);
let result = input.parse::<SysconfigData>().expect("Parsing failed");
let snapshot = result.to_string_pretty().unwrap();
insta::assert_snapshot!(snapshot, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value1",
"key2": 42,
"key3": "multi-part string"
}
"###);
}
#[test]
fn test_parse_integer_values() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": 12345,
"key2": -15
}
"#
);
let result = input.parse::<SysconfigData>().expect("Parsing failed");
let snapshot = result.to_string_pretty().unwrap();
insta::assert_snapshot!(snapshot, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": 12345,
"key2": -15
}
"###);
}
#[test]
fn test_parse_escaped_quotes() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value with \"escaped quotes\"",
"key2": 'single-quoted \'escaped\''
}
"#
);
let result = input.parse::<SysconfigData>().expect("Parsing failed");
let snapshot = result.to_string_pretty().unwrap();
insta::assert_snapshot!(snapshot, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "value with \"escaped quotes\"",
"key2": "single-quoted 'escaped'"
}
"###);
}
#[test]
fn test_parse_concatenated_strings() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "multi-"
"line "
"string"
}
"#
);
let result = input.parse::<SysconfigData>().expect("Parsing failed");
let snapshot = result.to_string_pretty().unwrap();
insta::assert_snapshot!(snapshot, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": "multi-line string"
}
"###);
}
#[test]
fn test_missing_header_error() {
let input = indoc::indoc!(
r#"
build_time_vars = {
"key1": "value1"
}
"#
);
let result = input.parse::<SysconfigData>();
assert!(matches!(result, Err(Error::MissingHeader)));
}
#[test]
fn test_missing_assignment_error() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
{
"key1": "value1"
}
"#
);
let result = input.parse::<SysconfigData>();
assert!(matches!(result, Err(Error::MissingAssignment)));
}
#[test]
fn test_unexpected_character_error() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": &123
}
"#
);
let result = input.parse::<SysconfigData>();
assert!(
result.is_err(),
"Expected parsing to fail due to unexpected character"
);
}
#[test]
fn test_unexpected_eof() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": 123
"#
);
let result = input.parse::<SysconfigData>();
assert!(
result.is_err(),
"Expected parsing to fail due to unexpected character"
);
}
#[test]
fn test_unexpected_comma() {
let input = indoc::indoc!(
r#"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"key1": 123,,
}
"#
);
let result = input.parse::<SysconfigData>();
assert!(
result.is_err(),
"Expected parsing to fail due to unexpected character"
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/sysconfig/mod.rs | src/sysconfig/mod.rs | //! Patch `sysconfig` data in a Python installation.
//!
//! Inspired by: <https://github.com/bluss/sysconfigpatcher/blob/c1ebf8ab9274dcde255484d93ce0f1fd1f76a248/src/sysconfigpatcher.py#L137C1-L140C100>,
//! available under the MIT license:
//!
//! ```text
//! Copyright 2024 Ulrik Sverdrup "bluss"
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy of
//! this software and associated documentation files (the "Software"), to deal in
//! the Software without restriction, including without limitation the rights to
//! use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//! the Software, and to permit persons to whom the Software is furnished to do so,
//! subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in all
//! copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//! FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//! COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! ```
use crate::sysconfig::parser::{Error as ParseError, SysconfigData, Value};
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::LazyLock;
mod cursor;
mod parser;
/// Replacement mode for sysconfig values.
#[derive(Debug)]
enum ReplacementMode {
Partial { from: String },
Full,
}
/// A replacement entry to patch in sysconfig data.
#[derive(Debug)]
struct ReplacementEntry {
mode: ReplacementMode,
to: String,
}
impl ReplacementEntry {
/// Patches a sysconfig value either partially (replacing a specific word) or fully.
fn patch(&self, entry: &str) -> String {
match &self.mode {
ReplacementMode::Partial { from } => entry
.split_whitespace()
.map(|word| if word == from { &self.to } else { word })
.collect::<Vec<_>>()
.join(" "),
ReplacementMode::Full => self.to.clone(),
}
}
}
/// Mapping for sysconfig keys to lookup and replace with the appropriate entry.
static DEFAULT_VARIABLE_UPDATES: LazyLock<BTreeMap<String, ReplacementEntry>> =
LazyLock::new(|| {
BTreeMap::from_iter([
(
"CC".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang".to_string(),
},
to: "cc".to_string(),
},
),
(
"CXX".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang++".to_string(),
},
to: "c++".to_string(),
},
),
(
"BLDSHARED".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang".to_string(),
},
to: "cc".to_string(),
},
),
(
"LDSHARED".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang".to_string(),
},
to: "cc".to_string(),
},
),
(
"LDCXXSHARED".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang++".to_string(),
},
to: "c++".to_string(),
},
),
(
"LINKCC".to_string(),
ReplacementEntry {
mode: ReplacementMode::Partial {
from: "clang".to_string(),
},
to: "cc".to_string(),
},
),
(
"AR".to_string(),
ReplacementEntry {
mode: ReplacementMode::Full,
to: "ar".to_string(),
},
),
])
});
/// Update the `sysconfig` data in a Python installation.
pub(crate) fn update_sysconfig(
install_root: &Path,
major: u8,
minor: u8,
suffix: &str,
) -> Result<(), Error> {
// Find the `_sysconfigdata_` file in the Python installation.
let real_prefix = std::path::absolute(install_root)?;
let sysconfigdata = find_sysconfigdata(&real_prefix, major, minor, suffix)?;
trace!(
"Discovered `sysconfig` data at: {}",
sysconfigdata.display()
);
// Update the `_sysconfigdata_` file in-memory.
let contents = std::fs::read_to_string(&sysconfigdata)?;
let data = SysconfigData::from_str(&contents)?;
let data = patch_sysconfigdata(data, &real_prefix);
let contents = data.to_string_pretty()?;
// Write the updated `_sysconfigdata_` file.
let mut file = std::fs::OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&sysconfigdata)?;
file.write_all(contents.as_bytes())?;
file.sync_data()?;
Ok(())
}
/// Find the `_sysconfigdata_` file in a Python installation.
///
/// For example, on macOS, returns `{real_prefix}/lib/python3.12/_sysconfigdata__darwin_darwin.py"`.
fn find_sysconfigdata(
real_prefix: &Path,
major: u8,
minor: u8,
suffix: &str,
) -> Result<PathBuf, Error> {
// Find the `lib` directory in the Python installation.
let lib_with_suffix = real_prefix
.join("lib")
.join(format!("python{major}.{minor}{suffix}"));
let lib_without_suffix = real_prefix
.join("lib")
.join(format!("python{major}.{minor}"));
let lib = if lib_with_suffix.exists() {
lib_with_suffix
} else if lib_without_suffix.exists() {
lib_without_suffix
} else {
return Err(Error::MissingLib);
};
// Probe the `lib` directory for `_sysconfigdata_`.
for entry in lib.read_dir()? {
let entry = entry?;
if entry.path().extension().is_none_or(|ext| ext != "py") {
continue;
}
if !entry
.path()
.file_stem()
.and_then(|stem| stem.to_str())
.is_some_and(|stem| stem.starts_with("_sysconfigdata_"))
{
continue;
}
let metadata = entry.metadata()?;
if metadata.is_symlink() {
continue;
};
if metadata.is_file() {
return Ok(entry.path());
}
}
Err(Error::MissingSysconfigdata)
}
/// Patch the given `_sysconfigdata_` contents.
fn patch_sysconfigdata(mut data: SysconfigData, real_prefix: &Path) -> SysconfigData {
/// Update the `/install` prefix in a whitespace-separated string.
fn update_prefix(s: &str, real_prefix: &Path) -> String {
s.split_whitespace()
.map(|part| {
if let Some(rest) = part.strip_prefix("/install") {
if rest.is_empty() {
real_prefix.display().to_string()
} else {
real_prefix.join(&rest[1..]).display().to_string()
}
} else {
part.to_string()
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Remove any references to `-isysroot` in a whitespace-separated string.
fn remove_isysroot(s: &str) -> String {
// If we see `-isysroot`, drop it and the next part.
let mut parts = s.split_whitespace().peekable();
let mut result = Vec::with_capacity(parts.size_hint().0);
while let Some(part) = parts.next() {
if part == "-isysroot" {
parts.next();
} else {
result.push(part);
}
}
result.join(" ")
}
// Patch each value, as needed.
let mut count = 0;
for (key, value) in data.iter_mut() {
let Value::String(value) = value else {
continue;
};
let patched = update_prefix(value, real_prefix);
let mut patched = remove_isysroot(&patched);
if let Some(replacement_entry) = DEFAULT_VARIABLE_UPDATES.get(key) {
patched = replacement_entry.patch(&patched);
}
if *value != patched {
trace!("Updated `{key}` from `{value}` to `{patched}`");
count += 1;
*value = patched;
}
}
match count {
0 => trace!("No updates required"),
1 => trace!("Updated 1 value"),
n => trace!("Updated {n} values"),
}
// Mark the Python installation as standalone.
data.insert("PYTHON_BUILD_STANDALONE".to_string(), Value::Int(1));
data
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("Python installation is missing a `lib` directory")]
MissingLib,
#[error("Python installation is missing a `_sysconfigdata_` file")]
MissingSysconfigdata,
#[error(transparent)]
Parse(#[from] ParseError),
#[error(transparent)]
Json(#[from] serde_json::Error),
}
#[cfg(test)]
#[cfg(unix)]
mod tests {
use super::*;
#[test]
fn update_real_prefix() -> Result<(), Error> {
let sysconfigdata = [
("BASEMODLIBS", ""),
("BINDIR", "/install/bin"),
("BINLIBDEST", "/install/lib/python3.10"),
("BLDLIBRARY", "-L. -lpython3.10"),
("BUILDPYTHON", "python.exe"),
("prefix", "/install/prefix"),
("exec_prefix", "/install/exec_prefix"),
("base", "/install/base"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), Value::String(v.to_string())))
.collect::<SysconfigData>();
let real_prefix = Path::new("/real/prefix");
let data = patch_sysconfigdata(sysconfigdata, real_prefix);
insta::assert_snapshot!(data.to_string_pretty()?, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"BASEMODLIBS": "",
"BINDIR": "/real/prefix/bin",
"BINLIBDEST": "/real/prefix/lib/python3.10",
"BLDLIBRARY": "-L. -lpython3.10",
"BUILDPYTHON": "python.exe",
"PYTHON_BUILD_STANDALONE": 1,
"base": "/real/prefix/base",
"exec_prefix": "/real/prefix/exec_prefix",
"prefix": "/real/prefix/prefix"
}
"###);
Ok(())
}
#[test]
fn test_replacements() -> Result<(), Error> {
let sysconfigdata = [
("CC", "clang -pthread"),
("CXX", "clang++ -pthread"),
("AR", "/tools/llvm/bin/llvm-ar"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), Value::String(v.to_string())))
.collect::<SysconfigData>();
let real_prefix = Path::new("/real/prefix");
let data = patch_sysconfigdata(sysconfigdata, real_prefix);
insta::assert_snapshot!(data.to_string_pretty()?, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"AR": "ar",
"CC": "cc -pthread",
"CXX": "c++ -pthread",
"PYTHON_BUILD_STANDALONE": 1
}
"###);
Ok(())
}
#[test]
fn remove_isysroot() -> Result<(), Error> {
let sysconfigdata = [
("BLDSHARED", "clang -bundle -undefined dynamic_lookup -arch arm64 -isysroot /Applications/MacOSX14.2.sdk"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), Value::String(v.to_string())))
.collect::<SysconfigData>();
let real_prefix = Path::new("/real/prefix");
let data = patch_sysconfigdata(sysconfigdata, real_prefix);
insta::assert_snapshot!(data.to_string_pretty()?, @r###"
# system configuration generated and used by the sysconfig module
build_time_vars = {
"BLDSHARED": "cc -bundle -undefined dynamic_lookup -arch arm64",
"PYTHON_BUILD_STANDALONE": 1
}
"###);
Ok(())
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/aqua/mod.rs | src/aqua/mod.rs | pub(crate) mod aqua_registry_wrapper;
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/aqua/aqua_registry_wrapper.rs | src/aqua/aqua_registry_wrapper.rs | use crate::backend::aqua::{arch, os};
use crate::config::Settings;
use crate::git::{CloneOptions, Git};
use crate::{dirs, duration::WEEKLY, env, file};
use aqua_registry::{AquaRegistry, AquaRegistryConfig};
use eyre::Result;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock as Lazy;
use tokio::sync::Mutex;
static AQUA_REGISTRY_PATH: Lazy<PathBuf> = Lazy::new(|| dirs::CACHE.join("aqua-registry"));
static AQUA_DEFAULT_REGISTRY_URL: &str = "https://github.com/aquaproj/aqua-registry";
pub static AQUA_REGISTRY: Lazy<MiseAquaRegistry> = Lazy::new(|| {
MiseAquaRegistry::standard().unwrap_or_else(|err| {
warn!("failed to initialize aqua registry: {err:?}");
MiseAquaRegistry::default()
})
});
/// Wrapper around the aqua-registry crate that provides mise-specific functionality
#[derive(Debug)]
pub struct MiseAquaRegistry {
inner: AquaRegistry,
#[allow(dead_code)]
path: PathBuf,
#[allow(dead_code)]
repo_exists: bool,
}
impl Default for MiseAquaRegistry {
fn default() -> Self {
let config = AquaRegistryConfig::default();
let inner = AquaRegistry::new(config.clone());
Self {
inner,
path: config.cache_dir,
repo_exists: false,
}
}
}
impl MiseAquaRegistry {
pub fn standard() -> Result<Self> {
let path = AQUA_REGISTRY_PATH.clone();
let repo = Git::new(&path);
let settings = Settings::get();
let registry_url =
settings
.aqua
.registry_url
.as_deref()
.or(if settings.aqua.baked_registry {
None
} else {
Some(AQUA_DEFAULT_REGISTRY_URL)
});
if let Some(registry_url) = registry_url {
if repo.exists() {
fetch_latest_repo(&repo)?;
} else {
info!("cloning aqua registry from {registry_url} to {path:?}");
repo.clone(registry_url, CloneOptions::default())?;
}
}
let config = AquaRegistryConfig {
cache_dir: path.clone(),
registry_url: registry_url.map(|s| s.to_string()),
use_baked_registry: settings.aqua.baked_registry,
prefer_offline: env::PREFER_OFFLINE.load(std::sync::atomic::Ordering::Relaxed),
};
let inner = AquaRegistry::new(config);
Ok(Self {
inner,
path,
repo_exists: repo.exists(),
})
}
pub async fn package(&self, id: &str) -> Result<AquaPackage> {
static CACHE: Lazy<Mutex<HashMap<String, AquaPackage>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
if let Some(pkg) = CACHE.lock().await.get(id) {
return Ok(pkg.clone());
}
let pkg = self.inner.package(id).await?;
CACHE.lock().await.insert(id.to_string(), pkg.clone());
Ok(pkg)
}
pub async fn package_with_version(&self, id: &str, versions: &[&str]) -> Result<AquaPackage> {
let pkg = self.package(id).await?;
Ok(pkg.with_version(versions, os(), arch()))
}
}
fn fetch_latest_repo(repo: &Git) -> Result<()> {
if file::modified_duration(&repo.dir)? < WEEKLY {
return Ok(());
}
if env::PREFER_OFFLINE.load(std::sync::atomic::Ordering::Relaxed) {
trace!("skipping aqua registry update due to PREFER_OFFLINE");
return Ok(());
}
info!("updating aqua registry repo");
repo.update(None)?;
Ok(())
}
// Re-export types and static for compatibility
pub use aqua_registry::{
AquaChecksum, AquaChecksumType, AquaMinisignType, AquaPackage, AquaPackageType,
};
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/vfox_plugin.rs | src/plugins/vfox_plugin.rs | use crate::file::{display_path, remove_all};
use crate::git::{CloneOptions, Git};
use crate::http::HTTP;
use crate::plugins::{Plugin, PluginSource};
use crate::result::Result;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use crate::{config::Config, dirs, file, registry};
use async_trait::async_trait;
use console::style;
use contracts::requires;
use eyre::{Context, eyre};
use indexmap::{IndexMap, indexmap};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, mpsc};
use url::Url;
use vfox::Vfox;
use vfox::embedded_plugins;
use xx::regex;
#[derive(Debug)]
pub struct VfoxPlugin {
pub name: String,
pub full: Option<String>,
pub plugin_path: PathBuf,
pub repo: Mutex<Git>,
repo_url: Mutex<Option<String>>,
}
impl VfoxPlugin {
#[requires(!name.is_empty())]
pub fn new(name: String, plugin_path: PathBuf) -> Self {
let repo = Git::new(&plugin_path);
Self {
name,
full: None,
repo_url: Mutex::new(None),
repo: Mutex::new(repo),
plugin_path,
}
}
fn repo(&self) -> MutexGuard<'_, Git> {
self.repo.lock().unwrap()
}
fn get_repo_url(&self, config: &Config) -> eyre::Result<Url> {
if let Some(url) = self.repo().get_remote_url() {
return Ok(Url::parse(&url)?);
}
if let Some(url) = config.get_repo_url(&self.name) {
return Ok(Url::parse(&url)?);
}
let url = self
.full
.as_ref()
.unwrap_or(&self.name)
.split_once(':')
.map(|f| f.1)
.unwrap_or(&self.name);
vfox_to_url(url)
}
pub async fn mise_env(&self, opts: &toml::Value) -> Result<Option<IndexMap<String, String>>> {
let (vfox, _) = self.vfox();
let mut out = indexmap!();
let results = vfox.mise_env(&self.name, opts).await?;
for env in results {
out.insert(env.key, env.value);
}
Ok(Some(out))
}
pub async fn mise_path(&self, opts: &toml::Value) -> Result<Option<Vec<String>>> {
let (vfox, _) = self.vfox();
let mut out = vec![];
let results = vfox.mise_path(&self.name, opts).await?;
for env in results {
out.push(env);
}
Ok(Some(out))
}
pub fn vfox(&self) -> (Vfox, mpsc::Receiver<String>) {
let mut vfox = Vfox::new();
vfox.plugin_dir = dirs::PLUGINS.to_path_buf();
vfox.cache_dir = dirs::CACHE.to_path_buf();
vfox.download_dir = dirs::DOWNLOADS.to_path_buf();
vfox.install_dir = dirs::INSTALLS.to_path_buf();
let rx = vfox.log_subscribe();
(vfox, rx)
}
async fn install_from_zip(&self, url: &str, pr: &dyn SingleReport) -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let temp_archive = temp_dir.path().join("archive.zip");
HTTP.download_file(url, &temp_archive, Some(pr)).await?;
pr.set_message("extracting zip file".to_string());
let strip_components = file::should_strip_components(&temp_archive, file::TarFormat::Zip)?;
file::unzip(
&temp_archive,
&self.plugin_path,
&file::ZipOptions {
strip_components: if strip_components { 1 } else { 0 },
},
)?;
Ok(())
}
pub fn is_embedded(&self) -> bool {
embedded_plugins::get_embedded_plugin(&self.name).is_some()
}
}
#[async_trait]
impl Plugin for VfoxPlugin {
fn name(&self) -> &str {
&self.name
}
fn path(&self) -> PathBuf {
self.plugin_path.clone()
}
fn get_remote_url(&self) -> eyre::Result<Option<String>> {
let url = self.repo().get_remote_url();
Ok(url.or(self.repo_url.lock().unwrap().clone()))
}
fn set_remote_url(&self, url: String) {
*self.repo_url.lock().unwrap() = Some(url);
}
fn current_abbrev_ref(&self) -> eyre::Result<Option<String>> {
// No git ref for embedded plugins or if plugin_path doesn't exist
if !self.plugin_path.exists() {
return Ok(None);
}
self.repo().current_abbrev_ref().map(Some)
}
fn current_sha_short(&self) -> eyre::Result<Option<String>> {
// No git sha for embedded plugins or if plugin_path doesn't exist
if !self.plugin_path.exists() {
return Ok(None);
}
self.repo().current_sha_short().map(Some)
}
fn is_installed(&self) -> bool {
// Embedded plugins are always "installed"
self.is_embedded() || self.plugin_path.exists()
}
fn is_installed_err(&self) -> eyre::Result<()> {
if self.is_installed() {
return Ok(());
}
Err(eyre!("asdf plugin {} is not installed", self.name())
.wrap_err("run with --yes to install plugin automatically"))
}
async fn ensure_installed(
&self,
config: &Arc<Config>,
mpr: &MultiProgressReport,
_force: bool,
dry_run: bool,
) -> Result<()> {
// Skip installation for embedded plugins
if self.is_embedded() {
return Ok(());
}
if !self.plugin_path.exists() {
let url = self.get_repo_url(config)?;
trace!("Cloning vfox plugin: {url}");
let pr = mpr.add_with_options(&format!("clone vfox plugin {url}"), dry_run);
if !dry_run {
self.repo()
.clone(url.as_str(), CloneOptions::default().pr(pr.as_ref()))?;
}
}
Ok(())
}
async fn update(&self, pr: &dyn SingleReport, gitref: Option<String>) -> Result<()> {
// If only embedded (no filesystem plugin), warn that it can't be updated
if self.is_embedded() && !self.plugin_path.exists() {
warn!(
"plugin:{} is embedded in mise, not updating",
style(&self.name).blue().for_stderr()
);
pr.finish_with_message("embedded plugin".into());
return Ok(());
}
let plugin_path = self.plugin_path.to_path_buf();
if plugin_path.is_symlink() {
warn!(
"plugin:{} is a symlink, not updating",
style(&self.name).blue().for_stderr()
);
return Ok(());
}
let git = Git::new(plugin_path);
if !git.is_repo() {
warn!(
"plugin:{} is not a git repository, not updating",
style(&self.name).blue().for_stderr()
);
return Ok(());
}
pr.set_message("update git repo".into());
git.update(gitref)?;
let sha = git.current_sha_short()?;
let repo_url = self.get_remote_url()?.unwrap_or_default();
pr.finish_with_message(format!(
"{repo_url}#{}",
style(&sha).bright().yellow().for_stderr(),
));
Ok(())
}
async fn uninstall(&self, pr: &dyn SingleReport) -> Result<()> {
if !self.is_installed() {
return Ok(());
}
// If only embedded (no filesystem plugin), warn that it can't be uninstalled
if self.is_embedded() && !self.plugin_path.exists() {
warn!(
"plugin:{} is embedded in mise, cannot uninstall",
style(&self.name).blue().for_stderr()
);
pr.finish_with_message("embedded plugin".into());
return Ok(());
}
pr.set_message("uninstall".into());
let rmdir = |dir: &Path| {
if !dir.exists() {
return Ok(());
}
pr.set_message(format!("remove {}", display_path(dir)));
remove_all(dir).wrap_err_with(|| {
format!(
"Failed to remove directory {}",
style(display_path(dir)).cyan().for_stderr()
)
})
};
rmdir(&self.plugin_path)?;
Ok(())
}
async fn install(&self, config: &Arc<Config>, pr: &dyn SingleReport) -> eyre::Result<()> {
let repository = self.get_repo_url(config)?;
let source = PluginSource::parse(repository.as_str());
debug!("vfox_plugin[{}]:install {:?}", self.name, repository);
if self.is_installed() {
self.uninstall(pr).await?;
}
match source {
PluginSource::Zip { url } => {
self.install_from_zip(&url, pr).await?;
pr.finish_with_message(url.to_string());
Ok(())
}
PluginSource::Git {
url: repo_url,
git_ref,
} => {
if regex!(r"^[/~]").is_match(&repo_url) {
Err(eyre!(
r#"Invalid repository URL: {repo_url}
If you are trying to link to a local directory, use `mise plugins link` instead.
Plugins could support local directories in the future but for now a symlink is required which `mise plugins link` will create for you."#
))?;
}
let git = Git::new(&self.plugin_path);
pr.set_message(format!("clone {repo_url}"));
git.clone(&repo_url, CloneOptions::default().pr(pr))?;
if let Some(ref_) = &git_ref {
pr.set_message(format!("git update {ref_}"));
git.update(Some(ref_.to_string()))?;
}
let sha = git.current_sha_short()?;
pr.finish_with_message(format!(
"{repo_url}#{}",
style(&sha).bright().yellow().for_stderr(),
));
Ok(())
}
}
}
}
fn vfox_to_url(name: &str) -> eyre::Result<Url> {
let name = name.strip_prefix("vfox:").unwrap_or(name);
if let Some(rt) = registry::REGISTRY.get(name.trim_start_matches("vfox-")) {
// bun -> version-fox/vfox-bun
if let Some((_, tool_name)) = rt.backends.iter().find_map(|f| f.full.split_once("vfox:")) {
return vfox_to_url(tool_name);
}
}
let res = if let Some(caps) = regex!(r#"^([^/]+)/([^/]+)$"#).captures(name) {
let user = caps.get(1).unwrap().as_str();
let repo = caps.get(2).unwrap().as_str();
format!("https://github.com/{user}/{repo}").parse()
} else {
name.to_string().parse()
};
res.wrap_err_with(|| format!("Invalid version: {name}"))
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/script_manager.rs | src/plugins/script_manager.rs | use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use color_eyre::eyre::{Context, Result};
use duct::Expression;
use indexmap::indexmap;
use std::sync::LazyLock as Lazy;
use crate::cmd::{CmdLineRunner, cmd};
use crate::config::Settings;
use crate::env::PATH_KEY;
use crate::errors::Error;
use crate::errors::Error::ScriptFailed;
use crate::fake_asdf::get_path_with_fake_asdf;
use crate::file::display_path;
use crate::ui::progress_report::SingleReport;
use crate::{dirs, env};
#[derive(Debug, Clone)]
pub struct ScriptManager {
pub plugin_path: PathBuf,
pub env: HashMap<OsString, OsString>,
}
#[derive(Debug, Clone)]
pub enum Script {
Hook(String),
// Plugin
LatestStable,
ListAliases,
ListAll,
ListIdiomaticFilenames,
ParseIdiomaticFile(String),
// RuntimeVersion
Download,
ExecEnv,
Install,
ListBinPaths,
RunExternalCommand(PathBuf, Vec<String>),
Uninstall,
}
impl Display for Script {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
// Plugin
Script::LatestStable => write!(f, "latest-stable"),
Script::ListAll => write!(f, "list-all"),
Script::ListIdiomaticFilenames => write!(f, "list-legacy-filenames"),
Script::ListAliases => write!(f, "list-aliases"),
Script::ParseIdiomaticFile(_) => write!(f, "parse-legacy-file"),
Script::Hook(script) => write!(f, "{script}"),
// RuntimeVersion
Script::Install => write!(f, "install"),
Script::Uninstall => write!(f, "uninstall"),
Script::ListBinPaths => write!(f, "list-bin-paths"),
Script::RunExternalCommand(_, _) => write!(f, "run-external-command"),
Script::ExecEnv => write!(f, "exec-env"),
Script::Download => write!(f, "download"),
}
}
}
static INITIAL_ENV: Lazy<HashMap<OsString, OsString>> = Lazy::new(|| {
let settings = Settings::get();
let mut env: HashMap<OsString, OsString> = env::PRISTINE_ENV
.iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
if settings.trace {
env.insert("MISE_TRACE".into(), "1".into());
}
if settings.debug {
env.insert("MISE_DEBUG".into(), "1".into());
env.insert("MISE_VERBOSE".into(), "1".into());
}
env.extend(
(indexmap! {
"ASDF_CONCURRENCY" => num_cpus::get().to_string(),
&*PATH_KEY => get_path_with_fake_asdf(),
"MISE_CACHE_DIR" => env::MISE_CACHE_DIR.to_string_lossy().to_string(),
"MISE_CONCURRENCY" => num_cpus::get().to_string(),
"MISE_DATA_DIR" => dirs::DATA.to_string_lossy().to_string(),
"MISE_LOG_LEVEL" => settings.log_level.to_string(),
"__MISE_BIN" => env::MISE_BIN.to_string_lossy().to_string(),
"__MISE_SCRIPT" => "1".to_string(),
})
.into_iter()
.map(|(k, v)| (k.into(), v.into())),
);
env
});
impl ScriptManager {
pub fn new(plugin_path: PathBuf) -> Self {
let mut env = INITIAL_ENV.clone();
if let Some(failure) = env::var_os("MISE_FAILURE") {
// used for testing failure cases
env.insert("MISE_FAILURE".into(), failure);
}
Self { env, plugin_path }
}
pub fn with_env<K, V>(mut self, k: K, v: V) -> Self
where
K: Into<OsString>,
V: Into<OsString>,
{
self.env.insert(k.into(), v.into());
self
}
pub fn prepend_path(&mut self, path: PathBuf) {
let k: OsString = PATH_KEY.to_string().into();
let mut paths = env::split_paths(&self.env[&k]).collect::<Vec<_>>();
paths.insert(0, path);
self.env
.insert(PATH_KEY.to_string().into(), env::join_paths(paths).unwrap());
}
pub fn get_script_path(&self, script: &Script) -> PathBuf {
match script {
Script::RunExternalCommand(path, _) => path.clone(),
_ => self.plugin_path.join("bin").join(script.to_string()),
}
}
pub fn script_exists(&self, script: &Script) -> bool {
self.get_script_path(script).is_file()
}
pub fn cmd(&self, script: &Script) -> Expression {
let args = match script {
Script::ParseIdiomaticFile(filename) => vec![filename.clone()],
Script::RunExternalCommand(_, args) => args.clone(),
_ => vec![],
};
let script_path = self.get_script_path(script);
// if !script_path.exists() {
// return Err(PluginNotInstalled(self.plugin_name.clone()).into());
// }
let mut cmd = cmd(script_path, args).full_env(&self.env);
let settings = &Settings::get();
if !settings.raw {
// ignore stdin, otherwise a prompt may show up where the user won't see it
cmd = cmd.stdin_null();
}
cmd
}
pub fn read(&self, script: &Script) -> Result<String> {
let mut cmd = self.cmd(script);
let settings = &Settings::try_get()?;
if !settings.verbose {
cmd = cmd.stderr_null();
}
cmd.read()
.wrap_err_with(|| ScriptFailed(display_path(self.get_script_path(script)), None))
}
pub fn run_by_line(&self, script: &Script, pr: &dyn SingleReport) -> Result<()> {
let path = self.get_script_path(script);
pr.set_message(display_path(&path));
let mut cmd = CmdLineRunner::new(path.clone());
if let Some(arch) = &Settings::get().arch
&& arch == "x86_64"
&& cfg!(macos)
{
cmd = CmdLineRunner::new("/usr/bin/arch")
.arg("-x86_64")
.arg(path.clone());
}
let cmd = cmd.with_pr(pr).env_clear().envs(&self.env);
if let Err(e) = cmd.execute() {
let status = match e.downcast_ref::<Error>() {
Some(ScriptFailed(_, status)) => *status,
_ => None,
};
return Err(ScriptFailed(display_path(&path), status).into());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use test_log::test;
use super::*;
#[test]
fn test_script_manager() {
let plugin_path = PathBuf::from("/tmp/asdf");
let script_manager = ScriptManager::new(plugin_path.clone());
assert_eq!(script_manager.plugin_path, plugin_path);
}
#[test]
fn test_get_script_path() {
let plugin_path = PathBuf::from("/tmp/asdf");
let script_manager = ScriptManager::new(plugin_path.clone());
let test = |script, expected| {
assert_eq!(script_manager.get_script_path(script), expected);
};
test(
&Script::LatestStable,
plugin_path.join("bin").join("latest-stable"),
);
let script = Script::RunExternalCommand(PathBuf::from("/bin/ls"), vec!["-l".to_string()]);
test(&script, PathBuf::from("/bin/ls"));
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/mise_plugin_toml.rs | src/plugins/mise_plugin_toml.rs | use std::path::Path;
use color_eyre::Result;
use color_eyre::eyre::eyre;
use eyre::WrapErr;
use toml_edit::{DocumentMut, Item, Value};
use crate::{file, parse_error};
#[derive(Debug, Default, Clone)]
pub struct MisePluginTomlScriptConfig {
pub cache_key: Option<Vec<String>>,
pub data: Option<String>,
}
#[derive(Debug, Default, Clone)]
pub struct MisePluginToml {
pub exec_env: MisePluginTomlScriptConfig,
pub list_aliases: MisePluginTomlScriptConfig,
pub list_bin_paths: MisePluginTomlScriptConfig,
pub list_idiomatic_filenames: MisePluginTomlScriptConfig,
}
impl MisePluginToml {
pub fn from_file(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Default::default());
}
trace!("parsing: {}", path.display());
let mut rf = Self::init();
let body = file::read_to_string(path).wrap_err("ensure file exists and can be read")?;
rf.parse(&body)?;
Ok(rf)
}
fn init() -> Self {
Self {
..Default::default()
}
}
fn parse(&mut self, s: &str) -> Result<()> {
let doc: DocumentMut = s.parse().wrap_err("ensure file is valid TOML")?;
for (k, v) in doc.iter() {
match k {
"exec-env" => self.exec_env = self.parse_script_config(k, v)?,
"list-aliases" => self.list_aliases = self.parse_script_config(k, v)?,
"list-bin-paths" => self.list_bin_paths = self.parse_script_config(k, v)?,
"list-idiomatic-filenames" | "list-legacy-filenames" => {
self.list_idiomatic_filenames = self.parse_script_config(k, v)?
}
// this is an old key used in rtx-python
// this file is invalid, so just stop parsing entirely if we see it
"idiomatic-filenames" | "legacy-filenames" => return Ok(()),
_ => Err(eyre!("unknown key: {}", k))?,
}
}
Ok(())
}
fn parse_script_config(&mut self, key: &str, v: &Item) -> Result<MisePluginTomlScriptConfig> {
match v.as_table_like() {
Some(table) => {
let mut config = MisePluginTomlScriptConfig::default();
for (k, v) in table.iter() {
let key = format!("{key}.{k}");
match k {
"cache-key" => config.cache_key = Some(self.parse_string_array(k, v)?),
"data" => match v.as_value() {
Some(v) => config.data = Some(self.parse_string(k, v)?),
_ => parse_error!(key, v, "string"),
},
_ => parse_error!(key, v, "one of: cache-key"),
}
}
Ok(config)
}
_ => parse_error!(key, v, "table"),
}
}
fn parse_string_array(&mut self, k: &str, v: &Item) -> Result<Vec<String>> {
match v.as_array() {
Some(arr) => {
let mut out = vec![];
for v in arr {
out.push(self.parse_string(k, v)?);
}
Ok(out)
}
_ => parse_error!(k, v, "array"),
}
}
fn parse_string(&mut self, k: &str, v: &Value) -> Result<String> {
match v.as_str() {
Some(v) => Ok(v.to_string()),
_ => parse_error!(k, v, "string"),
}
}
}
#[cfg(test)]
mod tests {
use indoc::formatdoc;
use insta::assert_debug_snapshot;
use crate::dirs;
use super::*;
#[test]
fn test_fixture() {
let cf = MisePluginToml::from_file(&dirs::HOME.join("fixtures/mise.plugin.toml")).unwrap();
assert_debug_snapshot!(cf.exec_env);
}
#[test]
fn test_exec_env() {
let cf = parse(&formatdoc! {r#"
[list-aliases]
data = "test-aliases"
[list-idiomatic-filenames]
data = "test-idiomatic-filenames"
[exec-env]
cache-key = ["foo", "bar"]
[list-bin-paths]
cache-key = ["foo"]
"#});
assert_debug_snapshot!(cf.exec_env, @r#"
MisePluginTomlScriptConfig {
cache_key: Some(
[
"foo",
"bar",
],
),
data: None,
}
"#);
}
fn parse(s: &str) -> MisePluginToml {
let mut cf = MisePluginToml::init();
cf.parse(s).unwrap();
cf
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/mod.rs | src/plugins/mod.rs | use crate::errors::Error::PluginNotInstalled;
use crate::git::Git;
use crate::plugins::asdf_plugin::AsdfPlugin;
use crate::plugins::vfox_plugin::VfoxPlugin;
use crate::toolset::install_state;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use crate::{config::Config, dirs};
use async_trait::async_trait;
use clap::Command;
use eyre::{Result, eyre};
use heck::ToKebabCase;
use regex::Regex;
pub use script_manager::{Script, ScriptManager};
use std::path::PathBuf;
use std::sync::LazyLock as Lazy;
use std::vec;
use std::{
fmt::{Debug, Display},
sync::Arc,
};
pub mod asdf_plugin;
pub mod core;
pub mod mise_plugin_toml;
pub mod script_manager;
pub mod vfox_plugin;
#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
pub enum PluginType {
Asdf,
Vfox,
VfoxBackend,
}
#[derive(Debug)]
pub enum PluginEnum {
Asdf(Arc<AsdfPlugin>),
Vfox(Arc<VfoxPlugin>),
VfoxBackend(Arc<VfoxPlugin>),
}
impl PluginEnum {
pub fn name(&self) -> &str {
match self {
PluginEnum::Asdf(plugin) => plugin.name(),
PluginEnum::Vfox(plugin) => plugin.name(),
PluginEnum::VfoxBackend(plugin) => plugin.name(),
}
}
pub fn path(&self) -> PathBuf {
match self {
PluginEnum::Asdf(plugin) => plugin.path(),
PluginEnum::Vfox(plugin) => plugin.path(),
PluginEnum::VfoxBackend(plugin) => plugin.path(),
}
}
pub fn get_plugin_type(&self) -> PluginType {
match self {
PluginEnum::Asdf(_) => PluginType::Asdf,
PluginEnum::Vfox(_) => PluginType::Vfox,
PluginEnum::VfoxBackend(_) => PluginType::VfoxBackend,
}
}
pub fn get_remote_url(&self) -> eyre::Result<Option<String>> {
match self {
PluginEnum::Asdf(plugin) => plugin.get_remote_url(),
PluginEnum::Vfox(plugin) => plugin.get_remote_url(),
PluginEnum::VfoxBackend(plugin) => plugin.get_remote_url(),
}
}
pub fn set_remote_url(&self, url: String) {
match self {
PluginEnum::Asdf(plugin) => plugin.set_remote_url(url),
PluginEnum::Vfox(plugin) => plugin.set_remote_url(url),
PluginEnum::VfoxBackend(plugin) => plugin.set_remote_url(url),
}
}
pub fn current_abbrev_ref(&self) -> eyre::Result<Option<String>> {
match self {
PluginEnum::Asdf(plugin) => plugin.current_abbrev_ref(),
PluginEnum::Vfox(plugin) => plugin.current_abbrev_ref(),
PluginEnum::VfoxBackend(plugin) => plugin.current_abbrev_ref(),
}
}
pub fn current_sha_short(&self) -> eyre::Result<Option<String>> {
match self {
PluginEnum::Asdf(plugin) => plugin.current_sha_short(),
PluginEnum::Vfox(plugin) => plugin.current_sha_short(),
PluginEnum::VfoxBackend(plugin) => plugin.current_sha_short(),
}
}
pub fn external_commands(&self) -> eyre::Result<Vec<Command>> {
match self {
PluginEnum::Asdf(plugin) => plugin.external_commands(),
PluginEnum::Vfox(plugin) => plugin.external_commands(),
PluginEnum::VfoxBackend(plugin) => plugin.external_commands(),
}
}
pub fn execute_external_command(&self, command: &str, args: Vec<String>) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.execute_external_command(command, args),
PluginEnum::Vfox(plugin) => plugin.execute_external_command(command, args),
PluginEnum::VfoxBackend(plugin) => plugin.execute_external_command(command, args),
}
}
pub async fn update(&self, pr: &dyn SingleReport, gitref: Option<String>) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.update(pr, gitref).await,
PluginEnum::Vfox(plugin) => plugin.update(pr, gitref).await,
PluginEnum::VfoxBackend(plugin) => plugin.update(pr, gitref).await,
}
}
pub async fn uninstall(&self, pr: &dyn SingleReport) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.uninstall(pr).await,
PluginEnum::Vfox(plugin) => plugin.uninstall(pr).await,
PluginEnum::VfoxBackend(plugin) => plugin.uninstall(pr).await,
}
}
pub async fn install(&self, config: &Arc<Config>, pr: &dyn SingleReport) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.install(config, pr).await,
PluginEnum::Vfox(plugin) => plugin.install(config, pr).await,
PluginEnum::VfoxBackend(plugin) => plugin.install(config, pr).await,
}
}
pub fn is_installed(&self) -> bool {
match self {
PluginEnum::Asdf(plugin) => plugin.is_installed(),
PluginEnum::Vfox(plugin) => plugin.is_installed(),
PluginEnum::VfoxBackend(plugin) => plugin.is_installed(),
}
}
pub fn is_installed_err(&self) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.is_installed_err(),
PluginEnum::Vfox(plugin) => plugin.is_installed_err(),
PluginEnum::VfoxBackend(plugin) => plugin.is_installed_err(),
}
}
pub async fn ensure_installed(
&self,
config: &Arc<Config>,
mpr: &MultiProgressReport,
force: bool,
dry_run: bool,
) -> eyre::Result<()> {
match self {
PluginEnum::Asdf(plugin) => plugin.ensure_installed(config, mpr, force, dry_run).await,
PluginEnum::Vfox(plugin) => plugin.ensure_installed(config, mpr, force, dry_run).await,
PluginEnum::VfoxBackend(plugin) => {
plugin.ensure_installed(config, mpr, force, dry_run).await
}
}
}
}
impl PluginType {
pub fn from_full(full: &str) -> eyre::Result<Self> {
match full.split(':').next() {
Some("asdf") => Ok(Self::Asdf),
Some("vfox") => Ok(Self::Vfox),
Some("vfox-backend") => Ok(Self::VfoxBackend),
_ => Err(eyre!("unknown plugin type: {full}")),
}
}
pub fn plugin(&self, short: String) -> PluginEnum {
let path = dirs::PLUGINS.join(short.to_kebab_case());
match self {
PluginType::Asdf => PluginEnum::Asdf(Arc::new(AsdfPlugin::new(short, path))),
PluginType::Vfox => PluginEnum::Vfox(Arc::new(VfoxPlugin::new(short, path))),
PluginType::VfoxBackend => {
PluginEnum::VfoxBackend(Arc::new(VfoxPlugin::new(short, path)))
}
}
}
}
pub static VERSION_REGEX: Lazy<regex::Regex> = Lazy::new(|| {
Regex::new(
r"(?i)(^Available versions:|-src|-dev|-latest|-stm|[-\\.]rc|-milestone|-alpha|-beta|[-\\.]pre|-next|([abc])[0-9]+|snapshot|SNAPSHOT|master)"
)
.unwrap()
});
pub fn get(short: &str) -> Result<PluginEnum> {
let (name, full) = short.split_once(':').unwrap_or((short, short));
// For plugin:tool format, look up the plugin by just the plugin name
let plugin_lookup_key = if short.contains(':') {
// Check if the part before the colon is a plugin name
if let Some(_plugin_type) = install_state::list_plugins().get(name) {
name
} else {
short
}
} else {
short
};
let plugin_type =
if let Some(plugin_type) = install_state::list_plugins().get(plugin_lookup_key) {
*plugin_type
} else {
PluginType::from_full(full)?
};
Ok(plugin_type.plugin(name.to_string()))
}
#[allow(unused_variables)]
#[async_trait]
pub trait Plugin: Debug + Send {
fn name(&self) -> &str;
fn path(&self) -> PathBuf;
fn get_remote_url(&self) -> eyre::Result<Option<String>>;
fn set_remote_url(&self, url: String) {}
fn current_abbrev_ref(&self) -> eyre::Result<Option<String>>;
fn current_sha_short(&self) -> eyre::Result<Option<String>>;
fn is_installed(&self) -> bool {
true
}
fn is_installed_err(&self) -> eyre::Result<()> {
if !self.is_installed() {
return Err(PluginNotInstalled(self.name().to_string()).into());
}
Ok(())
}
async fn ensure_installed(
&self,
_config: &Arc<Config>,
_mpr: &MultiProgressReport,
_force: bool,
_dry_run: bool,
) -> eyre::Result<()> {
Ok(())
}
async fn update(&self, _pr: &dyn SingleReport, _gitref: Option<String>) -> eyre::Result<()> {
Ok(())
}
async fn uninstall(&self, _pr: &dyn SingleReport) -> eyre::Result<()> {
Ok(())
}
async fn install(&self, _config: &Arc<Config>, _pr: &dyn SingleReport) -> eyre::Result<()> {
Ok(())
}
fn external_commands(&self) -> eyre::Result<Vec<Command>> {
Ok(vec![])
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn execute_external_command(&self, _command: &str, _args: Vec<String>) -> eyre::Result<()> {
unimplemented!(
"execute_external_command not implemented for {}",
self.name()
)
}
}
impl Ord for PluginEnum {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.name().cmp(other.name())
}
}
impl PartialOrd for PluginEnum {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for PluginEnum {
fn eq(&self, other: &Self) -> bool {
self.name() == other.name()
}
}
impl Eq for PluginEnum {}
impl Display for PluginEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name())
}
}
#[derive(Debug, Clone)]
pub enum PluginSource {
/// Git repository with URL and optional ref
Git {
url: String,
git_ref: Option<String>,
},
/// Zip file accessible via HTTPS
Zip { url: String },
}
impl PluginSource {
pub fn parse(repository: &str) -> Self {
// Split Parameters
let url_path = repository
.split('?')
.next()
.unwrap_or(repository)
.split('#')
.next()
.unwrap_or(repository);
// Check if it's a zip file (ends with -zip)
if url_path.to_lowercase().ends_with(".zip") {
return PluginSource::Zip {
url: repository.to_string(),
};
}
// Otherwise treat as git repository
let (url, git_ref) = Git::split_url_and_ref(repository);
PluginSource::Git {
url: url.to_string(),
git_ref: git_ref.map(|s| s.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_plugin_source_parse_git() {
// Test parsing Git URL
let source = PluginSource::parse("https://github.com/user/plugin.git");
match source {
PluginSource::Git { url, git_ref } => {
assert_eq!(url, "https://github.com/user/plugin.git");
assert_eq!(git_ref, None);
}
_ => panic!("Expected a git plugin"),
}
}
#[test]
fn test_plugin_source_parse_git_with_ref() {
// Test parsing Git URL with refs
let source = PluginSource::parse("https://github.com/user/plugin.git#v1.0.0");
match source {
PluginSource::Git { url, git_ref } => {
assert_eq!(url, "https://github.com/user/plugin.git");
assert_eq!(git_ref, Some("v1.0.0".to_string()));
}
_ => panic!("Expected a git plugin"),
}
}
#[test]
fn test_plugin_source_parse_zip() {
// Test parsing zip URL
let source = PluginSource::parse("https://example.com/plugins/my-plugin.zip");
match source {
PluginSource::Zip { url } => {
assert_eq!(url, "https://example.com/plugins/my-plugin.zip");
}
_ => panic!("Expected a Zip source"),
}
}
#[test]
fn test_plugin_source_parse_uppercase_zip_with_query() {
// Test parsing zip URL with query
let source =
PluginSource::parse("https://example.com/plugins/my-plugin.ZIP?version=v1.0.0");
match source {
PluginSource::Zip { url } => {
assert_eq!(
url,
"https://example.com/plugins/my-plugin.ZIP?version=v1.0.0"
);
}
_ => panic!("Expected a Zip source"),
}
}
#[test]
fn test_plugin_source_parse_edge_cases() {
// Test parsing git url which contains `.zip`
let source = PluginSource::parse("https://example.com/.zip/plugin");
match source {
PluginSource::Git { .. } => {}
_ => panic!("Expected a git plugin"),
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/asdf_plugin.rs | src/plugins/asdf_plugin.rs | use crate::config::{Config, Settings};
use crate::errors::Error::PluginNotInstalled;
use crate::file::{display_path, remove_all};
use crate::git::{CloneOptions, Git};
use crate::http::HTTP;
use crate::plugins::{Plugin, PluginSource, Script, ScriptManager};
use crate::result::Result;
use crate::timeout::run_with_timeout;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use crate::ui::prompt;
use crate::{dirs, env, exit, file, lock_file, registry};
use async_trait::async_trait;
use clap::Command;
use console::style;
use contracts::requires;
use eyre::{Context, bail, eyre};
use itertools::Itertools;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};
use std::{collections::HashMap, sync::Arc};
use xx::regex;
#[derive(Debug)]
pub struct AsdfPlugin {
pub name: String,
pub plugin_path: PathBuf,
pub repo: Mutex<Git>,
pub script_man: ScriptManager,
repo_url: Mutex<Option<String>>,
}
impl AsdfPlugin {
#[requires(!name.is_empty())]
pub fn new(name: String, plugin_path: PathBuf) -> Self {
let repo = Git::new(&plugin_path);
Self {
script_man: build_script_man(&name, &plugin_path),
name,
repo_url: Mutex::new(None),
repo: Mutex::new(repo),
plugin_path,
}
}
fn repo(&self) -> MutexGuard<'_, Git> {
self.repo.lock().unwrap()
}
fn get_repo_url(&self, config: &Config) -> eyre::Result<String> {
self.repo_url
.lock()
.unwrap()
.clone()
.or_else(|| self.repo().get_remote_url())
.or_else(|| config.get_repo_url(&self.name))
.ok_or_else(|| eyre!("No repository found for plugin {}", self.name))
}
fn exec_hook_post_plugin_update(
&self,
pr: &dyn SingleReport,
pre: String,
post: String,
) -> eyre::Result<()> {
if pre != post {
let env = [
("ASDF_PLUGIN_PREV_REF", pre.clone()),
("ASDF_PLUGIN_POST_REF", post.clone()),
("MISE_PLUGIN_PREV_REF", pre),
("MISE_PLUGIN_POST_REF", post),
]
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
self.exec_hook_env(pr, "post-plugin-update", env)?;
}
Ok(())
}
fn exec_hook(&self, pr: &dyn SingleReport, hook: &str) -> eyre::Result<()> {
self.exec_hook_env(pr, hook, Default::default())
}
fn exec_hook_env(
&self,
pr: &dyn SingleReport,
hook: &str,
env: HashMap<OsString, OsString>,
) -> eyre::Result<()> {
let script = Script::Hook(hook.to_string());
let mut sm = self.script_man.clone();
sm.env.extend(env);
if sm.script_exists(&script) {
pr.set_message(format!("bin/{hook}"));
sm.run_by_line(&script, pr)?;
}
Ok(())
}
pub fn fetch_remote_versions(&self) -> eyre::Result<Vec<String>> {
let cmd = self.script_man.cmd(&Script::ListAll);
let result = run_with_timeout(
move || {
let result = cmd.stdout_capture().stderr_capture().unchecked().run()?;
Ok(result)
},
Settings::get().fetch_remote_versions_timeout(),
)
.wrap_err_with(|| {
let script = self.script_man.get_script_path(&Script::ListAll);
eyre!("Failed to run {}", display_path(script))
})?;
let stdout = String::from_utf8(result.stdout).unwrap();
let stderr = String::from_utf8(result.stderr).unwrap().trim().to_string();
let display_stderr = || {
if !stderr.is_empty() {
eprintln!("{stderr}");
}
};
if !result.status.success() {
let s = Script::ListAll;
match result.status.code() {
Some(code) => bail!("error running {}: exited with code {}\n{}", s, code, stderr),
None => bail!("error running {}: terminated by signal\n{}", s, stderr),
};
} else if Settings::get().verbose {
display_stderr();
}
Ok(stdout
.split_whitespace()
.map(|v| regex!(r"^v(\d+)").replace(v, "$1").to_string())
.collect())
}
pub fn fetch_latest_stable(&self) -> eyre::Result<Option<String>> {
let latest_stable = self
.script_man
.read(&Script::LatestStable)?
.trim()
.to_string();
Ok(if latest_stable.is_empty() {
None
} else {
Some(latest_stable)
})
}
pub fn fetch_idiomatic_filenames(&self) -> eyre::Result<Vec<String>> {
let stdout = self.script_man.read(&Script::ListIdiomaticFilenames)?;
Ok(self.parse_idiomatic_filenames(&stdout))
}
pub fn parse_idiomatic_filenames(&self, data: &str) -> Vec<String> {
data.split_whitespace().map(|v| v.into()).collect()
}
pub fn has_list_alias_script(&self) -> bool {
self.script_man.script_exists(&Script::ListAliases)
}
pub fn has_list_idiomatic_filenames_script(&self) -> bool {
self.script_man
.script_exists(&Script::ListIdiomaticFilenames)
}
pub fn has_latest_stable_script(&self) -> bool {
self.script_man.script_exists(&Script::LatestStable)
}
pub fn fetch_aliases(&self) -> eyre::Result<Vec<(String, String)>> {
let stdout = self.script_man.read(&Script::ListAliases)?;
Ok(self.parse_aliases(&stdout))
}
pub(crate) fn parse_aliases(&self, data: &str) -> Vec<(String, String)> {
data.lines()
.filter_map(|line| {
let mut parts = line.split_whitespace().collect_vec();
if parts.len() != 2 {
if !parts.is_empty() {
trace!("invalid alias line: {}", line);
}
return None;
}
Some((parts.remove(0).into(), parts.remove(0).into()))
})
.collect()
}
async fn install_from_zip(&self, url: &str, pr: &dyn SingleReport) -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let temp_archive = temp_dir.path().join("archive.zip");
HTTP.download_file(url, &temp_archive, Some(pr)).await?;
pr.set_message("extracting zip file".to_string());
let strip_components = file::should_strip_components(&temp_archive, file::TarFormat::Zip)?;
file::unzip(
&temp_archive,
&self.plugin_path,
&file::ZipOptions {
strip_components: if strip_components { 1 } else { 0 },
},
)?;
Ok(())
}
}
#[async_trait]
impl Plugin for AsdfPlugin {
fn name(&self) -> &str {
&self.name
}
fn path(&self) -> PathBuf {
self.plugin_path.clone()
}
fn get_remote_url(&self) -> eyre::Result<Option<String>> {
let url = self.repo().get_remote_url();
Ok(url.or(self.repo_url.lock().unwrap().clone()))
}
fn set_remote_url(&self, url: String) {
*self.repo_url.lock().unwrap() = Some(url);
}
fn current_abbrev_ref(&self) -> eyre::Result<Option<String>> {
if !self.is_installed() {
return Ok(None);
}
self.repo().current_abbrev_ref().map(Some)
}
fn current_sha_short(&self) -> eyre::Result<Option<String>> {
if !self.is_installed() {
return Ok(None);
}
self.repo().current_sha_short().map(Some)
}
fn is_installed(&self) -> bool {
self.plugin_path.exists()
}
fn is_installed_err(&self) -> eyre::Result<()> {
if self.is_installed() {
return Ok(());
}
Err(eyre!("asdf plugin {} is not installed", self.name())
.wrap_err("run with --yes to install plugin automatically"))
}
async fn ensure_installed(
&self,
config: &Arc<Config>,
mpr: &MultiProgressReport,
force: bool,
dry_run: bool,
) -> Result<()> {
let settings = Settings::try_get()?;
if !force {
if self.is_installed() {
return Ok(());
}
if !settings.yes && self.repo_url.lock().unwrap().is_none() {
let url = self.get_repo_url(config).unwrap_or_default();
if !registry::is_trusted_plugin(self.name(), &url) {
warn!(
"⚠️ {} is a community-developed plugin – {}",
style(&self.name).blue(),
style(url.trim_end_matches(".git")).yellow()
);
if settings.paranoid {
bail!(
"Paranoid mode is enabled, refusing to install community-developed plugin"
);
}
if !prompt::confirm_with_all(format!(
"Would you like to install {}?",
self.name
))? {
Err(PluginNotInstalled(self.name.clone()))?
}
}
}
}
let prefix = format!("plugin:{}", style(&self.name).blue().for_stderr());
let pr = mpr.add_with_options(&prefix, dry_run);
if !dry_run {
let _lock = lock_file::get(&self.plugin_path, force)?;
self.install(config, pr.as_ref()).await
} else {
Ok(())
}
}
async fn update(&self, pr: &dyn SingleReport, gitref: Option<String>) -> Result<()> {
let plugin_path = self.plugin_path.to_path_buf();
if plugin_path.is_symlink() {
warn!(
"plugin:{} is a symlink, not updating",
style(&self.name).blue().for_stderr()
);
return Ok(());
}
let git = Git::new(plugin_path);
if !git.is_repo() {
warn!(
"plugin:{} is not a git repository, not updating",
style(&self.name).blue().for_stderr()
);
return Ok(());
}
pr.set_message("update git repo".into());
let (pre, post) = git.update(gitref)?;
let sha = git.current_sha_short()?;
let repo_url = self.get_remote_url()?.unwrap_or_default();
self.exec_hook_post_plugin_update(pr, pre, post)?;
pr.finish_with_message(format!(
"{repo_url}#{}",
style(&sha).bright().yellow().for_stderr(),
));
Ok(())
}
async fn uninstall(&self, pr: &dyn SingleReport) -> Result<()> {
if !self.is_installed() {
return Ok(());
}
self.exec_hook(pr, "pre-plugin-remove")?;
pr.set_message("uninstall".into());
let rmdir = |dir: &Path| {
if !dir.exists() {
return Ok(());
}
pr.set_message(format!("remove {}", display_path(dir)));
remove_all(dir).wrap_err_with(|| {
format!(
"Failed to remove directory {}",
style(display_path(dir)).cyan().for_stderr()
)
})
};
rmdir(&self.plugin_path)?;
Ok(())
}
async fn install(&self, config: &Arc<Config>, pr: &dyn SingleReport) -> eyre::Result<()> {
let repository = self.get_repo_url(config)?;
let source = PluginSource::parse(&repository);
debug!("asdf_plugin[{}]:install {:?}", self.name, repository);
if self.is_installed() {
self.uninstall(pr).await?;
}
match source {
PluginSource::Zip { url } => {
self.install_from_zip(&url, pr).await?;
self.exec_hook(pr, "post-plugin-add")?;
pr.finish_with_message(url.to_string());
Ok(())
}
PluginSource::Git {
url: repo_url,
git_ref,
} => {
if regex!(r"^[/~]").is_match(&repo_url) {
Err(eyre!(
r#"Invalid repository URL: {repo_url}
If you are trying to link to a local directory, use `mise plugins link` instead.
Plugins could support local directories in the future but for now a symlink is required which `mise plugins link` will create for you."#
))?;
}
let git = Git::new(&self.plugin_path);
pr.set_message(format!("clone {repo_url}"));
git.clone(&repo_url, CloneOptions::default().pr(pr))?;
if let Some(ref_) = &git_ref {
pr.set_message(format!("check out {ref_}"));
git.update(Some(ref_.to_string()))?;
}
self.exec_hook(pr, "post-plugin-add")?;
let sha = git.current_sha_short()?;
pr.finish_with_message(format!(
"{repo_url}#{}",
style(&sha).bright().yellow().for_stderr(),
));
Ok(())
}
}
}
fn external_commands(&self) -> eyre::Result<Vec<Command>> {
let command_path = self.plugin_path.join("lib/commands");
if !self.is_installed() || !command_path.exists() || self.name == "direnv" {
// asdf-direnv is disabled since it conflicts with mise's built-in direnv functionality
return Ok(vec![]);
}
let mut commands = vec![];
for p in crate::file::ls(&command_path)? {
let command = p.file_name().unwrap().to_string_lossy().to_string();
if !command.starts_with("command-") || !command.ends_with(".bash") {
continue;
}
let command = command
.strip_prefix("command-")
.unwrap()
.strip_suffix(".bash")
.unwrap()
.split('-')
.map(|s| s.to_string())
.collect::<Vec<String>>();
commands.push(command);
}
if commands.is_empty() {
return Ok(vec![]);
}
let topic = Command::new(self.name.clone())
.about(format!("Commands provided by {} plugin", &self.name))
.subcommands(commands.into_iter().map(|cmd| {
Command::new(cmd.join("-"))
.about(format!("{} command", cmd.join("-")))
.arg(
clap::Arg::new("args")
.num_args(1..)
.allow_hyphen_values(true)
.trailing_var_arg(true),
)
}));
Ok(vec![topic])
}
fn execute_external_command(&self, command: &str, args: Vec<String>) -> eyre::Result<()> {
if !self.is_installed() {
return Err(PluginNotInstalled(self.name.clone()).into());
}
let script = Script::RunExternalCommand(
self.plugin_path
.join("lib/commands")
.join(format!("command-{command}.bash")),
args,
);
let result = self.script_man.cmd(&script).unchecked().run()?;
exit(result.status.code().unwrap_or(-1));
}
}
fn build_script_man(name: &str, plugin_path: &Path) -> ScriptManager {
let plugin_path_s = plugin_path.to_string_lossy().to_string();
let token = env::GITHUB_TOKEN.as_deref().unwrap_or("");
ScriptManager::new(plugin_path.to_path_buf())
.with_env("ASDF_PLUGIN_PATH", plugin_path_s.clone())
.with_env("RTX_PLUGIN_PATH", plugin_path_s.clone())
.with_env("RTX_PLUGIN_NAME", name.to_string())
.with_env("RTX_SHIMS_DIR", *dirs::SHIMS)
.with_env("MISE_PLUGIN_NAME", name.to_string())
.with_env("MISE_PLUGIN_PATH", plugin_path)
.with_env("MISE_SHIMS_DIR", *dirs::SHIMS)
.with_env("GITHUB_TOKEN", token)
// asdf plugins often use GITHUB_API_TOKEN as the env var for GitHub API token
.with_env("GITHUB_API_TOKEN", token)
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/ruby.rs | src/plugins/core/ruby.rs | use std::collections::{BTreeMap, HashMap};
use std::env::temp_dir;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use async_trait::async_trait;
use eyre::{Result, WrapErr, eyre};
use itertools::Itertools;
use xx::regex;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::{Backend, VersionInfo};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::duration::DAILY;
use crate::env::{self, PATH_KEY};
use crate::git::{CloneOptions, Git};
use crate::github::{self, GithubRelease};
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::lock_file::LockFile;
use crate::lockfile::PlatformInfo;
use crate::plugins::PluginSource;
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{file, hash, plugins, timeout};
const RUBY_INDEX_URL: &str = "https://cache.ruby-lang.org/pub/ruby/index.txt";
const ATTESTATION_HELP: &str = "To disable attestation verification, set MISE_RUBY_GITHUB_ATTESTATIONS=false\n\
or add `ruby.github_attestations = false` to your mise config";
#[derive(Debug)]
pub struct RubyPlugin {
ba: Arc<BackendArg>,
}
impl RubyPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("ruby")),
}
}
fn ruby_build_path(&self) -> PathBuf {
self.ba.cache_path.join("ruby-build")
}
fn ruby_install_path(&self) -> PathBuf {
self.ba.cache_path.join("ruby-install")
}
fn ruby_build_bin(&self) -> PathBuf {
self.ruby_build_path().join("bin/ruby-build")
}
fn ruby_install_bin(&self) -> PathBuf {
self.ruby_install_path().join("bin/ruby-install")
}
fn lock_build_tool(&self) -> Result<fslock::LockFile> {
let settings = Settings::get();
let build_tool_path = if settings.ruby.ruby_install {
self.ruby_install_bin()
} else {
self.ruby_build_bin()
};
LockFile::new(&build_tool_path)
.with_callback(|l| {
trace!("install_or_update_ruby_build_tool {}", l.display());
})
.lock()
}
async fn update_build_tool(&self, ctx: Option<&InstallContext>) -> Result<()> {
let pr = ctx.map(|ctx| ctx.pr.as_ref());
if Settings::get().ruby.ruby_install {
self.update_ruby_install(pr)
.await
.wrap_err("failed to update ruby-install")
} else {
self.update_ruby_build(pr)
.await
.wrap_err("failed to update ruby-build")
}
}
async fn install_ruby_build(&self, pr: Option<&dyn SingleReport>) -> Result<()> {
debug!(
"Installing ruby-build to {}",
self.ruby_build_path().display()
);
let settings = Settings::get();
let tmp = self
.prepare_source_in_tmp(&settings.ruby.ruby_build_repo, pr, "mise-ruby-build")
.await?;
cmd!("sh", "install.sh")
.env("PREFIX", self.ruby_build_path())
.dir(&tmp)
.run()?;
file::remove_all(&tmp)?;
Ok(())
}
async fn update_ruby_build(&self, pr: Option<&dyn SingleReport>) -> Result<()> {
let _lock = self.lock_build_tool();
if self.ruby_build_bin().exists() {
let cur = self.ruby_build_version()?;
let latest = self.latest_ruby_build_version().await;
match (cur, latest) {
// ruby-build is up-to-date
(cur, Ok(latest)) if cur == latest => return Ok(()),
// ruby-build is not up-to-date
(_cur, Ok(_latest)) => {}
// error getting latest ruby-build version (usually github rate limit)
(_cur, Err(err)) => warn!("failed to get latest ruby-build version: {}", err),
}
}
debug!(
"Updating ruby-build in {}",
self.ruby_build_path().display()
);
file::remove_all(self.ruby_build_path())?;
self.install_ruby_build(pr).await?;
Ok(())
}
async fn install_ruby_install(&self, pr: Option<&dyn SingleReport>) -> Result<()> {
debug!(
"Installing ruby-install to {}",
self.ruby_install_path().display()
);
let settings = Settings::get();
let tmp = self
.prepare_source_in_tmp(&settings.ruby.ruby_install_repo, pr, "mise-ruby-install")
.await?;
cmd!("make", "install")
.env("PREFIX", self.ruby_install_path())
.dir(&tmp)
.stdout_to_stderr()
.run()?;
file::remove_all(&tmp)?;
Ok(())
}
async fn update_ruby_install(&self, pr: Option<&dyn SingleReport>) -> Result<()> {
let _lock = self.lock_build_tool();
let ruby_install_path = self.ruby_install_path();
if !ruby_install_path.exists() {
self.install_ruby_install(pr).await?;
}
if self.ruby_install_recently_updated()? {
return Ok(());
}
debug!("Updating ruby-install in {}", ruby_install_path.display());
plugins::core::run_fetch_task_with_timeout(move || {
cmd!(self.ruby_install_bin(), "--update")
.stdout_to_stderr()
.run()?;
file::touch_dir(&ruby_install_path)?;
Ok(())
})
}
fn ruby_install_recently_updated(&self) -> Result<bool> {
let updated_at = file::modified_duration(&self.ruby_install_path())?;
Ok(updated_at < DAILY)
}
async fn prepare_source_in_tmp(
&self,
repo: &str,
pr: Option<&dyn SingleReport>,
tmp_dir_name: &str,
) -> Result<PathBuf> {
let tmp = temp_dir().join(tmp_dir_name);
file::remove_all(&tmp)?;
file::create_dir_all(tmp.parent().unwrap())?;
let source = PluginSource::parse(repo);
match source {
PluginSource::Zip { url } => {
let temp_archive = tmp.join("ruby.zip");
HTTP.download_file(url, &temp_archive, pr).await?;
if let Some(pr) = pr {
pr.set_message("extracting zip file".to_string());
}
let strip_components =
file::should_strip_components(&temp_archive, file::TarFormat::Zip)?;
file::unzip(
&temp_archive,
&tmp,
&file::ZipOptions {
strip_components: if strip_components { 1 } else { 0 },
},
)?;
}
PluginSource::Git {
url: repo_url,
git_ref: _,
} => {
let git = Git::new(tmp.clone());
let mut clone_options = CloneOptions::default();
if let Some(pr) = pr {
clone_options = clone_options.pr(pr);
}
git.clone(&repo_url, clone_options)?;
}
}
Ok(tmp)
}
fn gem_path(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin/gem")
}
async fn install_default_gems(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
let settings = Settings::get();
let default_gems_file = file::replace_path(&settings.ruby.default_packages_file);
let body = file::read_to_string(&default_gems_file).unwrap_or_default();
for package in body.lines() {
let package = package.split('#').next().unwrap_or_default().trim();
if package.is_empty() {
continue;
}
pr.set_message(format!("install default gem: {package}"));
let gem = self.gem_path(tv);
let mut cmd = CmdLineRunner::new(gem)
.with_pr(pr)
.arg("install")
.envs(config.env().await?);
match package.split_once(' ') {
Some((name, "--pre")) => cmd = cmd.arg(name).arg("--pre"),
Some((name, version)) => cmd = cmd.arg(name).arg("--version").arg(version),
None => cmd = cmd.arg(package),
};
cmd.env(&*PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()?;
}
Ok(())
}
fn ruby_build_version(&self) -> Result<String> {
let output = cmd!(self.ruby_build_bin(), "--version").read()?;
let re = regex!(r"^ruby-build ([0-9.]+)");
let caps = re.captures(&output).expect("ruby-build version regex");
Ok(caps.get(1).unwrap().as_str().to_string())
}
async fn latest_ruby_build_version(&self) -> Result<String> {
let release: GithubRelease = HTTP_FETCH
.json("https://api.github.com/repos/rbenv/ruby-build/releases/latest")
.await?;
Ok(release.tag_name.trim_start_matches('v').to_string())
}
fn install_rubygems_hook(&self, tv: &ToolVersion) -> Result<()> {
let site_ruby_path = tv.install_path().join("lib/ruby/site_ruby");
let f = site_ruby_path.join("rubygems_plugin.rb");
file::create_dir_all(site_ruby_path)?;
file::write(f, include_str!("assets/rubygems_plugin.rb"))?;
Ok(())
}
async fn install_cmd<'a>(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &'a dyn SingleReport,
) -> Result<CmdLineRunner<'a>> {
let settings = Settings::get();
let cmd = if settings.ruby.ruby_install {
CmdLineRunner::new(self.ruby_install_bin()).args(self.install_args_ruby_install(tv)?)
} else {
CmdLineRunner::new(self.ruby_build_bin())
.args(self.install_args_ruby_build(tv)?)
.stdin_string(self.fetch_patches().await?)
};
Ok(cmd.with_pr(pr).envs(config.env().await?))
}
fn install_args_ruby_build(&self, tv: &ToolVersion) -> Result<Vec<String>> {
let settings = Settings::get();
let mut args = vec![];
if self.verbose_install() {
args.push("--verbose".into());
}
if settings.ruby.apply_patches.is_some() {
args.push("--patch".into());
}
args.push(tv.version.clone());
args.push(tv.install_path().to_string_lossy().to_string());
if let Some(opts) = &settings.ruby.ruby_build_opts {
args.push("--".into());
args.extend(shell_words::split(opts)?);
}
Ok(args)
}
fn install_args_ruby_install(&self, tv: &ToolVersion) -> Result<Vec<String>> {
let settings = Settings::get();
let mut args = vec![];
for patch in self.fetch_patch_sources() {
args.push("--patch".into());
args.push(patch);
}
let (engine, version) = match tv.version.split_once('-') {
Some((engine, version)) => (engine, version),
None => ("ruby", tv.version.as_str()),
};
args.push(engine.into());
args.push(version.into());
args.push("--install-dir".into());
args.push(tv.install_path().to_string_lossy().to_string());
if let Some(opts) = &settings.ruby.ruby_install_opts {
args.push("--".into());
args.extend(shell_words::split(opts)?);
}
Ok(args)
}
fn verbose_install(&self) -> bool {
let settings = Settings::get();
let verbose_env = settings.ruby.verbose_install;
verbose_env == Some(true) || (settings.verbose && verbose_env != Some(false))
}
fn fetch_patch_sources(&self) -> Vec<String> {
let settings = Settings::get();
let patch_sources = settings.ruby.apply_patches.clone().unwrap_or_default();
patch_sources
.split('\n')
.map(|s| s.to_string())
.filter(|s| !s.is_empty())
.collect()
}
async fn fetch_patches(&self) -> Result<String> {
let mut patches = vec![];
let re = regex!(r#"^[Hh][Tt][Tt][Pp][Ss]?://"#);
for f in &self.fetch_patch_sources() {
if re.is_match(f) {
patches.push(HTTP.get_text(f).await?);
} else {
patches.push(file::read_to_string(f)?);
}
}
Ok(patches.join("\n"))
}
/// Fetch Ruby source tarball info from cache.ruby-lang.org index
/// Returns (url, sha256) for the given version
async fn get_ruby_download_info(&self, version: &str) -> Result<Option<(String, String)>> {
// Only standard MRI Ruby versions are in the index (e.g., "3.3.0", not "jruby-9.4.0")
if !version.chars().next().is_some_and(|c| c.is_ascii_digit()) {
return Ok(None);
}
let index_text: String = HTTP_FETCH.get_text(RUBY_INDEX_URL).await?;
// Format: name\turl\tsha1\tsha256\tsha512
// Example: ruby-3.3.0\thttps://cache.ruby-lang.org/pub/ruby/3.3/ruby-3.3.0.tar.gz\t...\t<sha256>\t...
let target_name = format!("ruby-{version}");
for line in index_text.lines().skip(1) {
// skip header
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 4 {
let name = parts[0];
// Match exact version with .tar.gz (prefer over .tar.xz for compatibility)
if name == target_name {
let url = parts[1];
let sha256 = parts[3];
if url.ends_with(".tar.gz") && !sha256.is_empty() {
return Ok(Some((url.to_string(), format!("sha256:{sha256}"))));
}
}
}
}
Ok(None)
}
// ===== Precompiled Ruby support =====
/// Check if precompiled binaries should be tried
/// Requires experimental=true and compile not explicitly set to true
fn should_try_precompiled(&self) -> bool {
let settings = Settings::get();
settings.experimental && settings.ruby.compile != Some(true)
}
/// Get platform identifier for precompiled binaries
/// Returns platform in jdx/ruby format: "macos", "arm64_linux", or "x86_64_linux"
fn precompiled_platform(&self) -> Option<String> {
let settings = Settings::get();
// Check for user overrides first
if let (Some(arch), Some(os)) = (
settings.ruby.precompiled_arch.as_deref(),
settings.ruby.precompiled_os.as_deref(),
) {
return Some(format!("{}_{}", arch, os));
}
// Auto-detect platform
if cfg!(target_os = "macos") {
// macOS only supports arm64 and uses "macos" without arch prefix
match settings.arch() {
"arm64" | "aarch64" => Some("macos".to_string()),
_ => None,
}
} else if cfg!(target_os = "linux") {
// Linux uses arch_linux format
let arch = match settings.arch() {
"arm64" | "aarch64" => "arm64",
"x64" | "x86_64" => "x86_64",
_ => return None,
};
Some(format!("{}_linux", arch))
} else {
None
}
}
/// Get platform identifier for a specific target (used for lockfiles)
/// Returns platform in jdx/ruby format: "macos", "arm64_linux", or "x86_64_linux"
fn precompiled_platform_for_target(&self, target: &PlatformTarget) -> Option<String> {
match target.os_name() {
"macos" => {
// macOS only supports arm64 and uses "macos" without arch prefix
match target.arch_name() {
"arm64" | "aarch64" => Some("macos".to_string()),
_ => None,
}
}
"linux" => {
// Linux uses arch_linux format
let arch = match target.arch_name() {
"arm64" | "aarch64" => "arm64",
"x64" | "x86_64" => "x86_64",
_ => return None,
};
Some(format!("{}_linux", arch))
}
_ => None,
}
}
/// Render URL template with version and platform variables
fn render_precompiled_url(&self, template: &str, version: &str, platform: &str) -> String {
let (arch, os) = platform.split_once('_').unwrap_or((platform, ""));
template
.replace("{version}", version)
.replace("{platform}", platform)
.replace("{os}", os)
.replace("{arch}", arch)
}
/// Find precompiled asset from a GitHub repo's releases
async fn find_precompiled_asset_in_repo(
&self,
repo: &str,
version: &str,
platform: &str,
) -> Result<Option<(String, Option<String>)>> {
let releases = github::list_releases(repo).await?;
let expected_name = format!("ruby-{}.{}.tar.gz", version, platform);
for release in releases {
for asset in release.assets {
if asset.name == expected_name {
return Ok(Some((asset.browser_download_url, asset.digest)));
}
}
}
Ok(None)
}
/// Resolve precompiled binary URL and checksum for a given version and platform
async fn resolve_precompiled_url(
&self,
version: &str,
platform: &str,
) -> Result<Option<(String, Option<String>)>> {
let settings = Settings::get();
let source = &settings.ruby.precompiled_url;
if source.contains("://") {
// Full URL template - no checksum available
Ok(Some((
self.render_precompiled_url(source, version, platform),
None,
)))
} else {
// GitHub repo shorthand (default: "jdx/ruby")
self.find_precompiled_asset_in_repo(source, version, platform)
.await
}
}
/// Convert a Ruby GitHub tag name to a version string.
/// Ruby uses tags like "v3_3_0" for version "3.3.0"
fn tag_to_version(tag: &str) -> Option<String> {
// Ruby tags are in format v3_3_0, v3_3_0_preview1, etc.
let tag = tag.strip_prefix('v')?;
// Replace underscores with dots, but be careful with preview/rc suffixes
let re = regex!(r"^(\d+)_(\d+)_(\d+)(.*)$");
if let Some(caps) = re.captures(tag) {
let major = &caps[1];
let minor = &caps[2];
let patch = &caps[3];
let suffix = &caps[4];
// Convert suffix like "_preview1" to "-preview1"
let suffix = suffix.replace('_', "-");
Some(format!("{major}.{minor}.{patch}{suffix}"))
} else {
None
}
}
/// Fetch created_at timestamps for Ruby versions from GitHub releases
async fn fetch_ruby_release_dates(&self) -> HashMap<String, String> {
let mut dates = HashMap::new();
match github::list_releases("ruby/ruby").await {
Ok(releases) => {
for release in releases {
if let Some(version) = Self::tag_to_version(&release.tag_name) {
dates.insert(version, release.created_at);
}
}
}
Err(err) => {
debug!("Failed to fetch Ruby release dates: {err}");
}
}
dates
}
/// Try to install from precompiled binary
/// Returns Ok(None) if no precompiled version is available for this version/platform
async fn install_precompiled(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
) -> Result<Option<ToolVersion>> {
let Some(platform) = self.precompiled_platform() else {
return Ok(None);
};
let Some((url, checksum)) = self.resolve_precompiled_url(&tv.version, &platform).await?
else {
return Ok(None);
};
let filename = format!("ruby-{}.{}.tar.gz", tv.version, platform);
let tarball_path = tv.download_path().join(&filename);
ctx.pr.set_message(format!("download {}", filename));
HTTP.download_file(&url, &tarball_path, Some(ctx.pr.as_ref()))
.await?;
if let Some(hash_str) = checksum.as_ref().and_then(|c| c.strip_prefix("sha256:")) {
ctx.pr.set_message(format!("checksum {}", filename));
hash::ensure_checksum(&tarball_path, hash_str, Some(ctx.pr.as_ref()), "sha256")?;
}
// Verify GitHub attestations for precompiled binaries
self.verify_github_attestations(ctx, &tarball_path, &tv.version)
.await?;
ctx.pr.set_message(format!("extract {}", filename));
let install_path = tv.install_path();
file::create_dir_all(&install_path)?;
file::untar(
&tarball_path,
&install_path,
&file::TarOptions {
format: file::TarFormat::TarGz,
strip_components: 1,
pr: Some(ctx.pr.as_ref()),
..Default::default()
},
)?;
Ok(Some(tv.clone()))
}
/// Verify GitHub artifact attestations for precompiled Ruby binary
/// Returns Ok(()) if verification succeeds or is skipped (attestations unavailable)
/// Returns Err if verification is enabled and fails
async fn verify_github_attestations(
&self,
ctx: &InstallContext,
tarball_path: &std::path::Path,
version: &str,
) -> Result<()> {
let settings = Settings::get();
// Check Ruby-specific setting, fall back to global
let enabled = settings
.ruby
.github_attestations
.unwrap_or(settings.github_attestations);
if !enabled {
debug!("GitHub attestations verification disabled for Ruby");
return Ok(());
}
let source = &settings.ruby.precompiled_url;
// Skip for custom URL templates (not GitHub repos)
if source.contains("://") {
debug!("Skipping attestation verification for custom URL template");
return Ok(());
}
let (owner, repo) = match source.split_once('/') {
Some((o, r)) => (o, r),
None => {
warn!("Invalid precompiled_url format: {}", source);
return Ok(());
}
};
ctx.pr.set_message("verify GitHub attestations".to_string());
match sigstore_verification::verify_github_attestation(
tarball_path,
owner,
repo,
env::GITHUB_TOKEN.as_deref(),
None, // Accept any workflow from repo
)
.await
{
Ok(true) => {
ctx.pr
.set_message("✓ GitHub attestations verified".to_string());
debug!(
"GitHub attestations verified successfully for ruby@{}",
version
);
Ok(())
}
Ok(false) => Err(eyre!(
"GitHub attestations verification failed for ruby@{version}\n{ATTESTATION_HELP}"
)),
Err(sigstore_verification::AttestationError::NoAttestations) => Err(eyre!(
"No GitHub attestations found for ruby@{version}\n{ATTESTATION_HELP}"
)),
Err(e) => Err(eyre!(
"GitHub attestations verification failed for ruby@{version}: {e}\n{ATTESTATION_HELP}"
)),
}
}
}
#[async_trait]
impl Backend for RubyPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
let settings = Settings::get();
let mut features = vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}];
// Report GitHub attestations if enabled for precompiled binaries
let github_attestations_enabled = settings
.ruby
.github_attestations
.unwrap_or(settings.github_attestations);
if settings.experimental
&& settings.ruby.compile != Some(true)
&& github_attestations_enabled
{
features.push(SecurityFeature::GithubAttestations {
signer_workflow: None,
});
}
features
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
timeout::run_with_timeout_async(
async || {
if let Err(err) = self.update_build_tool(None).await {
warn!("{err}");
}
// Fetch Ruby release dates from GitHub in parallel with version list
let release_dates = self.fetch_ruby_release_dates().await;
let ruby_build_bin = self.ruby_build_bin();
let versions = plugins::core::run_fetch_task_with_timeout(move || {
let output = cmd!(ruby_build_bin, "--definitions").read()?;
let versions: Vec<String> = output
.split('\n')
.sorted_by_cached_key(|s| regex!(r#"^\d"#).is_match(s)) // show matz ruby first
.map(|s| s.to_string())
.collect();
Ok(versions)
})?;
// Map versions to VersionInfo with created_at timestamps
let version_infos = versions
.into_iter()
.map(|version| {
let created_at = release_dates.get(&version).cloned();
VersionInfo {
version,
created_at,
..Default::default()
}
})
.collect();
Ok(version_infos)
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".ruby-version".into(), "Gemfile".into()])
}
async fn parse_idiomatic_file(&self, path: &Path) -> Result<String> {
let v = match path.file_name() {
Some(name) if name == "Gemfile" => parse_gemfile(&file::read_to_string(path)?),
_ => {
// .ruby-version
let body = file::read_to_string(path)?;
body.trim()
.trim_start_matches("ruby-")
.trim_start_matches('v')
.to_string()
}
};
Ok(v)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
// Try precompiled if experimental mode is enabled and compile is not explicitly true
if self.should_try_precompiled()
&& let Some(installed_tv) = self.install_precompiled(ctx, &tv).await?
{
hint!(
"ruby_precompiled",
"installing precompiled ruby from jdx/ruby\n\
if you experience issues, switch to ruby-build by running",
"mise settings ruby.compile=1"
);
self.install_rubygems_hook(&installed_tv)?;
if let Err(err) = self
.install_default_gems(&ctx.config, &installed_tv, ctx.pr.as_ref())
.await
{
warn!("failed to install default ruby gems {err:#}");
}
return Ok(installed_tv);
}
// No precompiled available, fall through to compile from source
// Compile from source
if let Err(err) = self.update_build_tool(Some(ctx)).await {
warn!("ruby build tool update error: {err:#}");
}
ctx.pr.set_message("ruby-build".into());
self.install_cmd(&ctx.config, &tv, ctx.pr.as_ref())
.await?
.execute()?;
self.install_rubygems_hook(&tv)?;
if let Err(err) = self
.install_default_gems(&ctx.config, &tv, ctx.pr.as_ref())
.await
{
warn!("failed to install default ruby gems {err:#}");
}
Ok(tv)
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
_tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let map = BTreeMap::new();
// No modification to RUBYLIB
Ok(map)
}
fn resolve_lockfile_options(
&self,
_request: &ToolRequest,
target: &PlatformTarget,
) -> BTreeMap<String, String> {
let mut opts = BTreeMap::new();
let settings = Settings::get();
let is_current_platform = target.is_current();
// Ruby uses ruby-install vs ruby-build (ruby compiles from source either way)
// Only include if using non-default ruby-install tool
let ruby_install = if is_current_platform {
settings.ruby.ruby_install
} else {
false
};
if ruby_install {
opts.insert("ruby_install".to_string(), "true".to_string());
}
opts
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
// Precompiled binary info if enabled
if self.should_try_precompiled()
&& let Some(platform) = self.precompiled_platform_for_target(target)
&& let Some((url, checksum)) =
self.resolve_precompiled_url(&tv.version, &platform).await?
{
return Ok(PlatformInfo {
url: Some(url),
checksum,
size: None,
url_api: None,
});
}
// Default: source tarball
match self.get_ruby_download_info(&tv.version).await? {
Some((url, checksum)) => Ok(PlatformInfo {
url: Some(url),
checksum: Some(checksum),
size: None,
url_api: None,
}),
None => Ok(PlatformInfo::default()),
}
}
}
fn parse_gemfile(body: &str) -> String {
let v = body
.lines()
.find(|line| line.trim().starts_with("ruby "))
.unwrap_or_default()
.trim()
.split('#')
.next()
.unwrap_or_default()
.replace("engine:", ":engine =>")
.replace("engine_version:", ":engine_version =>");
let v = regex!(r#".*:engine *=> *['"](?<engine>[^'"]*).*:engine_version *=> *['"](?<engine_version>[^'"]*).*"#).replace_all(&v, "${engine_version}__ENGINE__${engine}").to_string();
let v = regex!(r#".*:engine_version *=> *['"](?<engine_version>[^'"]*).*:engine *=> *['"](?<engine>[^'"]*).*"#).replace_all(&v, "${engine_version}__ENGINE__${engine}").to_string();
let v = regex!(r#" *ruby *['"]([^'"]*).*"#)
.replace_all(&v, "$1")
.to_string();
let v = regex!(r#"^[^0-9]"#).replace_all(&v, "").to_string();
let v = regex!(r#"(.*)__ENGINE__(.*)"#)
.replace_all(&v, "$2-$1")
.to_string();
// make sure it's like "ruby-3.0.0" or "3.0.0"
if !regex!(r"^(\w+-)?([0-9])(\.[0-9])*$").is_match(&v) {
return "".to_string();
}
v
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
use pretty_assertions::assert_eq;
#[test]
fn test_tag_to_version() {
// Standard versions
assert_eq!(
RubyPlugin::tag_to_version("v3_3_0"),
Some("3.3.0".to_string())
);
assert_eq!(
RubyPlugin::tag_to_version("v3_2_2"),
Some("3.2.2".to_string())
);
assert_eq!(
RubyPlugin::tag_to_version("v2_7_8"),
Some("2.7.8".to_string())
);
// Preview and RC versions
assert_eq!(
RubyPlugin::tag_to_version("v3_3_0_preview1"),
Some("3.3.0-preview1".to_string())
);
assert_eq!(
RubyPlugin::tag_to_version("v3_3_0_rc1"),
Some("3.3.0-rc1".to_string())
);
// Invalid tags
assert_eq!(RubyPlugin::tag_to_version("3_3_0"), None); // Missing 'v' prefix
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/rust.rs | src/plugins/core/rust.rs | use std::path::{Path, PathBuf};
use std::{collections::BTreeMap, sync::Arc};
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::build_time::TARGET;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::toolset::ToolSource::IdiomaticVersionFile;
use crate::toolset::outdated_info::OutdatedInfo;
use crate::toolset::{ResolveOptions, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{dirs, env, file, github, plugins};
use async_trait::async_trait;
use eyre::Result;
use xx::regex;
#[derive(Debug)]
pub struct RustPlugin {
ba: Arc<BackendArg>,
}
impl RustPlugin {
pub fn new() -> Self {
Self {
ba: plugins::core::new_backend_arg("rust").into(),
}
}
async fn setup_rustup(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
let settings = Settings::get();
if rustup_home().join("settings.toml").exists() && cargo_bin().exists() {
return Ok(());
}
ctx.pr.set_message("Downloading rustup-init".into());
HTTP.download_file(rustup_url(&settings), &rustup_path(), Some(ctx.pr.as_ref()))
.await?;
file::make_executable(rustup_path())?;
file::create_dir_all(rustup_home())?;
let ts = ctx.config.get_toolset().await?;
let cmd = CmdLineRunner::new(rustup_path())
.with_pr(ctx.pr.as_ref())
.arg("--no-modify-path")
.arg("--default-toolchain")
.arg("none")
.arg("-y")
.envs(self.exec_env(&ctx.config, ts, tv).await?);
cmd.execute()?;
Ok(())
}
async fn test_rust(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
ctx.pr.set_message(format!("{RUSTC_BIN} -V"));
let ts = ctx.config.get_toolset().await?;
CmdLineRunner::new(RUSTC_BIN)
.with_pr(ctx.pr.as_ref())
.arg("-V")
.envs(self.exec_env(&ctx.config, ts, tv).await?)
.prepend_path(self.list_bin_paths(&ctx.config, tv).await?)?
.execute()
}
fn target_triple(&self, tv: &ToolVersion) -> String {
format!("{}-{}", tv.version, TARGET)
}
}
#[async_trait]
impl Backend for RustPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions: Vec<VersionInfo> = github::list_releases("rust-lang/rust")
.await?
.into_iter()
.map(|r| VersionInfo {
release_url: Some(format!("https://releases.rs/docs/{}/", r.tag_name)),
version: r.tag_name,
created_at: Some(r.created_at),
})
.rev()
.chain(vec![
// Special channels don't have release URLs since they're not actual releases
VersionInfo {
version: "nightly".into(),
..Default::default()
},
VersionInfo {
version: "beta".into(),
..Default::default()
},
VersionInfo {
version: "stable".into(),
..Default::default()
},
])
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec!["rust-toolchain.toml".into()])
}
async fn parse_idiomatic_file(&self, path: &Path) -> Result<String> {
let rt = parse_idiomatic_file(path)?;
Ok(rt.channel)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
self.setup_rustup(ctx, &tv).await?;
let ts = ctx.config.get_toolset().await?;
let (profile, components, targets) = get_args(&tv);
CmdLineRunner::new(RUSTUP_BIN)
.with_pr(ctx.pr.as_ref())
.arg("toolchain")
.arg("install")
.arg(&tv.version)
.opt_arg(profile.as_ref().map(|_| "--profile"))
.opt_arg(profile)
.opt_args("--component", components)
.opt_args("--target", targets)
.prepend_path(self.list_bin_paths(&ctx.config, &tv).await?)?
.envs(self.exec_env(&ctx.config, ts, &tv).await?)
.execute()?;
file::remove_all(tv.install_path())?;
file::make_symlink(&cargo_home().join("bin"), &tv.install_path())?;
self.test_rust(ctx, &tv).await?;
Ok(tv)
}
async fn uninstall_version_impl(
&self,
config: &Arc<Config>,
pr: &dyn SingleReport,
tv: &ToolVersion,
) -> Result<()> {
let ts = config.get_toolset().await?;
let mut env = self.exec_env(config, ts, tv).await?;
env.remove("RUSTUP_TOOLCHAIN");
CmdLineRunner::new(RUSTUP_BIN)
.with_pr(pr)
.arg("toolchain")
.arg("uninstall")
.arg(&tv.version)
.prepend_path(self.list_bin_paths(config, tv).await?)?
.envs(env)
.execute()
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
_tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
Ok(vec![cargo_bindir()])
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> Result<BTreeMap<String, String>> {
let toolchain = tv.version.to_string();
Ok([
(
"CARGO_HOME".to_string(),
cargo_home().to_string_lossy().to_string(),
),
(
"RUSTUP_HOME".to_string(),
rustup_home().to_string_lossy().to_string(),
),
("RUSTUP_TOOLCHAIN".to_string(), toolchain),
]
.into())
}
async fn outdated_info(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
bump: bool,
opts: &ResolveOptions,
) -> Result<Option<OutdatedInfo>> {
let v_re = regex!(r#"Update available : (.*) -> (.*)"#);
if regex!(r"(\d+)\.(\d+)\.(\d+)").is_match(&tv.version) {
let oi = OutdatedInfo::resolve(config, tv.clone(), bump, opts).await?;
Ok(oi)
} else {
let ts = config.get_toolset().await?;
let mut cmd =
cmd!(RUSTUP_BIN, "check").env("PATH", self.path_env_for_cmd(config, tv).await?);
for (k, v) in self.exec_env(config, ts, tv).await? {
cmd = cmd.env(k, v);
}
let out = cmd.read()?;
for line in out.lines() {
if line.starts_with(&self.target_triple(tv))
&& let Some(_cap) = v_re.captures(line)
{
// let requested = cap.get(1).unwrap().as_str().to_string();
// let latest = cap.get(2).unwrap().as_str().to_string();
let oi = OutdatedInfo::new(config, tv.clone(), tv.version.clone())?;
return Ok(Some(oi));
}
}
Ok(None)
}
}
}
#[derive(Debug, Default)]
struct RustToolchain {
channel: String,
profile: Option<String>,
components: Option<Vec<String>>,
targets: Option<Vec<String>>,
}
fn get_args(tv: &ToolVersion) -> (Option<String>, Option<Vec<String>>, Option<Vec<String>>) {
let rt = if tv.request.source().is_idiomatic_version_file() {
match tv.request.source() {
IdiomaticVersionFile(path) => parse_idiomatic_file(path).ok(),
_ => None,
}
} else {
None
};
let get_tooloption = |name: &str| {
tv.request
.options()
.get(name)
.map(|c| c.split(',').map(|s| s.to_string()).collect())
};
let profile = rt
.as_ref()
.and_then(|rt| rt.profile.clone())
.or_else(|| tv.request.options().get("profile").cloned());
let components = rt
.as_ref()
.and_then(|rt| rt.components.clone())
.or_else(|| get_tooloption("components"));
let targets = rt
.as_ref()
.and_then(|rt| rt.targets.clone())
.or_else(|| get_tooloption("targets"));
(profile, components, targets)
}
fn parse_idiomatic_file(path: &Path) -> Result<RustToolchain> {
let toml = file::read_to_string(path)?;
let toml = toml.parse::<toml::Value>()?;
let mut rt = RustToolchain::default();
if let Some(toolchain) = toml.get("toolchain") {
if let Some(channel) = toolchain.get("channel") {
rt.channel = channel.as_str().unwrap().to_string();
}
if let Some(profile) = toolchain.get("profile") {
rt.profile = Some(profile.as_str().unwrap().to_string());
}
if let Some(components) = toolchain.get("components") {
let components = components
.as_array()
.unwrap()
.iter()
.map(|c| c.as_str().unwrap().to_string())
.collect::<Vec<_>>();
if !components.is_empty() {
rt.components = Some(components);
}
}
if let Some(targets) = toolchain.get("targets") {
let targets = targets
.as_array()
.unwrap()
.iter()
.map(|c| c.as_str().unwrap().to_string())
.collect::<Vec<_>>();
if !targets.is_empty() {
rt.targets = Some(targets);
}
}
}
Ok(rt)
}
#[cfg(unix)]
const RUSTC_BIN: &str = "rustc";
#[cfg(windows)]
const RUSTC_BIN: &str = "rustc.exe";
#[cfg(unix)]
const RUSTUP_INIT_BIN: &str = "rustup-init";
#[cfg(windows)]
const RUSTUP_INIT_BIN: &str = "rustup-init.exe";
#[cfg(unix)]
const RUSTUP_BIN: &str = "rustup";
#[cfg(windows)]
const RUSTUP_BIN: &str = "rustup.exe";
#[cfg(unix)]
const CARGO_BIN: &str = "cargo";
#[cfg(windows)]
const CARGO_BIN: &str = "cargo.exe";
#[cfg(unix)]
fn rustup_url(_settings: &Settings) -> String {
"https://sh.rustup.rs".to_string()
}
#[cfg(windows)]
fn rustup_url(settings: &Settings) -> String {
let arch = match settings.arch() {
"x64" => "x86_64",
"arm64" => "aarch64",
other => other,
};
format!("https://win.rustup.rs/{arch}")
}
fn rustup_path() -> PathBuf {
dirs::CACHE.join("rust").join(RUSTUP_INIT_BIN)
}
fn rustup_home() -> PathBuf {
Settings::get()
.rust
.rustup_home
.clone()
.or(env::var_path("RUSTUP_HOME"))
.unwrap_or(dirs::HOME.join(".rustup"))
}
fn cargo_home() -> PathBuf {
Settings::get()
.rust
.cargo_home
.clone()
.or(env::var_path("CARGO_HOME"))
.unwrap_or(dirs::HOME.join(".cargo"))
}
fn cargo_bin() -> PathBuf {
cargo_bindir().join(CARGO_BIN)
}
fn cargo_bindir() -> PathBuf {
cargo_home().join("bin")
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/node.rs | src/plugins/core/node.rs | use crate::backend::VersionInfo;
use crate::backend::static_helpers::fetch_checksum_from_shasums;
use crate::backend::{Backend, VersionCacheManager, platform_target::PlatformTarget};
use crate::build_time::built_info;
use crate::cache::CacheManagerBuilder;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::file::{TarFormat, TarOptions};
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::ui::progress_report::SingleReport;
use crate::{env, file, gpg, hash, http, plugins};
use async_trait::async_trait;
use eyre::{Result, bail, ensure};
use serde_derive::Deserialize;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::OnceLock;
use tempfile::tempdir_in;
use tokio::sync::Mutex;
use url::Url;
use xx::regex;
#[derive(Debug)]
pub struct NodePlugin {
ba: Arc<BackendArg>,
}
enum FetchOutcome {
Downloaded,
NotFound,
}
impl NodePlugin {
pub fn new() -> Self {
Self {
ba: plugins::core::new_backend_arg("node").into(),
}
}
async fn fetch_binary(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
opts: &BuildOpts,
extract: impl FnOnce() -> Result<()>,
) -> Result<FetchOutcome> {
debug!("{:?}: we will fetch a precompiled version", self);
match self
.fetch_tarball(
ctx,
tv,
ctx.pr.as_ref(),
&opts.binary_tarball_url,
&opts.binary_tarball_path,
&opts.version,
)
.await
{
Ok(()) => {
debug!("{:?}: successfully downloaded node archive", self);
}
Err(e) if matches!(http::error_code(&e), Some(404)) => {
debug!("{:?}: precompiled node archive not found {e}", self);
return Ok(FetchOutcome::NotFound);
}
Err(e) => return Err(e),
};
let tarball_name = &opts.binary_tarball_name;
ctx.pr.set_message(format!("extract {tarball_name}"));
debug!("{:?}: extracting precompiled node", self);
if let Err(e) = extract() {
debug!("{:?}: extraction failed: {e}", self);
return Err(e);
}
debug!("{:?}: precompiled node extraction was successful", self);
Ok(FetchOutcome::Downloaded)
}
fn extract_zip(&self, opts: &BuildOpts, _ctx: &InstallContext) -> Result<()> {
let tmp_extract_path = tempdir_in(opts.install_path.parent().unwrap())?;
file::unzip(
&opts.binary_tarball_path,
tmp_extract_path.path(),
&Default::default(),
)?;
file::remove_all(&opts.install_path)?;
file::rename(
tmp_extract_path.path().join(slug(&opts.version)),
&opts.install_path,
)?;
Ok(())
}
async fn install_precompiled(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
opts: &BuildOpts,
) -> Result<()> {
match self
.fetch_binary(ctx, tv, opts, || {
file::untar(
&opts.binary_tarball_path,
&opts.install_path,
&TarOptions {
format: TarFormat::TarGz,
strip_components: 1,
pr: Some(ctx.pr.as_ref()),
..Default::default()
},
)?;
Ok(())
})
.await?
{
FetchOutcome::Downloaded => Ok(()),
FetchOutcome::NotFound => {
if Settings::get().node.compile != Some(false) {
self.install_compiling(ctx, tv, opts).await
} else {
bail!("precompiled node archive not found and compilation is disabled")
}
}
}
}
async fn install_windows(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
opts: &BuildOpts,
) -> Result<()> {
match self
.fetch_binary(ctx, tv, opts, || self.extract_zip(opts, ctx))
.await?
{
FetchOutcome::Downloaded => Ok(()),
FetchOutcome::NotFound => bail!("precompiled node archive not found (404)"),
}
}
async fn install_compiling(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
opts: &BuildOpts,
) -> Result<()> {
debug!("{:?}: we will fetch the source and compile", self);
let tarball_name = &opts.source_tarball_name;
self.fetch_tarball(
ctx,
tv,
ctx.pr.as_ref(),
&opts.source_tarball_url,
&opts.source_tarball_path,
&opts.version,
)
.await?;
ctx.pr.set_message(format!("extract {tarball_name}"));
file::remove_all(&opts.build_dir)?;
file::untar(
&opts.source_tarball_path,
opts.build_dir.parent().unwrap(),
&TarOptions {
format: TarFormat::TarGz,
pr: Some(ctx.pr.as_ref()),
..Default::default()
},
)?;
self.exec_configure(ctx, opts)?;
self.exec_make(ctx, opts)?;
self.exec_make_install(ctx, opts)?;
Ok(())
}
async fn fetch_tarball(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
pr: &dyn SingleReport,
url: &Url,
local: &Path,
version: &str,
) -> Result<()> {
let tarball_name = local.file_name().unwrap().to_string_lossy().to_string();
if local.exists() {
pr.set_message(format!("using previously downloaded {tarball_name}"));
} else {
pr.set_message(format!("download {tarball_name}"));
HTTP.download_file(url.clone(), local, Some(pr)).await?;
}
let platform_info = tv
.lock_platforms
.entry(self.get_platform_key())
.or_default();
platform_info.url = Some(url.to_string());
if *env::MISE_NODE_VERIFY && platform_info.checksum.is_none() {
platform_info.checksum = Some(self.get_checksum(ctx, local, version).await?);
}
self.verify_checksum(ctx, tv, local)?;
Ok(())
}
fn sh<'a>(&self, ctx: &'a InstallContext, opts: &BuildOpts) -> eyre::Result<CmdLineRunner<'a>> {
let mut cmd = CmdLineRunner::new("sh")
.prepend_path(opts.path.clone())?
.with_pr(ctx.pr.as_ref())
.current_dir(&opts.build_dir)
.arg("-c");
if let Some(cflags) = &*env::MISE_NODE_CFLAGS {
cmd = cmd.env("CFLAGS", cflags);
}
Ok(cmd)
}
fn exec_configure(&self, ctx: &InstallContext, opts: &BuildOpts) -> Result<()> {
self.sh(ctx, opts)?.arg(&opts.configure_cmd).execute()
}
fn exec_make(&self, ctx: &InstallContext, opts: &BuildOpts) -> Result<()> {
self.sh(ctx, opts)?.arg(&opts.make_cmd).execute()
}
fn exec_make_install(&self, ctx: &InstallContext, opts: &BuildOpts) -> Result<()> {
self.sh(ctx, opts)?.arg(&opts.make_install_cmd).execute()
}
async fn get_checksum(
&self,
ctx: &InstallContext,
tarball: &Path,
version: &str,
) -> Result<String> {
let tarball_name = tarball.file_name().unwrap().to_string_lossy().to_string();
let shasums_file = tarball.parent().unwrap().join("SHASUMS256.txt");
HTTP.download_file(
self.shasums_url(version)?,
&shasums_file,
Some(ctx.pr.as_ref()),
)
.await?;
if Settings::get().node.gpg_verify != Some(false) && version.starts_with("2") {
self.verify_with_gpg(ctx, &shasums_file, version).await?;
}
let shasums = file::read_to_string(&shasums_file)?;
let shasums = hash::parse_shasums(&shasums);
let shasum = shasums.get(&tarball_name).unwrap();
Ok(format!("sha256:{shasum}"))
}
async fn verify_with_gpg(
&self,
ctx: &InstallContext,
shasums_file: &Path,
v: &str,
) -> Result<()> {
if file::which_non_pristine("gpg").is_none() && Settings::get().node.gpg_verify.is_none() {
warn!("gpg not found, skipping verification");
return Ok(());
}
let sig_file = shasums_file.with_extension("asc");
let sig_url = format!("{}.sig", self.shasums_url(v)?);
if let Err(e) = HTTP
.download_file(sig_url, &sig_file, Some(ctx.pr.as_ref()))
.await
{
if matches!(http::error_code(&e), Some(404)) {
warn!("gpg signature not found, skipping verification");
return Ok(());
}
return Err(e);
}
gpg::add_keys_node(ctx)?;
CmdLineRunner::new("gpg")
.arg("--quiet")
.arg("--trust-model")
.arg("always")
.arg("--verify")
.arg(sig_file)
.arg(shasums_file)
.with_pr(ctx.pr.as_ref())
.execute()?;
Ok(())
}
fn node_path(&self, tv: &ToolVersion) -> PathBuf {
if cfg!(windows) {
tv.install_path().join("node.exe")
} else {
tv.install_path().join("bin").join("node")
}
}
fn npm_path(&self, tv: &ToolVersion) -> PathBuf {
if cfg!(windows) {
tv.install_path().join("npm.cmd")
} else {
tv.install_path().join("bin").join("npm")
}
}
fn corepack_path(&self, tv: &ToolVersion) -> PathBuf {
if cfg!(windows) {
tv.install_path().join("corepack.cmd")
} else {
tv.install_path().join("bin").join("corepack")
}
}
async fn install_default_packages(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
let body = file::read_to_string(&*env::MISE_NODE_DEFAULT_PACKAGES_FILE).unwrap_or_default();
for package in body.lines() {
let package = package.split('#').next().unwrap_or_default().trim();
if package.is_empty() {
continue;
}
pr.set_message(format!("install default package: {package}"));
let npm = self.npm_path(tv);
CmdLineRunner::new(npm)
.with_pr(pr)
.arg("install")
.arg("--global")
.arg(package)
.envs(config.env().await?)
.env(&*env::PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()?;
}
Ok(())
}
fn install_npm_shim(&self, tv: &ToolVersion) -> Result<()> {
file::remove_file(self.npm_path(tv)).ok();
file::write(self.npm_path(tv), include_str!("assets/node_npm_shim"))?;
file::make_executable(self.npm_path(tv))?;
Ok(())
}
fn enable_default_corepack_shims(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<()> {
pr.set_message("enable corepack shims".into());
let corepack = self.corepack_path(tv);
CmdLineRunner::new(corepack)
.with_pr(pr)
.arg("enable")
.env(&*env::PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()?;
Ok(())
}
async fn test_node(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
pr.set_message("node -v".into());
CmdLineRunner::new(self.node_path(tv))
.with_pr(pr)
.arg("-v")
.envs(config.env().await?)
.execute()
}
async fn test_npm(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
pr.set_message("npm -v".into());
CmdLineRunner::new(self.npm_path(tv))
.with_pr(pr)
.arg("-v")
.envs(config.env().await?)
.env(&*env::PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()
}
fn shasums_url(&self, v: &str) -> Result<Url> {
// let url = MISE_NODE_MIRROR_URL.join(&format!("v{v}/SHASUMS256.txt.asc"))?;
let settings = Settings::get();
let url = settings
.node
.mirror_url()
.join(&format!("v{v}/SHASUMS256.txt"))?;
Ok(url)
}
}
#[async_trait]
impl Backend for NodePlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
let mut features = vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}];
// GPG verification is available for Node.js v20+ when gpg is installed
if Settings::get().node.gpg_verify != Some(false) {
features.push(SecurityFeature::Gpg);
}
features
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let settings = Settings::get();
let base = Settings::get().node.mirror_url();
let versions = HTTP_FETCH
.json::<Vec<NodeVersion>, _>(base.join("index.json")?)
.await?
.into_iter()
.filter(|v| {
if let Some(flavor) = &settings.node.flavor {
v.files
.iter()
.any(|f| f == &format!("{}-{}-{}", os(), arch(&settings), flavor))
} else {
true
}
})
.map(|v| {
let version = if regex!(r"^v\d+\.").is_match(&v.version) {
v.version.strip_prefix('v').unwrap().to_string()
} else {
v.version
};
VersionInfo {
version,
created_at: v.date,
..Default::default()
}
})
.rev()
.collect();
Ok(versions)
}
fn get_aliases(&self) -> Result<BTreeMap<String, String>> {
let aliases = [
("lts/argon", "4"),
("lts/boron", "6"),
("lts/carbon", "8"),
("lts/dubnium", "10"),
("lts/erbium", "12"),
("lts/fermium", "14"),
("lts/gallium", "16"),
("lts/hydrogen", "18"),
("lts/iron", "20"),
("lts/jod", "22"),
("lts/krypton", "24"),
("lts-argon", "4"),
("lts-boron", "6"),
("lts-carbon", "8"),
("lts-dubnium", "10"),
("lts-erbium", "12"),
("lts-fermium", "14"),
("lts-gallium", "16"),
("lts-hydrogen", "18"),
("lts-iron", "20"),
("lts-jod", "22"),
("lts-krypton", "24"),
("lts", "24"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Ok(aliases)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".node-version".into(), ".nvmrc".into()])
}
async fn parse_idiomatic_file(&self, path: &Path) -> Result<String> {
let body = file::read_to_string(path)?;
// strip comments
let body = body.split('#').next().unwrap_or_default().to_string();
// trim "v" prefix
let body = body.trim().strip_prefix('v').unwrap_or(&body);
// replace lts/* with lts
let body = body.replace("lts/*", "lts");
Ok(body)
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
ensure!(
tv.version != "latest",
"version should not be 'latest' for node, something is wrong"
);
let settings = Settings::get();
let opts = BuildOpts::new(ctx, &tv).await?;
trace!("node build opts: {:#?}", opts);
ctx.pr.start_operations(3);
if cfg!(windows) {
self.install_windows(ctx, &mut tv, &opts).await?;
} else if settings.node.compile == Some(true) {
self.install_compiling(ctx, &mut tv, &opts).await?;
} else {
self.install_precompiled(ctx, &mut tv, &opts).await?;
}
debug!("{:?}: checking installation is working as expected", self);
self.test_node(&ctx.config, &tv, ctx.pr.as_ref()).await?;
if !cfg!(windows) {
self.install_npm_shim(&tv)?;
}
self.test_npm(&ctx.config, &tv, ctx.pr.as_ref()).await?;
if let Err(err) = self
.install_default_packages(&ctx.config, &tv, ctx.pr.as_ref())
.await
{
warn!("failed to install default npm packages: {err:#}");
}
if *env::MISE_NODE_COREPACK && self.corepack_path(&tv).exists() {
self.enable_default_corepack_shims(&tv, ctx.pr.as_ref())?;
}
Ok(tv)
}
#[cfg(windows)]
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<Vec<PathBuf>> {
Ok(vec![tv.install_path()])
}
fn get_remote_version_cache(&self) -> Arc<Mutex<VersionCacheManager>> {
static CACHE: OnceLock<Arc<Mutex<VersionCacheManager>>> = OnceLock::new();
CACHE
.get_or_init(|| {
Mutex::new(
CacheManagerBuilder::new(
self.ba().cache_path.join("remote_versions.msgpack.z"),
)
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.with_cache_key(Settings::get().node.mirror_url.clone().unwrap_or_default())
.with_cache_key(Settings::get().node.flavor.clone().unwrap_or_default())
.build(),
)
.into()
})
.clone()
}
// ========== Lockfile Metadata Fetching Implementation ==========
async fn get_tarball_url(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<Option<String>> {
let version = &tv.version;
let settings = Settings::get();
// Build platform-specific filename like Node.js does
let slug = self.build_platform_slug(version, target);
let filename = if target.os_name() == "windows" {
format!("{slug}.zip")
} else {
format!("{slug}.tar.gz")
};
// Use Node.js mirror URL to construct download URL
let url = settings
.node
.mirror_url()
.join(&format!("v{version}/{filename}"))
.map_err(|e| eyre::eyre!("Failed to construct Node.js download URL: {e}"))?;
Ok(Some(url.to_string()))
}
fn resolve_lockfile_options(
&self,
_request: &ToolRequest,
target: &PlatformTarget,
) -> BTreeMap<String, String> {
let mut opts = BTreeMap::new();
let settings = Settings::get();
let is_current_platform = target.is_current();
// Only include compile option if true (non-default)
let compile = if is_current_platform {
settings.node.compile.unwrap_or(false)
} else {
false
};
if compile {
opts.insert("compile".to_string(), "true".to_string());
}
// Flavor affects which binary variant is downloaded (only if set)
if is_current_platform && let Some(flavor) = settings.node.flavor.clone() {
opts.insert("flavor".to_string(), flavor);
}
opts
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let version = &tv.version;
let settings = Settings::get();
// Build platform-specific filename
let slug = self.build_platform_slug(version, target);
let filename = if target.os_name() == "windows" {
format!("{slug}.zip")
} else {
format!("{slug}.tar.gz")
};
// Build download URL
let url = settings
.node
.mirror_url()
.join(&format!("v{version}/{filename}"))
.map_err(|e| eyre::eyre!("Failed to construct Node.js download URL: {e}"))?;
// Fetch SHASUMS256.txt to get checksum without downloading the tarball
let shasums_url = settings
.node
.mirror_url()
.join(&format!("v{version}/SHASUMS256.txt"))?;
let checksum = fetch_checksum_from_shasums(shasums_url.as_str(), &filename).await;
Ok(PlatformInfo {
url: Some(url.to_string()),
checksum,
size: None,
url_api: None,
})
}
}
impl NodePlugin {
/// Map OS name from Platform to Node.js convention
fn map_os(os_name: &str) -> &str {
match os_name {
"macos" => "darwin",
"linux" => "linux",
"windows" => "win",
other => other,
}
}
/// Map arch name from Platform to Node.js convention
fn map_arch(arch_name: &str) -> &str {
match arch_name {
"x86" => "x86",
"x64" => "x64",
"arm" => "armv7l",
"arm64" => "arm64",
"aarch64" => "arm64",
"loongarch64" => "loong64",
"riscv64" => "riscv64",
other => other,
}
}
/// Build platform-specific slug for Node.js downloads
/// This mirrors the logic from BuildOpts::new() and slug() function
fn build_platform_slug(&self, version: &str, target: &PlatformTarget) -> String {
let settings = Settings::get();
let os = Self::map_os(target.os_name());
let arch = Self::map_arch(target.arch_name());
// Flavor (like "glibc") only applies to the current Linux platform
// Don't apply it to non-current platforms during cross-platform locking
if target.is_current()
&& target.os_name() == "linux"
&& let Some(flavor) = &settings.node.flavor
{
return format!("node-v{version}-{os}-{arch}-{flavor}");
}
format!("node-v{version}-{os}-{arch}")
}
}
#[derive(Debug)]
struct BuildOpts {
version: String,
path: Vec<PathBuf>,
install_path: PathBuf,
build_dir: PathBuf,
configure_cmd: String,
make_cmd: String,
make_install_cmd: String,
source_tarball_name: String,
source_tarball_path: PathBuf,
source_tarball_url: Url,
binary_tarball_name: String,
binary_tarball_path: PathBuf,
binary_tarball_url: Url,
}
impl BuildOpts {
async fn new(ctx: &InstallContext, tv: &ToolVersion) -> Result<Self> {
let v = &tv.version;
let install_path = tv.install_path();
let source_tarball_name = format!("node-v{v}.tar.gz");
let slug = slug(v);
#[cfg(windows)]
let binary_tarball_name = format!("{slug}.zip");
#[cfg(not(windows))]
let binary_tarball_name = format!("{slug}.tar.gz");
Ok(Self {
version: v.clone(),
path: ctx.ts.list_paths(&ctx.config).await,
build_dir: env::MISE_TMP_DIR.join(format!("node-v{v}")),
configure_cmd: configure_cmd(&install_path),
make_cmd: make_cmd(),
make_install_cmd: make_install_cmd(),
source_tarball_path: tv.download_path().join(&source_tarball_name),
source_tarball_url: Settings::get()
.node
.mirror_url()
.join(&format!("v{v}/{source_tarball_name}"))?,
source_tarball_name,
binary_tarball_path: tv.download_path().join(&binary_tarball_name),
binary_tarball_url: Settings::get()
.node
.mirror_url()
.join(&format!("v{v}/{binary_tarball_name}"))?,
binary_tarball_name,
install_path,
})
}
}
fn configure_cmd(install_path: &Path) -> String {
let mut configure_cmd = format!("./configure --prefix={}", install_path.display());
if *env::MISE_NODE_NINJA {
configure_cmd.push_str(" --ninja");
}
if let Some(opts) = &*env::MISE_NODE_CONFIGURE_OPTS {
configure_cmd.push_str(&format!(" {opts}"));
}
configure_cmd
}
fn make_cmd() -> String {
let mut make_cmd = env::MISE_NODE_MAKE.to_string();
if let Some(concurrency) = *env::MISE_NODE_CONCURRENCY {
make_cmd.push_str(&format!(" -j{concurrency}"));
}
if let Some(opts) = &*env::MISE_NODE_MAKE_OPTS {
make_cmd.push_str(&format!(" {opts}"));
}
make_cmd
}
fn make_install_cmd() -> String {
let mut make_install_cmd = format!("{} install", &*env::MISE_NODE_MAKE);
if let Some(opts) = &*env::MISE_NODE_MAKE_INSTALL_OPTS {
make_install_cmd.push_str(&format!(" {opts}"));
}
make_install_cmd
}
fn os() -> &'static str {
NodePlugin::map_os(built_info::CFG_OS)
}
fn arch(settings: &Settings) -> &str {
let arch = settings.arch();
// Special handling for ARM with target features
if arch == "arm" && cfg!(target_feature = "v6") {
return "armv6l";
}
NodePlugin::map_arch(arch)
}
fn slug(v: &str) -> String {
let settings = Settings::get();
if let Some(flavor) = &settings.node.flavor {
format!("node-v{v}-{}-{}-{flavor}", os(), arch(&settings))
} else {
format!("node-v{v}-{}-{}", os(), arch(&settings))
}
}
#[derive(Debug, Deserialize)]
struct NodeVersion {
version: String,
date: Option<String>,
files: Vec<String>,
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/go.rs | src/plugins/core/go.rs | use std::path::{Path, PathBuf};
use std::{collections::BTreeMap, sync::Arc};
use crate::Result;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::fetch_checksum_from_file;
use crate::backend::{Backend, VersionInfo};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::file::{TarFormat, TarOptions};
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{env, file, github, plugins};
use async_trait::async_trait;
use itertools::Itertools;
use tempfile::tempdir_in;
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct GoPlugin {
ba: Arc<BackendArg>,
}
impl GoPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("go")),
}
}
// Represents go binary path
fn go_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join("go")
}
// Represents GOPATH environment variable
fn gopath(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("packages")
}
// Represents GOROOT environment variable
fn goroot(&self, tv: &ToolVersion) -> PathBuf {
let old_path = tv.install_path().join("go");
if old_path.exists() {
return old_path;
}
tv.install_path()
}
// Represents GOBIN environment variable
fn gobin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin")
}
fn install_default_packages(
&self,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> eyre::Result<()> {
let settings = Settings::get();
let default_packages_file = file::replace_path(&settings.go_default_packages_file);
let body = file::read_to_string(default_packages_file).unwrap_or_default();
for package in body.lines() {
let package = package.split('#').next().unwrap_or_default().trim();
if package.is_empty() {
continue;
}
pr.set_message(format!("install default package: {package}"));
let package = if package.contains('@') {
package.to_string()
} else {
format!("{package}@latest")
};
CmdLineRunner::new(self.go_bin(tv))
.with_pr(pr)
.arg("install")
.arg(package)
.envs(self._exec_env(tv)?)
.execute()?;
}
Ok(())
}
fn test_go(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> eyre::Result<()> {
pr.set_message("go version".into());
CmdLineRunner::new(self.go_bin(tv))
// run the command in the install path to prevent issues with go.mod version mismatch
.current_dir(tv.install_path())
.with_pr(pr)
.arg("version")
.execute()
}
async fn download(&self, tv: &mut ToolVersion, pr: &dyn SingleReport) -> eyre::Result<PathBuf> {
let settings = Settings::get();
let tarball_url = Arc::new(
self.get_tarball_url(tv, &PlatformTarget::from_current())
.await?
.ok_or_else(|| eyre::eyre!("Failed to get go tarball URL"))?,
);
let filename = tarball_url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
let tarball_url_ = tarball_url.clone();
let checksum_handle = tokio::spawn(async move {
let checksum_url = format!("{}.sha256", &tarball_url_);
HTTP.get_text(checksum_url).await
});
pr.set_message(format!("download {filename}"));
HTTP.download_file(&*tarball_url, &tarball_path, Some(pr))
.await?;
if !settings.go_skip_checksum {
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(tarball_url.to_string());
if platform_info.checksum.is_none() {
let checksum = checksum_handle.await.unwrap()?;
platform_info.checksum = Some(format!("sha256:{checksum}"));
}
}
Ok(tarball_path)
}
fn install(
&self,
tv: &ToolVersion,
pr: &dyn SingleReport,
tarball_path: &Path,
) -> eyre::Result<()> {
let tarball = tarball_path
.file_name()
.unwrap_or_default()
.to_string_lossy();
pr.set_message(format!("extract {tarball}"));
let tmp_extract_path = tempdir_in(tv.install_path().parent().unwrap())?;
if cfg!(windows) {
file::unzip(tarball_path, tmp_extract_path.path(), &Default::default())?;
} else {
file::untar(
tarball_path,
tmp_extract_path.path(),
&TarOptions {
format: TarFormat::TarGz,
pr: Some(pr),
..Default::default()
},
)?;
}
file::remove_all(tv.install_path())?;
file::rename(tmp_extract_path.path().join("go"), tv.install_path())?;
Ok(())
}
fn verify(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> eyre::Result<()> {
self.test_go(tv, pr)?;
if let Err(err) = self.install_default_packages(tv, pr) {
warn!("failed to install default go packages: {err:#}");
}
let settings = Settings::get();
if settings.go_set_gopath {
warn!("setting go_set_gopath is deprecated");
}
Ok(())
}
fn _exec_env(&self, tv: &ToolVersion) -> eyre::Result<BTreeMap<String, String>> {
let mut map = BTreeMap::new();
let mut set = |k: &str, v: PathBuf| {
map.insert(k.to_string(), v.to_string_lossy().to_string());
};
let settings = Settings::get();
let gobin = settings.go_set_gobin;
let gobin_env_is_set = env::PRISTINE_ENV.contains_key("GOBIN");
if gobin == Some(true) || (gobin.is_none() && !gobin_env_is_set) {
set("GOBIN", self.gobin(tv));
}
if settings.go_set_goroot {
set("GOROOT", self.goroot(tv));
}
if settings.go_set_gopath {
set("GOPATH", self.gopath(tv));
}
Ok(map)
}
}
#[async_trait]
impl Backend for GoPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}]
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
// Extract repo name (e.g., "golang/go") from the configured URL
// The go_repo setting is like "https://github.com/golang/go"
let settings = Settings::get();
let repo = settings
.go_repo
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_start_matches("github.com/")
.trim_end_matches(".git")
.trim_end_matches('/');
// Go uses tags, not releases. When MISE_LIST_ALL_VERSIONS is set,
// we fetch tags with dates (slower). Otherwise, use fast method without dates.
let versions: Vec<VersionInfo> = if *env::MISE_LIST_ALL_VERSIONS {
// Slow path: fetch tags with commit dates for versions host
github::list_tags_with_dates(repo)
.await?
.into_iter()
.filter_map(|t| t.name.strip_prefix("go").map(|v| (v.to_string(), t.date)))
// remove beta and rc versions
.filter(|(v, _)| !regex!(r"(beta|rc)[0-9]*$").is_match(v))
.unique_by(|(v, _)| v.clone())
.sorted_by_cached_key(|(v, _)| (Versioning::new(v), v.to_string()))
.map(|(version, created_at)| VersionInfo {
version,
created_at,
..Default::default()
})
.collect()
} else {
// Fast path: use git ls-remote to get all go tags efficiently
// We can't use github::list_tags here because golang/go has 500+ tags
// and the "go1.x" version tags aren't on the first page of API results
plugins::core::run_fetch_task_with_timeout(move || {
let output = cmd!(
"git",
"ls-remote",
"--tags",
"--refs",
&Settings::get().go_repo,
"go*"
)
.read()?;
let versions: Vec<VersionInfo> = output
.lines()
.filter_map(|line| line.split("/go").last())
.filter(|s| !s.is_empty())
// remove beta and rc versions
.filter(|s| !regex!(r"(beta|rc)[0-9]*$").is_match(s))
.map(|s| s.to_string())
.unique()
.sorted_by_cached_key(|v| (Versioning::new(v), v.to_string()))
.map(|version| VersionInfo {
version,
..Default::default()
})
.collect();
Ok(versions)
})?
};
Ok(versions)
}
async fn idiomatic_filenames(&self) -> eyre::Result<Vec<String>> {
Ok(vec![".go-version".into()])
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
ctx.pr.start_operations(3);
let tarball_path = self.download(&mut tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(&tv, ctx.pr.as_ref(), &tarball_path)?;
self.verify(&tv, ctx.pr.as_ref())?;
Ok(tv)
}
async fn uninstall_version_impl(
&self,
_config: &Arc<Config>,
_pr: &dyn SingleReport,
tv: &ToolVersion,
) -> eyre::Result<()> {
let gopath = self.gopath(tv);
if gopath.exists() {
cmd!("chmod", "-R", "u+wx", gopath).run()?;
}
Ok(())
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<Vec<PathBuf>> {
if let ToolRequest::System { .. } = tv.request {
return Ok(vec![]);
}
// goroot/bin must always be included, irrespective of MISE_GO_SET_GOROOT
Ok(vec![self.gobin(tv)])
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
self._exec_env(tv)
}
async fn get_tarball_url(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<Option<String>> {
let settings = Settings::get();
let platform = match target.os_name() {
"macos" => "darwin",
"linux" => "linux",
"windows" => "windows",
_ => "linux",
};
let arch = match target.arch_name() {
"x64" => "amd64",
"arm64" => "arm64",
"arm" => "armv6l",
"riscv64" => "riscv64",
other => other,
};
let ext = if target.os_name() == "windows" {
"zip"
} else {
"tar.gz"
};
Ok(Some(format!(
"{}/go{}.{}-{}.{}",
&settings.go_download_mirror, tv.version, platform, arch, ext
)))
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let settings = Settings::get();
// Build tarball URL
let url = self
.get_tarball_url(tv, target)
.await?
.ok_or_else(|| eyre::eyre!("Failed to get go tarball URL"))?;
// Go provides .sha256 files alongside each tarball
let checksum = if !settings.go_skip_checksum {
let checksum_url = format!("{}.sha256", &url);
fetch_checksum_from_file(&checksum_url, "sha256").await
} else {
None
};
Ok(PlatformInfo {
url: Some(url),
checksum,
size: None,
url_api: None,
})
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/deno.rs | src/plugins/core/deno.rs | use std::collections::BTreeMap;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use serde::Deserialize;
use versions::Versioning;
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::fetch_checksum_from_file;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::Config;
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{file, plugins};
#[derive(Debug)]
pub struct DenoPlugin {
ba: Arc<BackendArg>,
}
impl DenoPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("deno")),
}
}
fn deno_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join(if cfg!(target_os = "windows") {
"bin/deno.exe"
} else {
"bin/deno"
})
}
fn test_deno(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<()> {
pr.set_message("deno -V".into());
CmdLineRunner::new(self.deno_bin(tv))
.with_pr(pr)
.arg("-V")
.execute()
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let url = self
.get_tarball_url(tv, &PlatformTarget::from_current())
.await?
.ok_or_else(|| eyre::eyre!("Failed to get deno tarball URL"))?;
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
pr.set_message(format!("download {filename}"));
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
Ok(tarball_path)
}
fn install(&self, tv: &ToolVersion, pr: &dyn SingleReport, tarball_path: &Path) -> Result<()> {
let filename = tarball_path.file_name().unwrap().to_string_lossy();
pr.set_message(format!("extract {filename}"));
file::remove_all(tv.install_path())?;
file::create_dir_all(tv.install_path().join("bin"))?;
file::unzip(tarball_path, &tv.download_path(), &Default::default())?;
file::rename(
tv.download_path().join(if cfg!(target_os = "windows") {
"deno.exe"
} else {
"deno"
}),
self.deno_bin(tv),
)?;
file::make_executable(self.deno_bin(tv))?;
Ok(())
}
fn verify(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<()> {
self.test_deno(tv, pr)
}
}
#[async_trait]
impl Backend for DenoPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}]
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions: DenoVersions = HTTP_FETCH.json("https://deno.com/versions.json").await?;
let versions = versions
.cli
.into_iter()
.filter(|v| v.starts_with('v'))
.map(|v| VersionInfo {
version: v.trim_start_matches('v').to_string(),
..Default::default()
})
.unique_by(|v| v.version.clone())
.sorted_by_cached_key(|v| (Versioning::new(&v.version), v.version.clone()))
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".deno-version".into()])
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
ctx.pr.start_operations(3);
let tarball_path = self.download(&tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(&tv, ctx.pr.as_ref(), &tarball_path)?;
self.verify(&tv, ctx.pr.as_ref())?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
if let ToolRequest::System { .. } = tv.request {
return Ok(vec![]);
}
let bin_paths = vec![
tv.install_path().join("bin"),
tv.install_path().join(".deno/bin"),
];
Ok(bin_paths)
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let map = BTreeMap::from([(
"DENO_INSTALL_ROOT".into(),
tv.install_path().join(".deno").to_string_lossy().into(),
)]);
Ok(map)
}
async fn get_tarball_url(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<Option<String>> {
let arch = match target.arch_name() {
"x64" => "x86_64",
"arm64" => "aarch64",
other => other,
};
let os = match target.os_name() {
"macos" => "apple-darwin",
"linux" => "unknown-linux-gnu",
"windows" => "pc-windows-msvc",
_ => "unknown-linux-gnu",
};
Ok(Some(format!(
"https://dl.deno.land/release/v{}/deno-{}-{}.zip",
tv.version, arch, os
)))
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let url = self
.get_tarball_url(tv, target)
.await?
.ok_or_else(|| eyre::eyre!("Failed to get deno tarball URL"))?;
// Deno provides .sha256sum files alongside each zip
let checksum_url = format!("{}.sha256sum", &url);
let checksum = fetch_checksum_from_file(&checksum_url, "sha256").await;
Ok(PlatformInfo {
url: Some(url),
checksum,
size: None,
url_api: None,
})
}
}
#[derive(Debug, Deserialize)]
struct DenoVersions {
cli: Vec<String>,
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/python.rs | src/plugins/core/python.rs | use crate::backend::platform_target::PlatformTarget;
use crate::backend::{Backend, VersionCacheManager, VersionInfo};
use crate::build_time::built_info;
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::file::{TarOptions, display_path};
use crate::git::{CloneOptions, Git};
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{Result, lock_file::LockFile};
use crate::{dirs, file, plugins, sysconfig};
use async_trait::async_trait;
use eyre::{bail, eyre};
use flate2::read::GzDecoder;
use itertools::Itertools;
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::LazyLock as Lazy;
use std::sync::{Arc, OnceLock};
use tokio::sync::Mutex;
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct PythonPlugin {
ba: Arc<BackendArg>,
}
pub fn python_path(tv: &ToolVersion) -> PathBuf {
if cfg!(windows) {
tv.install_path().join("python.exe")
} else {
tv.install_path().join("bin/python")
}
}
impl PythonPlugin {
pub fn new() -> Self {
let ba = Arc::new(plugins::core::new_backend_arg("python"));
Self { ba }
}
fn python_build_path(&self) -> PathBuf {
self.ba.cache_path.join("pyenv")
}
fn python_build_bin(&self) -> PathBuf {
self.python_build_path()
.join("plugins/python-build/bin/python-build")
}
fn lock_pyenv(&self) -> Result<fslock::LockFile> {
LockFile::new(&self.python_build_path())
.with_callback(|l| {
trace!("install_or_update_pyenv {}", l.display());
})
.lock()
}
fn install_or_update_python_build(&self, ctx: Option<&InstallContext>) -> eyre::Result<()> {
ensure_not_windows()?;
let _lock = self.lock_pyenv();
if self.python_build_bin().exists() {
self.update_python_build()
} else {
self.install_python_build(ctx)
}
}
fn install_python_build(&self, ctx: Option<&InstallContext>) -> eyre::Result<()> {
if self.python_build_bin().exists() {
return Ok(());
}
let python_build_path = self.python_build_path();
debug!("Installing python-build to {}", python_build_path.display());
file::remove_all(&python_build_path)?;
file::create_dir_all(self.python_build_path().parent().unwrap())?;
let git = Git::new(self.python_build_path());
let pr = ctx.map(|ctx| ctx.pr.as_ref());
let mut clone_options = CloneOptions::default();
if let Some(pr) = pr {
clone_options = clone_options.pr(pr);
}
git.clone(&Settings::get().python.pyenv_repo, clone_options)?;
Ok(())
}
fn update_python_build(&self) -> eyre::Result<()> {
// TODO: do not update if recently updated
debug!(
"Updating python-build in {}",
self.python_build_path().display()
);
let pyenv_path = self.python_build_path();
let git = Git::new(pyenv_path.clone());
match plugins::core::run_fetch_task_with_timeout(move || git.update(None)) {
Ok(_) => Ok(()),
Err(err) => {
warn!(
"failed to update python-build repo ({}), attempting self-repair by recloning",
err
);
// The cached pyenv repo can get corrupted (e.g. unable to read sha1 file).
// Repair by removing the cache and performing a fresh clone.
file::remove_all(&pyenv_path)?;
// Safe to reinstall without a context; progress reporting is optional here.
self.install_python_build(None)
}
}
}
async fn fetch_precompiled_remote_versions(
&self,
) -> eyre::Result<&Vec<(String, String, String)>> {
static PRECOMPILED_CACHE: Lazy<CacheManager<Vec<(String, String, String)>>> =
Lazy::new(|| {
CacheManagerBuilder::new(dirs::CACHE.join("python").join("precompiled.msgpack.z"))
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.with_cache_key(python_precompiled_platform())
.build()
});
PRECOMPILED_CACHE
.get_or_try_init_async(async || {
let settings = Settings::get();
let url_path = python_precompiled_url_path(&settings);
let rsp = HTTP_FETCH
.get_bytes(format!("https://mise-versions.jdx.dev/tools/{url_path}"))
.await?;
let mut decoder = GzDecoder::new(rsp.as_ref());
let mut raw = String::new();
decoder.read_to_string(&mut raw)?;
let platform = python_precompiled_platform();
// order by version, whether it is a release candidate, date, and in the preferred order of install types
let rank = |v: &str, date: &str, name: &str| {
let rc = if regex!(r"rc\d+$").is_match(v) { 0 } else { 1 };
let v = Versioning::new(v);
let date = date.parse::<i64>().unwrap_or_default();
let install_type = if name.contains("install_only_stripped") {
0
} else if name.contains("install_only") {
1
} else {
2
};
(v, rc, -date, install_type)
};
let versions = raw
.lines()
.filter(|v| v.contains(&platform))
.flat_map(|v| {
// cpython-3.9.5+20210525 or cpython-3.9.5rc3+20210525
regex!(r"^cpython-(\d+\.\d+\.[\da-z]+)\+(\d+).*")
.captures(v)
.map(|caps| {
(
caps[1].to_string(),
caps[2].to_string(),
caps[0].to_string(),
)
})
})
// multiple dates can have the same version, so sort by date and remove duplicates by unique
.sorted_by_cached_key(|(v, date, name)| rank(v, date, name))
.unique_by(|(v, _, _)| v.to_string())
.collect_vec();
Ok(versions)
})
.await
}
async fn install_precompiled(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
) -> eyre::Result<()> {
let precompiled_versions = self.fetch_precompiled_remote_versions().await?;
let precompile_info = precompiled_versions
.iter()
.rev()
.find(|(v, _, _)| &tv.version == v);
let (tag, filename) = match precompile_info {
Some((_, tag, filename)) => (tag, filename),
None => {
if cfg!(windows) || Settings::get().python.compile == Some(false) {
if !cfg!(windows) {
hint!(
"python_compile",
"To compile python from source, run",
"mise settings python.compile=1"
);
}
let platform = python_precompiled_platform();
bail!("no precompiled python found for {tv} on {platform}");
}
let available = precompiled_versions.iter().map(|(v, _, _)| v).collect_vec();
if available.is_empty() {
debug!("no precompiled python found for {}", tv.version);
} else {
warn!(
"no precompiled python found for {}, force mise to use a precompiled version with `mise settings set python.compile false`",
tv.version
);
}
trace!(
"available precompiled versions: {}",
available.into_iter().join(", ")
);
return self.install_compiled(ctx, tv).await;
}
};
if cfg!(unix) {
hint!(
"python_precompiled",
"installing precompiled python from astral-sh/python-build-standalone\n\
if you experience issues with this python (e.g.: running poetry), switch to python-build by running",
"mise settings python.compile=1"
);
}
let url = format!(
"https://github.com/astral-sh/python-build-standalone/releases/download/{tag}/{filename}"
);
let filename = url.split('/').next_back().unwrap();
let install = tv.install_path();
let download = tv.download_path();
let tarball_path = download.join(filename);
ctx.pr.set_message(format!("download {filename}"));
HTTP.download_file(&url, &tarball_path, Some(ctx.pr.as_ref()))
.await?;
file::remove_all(&install)?;
file::untar(
&tarball_path,
&install,
&TarOptions {
strip_components: 1,
pr: Some(ctx.pr.as_ref()),
..Default::default()
},
)?;
if !install.join("bin").exists() {
// debug builds of indygreg binaries have a different structure
for entry in file::ls(&install.join("install"))? {
let filename = entry.file_name().unwrap();
file::remove_all(install.join(filename))?;
file::rename(&entry, install.join(filename))?;
}
}
let re_digits = regex!(r"\d+");
let version_parts = tv.version.split('.').collect_vec();
let major = re_digits
.find(version_parts[0])
.and_then(|m| m.as_str().parse().ok());
let minor = re_digits
.find(version_parts[1])
.and_then(|m| m.as_str().parse().ok());
let suffix = version_parts
.get(2)
.map(|s| re_digits.replace(s, "").to_string());
if cfg!(unix) {
if let (Some(major), Some(minor), Some(suffix)) = (major, minor, suffix) {
if tv.request.options().get("patch_sysconfig") != Some(&"false".to_string()) {
sysconfig::update_sysconfig(&install, major, minor, &suffix)?;
}
} else {
debug!("failed to update sysconfig with version {}", tv.version);
}
}
if !install.join("bin").join("python").exists() {
#[cfg(unix)]
file::make_symlink(&install.join("bin/python3"), &install.join("bin/python"))?;
}
Ok(())
}
async fn install_compiled(&self, ctx: &InstallContext, tv: &ToolVersion) -> eyre::Result<()> {
self.install_or_update_python_build(Some(ctx))?;
if matches!(&tv.request, ToolRequest::Ref { .. }) {
return Err(eyre!("Ref versions not supported for python"));
}
ctx.pr.set_message("python-build".into());
let mut cmd = CmdLineRunner::new(self.python_build_bin())
.with_pr(ctx.pr.as_ref())
.arg(tv.version.as_str())
.arg(tv.install_path())
.env("PIP_REQUIRE_VIRTUALENV", "false")
.envs(ctx.config.env().await?);
if Settings::get().verbose {
cmd = cmd.arg("--verbose");
}
if let Some(patch_url) = &Settings::get().python.patch_url {
ctx.pr
.set_message(format!("with patch file from: {patch_url}"));
let patch = HTTP.get_text(patch_url).await?;
cmd = cmd.arg("--patch").stdin_string(patch)
}
if let Some(patches_dir) = &Settings::get().python.patches_directory {
let patch_file = patches_dir.join(format!("{}.patch", &tv.version));
if patch_file.exists() {
ctx.pr
.set_message(format!("with patch file: {}", patch_file.display()));
let contents = file::read_to_string(&patch_file)?;
cmd = cmd.arg("--patch").stdin_string(contents);
} else {
warn!("patch file not found: {}", patch_file.display());
}
}
cmd.execute()?;
Ok(())
}
async fn install_default_packages(
&self,
config: &Arc<Config>,
packages_file: &Path,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> eyre::Result<()> {
if !packages_file.exists() {
return Ok(());
}
pr.set_message("install default packages".into());
CmdLineRunner::new(tv.install_path().join("bin/python"))
.with_pr(pr)
.arg("-m")
.arg("pip")
.arg("install")
.arg("--upgrade")
.arg("-r")
.arg(packages_file)
.env("PIP_REQUIRE_VIRTUALENV", "false")
.envs(config.env().await?)
.execute()
}
async fn get_virtualenv(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: Option<&dyn SingleReport>,
) -> eyre::Result<Option<PathBuf>> {
if let Some(virtualenv) = tv.request.options().get("virtualenv") {
if !Settings::get().experimental {
warn!(
"please enable experimental mode with `mise settings experimental=true` \
to use python virtualenv activation"
);
}
let mut virtualenv: PathBuf = file::replace_path(Path::new(virtualenv));
if !virtualenv.is_absolute() {
// TODO: use the path of the config file that specified python, not the top one like this
if let Some(project_root) = &config.project_root {
virtualenv = project_root.join(virtualenv);
}
}
if !virtualenv.exists() {
if Settings::get().python.venv_auto_create {
info!("setting up virtualenv at: {}", virtualenv.display());
let mut cmd = CmdLineRunner::new(python_path(tv))
.arg("-m")
.arg("venv")
.arg(&virtualenv)
.envs(config.env().await?);
if let Some(pr) = pr {
cmd = cmd.with_pr(pr);
}
cmd.execute()?;
} else {
warn!(
"no venv found at: {p}\n\n\
To create a virtualenv manually, run:\n\
python -m venv {p}",
p = display_path(&virtualenv)
);
return Ok(None);
}
}
// TODO: enable when it is more reliable
// self.check_venv_python(&virtualenv, tv)?;
Ok(Some(virtualenv))
} else {
Ok(None)
}
}
// fn check_venv_python(&self, virtualenv: &Path, tv: &ToolVersion) -> eyre::Result<()> {
// let symlink = virtualenv.join("bin/python");
// let target = python_path(tv);
// let symlink_target = symlink.read_link().unwrap_or_default();
// ensure!(
// symlink_target == target,
// "expected venv {} to point to {}.\nTry deleting the venv at {}.",
// display_path(&symlink),
// display_path(&target),
// display_path(virtualenv)
// );
// Ok(())
// }
async fn test_python(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> eyre::Result<()> {
pr.set_message("python --version".into());
CmdLineRunner::new(python_path(tv))
.with_pr(pr)
.arg("--version")
.envs(config.env().await?)
.execute()
}
}
#[async_trait]
impl Backend for PythonPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
if cfg!(windows) || Settings::get().python.compile == Some(false) {
Ok(self
.fetch_precompiled_remote_versions()
.await?
.iter()
.map(|(v, _, _)| VersionInfo {
version: v.clone(),
..Default::default()
})
.collect())
} else {
self.install_or_update_python_build(None)?;
let python_build_bin = self.python_build_bin();
plugins::core::run_fetch_task_with_timeout(move || {
let output = cmd!(python_build_bin, "--definitions").read()?;
let versions = output
.split('\n')
// remove free-threaded pythons like 3.13t and 3.14t-dev
.filter(|s| !regex!(r"\dt(-dev)?$").is_match(s))
.map(|s| VersionInfo {
version: s.to_string(),
..Default::default()
})
.sorted_by_cached_key(|v| regex!(r"^\d+").is_match(&v.version))
.collect();
Ok(versions)
})
}
}
async fn idiomatic_filenames(&self) -> eyre::Result<Vec<String>> {
Ok(vec![
".python-version".to_string(),
".python-versions".to_string(),
])
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
if cfg!(windows) || Settings::get().python.compile != Some(true) {
self.install_precompiled(ctx, &tv).await?;
} else {
self.install_compiled(ctx, &tv).await?;
}
self.test_python(&ctx.config, &tv, ctx.pr.as_ref()).await?;
if let Err(e) = self
.get_virtualenv(&ctx.config, &tv, Some(ctx.pr.as_ref()))
.await
{
warn!("failed to get virtualenv: {e:#}");
}
if let Some(default_file) = &Settings::get().python.default_packages_file {
let default_file = file::replace_path(default_file);
if let Err(err) = self
.install_default_packages(&ctx.config, &default_file, &tv, ctx.pr.as_ref())
.await
{
warn!("failed to install default python packages: {err:#}");
}
}
Ok(tv)
}
#[cfg(windows)]
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<Vec<PathBuf>> {
Ok(vec![tv.install_path()])
}
async fn exec_env(
&self,
config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let mut hm = BTreeMap::new();
match self.get_virtualenv(config, tv, None).await {
Err(e) => warn!("failed to get virtualenv: {e}"),
Ok(Some(virtualenv)) => {
let bin = virtualenv.join("bin");
hm.insert("VIRTUAL_ENV".into(), virtualenv.to_string_lossy().into());
hm.insert("MISE_ADD_PATH".into(), bin.to_string_lossy().into());
}
Ok(None) => {}
};
Ok(hm)
}
fn get_remote_version_cache(&self) -> Arc<Mutex<VersionCacheManager>> {
static CACHE: OnceLock<Arc<Mutex<VersionCacheManager>>> = OnceLock::new();
CACHE
.get_or_init(|| {
Arc::new(Mutex::new(
CacheManagerBuilder::new(
self.ba().cache_path.join("remote_versions.msgpack.z"),
)
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.with_cache_key((Settings::get().python.compile == Some(false)).to_string())
.build(),
))
})
.clone()
}
fn resolve_lockfile_options(
&self,
_request: &ToolRequest,
target: &PlatformTarget,
) -> BTreeMap<String, String> {
let mut opts = BTreeMap::new();
let settings = Settings::get();
let is_current_platform = target.is_current();
// Only include compile option if true (non-default)
let compile = if is_current_platform {
settings.python.compile.unwrap_or(false)
} else {
false
};
if compile {
opts.insert("compile".to_string(), "true".to_string());
}
// Only include precompiled options if not compiling and if set
if !compile && is_current_platform {
if let Some(arch) = settings.python.precompiled_arch.clone() {
opts.insert("precompiled_arch".to_string(), arch);
}
if let Some(os) = settings.python.precompiled_os.clone() {
opts.insert("precompiled_os".to_string(), os);
}
if let Some(flavor) = settings.python.precompiled_flavor.clone() {
opts.insert("precompiled_flavor".to_string(), flavor);
}
}
opts
}
}
fn python_precompiled_url_path(settings: &Settings) -> String {
if cfg!(windows) || cfg!(linux) || cfg!(macos) {
format!(
"python-precompiled-{}-{}.gz",
python_arch(settings),
python_os(settings)
)
} else {
"python-precompiled.gz".into()
}
}
fn python_os(settings: &Settings) -> String {
if let Some(os) = &settings.python.precompiled_os {
return os.clone();
}
if cfg!(windows) {
"pc-windows-msvc".into()
} else if cfg!(target_os = "macos") {
"apple-darwin".into()
} else {
["unknown", built_info::CFG_OS, built_info::CFG_ENV]
.iter()
.filter(|s| !s.is_empty())
.join("-")
}
}
fn python_arch(settings: &Settings) -> &str {
if let Some(arch) = &settings.python.precompiled_arch {
return arch.as_str();
}
let arch = match settings.arch() {
"x64" => "x86_64",
"arm64" => "aarch64",
other => other,
};
if cfg!(windows) {
"x86_64"
} else if cfg!(linux) && arch == "x86_64" {
if cfg!(target_feature = "avx512f") {
"x86_64_v4"
} else if cfg!(target_feature = "avx2") {
"x86_64_v3"
} else if cfg!(target_feature = "sse4.1") {
"x86_64_v2"
} else {
"x86_64"
}
} else {
arch
}
}
fn python_precompiled_platform() -> String {
let settings = Settings::get();
let os = python_os(&settings);
let arch = python_arch(&settings);
if let Some(flavor) = &settings.python.precompiled_flavor {
format!("{arch}-{os}-{flavor}")
} else {
format!("{arch}-{os}")
}
}
fn ensure_not_windows() -> eyre::Result<()> {
if cfg!(windows) {
bail!(
"python can not currently be compiled on windows with core:python, use vfox:python instead"
);
}
Ok(())
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/mod.rs | src/plugins/core/mod.rs | use color_eyre::eyre::Context;
use eyre::Result;
use std::ffi::OsString;
use std::sync::Arc;
use std::sync::LazyLock as Lazy;
use crate::backend::{Backend, BackendMap};
use crate::cli::args::BackendArg;
use crate::config::Settings;
use crate::env;
use crate::env::PATH_KEY;
use crate::timeout::{TimeoutError, run_with_timeout};
use crate::toolset::ToolVersion;
mod bun;
mod deno;
mod elixir;
mod erlang;
mod go;
mod java;
mod node;
pub(crate) mod python;
#[cfg_attr(windows, path = "ruby_windows.rs")]
mod ruby;
mod rust;
mod swift;
mod zig;
pub static CORE_PLUGINS: Lazy<BackendMap> = Lazy::new(|| {
let plugins: Vec<Arc<dyn Backend>> = vec![
Arc::new(bun::BunPlugin::new()),
Arc::new(deno::DenoPlugin::new()),
Arc::new(elixir::ElixirPlugin::new()),
Arc::new(erlang::ErlangPlugin::new()),
Arc::new(go::GoPlugin::new()),
Arc::new(java::JavaPlugin::new()),
Arc::new(node::NodePlugin::new()),
Arc::new(python::PythonPlugin::new()),
Arc::new(ruby::RubyPlugin::new()),
Arc::new(rust::RustPlugin::new()),
Arc::new(swift::SwiftPlugin::new()),
Arc::new(zig::ZigPlugin::new()),
];
plugins
.into_iter()
.map(|p| (p.id().to_string(), p))
.collect()
});
pub fn path_env_with_tv_path(tv: &ToolVersion) -> Result<OsString> {
let mut path = env::split_paths(&env::var_os(&*PATH_KEY).unwrap()).collect::<Vec<_>>();
path.insert(0, tv.install_path().join("bin"));
Ok(env::join_paths(path)?)
}
pub fn run_fetch_task_with_timeout<F, T>(f: F) -> Result<T>
where
F: FnOnce() -> Result<T> + Send,
T: Send,
{
let timeout = Settings::get().fetch_remote_versions_timeout();
match run_with_timeout(f, timeout) {
Ok(v) => Ok(v),
Err(err) => {
// Only add a hint when the error was actually caused by a timeout
if err.downcast_ref::<TimeoutError>().is_some() {
Err(err).context(
"change with `fetch_remote_versions_timeout` or env `MISE_FETCH_REMOTE_VERSIONS_TIMEOUT`",
)
} else {
Err(err)
}
}
}
}
pub fn new_backend_arg(tool_name: &str) -> BackendArg {
BackendArg::new_raw(
tool_name.to_string(),
Some(format!("core:{tool_name}")),
tool_name.to_string(),
None,
)
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/java.rs | src/plugins/core/java.rs | use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Display;
use std::fs::{self};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::backend::{Backend, VersionInfo};
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::cli::version::OS;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::file::{TarFormat, TarOptions};
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::toolset::{ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{file, plugins};
use async_trait::async_trait;
use color_eyre::eyre::{Result, eyre};
use indoc::formatdoc;
use itertools::Itertools;
use regex::Regex;
use serde_derive::{Deserialize, Serialize};
use std::str::FromStr;
use std::sync::LazyLock as Lazy;
use versions::Versioning;
use xx::regex;
static VERSION_REGEX: Lazy<regex::Regex> = Lazy::new(|| {
Regex::new(
r"(?i)(^Available versions:|-src|-dev|-latest|-stm|[-\\.]rc|-milestone|-alpha|-beta|[-\\.]pre|-next|snapshot|SNAPSHOT|master)"
)
.unwrap()
});
#[derive(Debug)]
pub struct JavaPlugin {
ba: Arc<BackendArg>,
java_metadata_ea_cache: CacheManager<HashMap<String, JavaMetadata>>,
java_metadata_ga_cache: CacheManager<HashMap<String, JavaMetadata>>,
}
impl JavaPlugin {
pub fn new() -> Self {
let settings = Settings::get();
let ba = Arc::new(plugins::core::new_backend_arg("java"));
Self {
java_metadata_ea_cache: CacheManagerBuilder::new(
ba.cache_path.join("java_metadata_ea.msgpack.z"),
)
.with_fresh_duration(settings.fetch_remote_versions_cache())
.build(),
java_metadata_ga_cache: CacheManagerBuilder::new(
ba.cache_path.join("java_metadata_ga.msgpack.z"),
)
.with_fresh_duration(settings.fetch_remote_versions_cache())
.build(),
ba,
}
}
async fn fetch_java_metadata(
&self,
release_type: &str,
) -> Result<&HashMap<String, JavaMetadata>> {
let cache = if release_type == "ea" {
&self.java_metadata_ea_cache
} else {
&self.java_metadata_ga_cache
};
let release_type = release_type.to_string();
cache
.get_or_try_init_async(async || {
let mut metadata = HashMap::new();
for m in self.download_java_metadata(&release_type).await? {
// add openjdk short versions like "java@17.0.0" which default to openjdk
if m.vendor == "openjdk" {
metadata.insert(m.version.to_string(), m.clone());
}
metadata.insert(m.to_string(), m);
}
Ok(metadata)
})
.await
}
fn java_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin/java")
}
fn test_java(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<()> {
CmdLineRunner::new(self.java_bin(tv))
.with_pr(pr)
.env("JAVA_HOME", tv.install_path())
.arg("-version")
.execute()
}
async fn download(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
pr: &dyn SingleReport,
m: &JavaMetadata,
) -> Result<PathBuf> {
let filename = m.url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
pr.set_message(format!("download {filename}"));
HTTP.download_file(&m.url, &tarball_path, Some(pr)).await?;
let platform_key = self.get_platform_key();
if !tv.lock_platforms.contains_key(&platform_key) {
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(m.url.clone());
if m.checksum.is_some() {
platform_info.checksum = m.checksum.clone();
}
}
self.verify_checksum(ctx, tv, &tarball_path)?;
Ok(tarball_path)
}
fn install(
&self,
tv: &ToolVersion,
pr: &dyn SingleReport,
tarball_path: &Path,
m: &JavaMetadata,
) -> Result<()> {
let filename = tarball_path.file_name().unwrap().to_string_lossy();
pr.set_message(format!("extract {filename}"));
match m.file_type.as_deref() {
Some("zip") => file::unzip(tarball_path, &tv.download_path(), &Default::default())?,
_ => file::untar(
tarball_path,
&tv.download_path(),
&TarOptions {
format: TarFormat::Auto,
pr: Some(pr),
..Default::default()
},
)?,
}
self.move_to_install_path(tv, m)
}
fn move_to_install_path(&self, tv: &ToolVersion, m: &JavaMetadata) -> Result<()> {
let basedir = tv
.download_path()
.read_dir()?
.find(|e| e.as_ref().unwrap().file_type().unwrap().is_dir())
.unwrap()?
.path();
let contents_dir = basedir.join("Contents");
let source_dir = match m.vendor.as_str() {
"zulu" | "liberica" => basedir,
_ if os() == "macosx" => basedir.join("Contents").join("Home"),
_ => basedir,
};
file::remove_all(tv.install_path())?;
file::create_dir_all(tv.install_path())?;
for entry in fs::read_dir(source_dir)? {
let entry = entry?;
let dest = tv.install_path().join(entry.file_name());
trace!("moving {:?} to {:?}", entry.path(), &dest);
file::rename(entry.path(), dest)?;
}
if cfg!(target_os = "macos") {
self.handle_macos_integration(&contents_dir, tv, m)?;
}
Ok(())
}
fn handle_macos_integration(
&self,
contents_dir: &Path,
tv: &ToolVersion,
m: &JavaMetadata,
) -> Result<()> {
// move Contents dir to install path for macOS, if it exists
if contents_dir.exists() {
file::create_dir_all(tv.install_path().join("Contents"))?;
for entry in fs::read_dir(contents_dir)? {
let entry = entry?;
// skip Home dir, so we can symlink it later
if entry.file_name() == "Home" {
continue;
}
let dest = tv.install_path().join("Contents").join(entry.file_name());
trace!("moving {:?} to {:?}", entry.path(), &dest);
file::rename(entry.path(), dest)?;
}
file::make_symlink(
tv.install_path().as_path(),
&tv.install_path().join("Contents").join("Home"),
)?;
}
// if vendor is Zulu, symlink zulu-{major_version}.jdk/Contents to install path for macOS
if m.vendor.as_str() == "zulu" {
let (major_version, _) = m
.version
.split_once('.')
.unwrap_or_else(|| (&m.version, ""));
file::make_symlink(
tv.install_path()
.join(format!("zulu-{major_version}.jdk"))
.join("Contents")
.as_path(),
&tv.install_path().join("Contents"),
)?;
}
if tv.install_path().join("Contents").exists() {
info!(
"{}",
formatdoc! {r#"
To enable macOS integration, run the following commands:
sudo mkdir /Library/Java/JavaVirtualMachines/{version}.jdk
sudo ln -s {path}/Contents /Library/Java/JavaVirtualMachines/{version}.jdk/Contents
"#,
version = tv.version,
path = tv.install_path().display(),
}
);
}
Ok(())
}
fn verify(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<()> {
pr.set_message("java -version".into());
self.test_java(tv, pr)
}
fn tv_release_type(&self, tv: &ToolVersion) -> String {
tv.request
.options()
.get("release_type")
.cloned()
.unwrap_or(String::from("ga"))
}
fn tv_to_java_version(&self, tv: &ToolVersion) -> String {
if regex!(r"^\d").is_match(&tv.version) {
// undo openjdk shorthand
format!("openjdk-{}", tv.version)
} else {
tv.version.clone()
}
}
async fn tv_to_metadata(&self, tv: &ToolVersion) -> Result<&JavaMetadata> {
let v: String = self.tv_to_java_version(tv);
let release_type = self.tv_release_type(tv);
let m = self
.fetch_java_metadata(&release_type)
.await?
.get(&v)
.ok_or_else(|| eyre!("no metadata found for version {}", tv.version))?;
Ok(m)
}
async fn download_java_metadata(&self, release_type: &str) -> Result<Vec<JavaMetadata>> {
let settings = Settings::get();
let url = format!(
"https://mise-java.jdx.dev/jvm/{}/{}/{}.json",
release_type,
os(),
arch(&settings)
);
let metadata = HTTP_FETCH
.json::<Vec<JavaMetadata>, _>(url)
.await?
.into_iter()
.filter(|m| {
m.file_type
.as_ref()
.is_some_and(|file_type| JAVA_FILE_TYPES.contains(file_type))
})
.collect();
Ok(metadata)
}
}
#[async_trait]
impl Backend for JavaPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let release_type = config
.get_tool_request_set()
.await?
.list_tools()
.iter()
.find(|ba| ba.short == "java")
.and_then(|ba| ba.opts().get("release_type").cloned())
.unwrap_or_else(|| "ga".to_string());
let versions = self
.fetch_java_metadata(&release_type)
.await?
.iter()
.sorted_by_cached_key(|(v, m)| {
let is_shorthand = regex!(r"^\d").is_match(v);
let vendor = &m.vendor;
let is_jdk = m
.image_type
.as_ref()
.is_some_and(|image_type| image_type == "jdk");
let features = 10 - m.features.as_ref().map_or(0, |f| f.len());
let version = Versioning::new(v);
// Extract build suffix after a '+', '.' if present. If not present, treat as 0.
let build_num = v
.rsplit_once('+')
.or_else(|| v.rsplit_once('.'))
.and_then(|(_, tail)| {
// take leading digits of tail
let digits: String =
tail.chars().take_while(|c| c.is_ascii_digit()).collect();
if digits.is_empty() {
None
} else {
u64::from_str(&digits).ok()
}
})
.unwrap_or(0u64);
(
is_shorthand,
vendor,
is_jdk,
features,
version,
build_num,
v.to_string(),
)
})
.map(|(v, m)| VersionInfo {
version: v.clone(),
created_at: m.created_at.clone(),
..Default::default()
})
.unique_by(|v| v.version.clone())
.collect();
Ok(versions)
}
/// Override to bypass the shared remote_versions cache since Java has separate
/// caches for GA and EA release types in fetch_java_metadata.
async fn list_remote_versions_with_info(
&self,
config: &Arc<Config>,
) -> Result<Vec<VersionInfo>> {
self._list_remote_versions(config).await
}
fn list_installed_versions_matching(&self, query: &str) -> Vec<String> {
let versions = self.list_installed_versions();
self.fuzzy_match_filter(versions, query)
}
async fn list_versions_matching(
&self,
config: &Arc<Config>,
query: &str,
) -> eyre::Result<Vec<String>> {
let versions = self.list_remote_versions(config).await?;
Ok(self.fuzzy_match_filter(versions, query))
}
fn get_aliases(&self) -> Result<BTreeMap<String, String>> {
let aliases = BTreeMap::from([("lts".into(), "25".into())]);
Ok(aliases)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".java-version".into(), ".sdkmanrc".into()])
}
async fn parse_idiomatic_file(&self, path: &Path) -> Result<String> {
let contents = file::read_to_string(path)?;
if path.file_name() == Some(".sdkmanrc".as_ref()) {
let version = contents
.lines()
.find(|l| l.starts_with("java"))
.unwrap_or("java=")
.split_once('=')
.unwrap_or_default()
.1;
if !version.contains('-') {
return Ok(version.to_string());
}
let (version, vendor) = version.rsplit_once('-').unwrap_or_default();
let vendor = match vendor {
"amzn" => "corretto",
"albba" => "dragonwell",
"graalce" => "graalvm-community",
"librca" => "liberica",
"open" => "openjdk",
"ms" => "microsoft",
"sapmchn" => "sapmachine",
"sem" => "semeru-openj9",
"tem" => "temurin",
_ => vendor, // either same vendor name or unsupported
};
let mut version = version.split(['+', '-'].as_ref()).collect::<Vec<&str>>()[0];
// if vendor is zulu, we can only match the major version
if vendor == "zulu" {
version = version.split_once('.').unwrap_or_default().0;
}
Ok(format!("{vendor}-{version}"))
} else {
Ok(contents)
}
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
// Java installation has 3 operations: download, install (extract), verify
ctx.pr.start_operations(3);
// Check if URL already exists in lockfile platforms first
let platform_key = self.get_platform_key();
let (metadata, tarball_path) =
if let Some(platform_info) = tv.lock_platforms.get(&platform_key) {
if let Some(ref url) = platform_info.url {
// Use the filename from the URL, not the platform key
let filename = url.split('/').next_back().unwrap();
debug!("Using existing URL from lockfile for {}: {}", filename, url);
let tarball_path = tv.download_path().join(filename);
// If the file does not exist, download using the lockfile URL
if !tarball_path.exists() {
debug!("File not found, downloading from cached URL: {}", url);
// Download using the lockfile URL, not JavaMetadata
HTTP.download_file(url, &tarball_path, Some(ctx.pr.as_ref()))
.await?;
// Optionally verify checksum if present
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
}
// Fetch metadata for installation (for install/move logic)
let metadata = self.tv_to_metadata(&tv).await?;
(metadata, tarball_path)
} else {
// No URL in lockfile, fallback to metadata
let metadata = self.tv_to_metadata(&tv).await?;
let tarball_path = self
.download(ctx, &mut tv, ctx.pr.as_ref(), metadata)
.await?;
(metadata, tarball_path)
}
} else {
let metadata = self.tv_to_metadata(&tv).await?;
let tarball_path = self
.download(ctx, &mut tv, ctx.pr.as_ref(), metadata)
.await?;
(metadata, tarball_path)
};
self.install(&tv, ctx.pr.as_ref(), &tarball_path, metadata)?;
self.verify(&tv, ctx.pr.as_ref())?;
Ok(tv)
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let map = BTreeMap::from([(
"JAVA_HOME".into(),
tv.install_path().to_string_lossy().into(),
)]);
Ok(map)
}
fn fuzzy_match_filter(&self, versions: Vec<String>, query: &str) -> Vec<String> {
let is_vendor_prefix = query != "latest" && query.ends_with('-');
let query_escaped = regex::escape(query);
let query = match query {
"latest" => "[0-9].*",
// else; use escaped query
_ => &query_escaped,
};
// Same semantics as Backend::fuzzy_match_filter:
// - "1.2" should match "1.2.3" but not "1.20"
// - vendor prefixes like "temurin-" should match "temurin-25..."
let query_regex = if is_vendor_prefix {
Regex::new(&format!("^{query}.*$")).unwrap()
} else {
Regex::new(&format!("^{query}([+\\-.].+)?$")).unwrap()
};
versions
.into_iter()
.filter(|v| {
if query == v {
return true;
}
if VERSION_REGEX.is_match(v) {
return false;
}
query_regex.is_match(v)
})
.collect()
}
}
fn os() -> &'static str {
if cfg!(target_os = "macos") {
"macosx"
} else if OS.as_str() == "freebsd" {
"linux"
} else {
&OS
}
}
fn arch(settings: &Settings) -> &str {
match settings.arch() {
"x64" => "x86_64",
"arm64" => "aarch64",
"arm" => "arm32-vfp-hflt",
other => other,
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(default)]
struct JavaMetadata {
// architecture: String,
checksum: Option<String>,
// checksum_url: Option<String>,
created_at: Option<String>,
features: Option<Vec<String>>,
file_type: Option<String>,
// filename: String,
image_type: Option<String>,
java_version: String,
jvm_impl: String,
// os: String,
// release_type: String,
// size: Option<i32>,
url: String,
vendor: String,
version: String,
}
impl Display for JavaMetadata {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut v = vec![self.vendor.clone()];
if self
.image_type
.as_ref()
.is_some_and(|image_type| image_type == "jre")
{
v.push(self.image_type.clone().unwrap());
} else if self.image_type.is_none() {
v.push("unknown".to_string());
}
if let Some(features) = &self.features {
for f in features {
if JAVA_FEATURES.contains(f) {
v.push(f.clone());
}
}
}
if self.jvm_impl == "openj9" {
v.push(self.jvm_impl.clone());
}
if self.vendor == "liberica-nik" {
let major = self
.java_version
.split('.')
.next()
.unwrap_or(&self.java_version);
v.push(format!("openjdk{}", major));
}
v.push(self.version.clone());
write!(f, "{}", v.join("-"))
}
}
// only care about these features
static JAVA_FEATURES: Lazy<HashSet<String>> = Lazy::new(|| {
HashSet::from(["crac", "javafx", "jcef", "leyden", "lite", "musl"].map(|s| s.to_string()))
});
#[cfg(unix)]
static JAVA_FILE_TYPES: Lazy<HashSet<String>> =
Lazy::new(|| HashSet::from(["tar.gz", "tar.xz"].map(|s| s.to_string())));
#[cfg(windows)]
static JAVA_FILE_TYPES: Lazy<HashSet<String>> =
Lazy::new(|| HashSet::from(["zip"].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/plugins/core/zig.rs | src/plugins/core/zig.rs | use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Arc,
};
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::platform_target::PlatformTarget;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::duration::DAILY;
use crate::file::TarOptions;
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::ToolVersion;
use crate::ui::progress_report::SingleReport;
use crate::{file, minisign, plugins};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use rand::seq::SliceRandom;
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct ZigPlugin {
ba: Arc<BackendArg>,
}
const ZIG_MINISIGN_KEY: &str = "RWSGOq2NVecA2UPNdBUZykf1CCb147pkmdtYxgb3Ti+JO/wCYvhbAb/U";
const REQUEST_SUFFIX: &str = "?source=mise-en-place";
const MIRRORS_FILENAME: &str = "community-mirrors.txt";
impl ZigPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("zig")),
}
}
fn zig_bin(&self, tv: &ToolVersion) -> PathBuf {
if cfg!(windows) {
tv.install_path().join("zig.exe")
} else {
tv.install_path().join("bin").join("zig")
}
}
fn test_zig(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
ctx.pr.set_message("zig version".into());
CmdLineRunner::new(self.zig_bin(tv))
.with_pr(ctx.pr.as_ref())
.arg("version")
.execute()
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let settings = Settings::get();
let url = self
.get_tarball_url(tv, &PlatformTarget::from_current())
.await?
.ok_or_else(|| eyre::eyre!("Failed to resolve zig tarball URL for {}", tv.version))?;
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
let mut downloaded = false;
let mut used_url = url.clone();
// The ziglang.org website kindly asks for trying mirrors for automated downloads,
// read more on https://ziglang.org/download/community-mirrors/
let community_mirrors = if url.starts_with("https://ziglang.org") {
self.get_community_mirrors().await
} else {
None
};
if settings.zig.use_community_mirrors
&& let Some(mirrors) = community_mirrors
{
for i in 0..mirrors.len() {
let disp_i = i + 1;
let disp_len = mirrors.len();
pr.set_message(format!("mirror {disp_i}/{disp_len} {filename}"));
let mirror_url = &mirrors[i];
used_url = format!("{mirror_url}/{filename}");
if HTTP
.download_file(
format!("{used_url}{REQUEST_SUFFIX}"),
&tarball_path,
Some(pr),
)
.await
.is_ok()
{
downloaded = true;
break;
}
}
}
if !downloaded {
// Try the usual ziglang.org or machengine.org download
pr.set_message(format!("download {filename}"));
used_url = url.clone();
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
// If this was ziglang.org and error is not 404 and community_mirrors is None,
// the user might want to place the mirror list in cache dir by hand
}
pr.set_message(format!("minisign {filename}"));
let tarball_data = file::read(&tarball_path)?;
let sig = HTTP
.get_text(format!("{used_url}.minisig{REQUEST_SUFFIX}"))
.await?;
minisign::verify(ZIG_MINISIGN_KEY, &tarball_data, &sig)?;
// Since this passed the verify step, the format is guaranteed to be correct
let trusted_comment = sig.split('\n').nth(2).unwrap().to_string();
// Verify that this is the desired version using trusted comment to prevent downgrade attacks
if !trusted_comment.contains(&format!("file:{filename}")) {
return Err(eyre::eyre!(
"Expected {}, but signature {}.minisig had:\n{}",
filename,
used_url,
trusted_comment
));
}
Ok(tarball_path)
}
fn install(&self, ctx: &InstallContext, tv: &ToolVersion, tarball_path: &Path) -> Result<()> {
let filename = tarball_path.file_name().unwrap().to_string_lossy();
ctx.pr.set_message(format!("extract {filename}"));
file::remove_all(tv.install_path())?;
file::untar(
tarball_path,
&tv.install_path(),
&TarOptions {
strip_components: 1,
pr: Some(ctx.pr.as_ref()),
..Default::default()
},
)?;
if cfg!(unix) {
file::create_dir_all(tv.install_path().join("bin"))?;
file::make_symlink(Path::new("../zig"), &tv.install_path().join("bin/zig"))?;
}
Ok(())
}
fn verify(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
self.test_zig(ctx, tv)
}
async fn get_tarball_url_from_json(
&self,
json_url: &str,
version: &str,
arch: &str,
os: &str,
) -> Result<String> {
let version_json: serde_json::Value = HTTP_FETCH.json(json_url).await?;
let zig_tarball_url = version_json
.pointer(&format!("/{version}/{arch}-{os}/tarball"))
.and_then(|v| v.as_str())
.ok_or_else(|| eyre::eyre!("Failed to get zig tarball url from {:?}", json_url))?;
Ok(zig_tarball_url.to_string())
}
/// Get full download info (tarball URL, shasum, size) from JSON index
/// Uses cached request since same index is fetched for all platforms
async fn get_download_info_from_json(
&self,
json_url: &str,
version: &str,
arch: &str,
os: &str,
) -> Result<(String, Option<String>, Option<u64>)> {
let version_json: serde_json::Value = HTTP_FETCH.json_cached(json_url).await?;
let platform_info = version_json
.pointer(&format!("/{version}/{arch}-{os}"))
.ok_or_else(|| eyre::eyre!("Failed to get zig platform info from {:?}", json_url))?;
let tarball_url = platform_info
.get("tarball")
.and_then(|v| v.as_str())
.ok_or_else(|| eyre::eyre!("Failed to get zig tarball url from {:?}", json_url))?
.to_string();
let shasum = platform_info
.get("shasum")
.and_then(|v| v.as_str())
.map(|s| format!("sha256:{s}"));
let size = platform_info
.get("size")
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<u64>().ok());
Ok((tarball_url, shasum, size))
}
async fn get_community_mirrors(&self) -> Option<Vec<String>> {
let cache_path = self.ba.cache_path.join(MIRRORS_FILENAME);
let recent_cache =
file::modified_duration(&cache_path).is_ok_and(|updated_at| updated_at < DAILY);
if !recent_cache {
HTTP.download_file(
&format!("https://ziglang.org/download/{MIRRORS_FILENAME}"),
&cache_path,
None,
)
.await
.unwrap_or_else(|_| {
// We can still use an older mirror list
warn!("{}: Could not download {}", self.ba, MIRRORS_FILENAME);
});
}
let mirror_list = String::from_utf8(file::read(cache_path).ok()?).ok()?;
let mut mirrors: Vec<String> = mirror_list
.split('\n')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
let mut rng = rand::rng();
mirrors.shuffle(&mut rng);
Some(mirrors)
}
}
#[async_trait]
impl Backend for ZigPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
vec![
SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
},
SecurityFeature::Minisign {
public_key: Some(ZIG_MINISIGN_KEY.to_string()),
},
]
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let indexes = [
"https://ziglang.org/download/index.json",
// "https://machengine.org/zig/index.json", // need to handle mach's CalVer
];
let mut versions: Vec<(String, Option<String>)> = Vec::new();
for index in indexes {
let index_json: serde_json::Value = HTTP_FETCH.json(index).await?;
let index_obj = index_json
.as_object()
.ok_or_else(|| eyre::eyre!("Failed to get zig version from {:?}", index))?;
for (version, data) in index_obj {
let date = data.get("date").and_then(|d| d.as_str()).map(String::from);
versions.push((version.clone(), date));
}
}
let versions = versions
.into_iter()
.unique_by(|(v, _)| v.clone())
.sorted_by_cached_key(|(s, _)| (Versioning::new(s), s.to_string()))
.map(|(version, date)| VersionInfo {
version,
created_at: date,
..Default::default()
})
.collect();
Ok(versions)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
if cfg!(windows) {
Ok(vec![tv.install_path()])
} else {
Ok(vec![tv.install_path().join("bin")])
}
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".zig-version".into()])
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
ctx.pr.start_operations(3);
let tarball_path = self.download(&tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(ctx, &tv, &tarball_path)?;
self.verify(ctx, &tv)?;
Ok(tv)
}
async fn get_tarball_url(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<Option<String>> {
let indexes = HashMap::from([
("zig", "https://ziglang.org/download/index.json"),
("mach", "https://machengine.org/zig/index.json"),
]);
let arch = match target.arch_name() {
"x64" => "x86_64",
"arm64" => "aarch64",
"arm" => "armv7a",
"riscv64" => "riscv64",
other => other,
};
let os = match target.os_name() {
"macos" => "macos",
"linux" => "linux",
"freebsd" => "freebsd",
"windows" => "windows",
_ => "linux",
};
let (json_url, version) = if regex!(r"^mach-|-mach$").is_match(&tv.version) {
(indexes["mach"], tv.version.as_str())
} else {
(indexes["zig"], tv.version.as_str())
};
match self
.get_tarball_url_from_json(json_url, version, arch, os)
.await
{
Ok(url) => Ok(Some(url)),
Err(_) if regex!(r"^\d+\.\d+\.\d+$").is_match(&tv.version) => {
// Fallback: construct URL directly for numbered versions
Ok(Some(format!(
"https://ziglang.org/download/{}/zig-{}-{}-{}.tar.xz",
tv.version, os, arch, tv.version
)))
}
Err(_) => Ok(None),
}
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let indexes = HashMap::from([
("zig", "https://ziglang.org/download/index.json"),
("mach", "https://machengine.org/zig/index.json"),
]);
let arch = match target.arch_name() {
"x64" => "x86_64",
"arm64" => "aarch64",
"arm" => "armv7a",
"riscv64" => "riscv64",
other => other,
};
let os = match target.os_name() {
"macos" => "macos",
"linux" => "linux",
"freebsd" => "freebsd",
"windows" => "windows",
_ => "linux",
};
let (json_url, version) = if regex!(r"^mach-|-mach$").is_match(&tv.version) {
(indexes["mach"], tv.version.as_str())
} else {
(indexes["zig"], tv.version.as_str())
};
// Try to get full info from JSON (includes checksum and size)
match self
.get_download_info_from_json(json_url, version, arch, os)
.await
{
Ok((url, checksum, size)) => Ok(PlatformInfo {
url: Some(url),
checksum,
size,
url_api: None,
}),
Err(_) if regex!(r"^\d+\.\d+\.\d+$").is_match(&tv.version) => {
// Fallback: construct URL directly for numbered versions (no checksum available)
Ok(PlatformInfo {
url: Some(format!(
"https://ziglang.org/download/{}/zig-{}-{}-{}.tar.xz",
tv.version, os, arch, tv.version
)),
checksum: None,
size: None,
url_api: None,
})
}
Err(_) => Ok(PlatformInfo::default()),
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/bun.rs | src/plugins/core/bun.rs | use std::{
path::{Path, PathBuf},
sync::Arc,
};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use versions::Versioning;
use crate::backend::static_helpers::fetch_checksum_from_shasums;
use crate::cli::args::BackendArg;
use crate::cli::version::{ARCH, OS};
use crate::cmd::CmdLineRunner;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::ToolVersion;
use crate::ui::progress_report::SingleReport;
use crate::{
backend::{
Backend, GitHubReleaseInfo, ReleaseType, VersionInfo, platform_target::PlatformTarget,
},
config::{Config, Settings},
platform::Platform,
};
use crate::{file, github, plugins};
#[derive(Debug)]
pub struct BunPlugin {
ba: Arc<BackendArg>,
}
impl BunPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("bun")),
}
}
fn bun_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join(bun_bin_name())
}
fn test_bun(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
ctx.pr.set_message("bun -v".into());
CmdLineRunner::new(self.bun_bin(tv))
.with_pr(ctx.pr.as_ref())
.arg("-v")
.execute()
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let url = format!(
"https://github.com/oven-sh/bun/releases/download/bun-v{}/bun-{}-{}.zip",
tv.version,
os(),
arch()
);
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
pr.set_message(format!("download {filename}"));
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
Ok(tarball_path)
}
fn install(&self, ctx: &InstallContext, tv: &ToolVersion, tarball_path: &Path) -> Result<()> {
let filename = tarball_path.file_name().unwrap().to_string_lossy();
ctx.pr.set_message(format!("extract {filename}"));
file::remove_all(tv.install_path())?;
file::create_dir_all(tv.install_path().join("bin"))?;
file::unzip(tarball_path, &tv.download_path(), &Default::default())?;
file::rename(
tv.download_path()
.join(format!("bun-{}-{}", os(), arch()))
.join(bun_bin_name()),
self.bun_bin(tv),
)?;
if cfg!(unix) {
file::make_executable(self.bun_bin(tv))?;
file::make_symlink(Path::new("./bun"), &tv.install_path().join("bin/bunx"))?;
}
Ok(())
}
fn verify(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
self.test_bun(ctx, tv)
}
}
#[async_trait]
impl Backend for BunPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}]
}
/// Override get_platform_key to include bun's compile-time variant (baseline, musl, etc.)
/// This ensures lockfile lookups use the correct platform key that matches the variant
fn get_platform_key(&self) -> String {
let settings = Settings::get();
let os = settings.os();
let arch = settings.arch();
// Get the variant suffix based on compile-time features
let variant = Self::get_platform_variant();
if let Some(v) = variant {
format!("{os}-{arch}-{v}")
} else {
format!("{os}-{arch}")
}
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions = github::list_releases("oven-sh/bun")
.await?
.into_iter()
.filter_map(|r| {
r.tag_name
.strip_prefix("bun-v")
.map(|v| (v.to_string(), r.created_at))
})
.unique_by(|(v, _)| v.clone())
.sorted_by_cached_key(|(s, _)| (Versioning::new(s), s.to_string()))
.map(|(version, created_at)| VersionInfo {
version,
created_at: Some(created_at),
..Default::default()
})
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".bun-version".into()])
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
ctx.pr.start_operations(3);
let tarball_path = self.download(&tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(ctx, &tv, &tarball_path)?;
self.verify(ctx, &tv)?;
Ok(tv)
}
// ========== Lockfile Metadata Fetching Implementation ==========
async fn get_github_release_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<Option<GitHubReleaseInfo>> {
let version = &tv.version;
// Build the asset pattern for Bun's GitHub releases
// Pattern: bun-{os}-{arch}.zip (where arch may include variants like -musl, -baseline)
let os_name = Self::map_os_to_bun(target.os_name());
let arch_name = Self::get_bun_arch_for_target(target);
let asset_pattern = format!("bun-{os_name}-{arch_name}.zip");
Ok(Some(GitHubReleaseInfo {
repo: "oven-sh/bun".to_string(),
asset_pattern: Some(asset_pattern),
api_url: Some(format!(
"https://github.com/oven-sh/bun/releases/download/bun-v{version}"
)),
release_type: ReleaseType::GitHub,
}))
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let version = &tv.version;
// Build platform-specific filename
let os_name = Self::map_os_to_bun(target.os_name());
let arch_name = Self::get_bun_arch_for_target(target);
let filename = format!("bun-{os_name}-{arch_name}.zip");
// Build download URL
let url =
format!("https://github.com/oven-sh/bun/releases/download/bun-v{version}/{filename}");
// Fetch SHASUMS256.txt to get checksum without downloading the zip
let shasums_url = format!(
"https://github.com/oven-sh/bun/releases/download/bun-v{version}/SHASUMS256.txt"
);
let checksum = fetch_checksum_from_shasums(&shasums_url, &filename).await;
Ok(PlatformInfo {
url: Some(url),
checksum,
size: None,
url_api: None,
})
}
fn platform_variants(&self, platform: &Platform) -> Vec<Platform> {
// Bun has compile-time variants that affect the download URL and checksum:
// - baseline: for CPUs without AVX2 support
// - musl: for musl libc (Alpine Linux, etc.)
// - musl-baseline: musl + no AVX2
//
// Available variants by platform:
// - linux-x64: x64, x64-baseline, x64-musl, x64-musl-baseline
// - linux-arm64: aarch64, aarch64-musl
// - macos-x64: x64, x64-baseline
// - macos-arm64: aarch64
// - windows-x64: x64, x64-baseline
// If the platform already has a qualifier, it's already a specific variant
// Don't expand it to avoid duplicates
if platform.qualifier.is_some() {
return vec![platform.clone()];
}
let mut variants = vec![platform.clone()];
match (platform.os.as_str(), platform.arch.as_str()) {
("linux", "x64") => {
// Linux x64 has all variants
variants.push(Platform {
os: platform.os.clone(),
arch: platform.arch.clone(),
qualifier: Some("baseline".to_string()),
});
variants.push(Platform {
os: platform.os.clone(),
arch: platform.arch.clone(),
qualifier: Some("musl".to_string()),
});
variants.push(Platform {
os: platform.os.clone(),
arch: platform.arch.clone(),
qualifier: Some("musl-baseline".to_string()),
});
}
("linux", "arm64") => {
// Linux arm64 has musl variant
variants.push(Platform {
os: platform.os.clone(),
arch: platform.arch.clone(),
qualifier: Some("musl".to_string()),
});
}
("macos", "x64") | ("windows", "x64") => {
// macOS x64 and Windows x64 have baseline variant
variants.push(Platform {
os: platform.os.clone(),
arch: platform.arch.clone(),
qualifier: Some("baseline".to_string()),
});
}
// macos-arm64 has no variants (just aarch64)
_ => {}
}
variants
}
}
impl BunPlugin {
/// Map our platform OS names to Bun's naming convention
fn map_os_to_bun(os: &str) -> &str {
match os {
"macos" => "darwin",
"linux" => "linux",
"windows" => "windows",
other => other,
}
}
/// Map our platform arch names to Bun's naming convention
/// Note: This handles simple cases. Complex musl/baseline variants are handled in arch()
fn map_arch_to_bun(arch: &str) -> &str {
match arch {
"x64" => "x64",
"arm64" | "aarch64" => "aarch64",
other => other,
}
}
/// Get the full Bun arch string for a target platform
/// This handles musl, baseline, and other variants based on platform qualifiers
fn get_bun_arch_for_target(target: &PlatformTarget) -> String {
let base_arch = Self::map_arch_to_bun(target.arch_name());
// Handle qualifiers like musl, baseline, etc.
if let Some(qualifier) = target.qualifier() {
match qualifier {
"musl" => format!("{}-musl", base_arch),
"musl-baseline" => format!("{}-musl-baseline", base_arch),
"baseline" => format!("{}-baseline", base_arch),
other => format!("{}-{}", base_arch, other),
}
} else {
base_arch.to_string()
}
}
/// Check if the current system has AVX2 support (runtime detection)
#[cfg(target_arch = "x86_64")]
fn has_avx2() -> bool {
std::arch::is_x86_feature_detected!("avx2")
}
#[cfg(not(target_arch = "x86_64"))]
fn has_avx2() -> bool {
false
}
/// Check if we're running on a musl-based system
/// This is determined by the binary's compile-time target, since mixing
/// glibc and musl binaries on the same system doesn't work anyway
fn is_musl() -> bool {
cfg!(target_env = "musl")
}
/// Get the platform variant suffix for the current system
/// Returns Some("baseline"), Some("musl"), Some("musl-baseline"), or None
/// Uses runtime detection for AVX2 capability
fn get_platform_variant() -> Option<&'static str> {
if cfg!(target_arch = "x86_64") {
if Self::is_musl() {
if Self::has_avx2() {
Some("musl")
} else {
Some("musl-baseline")
}
} else if Self::has_avx2() {
None // Standard x64 with AVX2, no variant suffix
} else {
Some("baseline")
}
} else if cfg!(target_arch = "aarch64") {
if Self::is_musl() {
Some("musl")
} else {
None // Standard aarch64, no variant suffix
}
} else {
None
}
}
/// Get the full Bun arch string with variants (musl, baseline, etc.)
/// Uses runtime detection for AVX2 capability
fn get_bun_arch_with_variants() -> &'static str {
if cfg!(target_arch = "x86_64") {
if Self::is_musl() {
if Self::has_avx2() {
"x64-musl"
} else {
"x64-musl-baseline"
}
} else if Self::has_avx2() {
"x64"
} else {
"x64-baseline"
}
} else if cfg!(target_arch = "aarch64") {
if Self::is_musl() {
"aarch64-musl"
} else if cfg!(windows) {
"x64-baseline"
} else {
"aarch64"
}
} else {
&ARCH
}
}
}
fn os() -> &'static str {
BunPlugin::map_os_to_bun(&OS)
}
fn arch() -> &'static str {
BunPlugin::get_bun_arch_with_variants()
}
fn bun_bin_name() -> &'static str {
if cfg!(windows) { "bun.exe" } else { "bun" }
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/swift.rs | src/plugins/core/swift.rs | use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::Settings;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::toolset::ToolVersion;
use crate::ui::progress_report::SingleReport;
use crate::{backend::Backend, backend::VersionInfo, config::Config};
use crate::{file, github, gpg, plugins};
use async_trait::async_trait;
use eyre::Result;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use tempfile::tempdir_in;
#[derive(Debug)]
pub struct SwiftPlugin {
ba: Arc<BackendArg>,
}
impl SwiftPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("swift")),
}
}
fn swift_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join(swift_bin_name())
}
fn test_swift(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
ctx.pr.set_message("swift --version".into());
CmdLineRunner::new(self.swift_bin(tv))
.with_pr(ctx.pr.as_ref())
.arg("--version")
.execute()
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let settings = Settings::get();
let url = format!(
"https://download.swift.org/swift-{version}-release/{platform_directory}/swift-{version}-RELEASE/swift-{version}-RELEASE-{platform}{architecture}.{extension}",
version = tv.version,
platform = platform(),
platform_directory = platform_directory(),
extension = extension(),
architecture = match architecture(&settings) {
Some(arch) => format!("-{arch}"),
None => "".into(),
}
);
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
if !tarball_path.exists() {
pr.set_message(format!("download {filename}"));
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
}
Ok(tarball_path)
}
fn install(&self, ctx: &InstallContext, tv: &ToolVersion, tarball_path: &Path) -> Result<()> {
Settings::get().ensure_experimental("swift")?;
let filename = tarball_path.file_name().unwrap().to_string_lossy();
let version = &tv.version;
ctx.pr.set_message(format!("extract {filename}"));
if cfg!(macos) {
let tmp = {
tempdir_in(tv.install_path().parent().unwrap())?
.path()
.to_path_buf()
};
CmdLineRunner::new("pkgutil")
.arg("--expand-full")
.arg(tarball_path)
.arg(&tmp)
.with_pr(ctx.pr.as_ref())
.execute()?;
file::remove_all(tv.install_path())?;
file::rename(
tmp.join(format!("swift-{version}-RELEASE-osx-package.pkg"))
.join("Payload"),
tv.install_path(),
)?;
} else if cfg!(windows) {
todo!("install from exe");
} else {
file::untar(
tarball_path,
&tv.install_path(),
&file::TarOptions {
format: file::TarFormat::TarGz,
pr: Some(ctx.pr.as_ref()),
strip_components: 1,
..Default::default()
},
)?;
}
Ok(())
}
fn symlink_bins(&self, tv: &ToolVersion) -> Result<()> {
let usr_bin = tv.install_path().join("usr").join("bin");
let bin_dir = tv.install_path().join("bin");
file::create_dir_all(&bin_dir)?;
for bin in file::ls(&usr_bin)? {
if !file::is_executable(&bin) {
continue;
}
let file_name = bin.file_name().unwrap().to_string_lossy().to_string();
if file_name.contains("swift") || file_name.contains("sourcekit") {
file::make_symlink_or_copy(&bin, &bin_dir.join(file_name))?;
}
}
Ok(())
}
async fn verify_gpg(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
tarball_path: &Path,
) -> Result<()> {
if file::which_non_pristine("gpg").is_none() && Settings::get().swift.gpg_verify.is_none() {
ctx.pr
.println("gpg not found, skipping verification".to_string());
return Ok(());
}
gpg::add_keys_swift(ctx)?;
let sig_path = PathBuf::from(format!("{}.sig", tarball_path.to_string_lossy()));
HTTP.download_file(format!("{}.sig", url(tv)), &sig_path, Some(ctx.pr.as_ref()))
.await?;
self.gpg(ctx)
.arg("--quiet")
.arg("--trust-model")
.arg("always")
.arg("--verify")
.arg(&sig_path)
.arg(tarball_path)
.execute()?;
Ok(())
}
fn verify(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
self.test_swift(ctx, tv)
}
fn gpg<'a>(&self, ctx: &'a InstallContext) -> CmdLineRunner<'a> {
CmdLineRunner::new("gpg").with_pr(ctx.pr.as_ref())
}
}
#[async_trait]
impl Backend for SwiftPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
let mut features = vec![SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
}];
// GPG verification is available on Linux when gpg is installed
if cfg!(target_os = "linux") && Settings::get().swift.gpg_verify != Some(false) {
features.push(SecurityFeature::Gpg);
}
features
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions = github::list_releases("swiftlang/swift")
.await?
.into_iter()
.filter_map(|r| {
r.tag_name
.strip_prefix("swift-")
.and_then(|v| v.strip_suffix("-RELEASE"))
.map(|v| (v.to_string(), r.created_at))
})
.rev()
.map(|(version, created_at)| VersionInfo {
version,
created_at: Some(created_at),
..Default::default()
})
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
if Settings::get().experimental {
Ok(vec![".swift-version".into()])
} else {
Ok(vec![])
}
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
let tarball_path = self.download(&tv, ctx.pr.as_ref()).await?;
if cfg!(target_os = "linux") && Settings::get().swift.gpg_verify != Some(false) {
self.verify_gpg(ctx, &tv, &tarball_path).await?;
}
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(ctx, &tv, &tarball_path)?;
self.symlink_bins(&tv)?;
self.verify(ctx, &tv)?;
Ok(tv)
}
}
fn swift_bin_name() -> &'static str {
if cfg!(windows) { "swift.exe" } else { "swift" }
}
fn platform_directory() -> String {
if cfg!(macos) {
"xcode".into()
} else if cfg!(windows) {
"windows10".into()
} else if let Ok(os_release) = &*os_release::OS_RELEASE {
let settings = Settings::get();
let arch = settings.arch();
if os_release.id == "ubuntu" && arch == "arm64" {
let retval = format!("{}{}-aarch64", os_release.id, os_release.version_id);
retval.replace(".", "")
} else {
platform().replace(".", "")
}
} else {
platform().replace(".", "")
}
}
fn platform() -> String {
if let Some(platform) = &Settings::get().swift.platform {
return platform.clone();
}
if cfg!(macos) {
"osx".to_string()
} else if cfg!(windows) {
"windows10".to_string()
} else if let Ok(os_release) = &*os_release::OS_RELEASE {
if os_release.id == "amzn" {
format!("amazonlinux{}", os_release.version_id)
} else if os_release.id == "ubi" {
"ubi9".to_string() // only 9 is available
} else if os_release.id == "fedora" {
"fedora39".to_string() // only 39 is available
} else {
format!("{}{}", os_release.id, os_release.version_id)
}
} else {
"ubi9".to_string()
}
}
fn extension() -> &'static str {
if cfg!(macos) {
"pkg"
} else if cfg!(windows) {
"exe"
} else {
"tar.gz"
}
}
fn architecture(settings: &Settings) -> Option<&str> {
let arch = settings.arch();
if cfg!(target_os = "linux") {
return match arch {
"x64" => None,
"arm64" => Some("aarch64"),
_ => Some(arch),
};
} else if cfg!(windows) && arch == "arm64" {
return Some("arm64");
}
None
}
fn url(tv: &ToolVersion) -> String {
let settings = Settings::get();
format!(
"https://download.swift.org/swift-{version}-release/{platform_directory}/swift-{version}-RELEASE/swift-{version}-RELEASE-{platform}{architecture}.{extension}",
version = tv.version,
platform = platform(),
platform_directory = platform_directory(),
extension = extension(),
architecture = match architecture(&settings) {
Some(arch) => format!("-{arch}"),
None => "".into(),
}
)
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/elixir.rs | src/plugins/core/elixir.rs | use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::Arc,
};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::plugins::VERSION_REGEX;
use crate::toolset::{ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{backend::Backend, backend::VersionInfo, config::Config};
use crate::{env, file, plugins};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct ElixirPlugin {
ba: Arc<BackendArg>,
}
impl ElixirPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("elixir")),
}
}
fn elixir_bin(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join(elixir_bin_name())
}
async fn test_elixir(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
ctx.pr.set_message("elixir --version".into());
CmdLineRunner::new(self.elixir_bin(tv))
.with_pr(ctx.pr.as_ref())
.envs(self.dependency_env(&ctx.config).await?)
.arg("--version")
.execute()
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let version = &tv.version;
let version = if regex!(r"^[0-9]").is_match(version) {
&format!("v{version}")
} else {
version
};
let url = format!("https://builds.hex.pm/builds/elixir/{version}.zip");
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
pr.set_message(format!("download {filename}"));
if !tarball_path.exists() {
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
}
Ok(tarball_path)
}
async fn install(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
tarball_path: &Path,
) -> Result<()> {
let filename = tarball_path.file_name().unwrap().to_string_lossy();
ctx.pr.set_message(format!("extract {filename}"));
file::remove_all(tv.install_path())?;
file::unzip(tarball_path, &tv.install_path(), &Default::default())?;
Ok(())
}
async fn verify(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
self.test_elixir(ctx, tv).await
}
}
#[async_trait]
impl Backend for ElixirPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
// Format: "version hash timestamp checksum"
// Example: "v1.17.3 abc123 2024-12-01T00:00:00Z def456"
let versions: Vec<VersionInfo> = HTTP_FETCH
.get_text("https://builds.hex.pm/builds/elixir/builds.txt")
.await?
.lines()
.unique()
.filter_map(|s| {
let parts: Vec<&str> = s.split_whitespace().collect();
if parts.len() >= 3 {
let version = parts[0].trim_start_matches('v');
let timestamp = parts[2]; // Third field is the timestamp
Some((version.to_string(), timestamp.to_string()))
} else {
None
}
})
.filter(|(v, _)| regex!(r"^[0-9]+\.[0-9]+\.[0-9]").is_match(v))
.sorted_by_cached_key(|(s, _)| {
(
Versioning::new(s.split_once('-').map(|(v, _)| v).unwrap_or(s)),
!VERSION_REGEX.is_match(s),
s.contains("-otp-"),
Versioning::new(s),
s.to_string(),
)
})
.map(|(version, created_at)| VersionInfo {
version,
created_at: Some(created_at),
..Default::default()
})
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> eyre::Result<Vec<String>> {
Ok(vec![".exenv-version".into()])
}
fn get_dependencies(&self) -> Result<Vec<&str>> {
Ok(vec!["erlang"])
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
ctx.pr.start_operations(3);
let tarball_path = self.download(&tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
self.install(ctx, &tv, &tarball_path).await?;
self.verify(ctx, &tv).await?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
Ok(["bin", ".mix/escripts"]
.iter()
.map(|p| tv.install_path().join(p))
.collect())
}
async fn exec_env(
&self,
config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let mut map = BTreeMap::new();
let mut set = |k: &str, v: PathBuf| {
map.insert(k.to_string(), v.to_string_lossy().to_string());
};
let config_env = config.env().await?;
if !env::PRISTINE_ENV.contains_key("MIX_HOME") && !config_env.contains_key("MIX_HOME") {
set("MIX_HOME", tv.install_path().join(".mix"));
}
if !env::PRISTINE_ENV.contains_key("MIX_ARCHIVES")
&& !config_env.contains_key("MIX_ARCHIVES")
{
set(
"MIX_ARCHIVES",
tv.install_path().join(".mix").join("archives"),
);
}
Ok(map)
}
}
fn elixir_bin_name() -> &'static str {
if cfg!(windows) {
"elixir.bat"
} else {
"elixir"
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/ruby_windows.rs | src/plugins/core/ruby_windows.rs | use std::{
collections::BTreeMap,
path::{Path, PathBuf},
sync::Arc,
};
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::env::PATH_KEY;
use crate::github::GithubRelease;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::toolset::{ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{file, github, plugins};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct RubyPlugin {
ba: Arc<BackendArg>,
}
impl RubyPlugin {
pub fn new() -> Self {
Self {
ba: plugins::core::new_backend_arg("ruby").into(),
}
}
fn ruby_path(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join("ruby.exe")
}
fn gem_path(&self, tv: &ToolVersion) -> PathBuf {
tv.install_path().join("bin").join("gem.cmd")
}
async fn install_default_gems(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
let settings = Settings::get();
let default_gems_file = file::replace_path(&settings.ruby.default_packages_file);
let body = file::read_to_string(&default_gems_file).unwrap_or_default();
for package in body.lines() {
let package = package.split('#').next().unwrap_or_default().trim();
if package.is_empty() {
continue;
}
pr.set_message(format!("install default gem: {}", package));
let gem = self.gem_path(tv);
let mut cmd = CmdLineRunner::new(gem)
.with_pr(pr)
.arg("install")
.envs(config.env().await?);
match package.split_once(' ') {
Some((name, "--pre")) => cmd = cmd.arg(name).arg("--pre"),
Some((name, version)) => cmd = cmd.arg(name).arg("--version").arg(version),
None => cmd = cmd.arg(package),
};
cmd.env(&*PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()?;
}
Ok(())
}
async fn test_ruby(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
pr.set_message("ruby -v".into());
CmdLineRunner::new(self.ruby_path(tv))
.with_pr(pr)
.arg("-v")
.envs(config.env().await?)
.execute()
}
async fn test_gem(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
pr: &dyn SingleReport,
) -> Result<()> {
pr.set_message("gem -v".into());
CmdLineRunner::new(self.gem_path(tv))
.with_pr(pr)
.arg("-v")
.envs(config.env().await?)
.env(&*PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.execute()
}
fn install_rubygems_hook(&self, tv: &ToolVersion) -> Result<()> {
let site_ruby_path = tv.install_path().join("lib/ruby/site_ruby");
let f = site_ruby_path.join("rubygems_plugin.rb");
file::create_dir_all(site_ruby_path)?;
file::write(f, include_str!("assets/rubygems_plugin.rb"))?;
Ok(())
}
async fn download(&self, tv: &ToolVersion, pr: &dyn SingleReport) -> Result<PathBuf> {
let arch = arch();
let url = format!(
"https://github.com/oneclick/rubyinstaller2/releases/download/RubyInstaller-{version}-1/rubyinstaller-{version}-1-{arch}.7z",
version = tv.version,
);
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
pr.set_message(format!("downloading {filename}"));
HTTP.download_file(&url, &tarball_path, Some(pr)).await?;
Ok(tarball_path)
}
async fn install(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
tarball_path: &Path,
) -> Result<()> {
let arch = arch();
let filename = tarball_path.file_name().unwrap().to_string_lossy();
ctx.pr.set_message(format!("extract {filename}"));
file::remove_all(tv.install_path())?;
file::un7z(tarball_path, &tv.download_path(), &Default::default())?;
file::rename(
tv.download_path()
.join(format!("rubyinstaller-{}-1-{arch}", tv.version)),
tv.install_path(),
)?;
Ok(())
}
async fn verify(&self, ctx: &InstallContext, tv: &ToolVersion) -> Result<()> {
self.test_ruby(&ctx.config, tv, ctx.pr.as_ref()).await
}
}
#[async_trait]
impl Backend for RubyPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
// TODO: use windows set of versions
// match self.core.fetch_remote_versions_from_mise() {
// Ok(Some(versions)) => return Ok(versions),
// Ok(None) => {}
// Err(e) => warn!("failed to fetch remote versions: {}", e),
// }
let releases: Vec<GithubRelease> = github::list_releases("oneclick/rubyinstaller2").await?;
let versions = releases
.into_iter()
.filter_map(|r| {
regex!(r"RubyInstaller-([0-9.]+)-.*")
.replace(&r.tag_name, "$1")
.parse::<String>()
.ok()
.map(|version| VersionInfo {
version,
created_at: Some(r.created_at),
..Default::default()
})
})
.unique_by(|v| v.version.clone())
.sorted_by_cached_key(|v| (Versioning::new(&v.version), v.version.clone()))
.collect();
Ok(versions)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(vec![".ruby-version".into(), "Gemfile".into()])
}
async fn parse_idiomatic_file(&self, path: &Path) -> Result<String> {
let v = match path.file_name() {
Some(name) if name == "Gemfile" => parse_gemfile(&file::read_to_string(path)?),
_ => {
// .ruby-version
let body = file::read_to_string(path)?;
body.trim()
.trim_start_matches("ruby-")
.trim_start_matches('v')
.to_string()
}
};
Ok(v)
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
let tarball = self.download(&tv, ctx.pr.as_ref()).await?;
self.verify_checksum(ctx, &mut tv, &tarball)?;
self.install(ctx, &tv, &tarball).await?;
self.verify(ctx, &tv).await?;
self.install_rubygems_hook(&tv)?;
self.test_gem(&ctx.config, &tv, ctx.pr.as_ref()).await?;
if let Err(err) = self
.install_default_gems(&ctx.config, &tv, ctx.pr.as_ref())
.await
{
warn!("failed to install default ruby gems {err:#}");
}
Ok(tv)
}
async fn exec_env(
&self,
_config: &Arc<Config>,
_ts: &Toolset,
_tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let map = BTreeMap::new();
// No modification to RUBYLIB
Ok(map)
}
}
fn parse_gemfile(body: &str) -> String {
let v = body
.lines()
.find(|line| line.trim().starts_with("ruby "))
.unwrap_or_default()
.trim()
.split('#')
.next()
.unwrap_or_default()
.replace("engine:", ":engine =>")
.replace("engine_version:", ":engine_version =>");
let v = regex!(r#".*:engine *=> *['"](?<engine>[^'"]*).*:engine_version *=> *['"](?<engine_version>[^'"]*).*"#).replace_all(&v, "${engine_version}__ENGINE__${engine}").to_string();
let v = regex!(r#".*:engine_version *=> *['"](?<engine_version>[^'"]*).*:engine *=> *['"](?<engine>[^'"]*).*"#).replace_all(&v, "${engine_version}__ENGINE__${engine}").to_string();
let v = regex!(r#" *ruby *['"]([^'"]*).*"#)
.replace_all(&v, "$1")
.to_string();
let v = regex!(r#"^[^0-9]"#).replace_all(&v, "").to_string();
let v = regex!(r#"(.*)__ENGINE__(.*)"#)
.replace_all(&v, "$2-$1")
.to_string();
// make sure it's like "ruby-3.0.0" or "3.0.0"
if !regex!(r"^(\w+-)?([0-9])(\.[0-9])*$").is_match(&v) {
return "".to_string();
}
v
}
#[allow(clippy::if_same_then_else)]
fn arch() -> &'static str {
if cfg!(target_arch = "aarch64") {
"x64"
} else {
"x64"
}
}
#[cfg(test)]
mod tests {
use crate::config::Config;
use indoc::indoc;
use pretty_assertions::assert_eq;
use super::*;
#[tokio::test]
async fn test_list_versions_matching() {
let config = Config::get().await.unwrap();
let plugin = RubyPlugin::new();
assert!(
!plugin
.list_versions_matching(&config, "3")
.await
.unwrap()
.is_empty(),
"versions for 3 should not be empty"
);
assert!(
!plugin
.list_versions_matching(&config, "truffleruby-24")
.await
.unwrap()
.is_empty(),
"versions for truffleruby-24 should not be empty"
);
assert!(
!plugin
.list_versions_matching(&config, "truffleruby+graalvm-24")
.await
.unwrap()
.is_empty(),
"versions for truffleruby+graalvm-24 should not be empty"
);
}
#[test]
fn test_parse_gemfile() {
assert_eq!(
parse_gemfile(indoc! {r#"
ruby '2.7.2'
"#}),
"2.7.2"
);
assert_eq!(
parse_gemfile(indoc! {r#"
ruby '1.9.3', engine: 'jruby', engine_version: "1.6.7"
"#}),
"jruby-1.6.7"
);
assert_eq!(
parse_gemfile(indoc! {r#"
ruby '1.9.3', :engine => 'jruby', :engine_version => '1.6.7'
"#}),
"jruby-1.6.7"
);
assert_eq!(
parse_gemfile(indoc! {r#"
ruby '1.9.3', :engine_version => '1.6.7', :engine => 'jruby'
"#}),
"jruby-1.6.7"
);
assert_eq!(
parse_gemfile(indoc! {r#"
source "https://rubygems.org"
ruby File.read(File.expand_path(".ruby-version", __dir__)).strip
"#}),
""
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/plugins/core/erlang.rs | src/plugins/core/erlang.rs | use std::collections::BTreeMap;
use std::{path::PathBuf, sync::Arc};
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::platform_target::PlatformTarget;
use crate::cli::args::BackendArg;
use crate::config::{Config, Settings};
#[cfg(unix)]
use crate::file::TarOptions;
use crate::file::display_path;
use crate::http::{HTTP, HTTP_FETCH};
use crate::install_context::InstallContext;
use crate::lock_file::LockFile;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::{file, github, plugins};
use async_trait::async_trait;
use eyre::Result;
use xx::regex;
#[cfg(linux)]
use crate::cmd::CmdLineRunner;
#[cfg(linux)]
use std::fs;
#[derive(Debug)]
pub struct ErlangPlugin {
ba: Arc<BackendArg>,
}
const KERL_VERSION: &str = "4.4.0";
impl ErlangPlugin {
pub fn new() -> Self {
Self {
ba: Arc::new(plugins::core::new_backend_arg("erlang")),
}
}
fn kerl_path(&self) -> PathBuf {
self.ba.cache_path.join(format!("kerl-{KERL_VERSION}"))
}
fn kerl_base_dir(&self) -> PathBuf {
self.ba.cache_path.join("kerl")
}
fn lock_build_tool(&self) -> Result<fslock::LockFile> {
LockFile::new(&self.kerl_path())
.with_callback(|l| {
trace!("install_or_update_kerl {}", l.display());
})
.lock()
}
async fn update_kerl(&self) -> Result<()> {
let _lock = self.lock_build_tool();
if self.kerl_path().exists() {
// TODO: find a way to not have to do this #1209
file::remove_all(self.kerl_base_dir())?;
return Ok(());
}
self.install_kerl().await?;
cmd!(self.kerl_path(), "update", "releases")
.env("KERL_BASE_DIR", self.kerl_base_dir())
.run()?;
Ok(())
}
async fn install_kerl(&self) -> Result<()> {
debug!("Installing kerl to {}", display_path(self.kerl_path()));
HTTP_FETCH
.download_file(
format!("https://raw.githubusercontent.com/kerl/kerl/{KERL_VERSION}/kerl"),
&self.kerl_path(),
None,
)
.await?;
file::make_executable(self.kerl_path())?;
Ok(())
}
#[cfg(linux)]
async fn install_precompiled(
&self,
ctx: &InstallContext,
tv: ToolVersion,
) -> Result<Option<ToolVersion>> {
if Settings::get().erlang.compile == Some(true) {
return Ok(None);
}
let release_tag = format!("OTP-{}", tv.version);
let arch: String = match ARCH {
"x86_64" => "amd64".to_string(),
"aarch64" => "arm64".to_string(),
_ => {
debug!("Unsupported architecture: {}", ARCH);
return Ok(None);
}
};
let os_ver: String;
if let Ok(os) = std::env::var("ImageOS") {
os_ver = match os.as_str() {
"ubuntu24" => "ubuntu-24.04".to_string(),
"ubuntu22" => "ubuntu-22.04".to_string(),
"ubuntu20" => "ubuntu-20.04".to_string(),
_ => os,
};
} else if let Ok(os_release) = &*os_release::OS_RELEASE {
os_ver = format!("{}-{}", os_release.id, os_release.version_id);
} else {
return Ok(None);
};
// Currently, Bob only builds for Ubuntu, so we have to check that we're on ubuntu, and on a supported version
if !["ubuntu-20.04", "ubuntu-22.04", "ubuntu-24.04"].contains(&os_ver.as_str()) {
debug!("Unsupported OS version: {}", os_ver);
return Ok(None);
}
let url: String =
format!("https://builds.hex.pm/builds/otp/{arch}/{os_ver}/{release_tag}.tar.gz");
let filename = url.split('/').next_back().unwrap();
let tarball_path = tv.download_path().join(filename);
ctx.pr.set_message(format!("Downloading {filename}"));
if !tarball_path.exists() {
HTTP.download_file(&url, &tarball_path, Some(ctx.pr.as_ref()))
.await?;
}
ctx.pr.set_message(format!("Extracting {filename}"));
file::untar(
&tarball_path,
&tv.download_path(),
&TarOptions {
strip_components: 0,
pr: Some(ctx.pr.as_ref()),
format: file::TarFormat::TarGz,
..Default::default()
},
)?;
self.move_to_install_path(&tv)?;
CmdLineRunner::new(tv.install_path().join("Install"))
.with_pr(ctx.pr.as_ref())
.arg("-minimal")
.arg(tv.install_path())
.execute()?;
Ok(Some(tv))
}
#[cfg(linux)]
fn move_to_install_path(&self, tv: &ToolVersion) -> Result<()> {
let base_dir = tv
.download_path()
.read_dir()?
.find(|e| e.as_ref().unwrap().file_type().unwrap().is_dir())
.unwrap()?
.path();
file::remove_all(tv.install_path())?;
file::create_dir_all(tv.install_path())?;
for entry in fs::read_dir(base_dir)? {
let entry = entry?;
let dest = tv.install_path().join(entry.file_name());
trace!("moving {:?} to {:?}", entry.path(), &dest);
file::rename(entry.path(), dest)?;
}
Ok(())
}
#[cfg(macos)]
async fn install_precompiled(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<Option<ToolVersion>> {
if Settings::get().erlang.compile == Some(true) {
return Ok(None);
}
let release_tag = format!("OTP-{}", tv.version);
let gh_release = match github::get_release("erlef/otp_builds", &release_tag).await {
Ok(release) => release,
Err(e) => {
debug!("Failed to get release: {}", e);
return Ok(None);
}
};
let tarball_name = format!("otp-{ARCH}-{OS}.tar.gz");
let asset = match gh_release.assets.iter().find(|a| a.name == tarball_name) {
Some(asset) => asset,
None => {
debug!("No asset found for {}", release_tag);
return Ok(None);
}
};
ctx.pr.set_message(format!("Downloading {tarball_name}"));
let tarball_path = tv.download_path().join(&tarball_name);
HTTP.download_file(
&asset.browser_download_url,
&tarball_path,
Some(ctx.pr.as_ref()),
)
.await?;
self.verify_checksum(ctx, &mut tv, &tarball_path)?;
ctx.pr.set_message(format!("Extracting {tarball_name}"));
file::untar(
&tarball_path,
&tv.install_path(),
&TarOptions {
strip_components: 0,
pr: Some(ctx.pr.as_ref()),
format: file::TarFormat::TarGz,
..Default::default()
},
)?;
Ok(Some(tv))
}
#[cfg(windows)]
async fn install_precompiled(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<Option<ToolVersion>> {
if Settings::get().erlang.compile == Some(true) {
return Ok(None);
}
let release_tag = format!("OTP-{}", tv.version);
let gh_release = match github::get_release("erlang/otp", &release_tag).await {
Ok(release) => release,
Err(e) => {
debug!("Failed to get release: {}", e);
return Ok(None);
}
};
let zip_name = format!("otp_{OS}_{version}.zip", version = tv.version);
let asset = match gh_release.assets.iter().find(|a| a.name == zip_name) {
Some(asset) => asset,
None => {
debug!("No asset found for {}", release_tag);
return Ok(None);
}
};
ctx.pr.set_message(format!("Downloading {}", zip_name));
let zip_path = tv.download_path().join(&zip_name);
HTTP.download_file(
&asset.browser_download_url,
&zip_path,
Some(ctx.pr.as_ref()),
)
.await?;
self.verify_checksum(ctx, &mut tv, &zip_path)?;
ctx.pr.set_message(format!("Extracting {}", zip_name));
file::unzip(&zip_path, &tv.install_path(), &Default::default())?;
Ok(Some(tv))
}
#[cfg(not(any(linux, macos, windows)))]
async fn install_precompiled(
&self,
ctx: &InstallContext,
tv: ToolVersion,
) -> Result<Option<ToolVersion>> {
Ok(None)
}
async fn install_via_kerl(
&self,
_ctx: &InstallContext,
tv: ToolVersion,
) -> Result<ToolVersion> {
self.update_kerl().await?;
file::remove_all(tv.install_path())?;
match &tv.request {
ToolRequest::Ref { .. } => {
unimplemented!("erlang does not yet support refs");
}
_ => {
cmd!(
self.kerl_path(),
"build-install",
&tv.version,
&tv.version,
tv.install_path()
)
.env("KERL_BASE_DIR", self.ba.cache_path.join("kerl"))
.env("MAKEFLAGS", format!("-j{}", num_cpus::get()))
.run()?;
}
}
Ok(tv)
}
}
#[async_trait]
impl Backend for ErlangPlugin {
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions = if Settings::get().erlang.compile == Some(false) {
github::list_releases("erlef/otp_builds")
.await?
.into_iter()
.filter_map(|r| {
r.tag_name
.strip_prefix("OTP-")
.map(|s| (s.to_string(), Some(r.created_at)))
})
.map(|(version, created_at)| VersionInfo {
version,
created_at,
..Default::default()
})
.collect()
} else {
self.update_kerl().await?;
plugins::core::run_fetch_task_with_timeout(move || {
let output = cmd!(self.kerl_path(), "list", "releases", "all")
.env("KERL_BASE_DIR", self.ba.cache_path.join("kerl"))
.read()?;
let versions = output
.split('\n')
.filter(|s| regex!(r"^[0-9].+$").is_match(s))
.map(|s| VersionInfo {
version: s.to_string(),
..Default::default()
})
.collect();
Ok(versions)
})?
};
Ok(versions)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
if let Some(tv) = self.install_precompiled(ctx, tv.clone()).await? {
return Ok(tv);
}
self.install_via_kerl(ctx, tv).await
}
fn resolve_lockfile_options(
&self,
_request: &ToolRequest,
target: &PlatformTarget,
) -> BTreeMap<String, String> {
let mut opts = BTreeMap::new();
let settings = Settings::get();
let is_current_platform = target.is_current();
// Only include compile option if true (non-default)
let compile = if is_current_platform {
settings.erlang.compile.unwrap_or(false)
} else {
false
};
if compile {
opts.insert("compile".to_string(), "true".to_string());
}
opts
}
}
#[cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
pub const ARCH: &str = "x86_64";
#[cfg(all(target_arch = "aarch64", not(target_os = "windows")))]
const ARCH: &str = "aarch64";
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
const ARCH: &str = "unknown";
#[cfg(windows)]
const OS: &str = "win64";
#[cfg(macos)]
const OS: &str = "apple-darwin";
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/asdf.rs | src/backend/asdf.rs | use std::fmt::{Debug, Formatter};
use std::fs;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::{collections::BTreeMap, sync::Arc};
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::external_plugin_cache::ExternalPluginCache;
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::config::{Config, Settings};
use crate::env_diff::{EnvDiff, EnvDiffOperation, EnvMap};
use crate::hash::hash_to_str;
use crate::install_context::InstallContext;
use crate::plugins::Script::{Download, ExecEnv, Install, ParseIdiomaticFile};
use crate::plugins::asdf_plugin::AsdfPlugin;
use crate::plugins::mise_plugin_toml::MisePluginToml;
use crate::plugins::{PluginType, Script, ScriptManager};
use crate::toolset::{ToolRequest, ToolVersion, Toolset};
use crate::ui::progress_report::SingleReport;
use crate::{backend::Backend, plugins::PluginEnum, timeout};
use crate::{dirs, env, file};
use async_trait::async_trait;
use color_eyre::eyre::{Result, WrapErr, eyre};
use console::style;
use heck::ToKebabCase;
/// This represents a plugin installed to ~/.local/share/mise/plugins
pub struct AsdfBackend {
pub ba: Arc<BackendArg>,
pub name: String,
pub plugin_path: PathBuf,
pub repo_url: Option<String>,
pub toml: MisePluginToml,
plugin: Arc<AsdfPlugin>,
plugin_enum: PluginEnum,
cache: ExternalPluginCache,
latest_stable_cache: CacheManager<Option<String>>,
alias_cache: CacheManager<Vec<(String, String)>>,
idiomatic_filename_cache: CacheManager<Vec<String>>,
}
impl AsdfBackend {
pub fn from_arg(ba: BackendArg) -> Self {
let name = ba.tool_name.clone();
let plugin_path = dirs::PLUGINS.join(ba.short.to_kebab_case());
let plugin = AsdfPlugin::new(name.clone(), plugin_path.clone());
let mut toml_path = plugin_path.join("mise.plugin.toml");
if plugin_path.join("rtx.plugin.toml").exists() {
toml_path = plugin_path.join("rtx.plugin.toml");
}
let toml = MisePluginToml::from_file(&toml_path).unwrap();
let plugin = Arc::new(plugin);
let plugin_enum = PluginEnum::Asdf(plugin.clone());
Self {
cache: ExternalPluginCache::default(),
latest_stable_cache: CacheManagerBuilder::new(
ba.cache_path.join("latest_stable.msgpack.z"),
)
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.with_fresh_file(plugin_path.clone())
.with_fresh_file(plugin_path.join("bin/latest-stable"))
.build(),
alias_cache: CacheManagerBuilder::new(ba.cache_path.join("aliases.msgpack.z"))
.with_fresh_file(plugin_path.clone())
.with_fresh_file(plugin_path.join("bin/list-aliases"))
.build(),
idiomatic_filename_cache: CacheManagerBuilder::new(
ba.cache_path.join("idiomatic_filenames.msgpack.z"),
)
.with_fresh_file(plugin_path.clone())
.with_fresh_file(plugin_path.join("bin/list-legacy-filenames"))
.build(),
plugin_path,
plugin,
plugin_enum,
repo_url: None,
toml,
name,
ba: Arc::new(ba),
}
}
fn fetch_cached_idiomatic_file(&self, idiomatic_file: &Path) -> Result<Option<String>> {
let fp = self.idiomatic_cache_file_path(idiomatic_file);
if !fp.exists() || fp.metadata()?.modified()? < idiomatic_file.metadata()?.modified()? {
return Ok(None);
}
Ok(Some(fs::read_to_string(fp)?.trim().into()))
}
fn idiomatic_cache_file_path(&self, idiomatic_file: &Path) -> PathBuf {
self.ba
.cache_path
.join("idiomatic")
.join(&self.name)
.join(hash_to_str(&idiomatic_file.to_string_lossy()))
.with_extension("txt")
}
fn write_idiomatic_cache(&self, idiomatic_file: &Path, idiomatic_version: &str) -> Result<()> {
let fp = self.idiomatic_cache_file_path(idiomatic_file);
file::create_dir_all(fp.parent().unwrap())?;
file::write(fp, idiomatic_version)?;
Ok(())
}
async fn fetch_bin_paths(&self, config: &Arc<Config>, tv: &ToolVersion) -> Result<Vec<String>> {
let list_bin_paths = self.plugin_path.join("bin/list-bin-paths");
let bin_paths = if matches!(tv.request, ToolRequest::System { .. }) {
Vec::new()
} else if list_bin_paths.exists() {
let sm = self.script_man_for_tv(config, tv).await?;
// TODO: find a way to enable this without deadlocking
// for (t, tv) in ts.list_current_installed_versions(config) {
// if t.name == self.name {
// continue;
// }
// for p in t.list_bin_paths(config, ts, &tv)? {
// sm.prepend_path(p);
// }
// }
let output = sm.cmd(&Script::ListBinPaths).read()?;
output
.split_whitespace()
.map(|f| {
if f == "." {
String::new()
} else {
f.to_string()
}
})
.collect()
} else {
vec!["bin".into()]
};
Ok(bin_paths)
}
async fn fetch_exec_env(
&self,
config: &Arc<Config>,
ts: &Toolset,
tv: &ToolVersion,
) -> Result<EnvMap> {
let mut sm = self.script_man_for_tv(config, tv).await?;
for p in ts.list_paths(config).await {
sm.prepend_path(p);
}
let script = sm.get_script_path(&ExecEnv);
let dir = dirs::CWD.clone().unwrap_or_default();
let ed = EnvDiff::from_bash_script(&script, &dir, &sm.env, &Default::default())?;
let env = ed
.to_patches()
.into_iter()
.filter_map(|p| match p {
EnvDiffOperation::Add(key, value) => Some((key, value)),
EnvDiffOperation::Change(key, value) => Some((key, value)),
_ => None,
})
.collect();
Ok(env)
}
async fn script_man_for_tv(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<ScriptManager> {
let mut sm = self.plugin.script_man.clone();
for (key, value) in tv.request.options().opts {
let k = format!("RTX_TOOL_OPTS__{}", key.to_uppercase());
sm = sm.with_env(k, value.clone());
let k = format!("MISE_TOOL_OPTS__{}", key.to_uppercase());
sm = sm.with_env(k, value.clone());
}
for (key, value) in tv.request.options().install_env {
sm = sm.with_env(key, value.clone());
}
if let Some(project_root) = &config.project_root {
let project_root = project_root.to_string_lossy().to_string();
sm = sm.with_env("RTX_PROJECT_ROOT", project_root.clone());
sm = sm.with_env("MISE_PROJECT_ROOT", project_root);
}
let install_type = match &tv.request {
ToolRequest::Version { .. } | ToolRequest::Prefix { .. } => "version",
ToolRequest::Ref { .. } => "ref",
ToolRequest::Path { .. } => "path",
ToolRequest::Sub { .. } => "sub",
ToolRequest::System { .. } => {
panic!("should not be called for system tool")
}
};
let install_version = match &tv.request {
ToolRequest::Ref { ref_: v, .. } => v, // should not have "ref:" prefix
_ => &tv.version,
};
// add env vars from mise.toml files
for (key, value) in config.env().await? {
sm = sm.with_env(key, value.clone());
}
let install = tv.install_path().to_string_lossy().to_string();
let download = tv.download_path().to_string_lossy().to_string();
sm = sm
.with_env("ASDF_DOWNLOAD_PATH", &download)
.with_env("ASDF_INSTALL_PATH", &install)
.with_env("ASDF_INSTALL_TYPE", install_type)
.with_env("ASDF_INSTALL_VERSION", install_version)
.with_env("RTX_DOWNLOAD_PATH", &download)
.with_env("RTX_INSTALL_PATH", &install)
.with_env("RTX_INSTALL_TYPE", install_type)
.with_env("RTX_INSTALL_VERSION", install_version)
.with_env("MISE_DOWNLOAD_PATH", download)
.with_env("MISE_INSTALL_PATH", install)
.with_env("MISE_INSTALL_TYPE", install_type)
.with_env("MISE_INSTALL_VERSION", install_version);
Ok(sm)
}
}
impl Eq for AsdfBackend {}
impl PartialEq for AsdfBackend {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
impl Hash for AsdfBackend {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
#[async_trait]
impl Backend for AsdfBackend {
fn get_type(&self) -> BackendType {
BackendType::Asdf
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_plugin_type(&self) -> Option<PluginType> {
Some(PluginType::Asdf)
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions = self.plugin.fetch_remote_versions()?;
Ok(versions
.into_iter()
.map(|v| VersionInfo {
version: v,
..Default::default()
})
.collect())
}
async fn latest_stable_version(&self, config: &Arc<Config>) -> Result<Option<String>> {
timeout::run_with_timeout_async(
|| async {
if !self.plugin.has_latest_stable_script() {
return self.latest_version(config, Some("latest".into())).await;
}
self.latest_stable_cache
.get_or_try_init(|| self.plugin.fetch_latest_stable())
.wrap_err_with(|| {
eyre!(
"Failed fetching latest stable version for plugin {}",
style(&self.name).blue().for_stderr(),
)
})
.cloned()
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
}
fn get_aliases(&self) -> Result<BTreeMap<String, String>> {
if let Some(data) = &self.toml.list_aliases.data {
return Ok(self.plugin.parse_aliases(data).into_iter().collect());
}
if !self.plugin.has_list_alias_script() {
return Ok(BTreeMap::new());
}
let aliases = self
.alias_cache
.get_or_try_init(|| self.plugin.fetch_aliases())
.wrap_err_with(|| {
eyre!(
"Failed fetching aliases for plugin {}",
style(&self.name).blue().for_stderr(),
)
})?
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Ok(aliases)
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
if let Some(data) = &self.toml.list_idiomatic_filenames.data {
return Ok(self.plugin.parse_idiomatic_filenames(data));
}
if !self.plugin.has_list_idiomatic_filenames_script() {
return Ok(vec![]);
}
self.idiomatic_filename_cache
.get_or_try_init(|| self.plugin.fetch_idiomatic_filenames())
.wrap_err_with(|| {
eyre!(
"Failed fetching idiomatic filenames for plugin {}",
style(&self.name).blue().for_stderr(),
)
})
.cloned()
}
async fn parse_idiomatic_file(&self, idiomatic_file: &Path) -> Result<String> {
if let Some(cached) = self.fetch_cached_idiomatic_file(idiomatic_file)? {
return Ok(cached);
}
trace!(
"parsing idiomatic file: {}",
idiomatic_file.to_string_lossy()
);
let script = ParseIdiomaticFile(idiomatic_file.to_string_lossy().into());
let idiomatic_version = match self.plugin.script_man.script_exists(&script) {
true => self.plugin.script_man.read(&script)?,
false => fs::read_to_string(idiomatic_file)?,
}
.trim()
.to_string();
self.write_idiomatic_cache(idiomatic_file, &idiomatic_version)?;
Ok(idiomatic_version)
}
fn plugin(&self) -> Option<&PluginEnum> {
Some(&self.plugin_enum)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
let mut sm = self.script_man_for_tv(&ctx.config, &tv).await?;
for p in ctx.ts.list_paths(&ctx.config).await {
sm.prepend_path(p);
}
let run_script = |script| sm.run_by_line(script, ctx.pr.as_ref());
if sm.script_exists(&Download) {
ctx.pr.set_message("bin/download".into());
run_script(&Download)?;
}
ctx.pr.set_message("bin/install".into());
run_script(&Install)?;
file::remove_dir(&self.ba.downloads_path)?;
Ok(tv)
}
async fn uninstall_version_impl(
&self,
config: &Arc<Config>,
pr: &dyn SingleReport,
tv: &ToolVersion,
) -> Result<()> {
if self.plugin_path.join("bin/uninstall").exists() {
self.script_man_for_tv(config, tv)
.await?
.run_by_line(&Script::Uninstall, pr)?;
}
Ok(())
}
async fn list_bin_paths(&self, config: &Arc<Config>, tv: &ToolVersion) -> Result<Vec<PathBuf>> {
Ok(self
.cache
.list_bin_paths(config, self, tv, async || {
self.fetch_bin_paths(config, tv).await
})
.await?
.into_iter()
.map(|path| tv.install_path().join(path))
.collect())
}
async fn exec_env(
&self,
config: &Arc<Config>,
ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<EnvMap> {
let total_start = std::time::Instant::now();
if matches!(tv.request, ToolRequest::System { .. }) {
return Ok(BTreeMap::new());
}
if !self.plugin.script_man.script_exists(&ExecEnv) || *env::__MISE_SCRIPT {
// if the script does not exist, or we're already running from within a script,
// the second is to prevent infinite loops
return Ok(BTreeMap::new());
}
let res = self
.cache
.exec_env(config, self, tv, async || {
self.fetch_exec_env(config, ts, tv).await
})
.await;
trace!(
"exec_env cache.get_or_try_init_async for {} finished in {}ms",
self.name,
total_start.elapsed().as_millis()
);
res
}
}
impl Debug for AsdfBackend {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AsdfPlugin")
.field("name", &self.name)
.field("plugin_path", &self.plugin_path)
.field("cache_path", &self.ba.cache_path)
.field("downloads_path", &self.ba.downloads_path)
.field("installs_path", &self.ba.installs_path)
.field("repo_url", &self.repo_url)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_debug() {
let _config = Config::get().await.unwrap();
let plugin = AsdfBackend::from_arg("dummy".into());
assert!(format!("{plugin:?}").starts_with("AsdfPlugin { name: \"dummy\""));
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/external_plugin_cache.rs | src/backend/external_plugin_cache.rs | use crate::backend::asdf::AsdfBackend;
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::config::Config;
use crate::env;
use crate::env_diff::EnvMap;
use crate::hash::hash_to_str;
use crate::tera::{BASE_CONTEXT, get_tera};
use crate::toolset::{ToolRequest, ToolVersion};
use dashmap::DashMap;
use eyre::{WrapErr, eyre};
use std::sync::Arc;
#[derive(Debug, Default)]
pub struct ExternalPluginCache {
list_bin_paths: DashMap<ToolRequest, CacheManager<Vec<String>>>,
exec_env: DashMap<ToolRequest, CacheManager<EnvMap>>,
}
impl ExternalPluginCache {
pub async fn list_bin_paths<F, Fut>(
&self,
config: &Arc<Config>,
plugin: &AsdfBackend,
tv: &ToolVersion,
fetch: F,
) -> eyre::Result<Vec<String>>
where
Fut: Future<Output = eyre::Result<Vec<String>>>,
F: FnOnce() -> Fut,
{
let cm = self
.list_bin_paths
.entry(tv.request.clone())
.or_insert_with(|| {
let list_bin_paths_filename = match &plugin.toml.list_bin_paths.cache_key {
Some(key) => {
let key = render_cache_key(config, tv, key);
let filename = format!("{key}.msgpack.z");
tv.cache_path().join("list_bin_paths").join(filename)
}
None => tv.cache_path().join("list_bin_paths.msgpack.z"),
};
CacheManagerBuilder::new(list_bin_paths_filename)
.with_fresh_file(plugin.plugin_path.clone())
.with_fresh_file(tv.install_path())
.build()
});
let start = std::time::Instant::now();
let res = cm.get_or_try_init_async(fetch).await.cloned();
trace!(
"external_plugin_cache.list_bin_paths for {} took {}ms",
plugin.name,
start.elapsed().as_millis()
);
res
}
pub async fn exec_env<F, Fut>(
&self,
config: &Config,
plugin: &AsdfBackend,
tv: &ToolVersion,
fetch: F,
) -> eyre::Result<EnvMap>
where
Fut: Future<Output = eyre::Result<EnvMap>>,
F: FnOnce() -> Fut,
{
let cm = self.exec_env.entry(tv.request.clone()).or_insert_with(|| {
let exec_env_filename = match &plugin.toml.exec_env.cache_key {
Some(key) => {
let key = render_cache_key(config, tv, key);
let filename = format!("{key}.msgpack.z");
tv.cache_path().join("exec_env").join(filename)
}
None => tv.cache_path().join("exec_env.msgpack.z"),
};
CacheManagerBuilder::new(exec_env_filename)
.with_fresh_file(plugin.plugin_path.clone())
.with_fresh_file(tv.install_path())
.build()
});
let start = std::time::Instant::now();
let res = cm.get_or_try_init_async(fetch).await.cloned();
trace!(
"external_plugin_cache.exec_env for {} took {}ms",
plugin.name,
start.elapsed().as_millis()
);
res
}
}
fn render_cache_key(config: &Config, tv: &ToolVersion, cache_key: &[String]) -> String {
let elements = cache_key
.iter()
.map(|tmpl| {
let s = parse_template(config, tv, tmpl).unwrap();
let s = s.trim().to_string();
trace!("cache key element: {} -> {}", tmpl.trim(), s);
let mut s = hash_to_str(&s);
s = s.chars().take(10).collect();
s
})
.collect::<Vec<String>>();
elements.join("-")
}
fn parse_template(config: &Config, tv: &ToolVersion, tmpl: &str) -> eyre::Result<String> {
let mut ctx = BASE_CONTEXT.clone();
ctx.insert("project_root", &config.project_root);
ctx.insert("opts", &tv.request.options().opts);
get_tera(
config
.project_root
.as_ref()
.or(env::current_dir().as_ref().ok())
.map(|p| p.as_path()),
)
.render_str(tmpl, &ctx)
.wrap_err_with(|| eyre!("failed to parse template: {tmpl}"))
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/vfox.rs | src/backend/vfox.rs | use crate::{env, plugins::PluginEnum, timeout};
use async_trait::async_trait;
use eyre::WrapErr;
use heck::ToKebabCase;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread;
use tokio::sync::RwLock;
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::config::{Config, Settings};
use crate::dirs;
use crate::env_diff::EnvMap;
use crate::install_context::InstallContext;
use crate::plugins::Plugin;
use crate::plugins::vfox_plugin::VfoxPlugin;
use crate::toolset::{ToolVersion, Toolset};
use crate::ui::multi_progress_report::MultiProgressReport;
#[derive(Debug)]
pub struct VfoxBackend {
ba: Arc<BackendArg>,
plugin: Arc<VfoxPlugin>,
plugin_enum: PluginEnum,
exec_env_cache: RwLock<HashMap<String, CacheManager<EnvMap>>>,
pathname: String,
tool_name: Option<String>,
}
#[async_trait]
impl Backend for VfoxBackend {
fn get_type(&self) -> BackendType {
match self.plugin_enum {
PluginEnum::VfoxBackend(_) => BackendType::VfoxBackend(self.plugin.name().to_string()),
PluginEnum::Vfox(_) => BackendType::Vfox,
_ => unreachable!(),
}
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
let this = self;
timeout::run_with_timeout_async(
|| async {
let (vfox, _log_rx) = this.plugin.vfox();
this.ensure_plugin_installed(config).await?;
// Use backend methods if the plugin supports them
if this.is_backend_plugin() {
Settings::get().ensure_experimental("custom backends")?;
debug!("Using backend method for plugin: {}", this.pathname);
let tool_name = this.get_tool_name()?;
let versions = vfox
.backend_list_versions(&this.pathname, tool_name)
.await
.wrap_err("Backend list versions method failed")?;
return Ok(versions
.into_iter()
.map(|v| VersionInfo {
version: v,
..Default::default()
})
.collect());
}
// Use default vfox behavior for traditional plugins
let versions = vfox.list_available_versions(&this.pathname).await?;
Ok(versions
.into_iter()
.rev()
.map(|v| VersionInfo {
version: v.version,
..Default::default()
})
.collect())
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
}
async fn install_version_(
&self,
ctx: &InstallContext,
tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
self.ensure_plugin_installed(&ctx.config).await?;
let (vfox, log_rx) = self.plugin.vfox();
thread::spawn(|| {
for line in log_rx {
// TODO: put this in ctx.pr.set_message()
info!("{}", line);
}
});
// Use backend methods if the plugin supports them
if self.is_backend_plugin() {
Settings::get().ensure_experimental("custom backends")?;
let tool_name = self.get_tool_name()?;
vfox.backend_install(&self.pathname, tool_name, &tv.version, tv.install_path())
.await
.wrap_err("Backend install method failed")?;
return Ok(tv);
}
// Use default vfox behavior for traditional plugins
vfox.install(&self.pathname, &tv.version, tv.install_path())
.await?;
Ok(tv)
}
async fn list_bin_paths(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<Vec<PathBuf>> {
let path = self
._exec_env(config, tv)
.await?
.iter()
.find(|(k, _)| k.to_uppercase() == "PATH")
.map(|(_, v)| v.to_string())
.unwrap_or("bin".to_string());
Ok(env::split_paths(&path).collect())
}
async fn exec_env(
&self,
config: &Arc<Config>,
_ts: &Toolset,
tv: &ToolVersion,
) -> eyre::Result<EnvMap> {
Ok(self
._exec_env(config, tv)
.await?
.into_iter()
.filter(|(k, _)| k.to_uppercase() != "PATH")
.collect())
}
fn plugin(&self) -> Option<&PluginEnum> {
Some(&self.plugin_enum)
}
async fn idiomatic_filenames(&self) -> eyre::Result<Vec<String>> {
let (vfox, _log_rx) = self.plugin.vfox();
let metadata = vfox.metadata(&self.pathname).await?;
Ok(metadata.legacy_filenames)
}
async fn parse_idiomatic_file(&self, path: &Path) -> eyre::Result<String> {
let (vfox, _log_rx) = self.plugin.vfox();
let response = vfox.parse_legacy_file(&self.pathname, path).await?;
response.version.ok_or_else(|| {
eyre::eyre!(
"Version for {} not found in '{}'",
self.pathname,
path.display()
)
})
}
async fn get_tarball_url(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> eyre::Result<Option<String>> {
let config = Config::get().await?;
self.ensure_plugin_installed(&config).await?;
// Map mise platform names to vfox platform names
let os = match target.os_name() {
"macos" => "darwin",
os => os,
};
let arch = match target.arch_name() {
"x64" => "amd64",
arch => arch,
};
let (vfox, _log_rx) = self.plugin.vfox();
let pre_install = vfox
.pre_install_for_platform(&self.pathname, &tv.version, os, arch)
.await?;
Ok(pre_install.url)
}
}
impl VfoxBackend {
fn is_backend_plugin(&self) -> bool {
matches!(&self.plugin_enum, PluginEnum::VfoxBackend(_))
}
fn get_tool_name(&self) -> eyre::Result<&str> {
self.tool_name
.as_deref()
.ok_or_else(|| eyre::eyre!("VfoxBackend requires a tool name (plugin:tool format)"))
}
pub fn from_arg(ba: BackendArg, backend_plugin_name: Option<String>) -> Self {
let pathname = match &backend_plugin_name {
Some(plugin_name) => plugin_name.clone(),
None => ba.short.to_kebab_case(),
};
let plugin_path = dirs::PLUGINS.join(&pathname);
let mut plugin = VfoxPlugin::new(pathname.clone(), plugin_path.clone());
plugin.full = Some(ba.full());
let plugin = Arc::new(plugin);
// Extract tool name for plugin:tool format
let tool_name = if ba.short.contains(':') {
ba.short.split_once(':').map(|(_, tool)| tool.to_string())
} else {
None
};
Self {
exec_env_cache: Default::default(),
plugin: plugin.clone(),
plugin_enum: match backend_plugin_name {
Some(_) => PluginEnum::VfoxBackend(plugin),
None => PluginEnum::Vfox(plugin),
},
ba: Arc::new(ba),
pathname,
tool_name,
}
}
async fn _exec_env(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<BTreeMap<String, String>> {
let opts = tv.request.options();
let opts_hash = {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
opts.hash(&mut hasher);
hasher.finish()
};
let key = format!("{}:{:x}", tv, opts_hash);
let cache_file = format!("exec_env_{:x}.msgpack.z", opts_hash);
if !self.exec_env_cache.read().await.contains_key(&key) {
let mut caches = self.exec_env_cache.write().await;
caches.insert(
key.clone(),
CacheManagerBuilder::new(tv.cache_path().join(&cache_file))
.with_fresh_file(dirs::DATA.to_path_buf())
.with_fresh_file(self.plugin.plugin_path.to_path_buf())
.with_fresh_file(self.ba().installs_path.to_path_buf())
.build(),
);
}
let exec_env_cache = self.exec_env_cache.read().await;
let cache = exec_env_cache.get(&key).unwrap();
cache
.get_or_try_init_async(async || {
self.ensure_plugin_installed(config).await?;
let (vfox, _log_rx) = self.plugin.vfox();
// Use backend methods if the plugin supports them
let env_keys = if self.is_backend_plugin() {
let tool_name = self.get_tool_name()?;
vfox.backend_exec_env(&self.pathname, tool_name, &tv.version, tv.install_path())
.await
.wrap_err("Backend exec env method failed")?
} else {
vfox.env_keys(&self.pathname, &tv.version, &opts.opts)
.await?
};
Ok(env_keys
.into_iter()
.fold(BTreeMap::new(), |mut acc, env_key| {
let key = &env_key.key;
if let Some(val) = acc.get(key) {
let mut paths = env::split_paths(val).collect::<Vec<PathBuf>>();
paths.push(PathBuf::from(&env_key.value));
acc.insert(
env_key.key.clone(),
env::join_paths(paths)
.unwrap()
.to_string_lossy()
.to_string(),
);
} else {
acc.insert(key.clone(), env_key.value.clone());
}
acc
}))
})
.await
.cloned()
}
async fn ensure_plugin_installed(&self, config: &Arc<Config>) -> eyre::Result<()> {
self.plugin
.ensure_installed(config, &MultiProgressReport::get(), false, false)
.await
}
}
#[cfg(test)]
mod test {
use super::*;
#[tokio::test]
async fn test_vfox_props() {
let _config = Config::get().await.unwrap();
let backend = VfoxBackend::from_arg("vfox:version-fox/vfox-golang".into(), None);
assert_eq!(backend.pathname, "vfox-version-fox-vfox-golang");
assert_eq!(
backend.plugin.full,
Some("vfox:version-fox/vfox-golang".to_string())
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/jq.rs | src/backend/jq.rs | /// Simplified jq-like JSON path extraction.
///
/// Supports a subset of jq syntax for extracting values from JSON:
/// - `.` - root value
/// - `.[]` - iterate over array elements
/// - `.[].field` - extract field from each array element
/// - `.field` - extract field from object
/// - `.field[]` - iterate over array in field
/// - `.field[].subfield` - extract subfield from array elements
/// - `.field.subfield` - nested field access
///
/// Values are extracted as strings, with 'v' prefix stripped from version-like values.
use eyre::Result;
/// Extract string values from JSON using a jq-like path expression
///
/// # Examples
/// ```
/// use mise::backend::jq::extract;
/// use serde_json::json;
///
/// let data = json!(["1.0.0", "2.0.0"]);
/// assert_eq!(extract(&data, ".[]").unwrap(), vec!["1.0.0", "2.0.0"]);
///
/// let data = json!([{"version": "v1.0.0"}, {"version": "v2.0.0"}]);
/// assert_eq!(extract(&data, ".[].version").unwrap(), vec!["1.0.0", "2.0.0"]);
/// ```
pub fn extract(json: &serde_json::Value, path: &str) -> Result<Vec<String>> {
let mut results = Vec::new();
let path = path.trim();
// Handle empty path or "." as root
if path.is_empty() || path == "." {
extract_values(json, &mut results);
return Ok(results);
}
// Remove leading dot if present
let path = path.strip_prefix('.').unwrap_or(path);
// Parse the path and extract values
extract_recursive(json, path, &mut results);
Ok(results)
}
/// Extract values with auto-detection of common version patterns
pub fn extract_auto(json: &serde_json::Value) -> Vec<String> {
let mut results = Vec::new();
match json {
serde_json::Value::String(s) => {
let v = normalize_version(s);
if !v.is_empty() {
results.push(v);
}
}
serde_json::Value::Array(arr) => {
for val in arr {
if let Some(v) = val.as_str() {
let v = normalize_version(v);
if !v.is_empty() {
results.push(v);
}
} else if let Some(obj) = val.as_object() {
// Try common version field names
for field in ["version", "tag_name", "name", "tag", "v"] {
if let Some(v) = obj.get(field).and_then(|v| v.as_str()) {
let v = normalize_version(v);
if !v.is_empty() {
results.push(v);
break;
}
}
}
}
}
}
serde_json::Value::Object(obj) => {
// Check for common patterns like {"versions": [...]} or {"releases": [...]}
for field in ["versions", "releases", "tags", "version", "release"] {
if let Some(val) = obj.get(field) {
let extracted = extract_auto(val);
if !extracted.is_empty() {
return extracted;
}
}
}
}
_ => {}
}
results
}
fn extract_recursive(json: &serde_json::Value, path: &str, results: &mut Vec<String>) {
if path.is_empty() {
// End of path, extract value(s)
extract_values(json, results);
return;
}
// Handle array iteration "[]"
if path == "[]" {
if let Some(arr) = json.as_array() {
for val in arr {
extract_values(val, results);
}
}
return;
}
// Handle "[]." prefix (iterate then continue path)
if let Some(rest) = path.strip_prefix("[].") {
if let Some(arr) = json.as_array() {
for val in arr {
extract_recursive(val, rest, results);
}
}
return;
}
// Handle field access with possible continuation
// Find where the field name ends (at '.' or '[')
let (field, rest) = if let Some(idx) = path.find(['.', '[']) {
let (f, r) = path.split_at(idx);
// Strip the leading dot if present, but preserve '[' for array handling
let rest = r.strip_prefix('.').unwrap_or(r);
(f, rest)
} else {
(path, "")
};
if let Some(obj) = json.as_object()
&& let Some(val) = obj.get(field)
{
extract_recursive(val, rest, results);
}
}
fn extract_values(json: &serde_json::Value, results: &mut Vec<String>) {
match json {
serde_json::Value::String(s) => {
let v = normalize_version(s);
if !v.is_empty() {
results.push(v);
}
}
serde_json::Value::Array(arr) => {
for val in arr {
if let Some(s) = val.as_str() {
let v = normalize_version(s);
if !v.is_empty() {
results.push(v);
}
}
}
}
serde_json::Value::Number(n) => {
results.push(n.to_string());
}
_ => {}
}
}
/// Normalize a version string by trimming whitespace and stripping 'v' prefix
fn normalize_version(s: &str) -> String {
s.trim().trim_start_matches('v').to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_extract_root_string() {
let data = json!("v2.0.53");
assert_eq!(extract(&data, ".").unwrap(), vec!["2.0.53"]);
}
#[test]
fn test_extract_root_array() {
let data = json!(["1.0.0", "2.0.0"]);
assert_eq!(extract(&data, ".").unwrap(), vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_extract_array_iterate() {
let data = json!(["v1.0.0", "v2.0.0"]);
assert_eq!(extract(&data, ".[]").unwrap(), vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_extract_array_field() {
let data = json!([{"version": "1.0.0"}, {"version": "2.0.0"}]);
assert_eq!(
extract(&data, ".[].version").unwrap(),
vec!["1.0.0", "2.0.0"]
);
}
#[test]
fn test_extract_nested_field() {
let data = json!({"data": {"version": "1.0.0"}});
assert_eq!(extract(&data, ".data.version").unwrap(), vec!["1.0.0"]);
}
#[test]
fn test_extract_nested_array() {
let data = json!({"data": {"versions": ["1.0.0", "2.0.0"]}});
assert_eq!(
extract(&data, ".data.versions[]").unwrap(),
vec!["1.0.0", "2.0.0"]
);
}
#[test]
fn test_extract_deeply_nested() {
let data =
json!({"releases": [{"info": {"version": "1.0.0"}}, {"info": {"version": "2.0.0"}}]});
assert_eq!(
extract(&data, ".releases[].info.version").unwrap(),
vec!["1.0.0", "2.0.0"]
);
}
#[test]
fn test_extract_object_field_array() {
let data = json!({"versions": ["1.0.0", "2.0.0"]});
assert_eq!(
extract(&data, ".versions[]").unwrap(),
vec!["1.0.0", "2.0.0"]
);
}
#[test]
fn test_extract_empty_path() {
let data = json!("1.0.0");
assert_eq!(extract(&data, "").unwrap(), vec!["1.0.0"]);
}
#[test]
fn test_extract_missing_field() {
let data = json!({"foo": "bar"});
assert!(extract(&data, ".missing").unwrap().is_empty());
}
#[test]
fn test_extract_auto_string() {
let data = json!("v1.0.0");
assert_eq!(extract_auto(&data), vec!["1.0.0"]);
}
#[test]
fn test_extract_auto_array_strings() {
let data = json!(["v1.0.0", "v2.0.0"]);
assert_eq!(extract_auto(&data), vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_extract_auto_array_objects() {
let data = json!([{"version": "1.0.0"}, {"tag_name": "v2.0.0"}]);
assert_eq!(extract_auto(&data), vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_extract_auto_object_versions_field() {
let data = json!({"versions": ["1.0.0", "2.0.0"]});
assert_eq!(extract_auto(&data), vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_extract_auto_object_releases_field() {
let data = json!({"releases": ["1.0.0", "2.0.0"]});
assert_eq!(extract_auto(&data), vec!["1.0.0", "2.0.0"]);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/aqua.rs | src/backend/aqua.rs | use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::get_filename_from_url;
use crate::cli::args::BackendArg;
use crate::cli::version::{ARCH, OS};
use crate::config::Settings;
use crate::file::TarOptions;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::path::{Path, PathBuf, PathExt};
use crate::plugins::VERSION_REGEX;
use crate::registry::REGISTRY;
use crate::toolset::ToolVersion;
use crate::{
aqua::aqua_registry_wrapper::{
AQUA_REGISTRY, AquaChecksum, AquaChecksumType, AquaMinisignType, AquaPackage,
AquaPackageType,
},
cache::{CacheManager, CacheManagerBuilder},
};
use crate::{backend::Backend, config::Config};
use crate::{env, file, github, minisign};
use async_trait::async_trait;
use dashmap::DashMap;
use eyre::{ContextCompat, Result, bail, eyre};
use indexmap::IndexSet;
use itertools::Itertools;
use regex::Regex;
use std::borrow::Cow;
use std::fmt::Debug;
use std::{collections::HashSet, sync::Arc};
#[derive(Debug)]
pub struct AquaBackend {
ba: Arc<BackendArg>,
id: String,
version_tags_cache: CacheManager<Vec<(String, String)>>,
bin_path_caches: DashMap<String, CacheManager<Vec<PathBuf>>>,
}
#[async_trait]
impl Backend for AquaBackend {
fn get_type(&self) -> BackendType {
BackendType::Aqua
}
async fn description(&self) -> Option<String> {
AQUA_REGISTRY
.package(&self.ba.tool_name)
.await
.ok()
.and_then(|p| p.description.clone())
}
async fn security_info(&self) -> Vec<crate::backend::SecurityFeature> {
use crate::backend::SecurityFeature;
let pkg = match AQUA_REGISTRY.package(&self.ba.tool_name).await {
Ok(pkg) => pkg,
Err(_) => return vec![],
};
let mut features = vec![];
// Check base package and all version overrides for security features
// This gives a complete picture of available security features across all versions
let all_pkgs: Vec<&AquaPackage> = std::iter::once(&pkg)
.chain(pkg.version_overrides.iter())
.collect();
// Fetch release assets to detect actual security features
let release_assets = if !pkg.repo_owner.is_empty() && !pkg.repo_name.is_empty() {
let repo = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
github::list_releases(&repo)
.await
.ok()
.and_then(|releases| releases.first().cloned())
.map(|r| r.assets)
.unwrap_or_default()
} else {
vec![]
};
// Checksum - check registry config OR actual release assets
let has_checksum_config = all_pkgs.iter().any(|p| {
p.checksum
.as_ref()
.is_some_and(|checksum| checksum.enabled())
});
let has_checksum_assets = release_assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains("sha256")
|| name.contains("checksum")
|| name.ends_with(".sha256")
|| name.ends_with(".sha512")
});
if has_checksum_config || has_checksum_assets {
let algorithm = all_pkgs
.iter()
.filter_map(|p| p.checksum.as_ref())
.find_map(|c| c.algorithm.as_ref().map(|a| a.to_string()))
.or_else(|| {
if has_checksum_assets {
Some("sha256".to_string())
} else {
None
}
});
features.push(SecurityFeature::Checksum { algorithm });
}
// GitHub Attestations - check registry config OR actual release assets
let has_attestations_config = all_pkgs.iter().any(|p| {
p.github_artifact_attestations
.as_ref()
.is_some_and(|a| a.enabled.unwrap_or(true))
});
let has_attestations_assets = release_assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.ends_with(".sigstore.json") || name.ends_with(".sigstore")
});
if has_attestations_config || has_attestations_assets {
let signer_workflow = all_pkgs
.iter()
.filter_map(|p| p.github_artifact_attestations.as_ref())
.find_map(|a| a.signer_workflow.clone());
features.push(SecurityFeature::GithubAttestations { signer_workflow });
}
// SLSA - check registry config OR actual release assets
let has_slsa_config = all_pkgs.iter().any(|p| {
p.slsa_provenance
.as_ref()
.is_some_and(|s| s.enabled.unwrap_or(true))
});
let has_slsa_assets = release_assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains(".intoto.jsonl")
|| name.contains("provenance")
|| name.ends_with(".attestation")
});
if has_slsa_config || has_slsa_assets {
features.push(SecurityFeature::Slsa { level: None });
}
// Cosign (nested in checksum) - check registry config OR actual release assets
let has_cosign_config = all_pkgs.iter().any(|p| {
p.checksum
.as_ref()
.and_then(|c| c.cosign.as_ref())
.is_some_and(|cosign| cosign.enabled.unwrap_or(true))
});
let has_cosign_assets = release_assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.ends_with(".sig") || name.contains("cosign")
});
if has_cosign_config || has_cosign_assets {
features.push(SecurityFeature::Cosign);
}
// Minisign - check registry config OR actual release assets
let has_minisign_config = all_pkgs.iter().any(|p| {
p.minisign
.as_ref()
.is_some_and(|m| m.enabled.unwrap_or(true))
});
let has_minisign_assets = release_assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.ends_with(".minisig")
});
if has_minisign_config || has_minisign_assets {
let public_key = all_pkgs
.iter()
.filter_map(|p| p.minisign.as_ref())
.find_map(|m| m.public_key.clone());
features.push(SecurityFeature::Minisign { public_key });
}
features
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let pkg = match AQUA_REGISTRY.package(&self.id).await {
Ok(pkg) => pkg,
Err(e) => {
warn!("Remote versions cannot be fetched: {}", e);
return Ok(vec![]);
}
};
if pkg.repo_owner.is_empty() || pkg.repo_name.is_empty() {
warn!(
"aqua package {} does not have repo_owner and/or repo_name.",
self.id
);
return Ok(vec![]);
}
let tags_with_timestamps = match get_tags_with_created_at(&pkg).await {
Ok(tags) => tags,
Err(e) => {
warn!("Remote versions cannot be fetched: {}", e);
return Ok(vec![]);
}
};
let mut versions = Vec::new();
for (tag, created_at) in tags_with_timestamps.into_iter().rev() {
let mut version = tag.as_str();
match pkg.version_filter_ok(version) {
Ok(true) => {}
Ok(false) => continue,
Err(e) => {
warn!("[{}] aqua version filter error: {e}", self.ba());
continue;
}
}
let versioned_pkg = pkg.clone().with_version(&[version], os(), arch());
if let Some(prefix) = &versioned_pkg.version_prefix {
if let Some(_v) = version.strip_prefix(prefix) {
version = _v;
} else {
continue;
}
}
version = version.strip_prefix('v').unwrap_or(version);
// Validate the package has assets
let check_pkg = AQUA_REGISTRY
.package_with_version(&self.id, &[&tag])
.await
.unwrap_or_default();
if !check_pkg.no_asset && check_pkg.error_message.is_none() {
let release_url = format!(
"https://github.com/{}/{}/releases/tag/{}",
pkg.repo_owner, pkg.repo_name, tag
);
versions.push(VersionInfo {
version: version.to_string(),
created_at,
release_url: Some(release_url),
});
}
}
Ok(versions)
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
// Check if URL already exists in lockfile platforms first
// This allows us to skip API calls when lockfile has the URL
let platform_key = self.get_platform_key();
let existing_platform = tv
.lock_platforms
.get(&platform_key)
.and_then(|asset| asset.url.clone());
// Skip get_version_tags() API call if we have lockfile URL
let tag = if existing_platform.is_some() {
None // We'll determine version from URL instead
} else {
self.get_version_tags()
.await
.ok()
.into_iter()
.flatten()
.find(|(version, _)| version == &tv.version)
.map(|(_, tag)| tag.clone())
};
let mut v = tag.clone().unwrap_or_else(|| tv.version.clone());
let mut v_prefixed =
(tag.is_none() && !tv.version.starts_with('v')).then(|| format!("v{v}"));
let versions = match &v_prefixed {
Some(v_prefixed) => vec![v.as_str(), v_prefixed.as_str()],
None => vec![v.as_str()],
};
let pkg = AQUA_REGISTRY
.package_with_version(&self.id, &versions)
.await?;
if let Some(prefix) = &pkg.version_prefix
&& !v.starts_with(prefix)
{
v = format!("{prefix}{v}");
// Don't add prefix to v_prefixed if it already starts with the prefix
v_prefixed = v_prefixed.map(|vp| {
if vp.starts_with(prefix) {
vp
} else {
format!("{prefix}{vp}")
}
});
}
validate(&pkg)?;
let (url, v, filename, api_digest) =
if let Some(existing_platform) = existing_platform.clone() {
let url = existing_platform;
let filename = get_filename_from_url(&url);
// Determine which version variant was used based on the URL or filename
// Check for version_prefix (e.g., "jq-" for jq), "v" prefix, or raw version
let v = if let Some(prefix) = &pkg.version_prefix {
let prefixed_version = format!("{prefix}{}", tv.version);
if url.contains(&prefixed_version) || filename.contains(&prefixed_version) {
prefixed_version
} else if url.contains(&format!("v{}", tv.version))
|| filename.contains(&format!("v{}", tv.version))
{
format!("v{}", tv.version)
} else {
tv.version.clone()
}
} else if url.contains(&format!("v{}", tv.version))
|| filename.contains(&format!("v{}", tv.version))
{
format!("v{}", tv.version)
} else {
tv.version.clone()
};
(url, v, filename, None)
} else {
let (url, v, digest) = if let Some(v_prefixed) = v_prefixed {
// Try v-prefixed version first because most aqua packages use v-prefixed versions
match self.get_url(&pkg, v_prefixed.as_ref()).await {
// If the url is already checked, use it
Ok((url, true, digest)) => (url, v_prefixed, digest),
Ok((url_prefixed, false, digest_prefixed)) => {
let (url, _, digest) = self.get_url(&pkg, &v).await?;
// If the v-prefixed URL is the same as the non-prefixed URL, use it
if url == url_prefixed {
(url_prefixed, v_prefixed, digest_prefixed)
} else {
// If they are different, check existence
match HTTP.head(&url_prefixed).await {
Ok(_) => (url_prefixed, v_prefixed, digest_prefixed),
Err(_) => (url, v, digest),
}
}
}
Err(err) => {
let (url, _, digest) =
self.get_url(&pkg, &v).await.map_err(|e| err.wrap_err(e))?;
(url, v, digest)
}
}
} else {
let (url, _, digest) = self.get_url(&pkg, &v).await?;
(url, v, digest)
};
let filename = get_filename_from_url(&url);
(url, v.to_string(), filename, digest)
};
// Determine operation count for progress reporting
let format = pkg.format(&v, os(), arch()).unwrap_or_default();
let op_count = Self::calculate_op_count(&pkg, &api_digest, format);
ctx.pr.start_operations(op_count);
self.download(ctx, &tv, &url, &filename).await?;
if existing_platform.is_none() {
// Store the asset URL and digest (if available) in the tool version
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(url.clone());
if let Some(digest) = api_digest {
debug!("using GitHub API digest for checksum verification");
platform_info.checksum = Some(digest);
}
}
self.verify(ctx, &mut tv, &pkg, &v, &filename).await?;
self.install(ctx, &tv, &pkg, &v, &filename)?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
if self.symlink_bins(tv) {
return Ok(vec![tv.install_path().join(".mise-bins")]);
}
let cache = self
.bin_path_caches
.entry(tv.version.clone())
.or_insert_with(|| {
CacheManagerBuilder::new(tv.cache_path().join("bin_paths.msgpack.z"))
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.build()
});
let install_path = tv.install_path();
let paths = cache
.get_or_try_init_async(async || {
// TODO: align this logic with the one in `install_version_`
let pkg = AQUA_REGISTRY
.package_with_version(&self.id, &[&tv.version])
.await?;
let srcs = self.srcs(&pkg, tv)?;
let paths = if srcs.is_empty() {
vec![install_path.clone()]
} else {
srcs.iter()
.map(|(_, dst)| dst.parent().unwrap().to_path_buf())
.collect()
};
Ok(paths
.into_iter()
.unique()
.filter(|p| p.exists())
.map(|p| p.strip_prefix(&install_path).unwrap().to_path_buf())
.collect())
})
.await?
.iter()
.map(|p| p.mount(&install_path))
.collect();
Ok(paths)
}
fn fuzzy_match_filter(&self, versions: Vec<String>, query: &str) -> Vec<String> {
let escaped_query = regex::escape(query);
let query = if query == "latest" {
"\\D*[0-9].*"
} else {
&escaped_query
};
let query_regex = Regex::new(&format!("^{query}([-.].+)?$")).unwrap();
versions
.into_iter()
.filter(|v| {
if query == v {
return true;
}
if VERSION_REGEX.is_match(v) {
return false;
}
query_regex.is_match(v)
})
.collect()
}
/// Resolve platform-specific lock information for any target platform.
/// This enables cross-platform lockfile generation without installation.
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
// Map Platform to Aqua's os/arch conventions
let target_os = match target.os_name() {
"macos" => "darwin",
other => other,
};
let target_arch = match target.arch_name() {
"x64" => "amd64",
other => other,
};
// Get version tag
let tag = self
.get_version_tags()
.await
.ok()
.into_iter()
.flatten()
.find(|(version, _)| version == &tv.version)
.map(|(_, tag)| tag);
let mut v = tag.cloned().unwrap_or_else(|| tv.version.clone());
let v_prefixed = (tag.is_none() && !tv.version.starts_with('v')).then(|| format!("v{v}"));
let versions = match &v_prefixed {
Some(v_prefixed) => vec![v.as_str(), v_prefixed.as_str()],
None => vec![v.as_str()],
};
// Get package with version for the target platform
let pkg = AQUA_REGISTRY
.package_with_version(&self.id, &versions)
.await?;
let pkg = pkg.with_version(&versions, target_os, target_arch);
// Apply version prefix if present
if let Some(prefix) = &pkg.version_prefix
&& !v.starts_with(prefix)
{
v = format!("{prefix}{v}");
}
// Check if this platform is supported
if !is_platform_supported(&pkg.supported_envs, target_os, target_arch) {
debug!(
"aqua package {} does not support {}: supported_envs={:?}",
self.id,
target.to_key(),
pkg.supported_envs
);
return Ok(PlatformInfo::default());
}
// Get URL and checksum for the target platform
let (url, checksum) = match pkg.r#type {
AquaPackageType::GithubRelease => {
// For GitHub releases, we need to find the asset for the target platform
let asset_strs = pkg.asset_strs(&v, target_os, target_arch)?;
match self.github_release_asset(&pkg, &v, asset_strs).await {
Ok((url, digest)) => (Some(url), digest),
Err(e) => {
debug!(
"Failed to get GitHub release asset for {} on {}: {}",
self.id,
target.to_key(),
e
);
(None, None)
}
}
}
AquaPackageType::GithubArchive | AquaPackageType::GithubContent => {
(Some(self.github_archive_url(&pkg, &v)), None)
}
AquaPackageType::Http => (pkg.url(&v, target_os, target_arch).ok(), None),
_ => (None, None),
};
let name = url.as_ref().map(|u| get_filename_from_url(u));
// Try to get checksum from checksum file if not available from GitHub API
let checksum = match checksum {
Some(c) => Some(c),
None => self
.fetch_checksum_from_file(&pkg, &v, target_os, target_arch, name.as_deref())
.await
.ok()
.flatten(),
};
Ok(PlatformInfo {
url,
checksum,
size: None,
url_api: None,
})
}
}
impl AquaBackend {
pub fn from_arg(ba: BackendArg) -> Self {
let full = ba.full_without_opts();
let mut id = full.split_once(":").unwrap_or(("", &full)).1;
if !id.contains("/") {
id = REGISTRY
.get(id)
.and_then(|t| t.backends.iter().find_map(|s| s.full.strip_prefix("aqua:")))
.unwrap_or_else(|| {
warn!("invalid aqua tool: {}", id);
id
});
}
let cache_path = ba.cache_path.clone();
Self {
id: id.to_string(),
ba: Arc::new(ba),
version_tags_cache: CacheManagerBuilder::new(cache_path.join("version_tags.msgpack.z"))
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.build(),
bin_path_caches: Default::default(),
}
}
async fn get_version_tags(&self) -> Result<&Vec<(String, String)>> {
self.version_tags_cache
.get_or_try_init_async(|| async {
let pkg = AQUA_REGISTRY.package(&self.id).await?;
let mut versions = Vec::new();
if !pkg.repo_owner.is_empty() && !pkg.repo_name.is_empty() {
let tags = get_tags(&pkg).await?;
for tag in tags.into_iter().rev() {
let mut version = tag.as_str();
match pkg.version_filter_ok(version) {
Ok(true) => {}
Ok(false) => continue,
Err(e) => {
warn!("[{}] aqua version filter error: {e}", self.ba());
continue;
}
}
let pkg = pkg.clone().with_version(&[version], os(), arch());
if let Some(prefix) = &pkg.version_prefix {
if let Some(_v) = version.strip_prefix(prefix) {
version = _v;
} else {
continue;
}
}
version = version.strip_prefix('v').unwrap_or(version);
versions.push((version.to_string(), tag));
}
} else {
bail!(
"aqua package {} does not have repo_owner and/or repo_name.",
self.id
);
}
Ok(versions)
})
.await
}
async fn get_url(&self, pkg: &AquaPackage, v: &str) -> Result<(String, bool, Option<String>)> {
match pkg.r#type {
AquaPackageType::GithubRelease => self
.github_release_url(pkg, v)
.await
.map(|(url, digest)| (url, true, digest)),
AquaPackageType::GithubArchive | AquaPackageType::GithubContent => {
Ok((self.github_archive_url(pkg, v), false, None))
}
AquaPackageType::Http => pkg.url(v, os(), arch()).map(|url| (url, false, None)),
ref t => bail!("unsupported aqua package type: {t}"),
}
}
/// Calculate the number of operations for progress reporting.
/// Operations: download (always), checksum (if enabled or api_digest), extraction (if needed)
fn calculate_op_count(pkg: &AquaPackage, api_digest: &Option<String>, format: &str) -> usize {
let mut op_count = 1; // download
// Checksum verification (from pkg config or GitHub API digest)
if pkg.checksum.as_ref().is_some_and(|c| c.enabled()) || api_digest.is_some() {
op_count += 1;
}
// Extraction (for archives, or GithubArchive/GithubContent which always extract)
if (!format.is_empty() && format != "raw")
|| matches!(
pkg.r#type,
AquaPackageType::GithubArchive | AquaPackageType::GithubContent
)
{
op_count += 1;
}
op_count
}
async fn github_release_url(
&self,
pkg: &AquaPackage,
v: &str,
) -> Result<(String, Option<String>)> {
let asset_strs = pkg.asset_strs(v, os(), arch())?;
self.github_release_asset(pkg, v, asset_strs).await
}
async fn github_release_asset(
&self,
pkg: &AquaPackage,
v: &str,
asset_strs: IndexSet<String>,
) -> Result<(String, Option<String>)> {
let gh_id = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
let gh_release = github::get_release(&gh_id, v).await?;
// Prioritize order of asset_strs
let asset = asset_strs
.iter()
.find_map(|expected| {
gh_release.assets.iter().find(|a| {
a.name == *expected || a.name.to_lowercase() == expected.to_lowercase()
})
})
.wrap_err_with(|| {
format!(
"no asset found: {}\nAvailable assets:\n{}",
asset_strs.iter().join(", "),
gh_release.assets.iter().map(|a| &a.name).join("\n")
)
})?;
Ok((asset.browser_download_url.to_string(), asset.digest.clone()))
}
fn github_archive_url(&self, pkg: &AquaPackage, v: &str) -> String {
let gh_id = format!("{}/{}", pkg.repo_owner, pkg.repo_name);
format!("https://github.com/{gh_id}/archive/refs/tags/{v}.tar.gz")
}
/// Fetch checksum from a checksum file without downloading the actual tarball.
/// This is used for cross-platform lockfile generation.
async fn fetch_checksum_from_file(
&self,
pkg: &AquaPackage,
v: &str,
target_os: &str,
target_arch: &str,
filename: Option<&str>,
) -> Result<Option<String>> {
let Some(checksum_config) = &pkg.checksum else {
return Ok(None);
};
if !checksum_config.enabled() {
return Ok(None);
}
let Some(filename) = filename else {
return Ok(None);
};
// Get the checksum file URL
let url = match checksum_config._type() {
AquaChecksumType::GithubRelease => {
let asset_strs = checksum_config.asset_strs(pkg, v, target_os, target_arch)?;
match self.github_release_asset(pkg, v, asset_strs).await {
Ok((url, _)) => url,
Err(e) => {
debug!("Failed to get checksum file asset: {}", e);
return Ok(None);
}
}
}
AquaChecksumType::Http => checksum_config.url(pkg, v, target_os, target_arch)?,
};
// Download checksum file content
let checksum_content = match HTTP.get_text(&url).await {
Ok(content) => content,
Err(e) => {
debug!("Failed to download checksum file {}: {}", url, e);
return Ok(None);
}
};
// Parse checksum from file content
let checksum_str =
self.parse_checksum_from_content(&checksum_content, checksum_config, filename)?;
Ok(Some(format!(
"{}:{}",
checksum_config.algorithm(),
checksum_str
)))
}
/// Parse a checksum from checksum file content for a specific filename.
fn parse_checksum_from_content(
&self,
content: &str,
checksum_config: &AquaChecksum,
filename: &str,
) -> Result<String> {
let mut checksum_file = content.to_string();
if checksum_config.file_format() == "regexp" {
let pattern = checksum_config.pattern();
if let Some(file_pattern) = &pattern.file {
let re = regex::Regex::new(file_pattern.as_str())?;
if let Some(line) = checksum_file
.lines()
.find(|l| re.captures(l).is_some_and(|c| c[1].to_string() == filename))
{
checksum_file = line.to_string();
} else {
debug!(
"no line found matching {} in checksum file for {}",
file_pattern, filename
);
}
}
let re = regex::Regex::new(pattern.checksum.as_str())?;
if let Some(caps) = re.captures(checksum_file.as_str()) {
checksum_file = caps[1].to_string();
} else {
debug!(
"no checksum found matching {} in checksum file",
pattern.checksum
);
}
}
// Standard format: "<hash> <filename>" or "<hash> *<filename>"
let checksum_str = checksum_file
.lines()
.filter_map(|l| {
let split = l.split_whitespace().collect_vec();
if split.len() == 2 {
Some((
split[0].to_string(),
split[1]
.rsplit_once('/')
.map(|(_, f)| f)
.unwrap_or(split[1])
.trim_matches('*')
.to_string(),
))
} else {
None
}
})
.find(|(_, f)| f == filename)
.map(|(c, _)| c)
.unwrap_or(checksum_file);
let checksum_str = checksum_str
.split_whitespace()
.next()
.unwrap_or(&checksum_str);
Ok(checksum_str.to_string())
}
/// Download a URL to a path, or convert a local path string to PathBuf.
/// Returns the path where the file is located.
async fn download_url_to_path(
&self,
url: &str,
download_path: &Path,
ctx: &InstallContext,
) -> Result<PathBuf> {
if url.starts_with("http") {
let path = download_path.join(get_filename_from_url(url));
HTTP.download_file(url, &path, Some(ctx.pr.as_ref()))
.await?;
Ok(path)
} else {
Ok(PathBuf::from(url))
}
}
async fn download(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
url: &str,
filename: &str,
) -> Result<()> {
let tarball_path = tv.download_path().join(filename);
if tarball_path.exists() {
return Ok(());
}
ctx.pr.set_message(format!("download {filename}"));
HTTP.download_file(url, &tarball_path, Some(ctx.pr.as_ref()))
.await?;
Ok(())
}
async fn verify(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
pkg: &AquaPackage,
v: &str,
filename: &str,
) -> Result<()> {
self.verify_slsa(ctx, tv, pkg, v, filename).await?;
self.verify_minisign(ctx, tv, pkg, v, filename).await?;
self.verify_github_attestations(ctx, tv, pkg, v, filename)
.await?;
let download_path = tv.download_path();
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
if platform_info.checksum.is_none()
&& let Some(checksum) = &pkg.checksum
&& checksum.enabled()
{
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/http.rs | src/backend/http.rs | use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::static_helpers::{
clean_binary_name, get_filename_from_url, list_available_platforms_with_key,
lookup_platform_key, template_string, verify_artifact,
};
use crate::backend::version_list;
use crate::cli::args::BackendArg;
use crate::config::Config;
use crate::config::Settings;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::toolset::ToolVersion;
use crate::toolset::ToolVersionOptions;
use crate::ui::progress_report::SingleReport;
use crate::{dirs, file, hash};
use async_trait::async_trait;
use eyre::Result;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
// Constants
const HTTP_TARBALLS_DIR: &str = "http-tarballs";
const METADATA_FILE: &str = "metadata.json";
/// Helper to get an option value with platform-specific fallback
fn get_opt(opts: &ToolVersionOptions, key: &str) -> Option<String> {
lookup_platform_key(opts, key).or_else(|| opts.get(key).cloned())
}
/// Metadata stored alongside cached extractions
#[derive(Debug, Serialize, Deserialize)]
struct CacheMetadata {
url: String,
checksum: Option<String>,
size: u64,
extracted_at: u64,
platform: String,
}
/// Describes what type of content was extracted to cache
#[derive(Debug, Clone)]
enum ExtractionType {
/// A single raw file (not an archive) with its filename
RawFile { filename: String },
/// An archive (tarball, zip, etc.) that was extracted
Archive,
}
/// Information about a downloaded file's format
struct FileInfo {
/// Path with effective extension (after applying format option)
effective_path: PathBuf,
/// File extension
extension: String,
/// Detected archive format
format: file::TarFormat,
/// Whether this is a compressed single binary (not a tar archive)
is_compressed_binary: bool,
}
impl FileInfo {
/// Analyze a file path and options to determine format information
fn new(file_path: &Path, opts: &ToolVersionOptions) -> Self {
// Apply format config to determine effective extension
let effective_path = if let Some(added_ext) = get_opt(opts, "format") {
let mut path = file_path.to_path_buf();
let current_ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let new_ext = if current_ext.is_empty() {
added_ext
} else {
format!("{}.{}", current_ext, added_ext)
};
path.set_extension(new_ext);
path
} else {
file_path.to_path_buf()
};
let extension = effective_path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let format = file::TarFormat::from_ext(&extension);
let file_name = effective_path.file_name().unwrap().to_string_lossy();
let is_compressed_binary = !file_name.contains(".tar")
&& matches!(extension.as_str(), "gz" | "xz" | "bz2" | "zst");
Self {
effective_path,
extension,
format,
is_compressed_binary,
}
}
/// Get the filename portion of the effective path
fn file_name(&self) -> String {
self.effective_path
.file_name()
.unwrap()
.to_string_lossy()
.to_string()
}
/// Get the decompressed name (for compressed binaries)
fn decompressed_name(&self) -> String {
self.file_name()
.trim_end_matches(&format!(".{}", self.extension))
.to_string()
}
}
#[derive(Debug)]
pub struct HttpBackend {
ba: Arc<BackendArg>,
}
impl HttpBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
// -------------------------------------------------------------------------
// Cache path helpers
// -------------------------------------------------------------------------
/// Get the http-tarballs directory in DATA (survives `mise cache clear`)
fn tarballs_dir() -> PathBuf {
dirs::DATA.join(HTTP_TARBALLS_DIR)
}
/// Get the path to a specific cache entry
fn cache_path(&self, cache_key: &str) -> PathBuf {
Self::tarballs_dir().join(cache_key)
}
/// Get the path to the metadata file for a cache entry
fn metadata_path(&self, cache_key: &str) -> PathBuf {
self.cache_path(cache_key).join(METADATA_FILE)
}
/// Check if a cache entry exists and is valid
fn is_cached(&self, cache_key: &str) -> bool {
self.cache_path(cache_key).exists() && self.metadata_path(cache_key).exists()
}
// -------------------------------------------------------------------------
// Cache key generation
// -------------------------------------------------------------------------
/// Generate a cache key based on file content and extraction options
fn cache_key(&self, file_path: &Path, opts: &ToolVersionOptions) -> Result<String> {
let checksum = hash::file_hash_blake3(file_path, None)?;
// Include extraction options that affect output structure
// Note: bin_path is NOT included - handled at symlink time for deduplication
let mut parts = vec![checksum];
if let Some(strip) = get_opt(opts, "strip_components") {
parts.push(format!("strip_{strip}"));
}
let key = parts.join("_");
debug!("Cache key: {}", key);
Ok(key)
}
// -------------------------------------------------------------------------
// Filename determination
// -------------------------------------------------------------------------
/// Determine the destination filename for a raw file or compressed binary
fn dest_filename(
&self,
file_path: &Path,
file_info: &FileInfo,
opts: &ToolVersionOptions,
) -> String {
// Check for explicit bin name first
if let Some(bin_name) = get_opt(opts, "bin") {
return bin_name;
}
// Auto-clean the binary name
let raw_name = if file_info.is_compressed_binary {
file_info.decompressed_name()
} else {
file_path.file_name().unwrap().to_string_lossy().to_string()
};
clean_binary_name(&raw_name, Some(&self.ba.tool_name))
}
// -------------------------------------------------------------------------
// Extraction type detection
// -------------------------------------------------------------------------
/// Detect extraction type from an existing cache directory
/// This handles the case where a cache hit occurs but the original extraction
/// used different options (e.g., different `bin` name)
fn extraction_type_from_cache(&self, cache_key: &str, file_info: &FileInfo) -> ExtractionType {
// For archives, we don't need to detect the filename
if !file_info.is_compressed_binary && file_info.format != file::TarFormat::Raw {
return ExtractionType::Archive;
}
// For raw files, find the actual filename in the cache directory
let cache_path = self.cache_path(cache_key);
for entry in xx::file::ls(&cache_path).unwrap_or_default() {
if let Some(name) = entry.file_name().map(|n| n.to_string_lossy().to_string()) {
// Skip metadata file
if name != METADATA_FILE {
return ExtractionType::RawFile { filename: name };
}
}
}
// Fallback: shouldn't happen if cache is valid, but use a sensible default
ExtractionType::RawFile {
filename: self.ba.tool_name.clone(),
}
}
// -------------------------------------------------------------------------
// Extraction
// -------------------------------------------------------------------------
/// Extract artifact to cache with atomic rename
fn extract_to_cache(
&self,
file_path: &Path,
cache_key: &str,
url: &str,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<ExtractionType> {
let cache_path = self.cache_path(cache_key);
// Ensure parent directory exists
file::create_dir_all(Self::tarballs_dir())?;
// Create unique temp directory for atomic extraction
let tmp_path = Self::tarballs_dir().join(format!(
"{}.tmp-{}-{}",
cache_key,
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
));
// Clean up any stale temp directory
if tmp_path.exists() {
let _ = file::remove_all(&tmp_path);
}
// Perform extraction
let extraction_type = self.extract_artifact(&tmp_path, file_path, opts, pr)?;
// Atomic replace
if cache_path.exists() {
file::remove_all(&cache_path)?;
}
std::fs::rename(&tmp_path, &cache_path)?;
// Write metadata
self.write_metadata(cache_key, url, file_path, opts)?;
Ok(extraction_type)
}
/// Extract a single artifact to the given directory
fn extract_artifact(
&self,
dest: &Path,
file_path: &Path,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<ExtractionType> {
file::create_dir_all(dest)?;
let file_info = FileInfo::new(file_path, opts);
if file_info.is_compressed_binary {
self.extract_compressed_binary(dest, file_path, &file_info, opts, pr)
} else if file_info.format == file::TarFormat::Raw {
self.extract_raw_file(dest, file_path, &file_info, opts, pr)
} else {
self.extract_archive(dest, file_path, &file_info, opts, pr)
}
}
/// Extract a compressed binary (gz, xz, bz2, zst)
fn extract_compressed_binary(
&self,
dest: &Path,
file_path: &Path,
file_info: &FileInfo,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<ExtractionType> {
let filename = self.dest_filename(file_path, file_info, opts);
let dest_file = dest.join(&filename);
// Report extraction progress
if let Some(pr) = pr {
pr.set_message(format!("extract {}", file_info.file_name()));
if let Ok(metadata) = file_path.metadata() {
pr.set_length(metadata.len());
}
}
match file_info.extension.as_str() {
"gz" => file::un_gz(file_path, &dest_file)?,
"xz" => file::un_xz(file_path, &dest_file)?,
"bz2" => file::un_bz2(file_path, &dest_file)?,
"zst" => file::un_zst(file_path, &dest_file)?,
_ => unreachable!(),
}
// Mark extraction complete
if let Some(pr) = pr
&& let Ok(metadata) = file_path.metadata()
{
pr.set_position(metadata.len());
}
file::make_executable(&dest_file)?;
Ok(ExtractionType::RawFile { filename })
}
/// Extract a raw (uncompressed) file
fn extract_raw_file(
&self,
dest: &Path,
file_path: &Path,
file_info: &FileInfo,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<ExtractionType> {
let filename = self.dest_filename(file_path, file_info, opts);
let dest_file = dest.join(&filename);
// Report extraction progress
if let Some(pr) = pr {
pr.set_message(format!("extract {}", file_info.file_name()));
if let Ok(metadata) = file_path.metadata() {
pr.set_length(metadata.len());
}
}
file::copy(file_path, &dest_file)?;
// Mark extraction complete
if let Some(pr) = pr
&& let Ok(metadata) = file_path.metadata()
{
pr.set_position(metadata.len());
}
file::make_executable(&dest_file)?;
Ok(ExtractionType::RawFile { filename })
}
/// Extract an archive (tar, zip, etc.)
fn extract_archive(
&self,
dest: &Path,
file_path: &Path,
file_info: &FileInfo,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<ExtractionType> {
let mut strip_components: Option<usize> =
get_opt(opts, "strip_components").and_then(|s| s.parse().ok());
// Auto-detect strip_components=1 for single-directory archives
if strip_components.is_none()
&& get_opt(opts, "bin_path").is_none()
&& file::should_strip_components(file_path, file_info.format).unwrap_or(false)
{
debug!("Auto-detected single directory archive, using strip_components=1");
strip_components = Some(1);
}
let tar_opts = file::TarOptions {
format: file_info.format,
strip_components: strip_components.unwrap_or(0),
pr,
preserve_mtime: false,
};
file::untar(file_path, dest, &tar_opts)?;
Ok(ExtractionType::Archive)
}
/// Write cache metadata file
fn write_metadata(
&self,
cache_key: &str,
url: &str,
file_path: &Path,
opts: &ToolVersionOptions,
) -> Result<()> {
let metadata = CacheMetadata {
url: url.to_string(),
checksum: get_opt(opts, "checksum"),
size: file_path.metadata()?.len(),
extracted_at: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
platform: self.get_platform_key(),
};
let json = serde_json::to_string_pretty(&metadata)?;
file::write(self.metadata_path(cache_key), json)?;
Ok(())
}
// -------------------------------------------------------------------------
// Symlink creation
// -------------------------------------------------------------------------
/// Create install symlink(s) from install directory to cache
fn create_install_symlink(
&self,
tv: &ToolVersion,
cache_key: &str,
extraction_type: &ExtractionType,
opts: &ToolVersionOptions,
) -> Result<()> {
let cache_path = self.cache_path(cache_key);
// Determine version name for install path
let version_name = if tv.version == "latest" || tv.version.is_empty() {
&cache_key[..7.min(cache_key.len())] // Content-based versioning
} else {
&tv.version
};
let install_path = tv.ba().installs_path.join(version_name);
// Clean up existing install
if install_path.exists() {
file::remove_all(&install_path)?;
}
if let Some(parent) = install_path.parent() {
file::create_dir_all(parent)?;
}
// Handle raw files with bin_path specially for deduplication
if let ExtractionType::RawFile { filename } = extraction_type
&& let Some(bin_path_template) = get_opt(opts, "bin_path")
{
let bin_path = template_string(&bin_path_template, tv);
let dest_dir = install_path.join(&bin_path);
file::create_dir_all(&dest_dir)?;
let cached_file = cache_path.join(filename);
let install_file = dest_dir.join(filename);
file::make_symlink(&cached_file, &install_file)?;
return Ok(());
}
// Default: symlink entire install path to cache
file::make_symlink(&cache_path, &install_path)?;
Ok(())
}
/// Create additional symlink for implicit versions (latest, empty)
fn create_version_alias_symlink(&self, tv: &ToolVersion, cache_key: &str) -> Result<()> {
if tv.version != "latest" && !tv.version.is_empty() {
return Ok(());
}
let content_version = &cache_key[..7.min(cache_key.len())];
let original_path = tv.ba().installs_path.join(&tv.version);
let content_path = tv.ba().installs_path.join(content_version);
if original_path.exists() {
file::remove_all(&original_path)?;
}
if let Some(parent) = original_path.parent() {
file::create_dir_all(parent)?;
}
file::make_symlink(&content_path, &original_path)?;
Ok(())
}
// -------------------------------------------------------------------------
// Checksum verification
// -------------------------------------------------------------------------
/// Verify or generate checksum for lockfile support
fn verify_checksum(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
file_path: &Path,
) -> Result<()> {
let settings = Settings::get();
let filename = file_path.file_name().unwrap().to_string_lossy();
let lockfile_enabled = settings.lockfile && settings.experimental;
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
// Verify or generate checksum
if let Some(checksum) = &platform_info.checksum {
ctx.pr.set_message(format!("checksum {filename}"));
let (algo, check) = checksum
.split_once(':')
.ok_or_else(|| eyre::eyre!("Invalid checksum format: {checksum}"))?;
hash::ensure_checksum(file_path, check, Some(ctx.pr.as_ref()), algo)?;
} else if lockfile_enabled {
ctx.pr.set_message(format!("generate checksum {filename}"));
let h = hash::file_hash_blake3(file_path, Some(ctx.pr.as_ref()))?;
platform_info.checksum = Some(format!("blake3:{h}"));
}
// Verify or record size
if let Some(expected_size) = platform_info.size {
ctx.pr.set_message(format!("verify size {filename}"));
let actual_size = file_path.metadata()?.len();
if actual_size != expected_size {
return Err(eyre::eyre!(
"Size mismatch for {filename}: expected {expected_size}, got {actual_size}"
));
}
} else if lockfile_enabled {
platform_info.size = Some(file_path.metadata()?.len());
}
Ok(())
}
// -------------------------------------------------------------------------
// Version listing
// -------------------------------------------------------------------------
/// Fetch versions from version_list_url if configured
async fn fetch_versions(&self) -> Result<Vec<String>> {
let opts = self.ba.opts();
let url = match opts.get("version_list_url") {
Some(url) => url.clone(),
None => return Ok(vec![]),
};
let regex = opts.get("version_regex").map(|s| s.as_str());
let json_path = opts.get("version_json_path").map(|s| s.as_str());
version_list::fetch_versions(&url, regex, json_path).await
}
}
/// Returns install-time-only option keys for HTTP backend.
pub fn install_time_option_keys() -> Vec<String> {
vec![
"url".into(),
"checksum".into(),
"version_list_url".into(),
"version_regex".into(),
"version_json_path".into(),
"format".into(),
]
}
#[async_trait]
impl Backend for HttpBackend {
fn get_type(&self) -> BackendType {
BackendType::Http
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let versions = self.fetch_versions().await?;
Ok(versions
.into_iter()
.map(|v| VersionInfo {
version: v,
..Default::default()
})
.collect())
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
let opts = tv.request.options();
// Get URL template
let url_template = get_opt(&opts, "url").ok_or_else(|| {
let platform_key = self.get_platform_key();
let available = list_available_platforms_with_key(&opts, "url");
if !available.is_empty() {
eyre::eyre!(
"No URL for platform {platform_key}. Available: {}. \
Provide 'url' or add 'platforms.{platform_key}.url'",
available.join(", ")
)
} else {
eyre::eyre!("Http backend requires 'url' option")
}
})?;
let url = template_string(&url_template, &tv);
// Download
let filename = get_filename_from_url(&url);
let file_path = tv.download_path().join(&filename);
// Record URL in lock platforms
let platform_key = self.get_platform_key();
tv.lock_platforms
.entry(platform_key.clone())
.or_default()
.url = Some(url.clone());
// Determine operation count for progress reporting
let mut op_count = 1; // download
if get_opt(&opts, "checksum").is_some() {
op_count += 1;
}
op_count += 1; // extraction
// Account for lockfile checksum verification/generation
let settings = Settings::get();
let lockfile_enabled = settings.lockfile && settings.experimental;
let has_lockfile_checksum = tv
.lock_platforms
.get(&platform_key)
.and_then(|p| p.checksum.as_ref())
.is_some();
if lockfile_enabled || has_lockfile_checksum {
op_count += 1;
}
ctx.pr.start_operations(op_count);
ctx.pr.set_message(format!("download {filename}"));
HTTP.download_file(&url, &file_path, Some(ctx.pr.as_ref()))
.await?;
// Verify artifact
verify_artifact(&tv, &file_path, &opts, Some(ctx.pr.as_ref()))?;
// Generate cache key
let cache_key = self.cache_key(&file_path, &opts)?;
let file_info = FileInfo::new(&file_path, &opts);
// Acquire lock and extract or reuse cache
let cache_path = self.cache_path(&cache_key);
let _lock = crate::lock_file::get(&cache_path, ctx.force)?;
// Determine extraction type based on whether we're using cache or extracting fresh
// On cache hit, we need to detect the actual filename from the cache (which may differ
// from current options if a previous extraction used different `bin` name)
let extraction_type = if self.is_cached(&cache_key) {
ctx.pr.set_message("using cached tarball".into());
// Report extraction operation as complete (instant since we're using cache)
ctx.pr.set_length(1);
ctx.pr.set_position(1);
self.extraction_type_from_cache(&cache_key, &file_info)
} else {
ctx.pr.set_message("extracting to cache".into());
self.extract_to_cache(&file_path, &cache_key, &url, &opts, Some(ctx.pr.as_ref()))?
};
// Create symlinks
self.create_install_symlink(&tv, &cache_key, &extraction_type, &opts)?;
self.create_version_alias_symlink(&tv, &cache_key)?;
// Verify checksum for lockfile
self.verify_checksum(ctx, &mut tv, &file_path)?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
let opts = tv.request.options();
// Check for explicit bin_path
if let Some(bin_path_template) = get_opt(&opts, "bin_path") {
let bin_path = template_string(&bin_path_template, tv);
return Ok(vec![tv.install_path().join(bin_path)]);
}
// Check for bin directory
let bin_dir = tv.install_path().join("bin");
if bin_dir.exists() {
return Ok(vec![bin_dir]);
}
// Search subdirectories for bin directories
let mut paths = Vec::new();
if let Ok(entries) = std::fs::read_dir(tv.install_path()) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let sub_bin = path.join("bin");
if sub_bin.exists() {
paths.push(sub_bin);
}
}
}
}
if paths.is_empty() {
Ok(vec![tv.install_path()])
} else {
Ok(paths)
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/static_helpers.rs | src/backend/static_helpers.rs | // Shared template logic for backends
use crate::backend::platform_target::PlatformTarget;
use crate::file;
use crate::hash;
use crate::http::HTTP;
use crate::toolset::ToolVersion;
use crate::toolset::ToolVersionOptions;
use crate::ui::progress_report::SingleReport;
use eyre::{Result, bail};
use indexmap::IndexSet;
use std::path::Path;
use std::sync::LazyLock;
/// Regex pattern for matching version suffixes like -v1.2.3, _1.2.3, etc.
static VERSION_PATTERN: LazyLock<regex::Regex> =
LazyLock::new(|| regex::Regex::new(r"[-_]v?\d+(\.\d+)*(-[a-zA-Z0-9]+(\.\d+)?)?$").unwrap());
// ========== Checksum Fetching Helpers ==========
/// Fetches a checksum for a specific file from a SHASUMS256.txt-style file.
/// Uses cached HTTP requests since the same SHASUMS file is fetched for all platforms.
///
/// # Arguments
/// * `shasums_url` - URL to the SHASUMS256.txt file
/// * `filename` - The filename to look up in the SHASUMS file
///
/// # Returns
/// * `Some("sha256:<hash>")` if found
/// * `None` if the SHASUMS file couldn't be fetched or filename not found
pub async fn fetch_checksum_from_shasums(shasums_url: &str, filename: &str) -> Option<String> {
match HTTP.get_text_cached(shasums_url).await {
Ok(shasums_content) => {
let shasums = hash::parse_shasums(&shasums_content);
shasums.get(filename).map(|h| format!("sha256:{h}"))
}
Err(e) => {
debug!("Failed to fetch SHASUMS from {}: {e}", shasums_url);
None
}
}
}
/// Fetches a checksum from an individual checksum file (e.g., file.tar.gz.sha256).
/// The checksum file should contain just the hash, optionally followed by filename.
///
/// # Arguments
/// * `checksum_url` - URL to the checksum file (e.g., `https://example.com/file.tar.gz.sha256`)
/// * `algo` - The algorithm name to prefix (e.g., "sha256")
///
/// # Returns
/// * `Some("<algo>:<hash>")` if found
/// * `None` if the checksum file couldn't be fetched
pub async fn fetch_checksum_from_file(checksum_url: &str, algo: &str) -> Option<String> {
match HTTP.get_text(checksum_url).await {
Ok(content) => {
// Format is typically "<hash> <filename>" or just "<hash>"
content
.split_whitespace()
.next()
.map(|h| format!("{algo}:{}", h.trim()))
}
Err(e) => {
debug!("Failed to fetch checksum from {}: {e}", checksum_url);
None
}
}
}
// ========== Platform Patterns ==========
// Shared OS/arch patterns used across helpers
const OS_PATTERNS: &[&str] = &[
"linux", "darwin", "macos", "windows", "win", "freebsd", "openbsd", "netbsd", "android",
"unknown",
];
// Longer arch patterns first to avoid partial matches
const ARCH_PATTERNS: &[&str] = &[
"x86_64", "aarch64", "ppc64le", "ppc64", "armv7", "armv6", "arm64", "amd64", "mipsel",
"riscv64", "s390x", "i686", "i386", "x64", "mips", "arm", "x86",
];
pub trait VerifiableError: Sized + Send + Sync + 'static {
fn is_not_found(&self) -> bool;
fn into_eyre(self) -> eyre::Report;
}
impl VerifiableError for eyre::Report {
fn is_not_found(&self) -> bool {
self.chain().any(|cause| {
if let Some(err) = cause.downcast_ref::<reqwest::Error>() {
err.status() == Some(reqwest::StatusCode::NOT_FOUND)
} else {
false
}
})
}
fn into_eyre(self) -> eyre::Report {
self
}
}
impl VerifiableError for anyhow::Error {
fn is_not_found(&self) -> bool {
if self.to_string().contains("404") {
return true;
}
self.chain().any(|cause| {
if let Some(err) = cause.downcast_ref::<reqwest::Error>() {
err.status() == Some(reqwest::StatusCode::NOT_FOUND)
} else {
false
}
})
}
fn into_eyre(self) -> eyre::Report {
eyre::eyre!(self)
}
}
/// Helper to try both prefixed and non-prefixed tags for a resolver function
pub async fn try_with_v_prefix<F, Fut, T, E>(
version: &str,
version_prefix: Option<&str>,
resolver: F,
) -> Result<T>
where
F: Fn(String) -> Fut,
Fut: Future<Output = std::result::Result<T, E>>,
E: VerifiableError,
{
let mut errors = vec![];
// Generate candidates based on version prefix configuration
let candidates = if let Some(prefix) = version_prefix {
// If a custom prefix is configured, try both prefixed and non-prefixed versions
if version.starts_with(prefix) {
vec![
version.to_string(),
version.trim_start_matches(prefix).to_string(),
]
} else {
vec![format!("{}{}", prefix, version), version.to_string()]
}
} else if version.starts_with('v') {
vec![
version.to_string(),
version.trim_start_matches('v').to_string(),
]
} else {
vec![format!("v{version}"), version.to_string()]
};
for candidate in candidates {
match resolver(candidate).await {
Ok(res) => return Ok(res),
Err(e) => {
if e.is_not_found() {
errors.push(e.into_eyre());
} else {
return Err(e.into_eyre());
}
}
}
}
Err(errors
.pop()
.unwrap_or_else(|| eyre::eyre!("No matching release found for {version}")))
}
/// Returns all possible aliases for the current platform (os, arch),
/// with the preferred spelling first (macos/x64, linux/x64, etc).
pub fn platform_aliases() -> Vec<(String, String)> {
let os = std::env::consts::OS;
let arch = std::env::consts::ARCH;
let mut aliases = vec![];
// OS aliases
let os_aliases = match os {
"macos" | "darwin" => vec!["macos", "darwin"],
"linux" => vec!["linux"],
"windows" => vec!["windows"],
_ => vec![os],
};
// Arch aliases
let arch_aliases = match arch {
"x86_64" | "amd64" => vec!["x64", "amd64", "x86_64"],
"aarch64" | "arm64" => vec!["arm64", "aarch64"],
_ => vec![arch],
};
for os in &os_aliases {
for arch in &arch_aliases {
aliases.push((os.to_string(), arch.to_string()));
}
}
aliases
}
/// Looks up a value in ToolVersionOptions using nested platform key format.
/// Supports nested format (platforms.macos-x64.url) with os-arch dash notation.
/// Also supports both "platforms" and "platform" prefixes.
pub fn lookup_platform_key(opts: &ToolVersionOptions, key_type: &str) -> Option<String> {
// Try nested platform structure with os-arch format
for (os, arch) in platform_aliases() {
for prefix in ["platforms", "platform"] {
// Try nested format: platforms.macos-x64.url
let nested_key = format!("{prefix}.{os}-{arch}.{key_type}");
if let Some(val) = opts.get_nested_string(&nested_key) {
return Some(val);
}
// Try flat format: platforms_macos_arm64_url
let flat_key = format!("{prefix}_{os}_{arch}_{key_type}");
if let Some(val) = opts.get(&flat_key) {
return Some(val.clone());
}
}
}
None
}
/// Looks up an option value with platform-specific fallback.
/// First tries platform-specific lookup, then falls back to the base key.
///
/// # Arguments
/// * `opts` - The tool version options to search
/// * `key` - The option key to look up (e.g., "bin_path", "checksum")
///
/// # Returns
/// * `Some(value)` if found in platform-specific or base options
/// * `None` if not found
pub fn lookup_with_fallback(opts: &ToolVersionOptions, key: &str) -> Option<String> {
lookup_platform_key(opts, key).or_else(|| opts.get(key).cloned())
}
/// Returns all possible aliases for a given platform target (os, arch).
fn target_platform_aliases(target: &PlatformTarget) -> Vec<(String, String)> {
let os = target.os_name();
let arch = target.arch_name();
let mut aliases = vec![];
// OS aliases
let os_aliases = match os {
"macos" | "darwin" => vec!["macos", "darwin"],
"linux" => vec!["linux"],
"windows" => vec!["windows"],
_ => vec![os],
};
// Arch aliases
let arch_aliases = match arch {
"x64" | "amd64" | "x86_64" => vec!["x64", "amd64", "x86_64"],
"arm64" | "aarch64" => vec!["arm64", "aarch64"],
_ => vec![arch],
};
for os in &os_aliases {
for arch in &arch_aliases {
aliases.push((os.to_string(), arch.to_string()));
}
}
aliases
}
/// Looks up a value in ToolVersionOptions for a specific target platform.
/// Used for cross-platform lockfile generation.
pub fn lookup_platform_key_for_target(
opts: &ToolVersionOptions,
key_type: &str,
target: &PlatformTarget,
) -> Option<String> {
// Try nested platform structure with os-arch format
for (os, arch) in target_platform_aliases(target) {
for prefix in ["platforms", "platform"] {
// Try nested format: platforms.macos-x64.url
let nested_key = format!("{prefix}.{os}-{arch}.{key_type}");
if let Some(val) = opts.get_nested_string(&nested_key) {
return Some(val);
}
// Try flat format: platforms_macos_arm64_url
let flat_key = format!("{prefix}_{os}_{arch}_{key_type}");
if let Some(val) = opts.get(&flat_key) {
return Some(val.clone());
}
}
}
None
}
/// Lists platform keys (e.g. "macos-x64") for which a given key_type exists (e.g. "url").
pub fn list_available_platforms_with_key(opts: &ToolVersionOptions, key_type: &str) -> Vec<String> {
let mut set = IndexSet::new();
// Gather from flat keys
for (k, _) in opts.iter() {
if let Some(rest) = k
.strip_prefix("platforms_")
.or_else(|| k.strip_prefix("platform_"))
&& let Some(platform_part) = rest.strip_suffix(&format!("_{}", key_type))
{
// Only convert the OS/arch separator underscore to a dash, preserving
// underscores inside architecture names like x86_64
let platform_key = if let Some((os_part, rest)) = platform_part.split_once('_') {
format!("{os_part}-{rest}")
} else {
platform_part.to_string()
};
set.insert(platform_key);
}
}
// Probe nested keys using shared patterns
for os in OS_PATTERNS {
for arch in ARCH_PATTERNS {
for prefix in ["platforms", "platform"] {
let nested_key = format!("{prefix}.{os}-{arch}.{key_type}");
if opts.contains_key(&nested_key) {
set.insert(format!("{os}-{arch}"));
}
}
}
}
set.into_iter().collect()
}
pub fn template_string(template: &str, tv: &ToolVersion) -> String {
let version = &tv.version;
template.replace("{version}", version)
}
pub fn get_filename_from_url(url_str: &str) -> String {
let filename = if let Ok(url) = url::Url::parse(url_str) {
// Use proper URL parsing to get the path and extract filename
url.path_segments()
.and_then(|mut segments| segments.next_back())
.map(|s| s.to_string())
.unwrap_or_else(|| url_str.to_string())
} else {
// Fallback to simple parsing for non-URL strings or malformed URLs
url_str
.split('/')
.next_back()
.unwrap_or(url_str)
.to_string()
};
urlencoding::decode(&filename)
.map(|s| s.to_string())
.unwrap_or(filename)
}
pub fn install_artifact(
tv: &crate::toolset::ToolVersion,
file_path: &Path,
opts: &ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> eyre::Result<()> {
let install_path = tv.install_path();
let mut strip_components = lookup_platform_key(opts, "strip_components")
.or_else(|| opts.get("strip_components").cloned())
.and_then(|s| s.parse().ok());
file::remove_all(&install_path)?;
file::create_dir_all(&install_path)?;
// Use TarFormat for format detection
let ext = file_path.extension().and_then(|s| s.to_str()).unwrap_or("");
let format = file::TarFormat::from_ext(ext);
// Get file extension and detect format
let file_name = file_path.file_name().unwrap().to_string_lossy();
// Check if it's a compressed binary (not a tar archive)
let is_compressed_binary =
!file_name.contains(".tar") && matches!(ext, "gz" | "xz" | "bz2" | "zst");
if is_compressed_binary {
// Handle compressed single binary
let decompressed_name = file_name.trim_end_matches(&format!(".{}", ext));
// Determine the destination path with support for bin_path
let dest = if let Some(bin_path_template) = lookup_with_fallback(opts, "bin_path") {
let bin_path = template_string(&bin_path_template, tv);
let bin_dir = install_path.join(&bin_path);
file::create_dir_all(&bin_dir)?;
bin_dir.join(decompressed_name)
} else if let Some(bin_name) = lookup_with_fallback(opts, "bin") {
install_path.join(&bin_name)
} else {
// Auto-clean binary names by removing OS/arch suffixes
let cleaned_name = clean_binary_name(decompressed_name, Some(&tv.ba().tool_name));
install_path.join(cleaned_name)
};
match ext {
"gz" => file::un_gz(file_path, &dest)?,
"xz" => file::un_xz(file_path, &dest)?,
"bz2" => file::un_bz2(file_path, &dest)?,
"zst" => file::un_zst(file_path, &dest)?,
_ => unreachable!(),
}
file::make_executable(&dest)?;
} else if format == file::TarFormat::Raw {
// Copy the file directly to the bin_path directory or install_path
if let Some(bin_path_template) = lookup_with_fallback(opts, "bin_path") {
let bin_path = template_string(&bin_path_template, tv);
let bin_dir = install_path.join(&bin_path);
file::create_dir_all(&bin_dir)?;
let dest = bin_dir.join(file_path.file_name().unwrap());
file::copy(file_path, &dest)?;
file::make_executable(&dest)?;
} else if let Some(bin_name) = lookup_with_fallback(opts, "bin") {
// If bin is specified, rename the file to this name
let dest = install_path.join(&bin_name);
file::copy(file_path, &dest)?;
file::make_executable(&dest)?;
} else {
// Always auto-clean binary names by removing OS/arch suffixes
let original_name = file_path.file_name().unwrap().to_string_lossy();
let cleaned_name = clean_binary_name(&original_name, Some(&tv.ba().tool_name));
let dest = install_path.join(cleaned_name);
file::copy(file_path, &dest)?;
file::make_executable(&dest)?;
}
} else {
// Handle archive formats
// Auto-detect if we need strip_components=1 before extracting
// Only do this if strip_components was not explicitly set by the user AND bin_path is not configured
if strip_components.is_none()
&& lookup_platform_key(opts, "bin_path")
.or_else(|| opts.get("bin_path").cloned())
.is_none()
&& let Ok(should_strip) = file::should_strip_components(file_path, format)
&& should_strip
{
debug!("Auto-detected single directory archive, extracting with strip_components=1");
strip_components = Some(1);
}
let tar_opts = file::TarOptions {
format,
strip_components: strip_components.unwrap_or(0),
pr,
..Default::default()
};
// Extract with determined strip_components
file::untar(file_path, &install_path, &tar_opts)?;
// Extract just the repo name from tool_name (e.g., "opsgenie/opsgenie-lamp" -> "opsgenie-lamp")
// This is needed for matching binary names in ZIP archives where exec bits are lost
let full_tool_name = tv.ba().tool_name.as_str();
let tool_name = full_tool_name.rsplit('/').next().unwrap_or(full_tool_name);
// Determine search directory based on bin_path option (used by both bin= and rename_exe=)
let search_dir = if let Some(bin_path_template) = lookup_with_fallback(opts, "bin_path") {
let bin_path = template_string(&bin_path_template, tv);
install_path.join(&bin_path)
} else {
install_path.clone()
};
// Handle bin= option for archives (renames executable to specified name)
if let Some(bin_name) = lookup_with_fallback(opts, "bin") {
rename_executable_in_dir(&search_dir, &bin_name, Some(tool_name))?;
}
// Handle rename_exe option for archives
if let Some(rename_to) = lookup_with_fallback(opts, "rename_exe") {
rename_executable_in_dir(&search_dir, &rename_to, Some(tool_name))?;
}
}
Ok(())
}
pub fn verify_artifact(
_tv: &crate::toolset::ToolVersion,
file_path: &Path,
opts: &crate::toolset::ToolVersionOptions,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
// Check platform-specific checksum first, then fall back to generic
let checksum = lookup_with_fallback(opts, "checksum");
if let Some(checksum) = checksum {
verify_checksum_str(file_path, &checksum, pr)?;
}
// Check platform-specific size first, then fall back to generic
let size_str = lookup_with_fallback(opts, "size");
if let Some(size_str) = size_str {
let expected_size: u64 = size_str.parse()?;
let actual_size = file_path.metadata()?.len();
if actual_size != expected_size {
bail!(
"Size mismatch: expected {}, got {}",
expected_size,
actual_size
);
}
}
Ok(())
}
pub fn verify_checksum_str(
file_path: &Path,
checksum: &str,
pr: Option<&dyn SingleReport>,
) -> Result<()> {
if let Some((algo, hash_str)) = checksum.split_once(':') {
hash::ensure_checksum(file_path, hash_str, pr, algo)?;
} else {
bail!("Invalid checksum format: {}", checksum);
}
Ok(())
}
/// File extensions that indicate non-binary files.
const SKIP_EXTENSIONS: &[&str] = &[".txt", ".md", ".json", ".yml", ".yaml"];
/// File names (case-insensitive) that should be skipped when looking for executables.
const SKIP_FILE_NAMES: &[&str] = &["LICENSE", "README"];
/// Checks if a file should be skipped when searching for executables.
///
/// # Arguments
/// * `file_name` - The file name to check
/// * `strict` - If true, also checks against SKIP_FILE_NAMES and README.* patterns
///
/// # Returns
/// * `true` if the file should be skipped (not a binary)
/// * `false` if the file might be a binary
fn should_skip_file(file_name: &str, strict: bool) -> bool {
// Skip hidden files
if file_name.starts_with('.') {
return true;
}
// Skip known non-binary extensions
if SKIP_EXTENSIONS.iter().any(|ext| file_name.ends_with(ext)) {
return true;
}
// In strict mode, also skip LICENSE/README files
if strict {
let upper = file_name.to_uppercase();
if SKIP_FILE_NAMES.iter().any(|name| upper == *name) || upper.starts_with("README.") {
return true;
}
}
false
}
/// Renames the first executable file found in a directory to a new name.
/// Used by the `rename_exe` and `bin` options to rename binaries after archive extraction.
///
/// # Parameters
/// - `dir`: The directory to search for executables
/// - `new_name`: The new name for the executable
/// - `tool_name`: Optional hint for finding non-executable files by name matching.
/// When provided, if no executable is found, will search for files matching the tool name
/// and make them executable before renaming.
fn rename_executable_in_dir(
dir: &Path,
new_name: &str,
tool_name: Option<&str>,
) -> eyre::Result<()> {
let target_path = dir.join(new_name);
// Check if target already exists before iterating
// (read_dir order is non-deterministic, so we must check first)
if target_path.is_file() && file::is_executable(&target_path) {
return Ok(());
}
// First pass: Find executables in the directory (non-recursive for top level)
for path in file::ls(dir)? {
if path.is_file() && file::is_executable(&path) {
let file_name = path.file_name().unwrap().to_string_lossy();
if should_skip_file(&file_name, false) {
continue;
}
file::rename(&path, &target_path)?;
debug!("Renamed {} to {}", path.display(), target_path.display());
return Ok(());
}
}
// Second pass: Find non-executable files by name matching (for ZIP archives without exec bit)
if let Some(tool_name) = tool_name {
for path in file::ls(dir)? {
if path.is_file() {
let file_name = path.file_name().unwrap().to_string_lossy();
if should_skip_file(&file_name, true) {
continue;
}
// Check if filename matches tool name pattern or the target name
if file_name.contains(tool_name) || *file_name == *new_name {
file::make_executable(&path)?;
file::rename(&path, &target_path)?;
debug!(
"Found and renamed {} to {} (added exec permissions)",
path.display(),
target_path.display()
);
return Ok(());
}
}
}
}
Ok(())
}
/// Cleans a binary name by removing OS/arch suffixes and version numbers.
/// This is useful when downloading single binaries that have platform-specific names.
/// Executable extensions (.exe, .bat, .sh, etc.) are preserved.
///
/// # Parameters
/// - `name`: The binary name to clean
/// - `tool_name`: Optional hint for the expected tool name. When provided:
/// - Version removal is more aggressive, only keeping the result if it matches the tool name
/// - Helps ensure the cleaned name matches the expected tool
/// – When `None`, version removal is more conservative to avoid over-cleaning
///
/// # Examples
/// - "docker-compose-linux-x86_64" -> "docker-compose"
/// - "tool-darwin-arm64.exe" -> "tool.exe" (preserves extension)
/// - "mytool-v1.2.3-windows-amd64" -> "mytool"
/// - "app-2.0.0-linux-x64" -> "app" (with tool_name="app")
/// - "script-darwin-arm64.sh" -> "script.sh" (preserves .sh extension)
pub fn clean_binary_name(name: &str, tool_name: Option<&str>) -> String {
// Extract extension if present (to preserve it)
let (name_without_ext, extension) = if let Some(pos) = name.rfind('.') {
let potential_ext = &name[pos + 1..];
// Common executable extensions to preserve
let executable_extensions = [
"exe", "bat", "cmd", "sh", "ps1", "app", "AppImage", "run", "bin",
];
if executable_extensions.contains(&potential_ext) {
(&name[..pos], Some(&name[pos..]))
} else {
// Not an executable extension, treat it as part of the name
(name, None)
}
} else {
(name, None)
};
// Helper to add extension back to a cleaned name
let with_ext = |s: String| -> String {
match extension {
Some(ext) => format!("{}{}", s, ext),
None => s,
}
};
// Try to find and remove platform suffixes
let mut cleaned = name_without_ext.to_string();
// First try combined OS-arch patterns
for os in OS_PATTERNS {
for arch in ARCH_PATTERNS {
// Try different separator combinations
let patterns = [
format!("-{os}-{arch}"),
format!("-{os}_{arch}"),
format!("_{os}-{arch}"),
format!("_{os}_{arch}"),
format!("-{arch}-{os}"), // Sometimes arch comes before OS
format!("_{arch}_{os}"),
];
for pattern in &patterns {
if let Some(pos) = cleaned.rfind(pattern) {
cleaned = cleaned[..pos].to_string();
// Continue processing to also remove version numbers
let result = clean_version_suffix(&cleaned, tool_name);
return with_ext(result);
}
}
}
}
// Try just OS suffix (sometimes arch is omitted)
for os in OS_PATTERNS {
let patterns = [format!("-{os}"), format!("_{os}")];
for pattern in &patterns {
if let Some(pos) = cleaned.rfind(pattern.as_str()) {
// Only remove if it's at the end or followed by more platform info
let after = &cleaned[pos + pattern.len()..];
if after.is_empty() || after.starts_with('-') || after.starts_with('_') {
// Check if what comes before looks like a valid name
let before = &cleaned[..pos];
if !before.is_empty() {
cleaned = before.to_string();
let result = clean_version_suffix(&cleaned, tool_name);
// Add the extension back if we had one
return with_ext(result);
}
}
}
}
}
// Try just arch suffix (sometimes OS is omitted)
for arch in ARCH_PATTERNS {
let patterns = [format!("-{arch}"), format!("_{arch}")];
for pattern in &patterns {
if let Some(pos) = cleaned.rfind(pattern.as_str()) {
// Only remove if it's at the end or followed by more platform info
let after = &cleaned[pos + pattern.len()..];
if after.is_empty() || after.starts_with('-') || after.starts_with('_') {
// Check if what comes before looks like a valid name
let before = &cleaned[..pos];
if !before.is_empty() {
cleaned = before.to_string();
let result = clean_version_suffix(&cleaned, tool_name);
// Add the extension back if we had one
return with_ext(result);
}
}
}
}
}
// Try to remove version suffixes as a final step
let cleaned = clean_version_suffix(&cleaned, tool_name);
// Add the extension back if we had one
with_ext(cleaned)
}
/// Remove version suffixes from binary names.
///
/// When `tool_name` is provided, aggressively removes version patterns but only
/// if the result matches or relates to the tool name. This prevents accidentally
/// removing too much from the name.
///
/// When `tool_name` is None, only removes clear version patterns at the end
/// while ensuring we don't leave an empty or invalid result.
fn clean_version_suffix(name: &str, tool_name: Option<&str>) -> String {
// Common version patterns to remove
if let Some(tool) = tool_name {
// If we have a tool name, only remove version if what remains matches the tool
if let Some(m) = VERSION_PATTERN.find(name) {
let without_version = &name[..m.start()];
if without_version == tool
|| tool.contains(without_version)
|| without_version.contains(tool)
{
return without_version.to_string();
}
}
} else {
// No tool name hint, be more conservative
// Only remove if it looks like a clear version pattern at the end
if let Some(m) = VERSION_PATTERN.find(name) {
let without_version = &name[..m.start()];
// Make sure we're not left with nothing or just a dash/underscore
if !without_version.is_empty()
&& !without_version.ends_with('-')
&& !without_version.ends_with('_')
{
return without_version.to_string();
}
}
}
name.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::toolset::ToolVersionOptions;
use indexmap::IndexMap;
#[test]
fn test_clean_binary_name() {
// Test basic OS/arch removal
assert_eq!(
clean_binary_name("docker-compose-linux-x86_64", None),
"docker-compose"
);
assert_eq!(
clean_binary_name("docker-compose-linux-x86_64.exe", None),
"docker-compose.exe"
);
assert_eq!(clean_binary_name("tool-darwin-arm64", None), "tool");
assert_eq!(
clean_binary_name("mytool-v1.2.3-windows-amd64", None),
"mytool"
);
// Test different separators
assert_eq!(clean_binary_name("app_linux_amd64", None), "app");
assert_eq!(clean_binary_name("app-linux_x64", None), "app");
assert_eq!(clean_binary_name("app_darwin-arm64", None), "app");
// Test arch before OS
assert_eq!(clean_binary_name("tool-x86_64-linux", None), "tool");
assert_eq!(clean_binary_name("tool_amd64_windows", None), "tool");
// Test with tool name hint
assert_eq!(
clean_binary_name("docker-compose-linux-x86_64", Some("docker-compose")),
"docker-compose"
);
assert_eq!(
clean_binary_name("compose-linux-x86_64", Some("compose")),
"compose"
);
// Test single OS or arch suffix
assert_eq!(clean_binary_name("binary-linux", None), "binary");
assert_eq!(clean_binary_name("binary-x86_64", None), "binary");
assert_eq!(clean_binary_name("binary_arm64", None), "binary");
// Test version removal
assert_eq!(clean_binary_name("tool-v1.2.3", None), "tool");
assert_eq!(clean_binary_name("app-2.0.0", None), "app");
assert_eq!(clean_binary_name("binary_v3.2.1", None), "binary");
assert_eq!(clean_binary_name("tool-1.0.0-alpha", None), "tool");
assert_eq!(clean_binary_name("app-v2.0.0-rc1", None), "app");
// Test version removal with tool name hint
assert_eq!(
clean_binary_name("docker-compose-v2.29.1", Some("docker-compose")),
"docker-compose"
);
assert_eq!(
clean_binary_name("compose-2.29.1", Some("compose")),
"compose"
);
// Test no cleaning needed
assert_eq!(clean_binary_name("simple-tool", None), "simple-tool");
// Test that executable extensions are preserved
assert_eq!(clean_binary_name("app-linux-x64.exe", None), "app.exe");
assert_eq!(
clean_binary_name("tool-v1.2.3-windows.bat", None),
"tool.bat"
);
assert_eq!(
clean_binary_name("script-darwin-arm64.sh", None),
"script.sh"
);
assert_eq!(
clean_binary_name("app-linux.AppImage", None),
"app.AppImage"
);
// Test edge cases
assert_eq!(clean_binary_name("linux", None), "linux"); // Just OS name
assert_eq!(clean_binary_name("", None), "");
}
#[test]
fn test_list_available_platforms_with_key_flat_preserves_arch_underscore() {
let mut opts = IndexMap::new();
// Flat keys with os_arch_keytype naming
opts.insert(
"platforms_macos_x86_64_url".to_string(),
"https://example.com/macos-x86_64.tar.gz".to_string(),
);
opts.insert(
"platforms_linux_x64_url".to_string(),
"https://example.com/linux-x64.tar.gz".to_string(),
);
// Different prefix variant also supported
opts.insert(
"platform_windows_arm64_url".to_string(),
"https://example.com/windows-arm64.zip".to_string(),
);
let tool_opts = ToolVersionOptions {
opts,
..Default::default()
};
let platforms = list_available_platforms_with_key(&tool_opts, "url");
// Should convert only the OS/arch separator underscore to dash
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/pipx.rs | src/backend/pipx.rs | use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::{Backend, VersionInfo};
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::env;
use crate::file;
use crate::github;
use crate::http::HTTP_FETCH;
use crate::install_context::InstallContext;
use crate::timeout;
use crate::toolset::{ToolRequest, ToolVersion, ToolVersionOptions, Toolset, ToolsetBuilder};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::progress_report::SingleReport;
use async_trait::async_trait;
use eyre::{Result, eyre};
use indexmap::IndexMap;
use itertools::Itertools;
use regex::Regex;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt::Debug, sync::Arc};
use versions::Versioning;
use xx::regex;
#[derive(Debug)]
pub struct PIPXBackend {
ba: Arc<BackendArg>,
latest_version_cache: CacheManager<Option<String>>,
}
#[async_trait]
impl Backend for PIPXBackend {
fn get_type(&self) -> BackendType {
BackendType::Pipx
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["pipx"])
}
fn get_optional_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["uv"])
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
match self.tool_name().parse()? {
PipxRequest::Pypi(package) => {
let registry_url = Self::get_registry_url()?;
if registry_url.contains("/json") {
debug!("Fetching JSON for {}", package);
let url = registry_url.replace("{}", &package);
let data: PypiPackage = HTTP_FETCH.json(url).await?;
// Get versions sorted and attach timestamps from the first file in each release
let versions = data
.releases
.into_iter()
.sorted_by_cached_key(|(v, _)| Versioning::new(v))
.map(|(version, files)| {
// Get the earliest upload_time from the release files
let created_at = files
.iter()
.filter_map(|f| f.upload_time.as_ref())
.min()
.cloned();
VersionInfo {
version,
created_at,
..Default::default()
}
})
.collect();
Ok(versions)
} else {
debug!("Fetching HTML for {}", package);
let url = registry_url.replace("{}", &package);
let html = HTTP_FETCH.get_html(url).await?;
// PEP-0503 (HTML format doesn't include timestamps)
let version_re = regex!(
r#"href=["'][^"']*/([^/]+)\.tar\.gz(?:#(md5|sha1|sha224|sha256|sha384|sha512)=[0-9A-Fa-f]+)?["']"#
);
let versions: Vec<VersionInfo> = version_re
.captures_iter(&html)
.filter_map(|cap| {
let filename = cap.get(1)?.as_str();
let escaped_package = regex::escape(&package);
// PEP-503: normalize package names by replacing hyphens with character class that allows -, _, .
let re_str = escaped_package.replace(r"\-", r"[\-_.]");
let re_str = format!("^{re_str}-(.+)$");
let pkg_re = regex::Regex::new(&re_str).ok()?;
let pkg_version = pkg_re.captures(filename)?.get(1)?.as_str();
Some(VersionInfo {
version: pkg_version.to_string(),
..Default::default()
})
})
.sorted_by_cached_key(|v| Versioning::new(&v.version))
.collect();
Ok(versions)
}
}
PipxRequest::Git(url) if url.starts_with("https://github.com/") => {
let repo = url.strip_prefix("https://github.com/").unwrap();
let data = github::list_releases(repo).await?;
Ok(data
.into_iter()
.rev()
.map(|r| VersionInfo {
version: r.tag_name,
created_at: Some(r.created_at),
..Default::default()
})
.collect())
}
PipxRequest::Git { .. } => Ok(vec![VersionInfo {
version: "latest".to_string(),
..Default::default()
}]),
}
}
async fn latest_stable_version(&self, config: &Arc<Config>) -> eyre::Result<Option<String>> {
let this = self;
timeout::run_with_timeout_async(
async || {
this.latest_version_cache
.get_or_try_init_async(async || match this.tool_name().parse()? {
PipxRequest::Pypi(package) => {
let registry_url = Self::get_registry_url()?;
if registry_url.contains("/json") {
debug!("Fetching JSON for {}", package);
let url = registry_url.replace("{}", &package);
let pkg: PypiPackage = HTTP_FETCH.json(url).await?;
Ok(Some(pkg.info.version))
} else {
debug!("Fetching HTML for {}", package);
let url = registry_url.replace("{}", &package);
let html = HTTP_FETCH.get_html(url).await?;
// PEP-0503
let version_re = regex!(r#"href=["'][^"']*/([^/]+)\.tar\.gz(?:#(md5|sha1|sha224|sha256|sha384|sha512)=[0-9A-Fa-f]+)?["']"#);
let version = version_re
.captures_iter(&html)
.filter_map(|cap| {
let filename = cap.get(1)?.as_str();
let escaped_package = regex::escape(&package);
// PEP-503: normalize package names by replacing hyphens with character class that allows -, _, .
let re_str = escaped_package.replace(r"\-", r"[\-_.]");
let re_str = format!("^{re_str}-(.+)$");
let pkg_re = regex::Regex::new(&re_str).ok()?;
let pkg_version =
pkg_re.captures(filename)?.get(1)?.as_str();
Some(pkg_version.to_string())
})
.filter(|v| {
!v.contains("dev")
&& !v.contains("a")
&& !v.contains("b")
&& !v.contains("rc")
})
.sorted_by_cached_key(|v| Versioning::new(v))
.next_back();
Ok(version)
}
}
_ => this.latest_version(config, Some("latest".into())).await,
})
.await
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
.cloned()
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
// Check if pipx is available (unless uvx is being used)
let use_uvx = self.uv_is_installed(&ctx.config).await
&& Settings::get().pipx.uvx != Some(false)
&& tv.request.options().get("uvx") != Some(&"false".to_string());
if !use_uvx {
self.warn_if_dependency_missing(
&ctx.config,
"pipx",
"To use pipx packages with mise, you need to install pipx first:\n\
mise use pipx@latest\n\n\
Alternatively, you can use uv/uvx by installing uv:\n\
mise use uv@latest",
)
.await;
}
let pipx_request = self
.tool_name()
.parse::<PipxRequest>()?
.pipx_request(&tv.version, &tv.request.options());
if use_uvx {
ctx.pr
.set_message(format!("uv tool install {pipx_request}"));
let mut cmd = Self::uvx_cmd(
&ctx.config,
&["tool", "install", &pipx_request],
self,
&tv,
&ctx.ts,
ctx.pr.as_ref(),
)
.await?;
if let Some(args) = tv.request.options().get("uvx_args") {
cmd = cmd.args(shell_words::split(args)?);
}
cmd.execute()?;
} else {
ctx.pr.set_message(format!("pipx install {pipx_request}"));
let mut cmd = Self::pipx_cmd(
&ctx.config,
&["install", &pipx_request],
self,
&tv,
&ctx.ts,
ctx.pr.as_ref(),
)
.await?;
if let Some(args) = tv.request.options().get("pipx_args") {
cmd = cmd.args(shell_words::split(args)?);
}
cmd.execute()?;
}
// Fix venv Python symlink to use minor version path
// This allows patch upgrades (3.12.1 → 3.12.2) to work without reinstalling
let pkg_name = self.tool_name();
fix_venv_python_symlink(&tv.install_path(), &pkg_name)?;
Ok(tv)
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// These options affect what gets installed
for key in ["extras", "pipx_args", "uvx_args", "uvx"] {
if let Some(value) = opts.get(key) {
result.insert(key.to_string(), value.clone());
}
}
result
}
}
/// Returns install-time-only option keys for PIPX backend.
pub fn install_time_option_keys() -> Vec<String> {
vec![
"extras".into(),
"pipx_args".into(),
"uvx_args".into(),
"uvx".into(),
]
}
impl PIPXBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self {
latest_version_cache: CacheManagerBuilder::new(
ba.cache_path.join("latest_version.msgpack.z"),
)
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.build(),
ba: Arc::new(ba),
}
}
fn get_index_url() -> eyre::Result<String> {
let registry_url = Settings::get().pipx.registry_url.clone();
// Remove {} placeholders and trailing slashes
let mut url = registry_url
.replace("{}", "")
.trim_end_matches('/')
.to_string();
// Handle different URL formats and convert to simple format
if url.contains("pypi.org") {
// For pypi.org, convert any format to simple format
if url.contains("/pypi/") {
// Replace /pypi/*/json or /pypi/*/simple with /simple
let re = Regex::new(r"/pypi/[^/]*/(?:json|simple)$").unwrap();
url = re.replace(&url, "/simple").to_string();
} else if !url.ends_with("/simple") {
// If it's pypi.org but doesn't already end with /simple, make it /simple
let base_url = url.split("/simple").next().unwrap_or(&url);
url = format!("{}/simple", base_url.trim_end_matches('/'));
}
} else {
// For custom registries, ensure they end with /simple
if url.ends_with("/json") {
// Replace /json with /simple
url = url.replace("/json", "/simple");
} else if !url.ends_with("/simple") {
// If it doesn't end with /simple, append it
url = format!("{url}/simple");
}
}
debug!("Converted registry URL to index URL: {}", url);
Ok(url)
}
fn get_registry_url() -> eyre::Result<String> {
let registry_url = Settings::get().pipx.registry_url.clone();
debug!("Pipx registry URL: {}", registry_url);
let re = Regex::new(r"^(http|https)://.*\{\}.*$").unwrap();
if !re.is_match(®istry_url) {
return Err(eyre!(
"Registry URL must be a valid URL and contain a {{}} placeholder"
));
}
Ok(registry_url)
}
pub async fn reinstall_all(config: &Arc<Config>) -> Result<()> {
let ts = ToolsetBuilder::new().build(config).await?;
let pipx_tools = ts
.list_installed_versions(config)
.await?
.into_iter()
.filter(|(b, _tv)| b.ba().backend_type() == BackendType::Pipx)
.collect_vec();
if Settings::get().pipx.uvx != Some(false) {
let pr = MultiProgressReport::get().add("reinstalling pipx tools with uvx");
for (b, tv) in pipx_tools {
for (cmd, tool) in &[
("uninstall", tv.ba().tool_name.to_string()),
("install", format!("{}=={}", tv.ba().tool_name, tv.version)),
] {
let args = &["tool", cmd, tool];
Self::uvx_cmd(config, args, &*b, &tv, &ts, pr.as_ref())
.await?
.execute()?;
}
}
} else {
let pr = MultiProgressReport::get().add("reinstalling pipx tools");
for (b, tv) in pipx_tools {
let args = &["reinstall", &tv.ba().tool_name];
Self::pipx_cmd(config, args, &*b, &tv, &ts, pr.as_ref())
.await?
.execute()?;
}
}
Ok(())
}
async fn uvx_cmd<'a>(
config: &Arc<Config>,
args: &[&str],
b: &dyn Backend,
tv: &ToolVersion,
ts: &Toolset,
pr: &'a dyn SingleReport,
) -> Result<CmdLineRunner<'a>> {
let mut cmd = CmdLineRunner::new("uv");
for arg in args {
cmd = cmd.arg(arg);
}
cmd.with_pr(pr)
.env("UV_TOOL_DIR", tv.install_path())
.env("UV_TOOL_BIN_DIR", tv.install_path().join("bin"))
.env("UV_INDEX", Self::get_index_url()?)
.envs(ts.env_with_path(config).await?)
.prepend_path(ts.list_paths(config).await)?
.prepend_path(vec![tv.install_path().join("bin")])?
.prepend_path(b.dependency_toolset(config).await?.list_paths(config).await)
}
async fn pipx_cmd<'a>(
config: &Arc<Config>,
args: &[&str],
b: &dyn Backend,
tv: &ToolVersion,
ts: &Toolset,
pr: &'a dyn SingleReport,
) -> Result<CmdLineRunner<'a>> {
let mut cmd = CmdLineRunner::new("pipx");
for arg in args {
cmd = cmd.arg(arg);
}
cmd.with_pr(pr)
.env("PIPX_HOME", tv.install_path())
.env("PIPX_BIN_DIR", tv.install_path().join("bin"))
.env("PIP_INDEX_URL", Self::get_index_url()?)
.envs(ts.env_with_path(config).await?)
.prepend_path(ts.list_paths(config).await)?
.prepend_path(vec![tv.install_path().join("bin")])?
.prepend_path(b.dependency_toolset(config).await?.list_paths(config).await)
}
async fn uv_is_installed(&self, config: &Arc<Config>) -> bool {
self.dependency_which(config, "uv").await.is_some()
}
}
enum PipxRequest {
/// git+https://github.com/psf/black.git@24.2.0
/// psf/black@24.2.0
Git(String),
/// black@24.2.0
Pypi(String),
}
impl PipxRequest {
fn extras_from_opts(&self, opts: &ToolVersionOptions) -> String {
match opts.get("extras") {
Some(extras) => format!("[{extras}]"),
None => String::new(),
}
}
fn pipx_request(&self, v: &str, opts: &ToolVersionOptions) -> String {
let extras = self.extras_from_opts(opts);
if v == "latest" {
match self {
PipxRequest::Git(url) => format!("git+{url}.git"),
PipxRequest::Pypi(package) => format!("{package}{extras}"),
}
} else {
match self {
PipxRequest::Git(url) => format!("git+{url}.git@{v}"),
PipxRequest::Pypi(package) => format!("{package}{extras}=={v}"),
}
}
}
}
#[derive(serde::Deserialize)]
struct PypiPackage {
releases: IndexMap<String, Vec<PypiRelease>>,
info: PypiInfo,
}
#[derive(serde::Deserialize)]
struct PypiInfo {
version: String,
}
#[derive(serde::Deserialize)]
struct PypiRelease {
upload_time: Option<String>,
}
impl FromStr for PipxRequest {
type Err = eyre::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(cap) = regex!(r"(git\+)(.*)(\.git)").captures(s) {
Ok(PipxRequest::Git(cap.get(2).unwrap().as_str().to_string()))
} else if s.contains('/') {
Ok(PipxRequest::Git(format!("https://github.com/{s}")))
} else {
Ok(PipxRequest::Pypi(s.to_string()))
}
}
}
/// Check if a path is within mise's Python installs directory
#[cfg(unix)]
fn is_mise_managed_python(path: &Path) -> bool {
let installs_dir = &*env::MISE_INSTALLS_DIR;
path.starts_with(installs_dir.join("python"))
}
/// Convert a Python path with full version to use minor version
/// e.g., .../python/3.12.1/bin/python → .../python/3.12/bin/python
#[cfg(unix)]
fn path_with_minor_version(path: &Path) -> Option<PathBuf> {
let path_str = path.to_str()?;
// Match pattern: /python/X.Y.Z/ and replace with /python/X.Y/
let re = regex!(r"/python/(\d+)\.(\d+)\.\d+/");
if re.is_match(path_str) {
let result = re.replace(path_str, "/python/$1.$2/");
Some(PathBuf::from(result.to_string()))
} else {
None
}
}
/// Fix the venv Python symlinks to use mise's minor version path
/// This allows patch upgrades (3.12.1 → 3.12.2) to work without reinstalling
///
/// The venv structure typically has:
/// - python -> python3 (relative symlink)
/// - python3 -> /path/to/mise/installs/python/3.12.1/bin/python3 (absolute symlink)
///
/// We need to fix the absolute symlink to use minor version path (3.12 instead of 3.12.1)
#[cfg(unix)]
fn fix_venv_python_symlink(install_path: &Path, pkg_name: &str) -> Result<()> {
// For Git-based packages like "psf/black", the venv directory is just "black"
// Extract the actual package name (last component after any '/')
let actual_pkg_name = pkg_name.rsplit('/').next().unwrap_or(pkg_name);
// Check both possible venv locations: {pkg}/ for uvx, venvs/{pkg}/ for pipx
let venv_dirs = [
install_path.join(actual_pkg_name),
install_path.join("venvs").join(actual_pkg_name),
];
trace!(
"fix_venv_python_symlink: checking venv dirs: {:?}",
venv_dirs
);
for venv_dir in &venv_dirs {
let bin_dir = venv_dir.join("bin");
if !bin_dir.exists() {
continue;
}
// Check python, python3, and python3.X symlinks for the one with absolute mise path
for name in &["python", "python3"] {
let symlink_path = bin_dir.join(name);
if !symlink_path.is_symlink() {
continue;
}
let target = match file::resolve_symlink(&symlink_path)? {
Some(t) => t,
None => continue,
};
// Skip relative symlinks (like python -> python3)
if !target.is_absolute() {
continue;
}
if !is_mise_managed_python(&target) {
continue; // Leave non-mise Python alone (homebrew, uv, etc.)
}
if let Some(minor_path) = path_with_minor_version(&target) {
// The minor version symlink (e.g., python/3.12) might not exist yet
// as runtime_symlinks::rebuild runs after all tools are installed.
// Check if the full version path exists instead (e.g., python/3.12.12/bin/python3).
// The symlink might be temporarily broken but will work after runtime symlinks are created.
if target.exists() {
trace!(
"Updating venv Python symlink {:?} to use minor version: {:?}",
symlink_path, minor_path
);
file::make_symlink(&minor_path, &symlink_path)?;
}
}
}
}
Ok(())
}
/// No-op on non-Unix platforms
#[cfg(not(unix))]
fn fix_venv_python_symlink(_install_path: &Path, _pkg_name: &str) -> Result<()> {
Ok(())
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/go.rs | src/backend/go.rs | use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::Config;
use crate::config::Settings;
use crate::install_context::InstallContext;
use crate::timeout;
use crate::toolset::{ToolRequest, ToolVersion};
use async_trait::async_trait;
use itertools::Itertools;
use std::collections::BTreeMap;
use std::{fmt::Debug, sync::Arc};
use xx::regex;
#[derive(Debug)]
pub struct GoBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for GoBackend {
fn get_type(&self) -> BackendType {
BackendType::Go
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["go"])
}
async fn _list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
// Check if go is available
self.warn_if_dependency_missing(
config,
"go",
"To use go packages with mise, you need to install Go first:\n\
mise use go@latest\n\n\
Or install Go via https://go.dev/dl/",
)
.await;
timeout::run_with_timeout_async(
async || {
let tool_name = self.tool_name();
let parts = tool_name.split('/').collect::<Vec<_>>();
let module_root_index = if parts[0] == "github.com" {
// Try likely module root index first
if parts.len() >= 3 {
if parts.len() > 3 && regex!(r"^v\d+$").is_match(parts[3]) {
Some(3)
} else {
Some(2)
}
} else {
None
}
} else {
None
};
let indices = module_root_index
.into_iter()
.chain((1..parts.len()).rev())
.unique()
.collect::<Vec<_>>();
for i in indices {
let mod_path = parts[..=i].join("/");
let res = cmd!(
"go",
"list",
"-mod=readonly",
"-m",
"-versions",
"-json",
mod_path
)
.full_env(self.dependency_env(config).await?)
.read();
if let Ok(raw) = res {
let res = serde_json::from_str::<GoModInfo>(&raw);
if let Ok(mod_info) = res {
// remove the leading v from the versions
let versions = mod_info
.versions
.into_iter()
.map(|v| VersionInfo {
version: v.trim_start_matches('v').to_string(),
..Default::default()
})
.collect();
return Ok(versions);
}
};
}
Ok(vec![])
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
}
async fn install_version_(
&self,
ctx: &InstallContext,
tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
// Check if go is available
self.warn_if_dependency_missing(
&ctx.config,
"go",
"To use go packages with mise, you need to install Go first:\n\
mise use go@latest\n\n\
Or install Go via https://go.dev/dl/",
)
.await;
let opts = self.ba.opts();
let install = async |v| {
let mut cmd = CmdLineRunner::new("go").arg("install").arg("-mod=readonly");
if let Some(tags) = opts.get("tags") {
cmd = cmd.arg("-tags").arg(tags);
}
cmd.arg(format!("{}@{v}", self.tool_name()))
.with_pr(ctx.pr.as_ref())
.envs(self.dependency_env(&ctx.config).await?)
.env("GOBIN", tv.install_path().join("bin"))
.execute()
};
// try "v" prefix if the version starts with semver
let use_v = regex!(r"^\d+\.\d+\.\d+").is_match(&tv.version);
if use_v {
if install(format!("v{}", tv.version)).await.is_err() {
warn!("Failed to install, trying again without added 'v' prefix");
} else {
return Ok(tv);
}
}
install(tv.version.clone()).await?;
Ok(tv)
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// tags affect compilation
if let Some(value) = opts.get("tags") {
result.insert("tags".to_string(), value.clone());
}
result
}
}
/// Returns install-time-only option keys for Go backend.
pub fn install_time_option_keys() -> Vec<String> {
vec!["tags".into()]
}
impl GoBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct GoModInfo {
versions: Vec<String>,
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/gem.rs | src/backend/gem.rs | use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::file;
use crate::http::HTTP_FETCH;
use crate::install_context::InstallContext;
use crate::toolset::ToolVersion;
use crate::{Result, config::Config, env};
use async_trait::async_trait;
use indoc::formatdoc;
use once_cell::sync::OnceCell;
use serde::Deserialize;
use std::path::Path;
use std::{fmt::Debug, sync::Arc};
/// Cached gem source URL, memoized globally after first successful detection
static GEM_SOURCE: OnceCell<String> = OnceCell::new();
#[derive(Debug)]
pub struct GemBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for GemBackend {
fn get_type(&self) -> BackendType {
BackendType::Gem
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["ruby"])
}
async fn _list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
// Get the gem source URL using the mise-managed Ruby environment
let source_url = self.get_gem_source(config).await;
// Use RubyGems-compatible API to get versions with timestamps
let url = format!("{}api/v1/versions/{}.json", source_url, self.tool_name());
let response: Vec<RubyGemsVersion> = HTTP_FETCH.json(&url).await?;
// RubyGems API returns newest-first, mise expects oldest-first
let mut versions: Vec<VersionInfo> = response
.into_iter()
.map(|v| VersionInfo {
version: v.number,
created_at: v.created_at,
..Default::default()
})
.collect();
versions.reverse();
Ok(versions)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
// Check if gem is available
self.warn_if_dependency_missing(
&ctx.config,
"gem",
"To use gem packages with mise, you need to install Ruby first:\n\
mise use ruby@latest",
)
.await;
CmdLineRunner::new("gem")
.arg("install")
.arg(self.tool_name())
.arg("--version")
.arg(&tv.version)
.arg("--install-dir")
.arg(tv.install_path().join("libexec"))
.with_pr(ctx.pr.as_ref())
.envs(self.dependency_env(&ctx.config).await?)
.execute()?;
// We install the gem to {install_path}/libexec and create a wrapper script for each executable
// in {install_path}/bin that sets GEM_HOME and executes the gem installed
env_script_all_bin_files(&tv.install_path())?;
// Rewrite shebangs for better compatibility:
// - System Ruby: uses `#!/usr/bin/env ruby` for PATH-based resolution
// - Mise Ruby: uses minor version symlink (e.g., .../ruby/3.1/bin/ruby) so patch
// upgrades don't break gems, while still being pinned to a minor version
rewrite_gem_shebangs(&tv.install_path())?;
// Create a ruby symlink in libexec/bin for polyglot script fallback
// RubyGems polyglot scripts have: exec "$bindir/ruby" "-x" "$0" "$@"
create_ruby_symlink(&tv.install_path())?;
Ok(tv)
}
}
impl GemBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
/// Get the primary gem source URL using the mise-managed Ruby environment.
/// The result is memoized globally after first successful detection.
async fn get_gem_source(&self, config: &Arc<Config>) -> &'static str {
const DEFAULT_SOURCE: &str = "https://rubygems.org/";
// Return cached source if available
if let Some(source) = GEM_SOURCE.get() {
return source.as_str();
}
// Get the mise-managed Ruby environment
let env = self.dependency_env(config).await.unwrap_or_default();
// Try to initialize the source - only memoize on success
match GEM_SOURCE.get_or_try_init(|| {
let output = cmd!("gem", "sources")
.full_env(&env)
.read()
.map_err(|e| eyre::eyre!("failed to run `gem sources`: {e}"))?;
Ok::<_, eyre::Report>(parse_gem_source_output(&output))
}) {
Ok(source) => source.as_str(),
Err(e) => {
warn!("{e}, falling back to rubygems.org");
DEFAULT_SOURCE
}
}
}
}
/// RubyGems API response for version info
#[derive(Debug, Deserialize)]
struct RubyGemsVersion {
number: String,
created_at: Option<String>,
}
/// Parse gem sources output to extract the primary source URL.
/// Output format:
/// ```
/// *** CURRENT SOURCES ***
///
/// https://rubygems.org/
/// ```
fn parse_gem_source_output(output: &str) -> String {
for line in output.lines() {
let line = line.trim();
if line.starts_with("http://") || line.starts_with("https://") {
// Ensure URL ends with /
return if line.ends_with('/') {
line.to_string()
} else {
format!("{}/", line)
};
}
}
// Default to rubygems.org if no source found
"https://rubygems.org/".to_string()
}
fn env_script_all_bin_files(install_path: &Path) -> eyre::Result<bool> {
let install_bin_path = install_path.join("bin");
let install_libexec_path = install_path.join("libexec");
file::create_dir_all(&install_bin_path)?;
get_gem_executables(install_path)?
.into_iter()
.for_each(|path| {
let exec_path = install_bin_path.join(path.file_name().unwrap());
file::write(
&exec_path,
formatdoc!(
r#"
#!/usr/bin/env bash
GEM_HOME="{gem_home}" exec {gem_exec_path} "$@"
"#,
gem_home = install_libexec_path.to_str().unwrap(),
gem_exec_path = path.to_str().unwrap(),
),
)
.unwrap();
file::make_executable(&exec_path).unwrap();
});
Ok(true)
}
fn get_gem_executables(install_path: &Path) -> eyre::Result<Vec<std::path::PathBuf>> {
// TODO: Find a way to get the list of executables from the gemspec of the
// installed gem rather than just listing the files in the bin directory.
let install_libexec_bin_path = install_path.join("libexec/bin");
let files = file::ls(&install_libexec_bin_path)?
.into_iter()
.filter(|p| file::is_executable(p))
.collect();
Ok(files)
}
/// Creates a `ruby` symlink in libexec/bin/ for RubyGems polyglot script fallback.
///
/// RubyGems polyglot scripts include: `exec "$bindir/ruby" "-x" "$0" "$@"`
/// This fallback runs when the script is executed via /bin/sh instead of ruby.
/// We create a symlink to the mise-managed Ruby (using minor version) so
/// the fallback works correctly.
fn create_ruby_symlink(install_path: &Path) -> eyre::Result<()> {
let libexec_bin = install_path.join("libexec/bin");
let ruby_symlink = libexec_bin.join("ruby");
// Don't overwrite if it already exists
if ruby_symlink.exists() || ruby_symlink.is_symlink() {
return Ok(());
}
// Find which Ruby we're using by checking an existing gem executable's shebang
let executables = get_gem_executables(install_path)?;
let Some(exec_path) = executables.first() else {
return Ok(());
};
let content = file::read_to_string(exec_path)?;
let lines: Vec<&str> = content.lines().collect();
let Some((_, shebang_line)) = find_ruby_shebang(&lines) else {
return Ok(());
};
// Extract the ruby path from the shebang
let ruby_path = shebang_line
.trim_start_matches("#!")
.split_whitespace()
.next()
.unwrap_or("");
if ruby_path.is_empty() {
return Ok(());
}
// Only create symlink for mise-managed Ruby
// For system Ruby, the shebang is #!/usr/bin/env ruby, which we can't symlink to
if !is_mise_ruby_path(ruby_path) {
return Ok(());
}
// Create symlink to the ruby executable
file::make_symlink(Path::new(ruby_path), &ruby_symlink)?;
Ok(())
}
/// Rewrites shebangs in gem executables to improve compatibility.
///
/// For system Ruby: Uses `#!/usr/bin/env ruby` for PATH-based resolution.
/// For mise-managed Ruby: Uses minor version symlink (e.g., `.../ruby/3.1/bin/ruby`)
/// so that patch upgrades (3.1.0 → 3.1.1) don't break gems.
///
/// Handles both regular Ruby scripts and RubyGems polyglot scripts which have
/// `#!/bin/sh` on line 1 but the actual Ruby shebang after `=end`.
fn rewrite_gem_shebangs(install_path: &Path) -> eyre::Result<()> {
let executables = get_gem_executables(install_path)?;
for exec_path in executables {
let content = file::read_to_string(&exec_path)?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
continue;
}
// Find the Ruby shebang line - either line 1 or after =end for polyglot scripts
let (shebang_line_idx, shebang_line) = if let Some(info) = find_ruby_shebang(&lines) {
info
} else {
continue;
};
// Extract the Ruby path and any arguments from the shebang
let shebang_content = shebang_line.trim_start_matches("#!");
let mut parts = shebang_content.split_whitespace();
let ruby_path = parts.next().unwrap_or("");
let shebang_args: Vec<&str> = parts.collect();
let new_shebang = if is_mise_ruby_path(ruby_path) {
// Mise-managed Ruby: use minor version symlink, preserving any arguments
match to_minor_version_shebang(ruby_path) {
Some(path) => {
if shebang_args.is_empty() {
format!("#!{path}")
} else {
format!("#!{path} {}", shebang_args.join(" "))
}
}
None => continue, // Keep original if we can't parse
}
} else {
// System Ruby: use env-based shebang
// Note: env shebangs generally can't preserve arguments portably
"#!/usr/bin/env ruby".to_string()
};
// Rewrite the file with new shebang at the correct line
let mut new_lines: Vec<&str> = lines.clone();
let new_shebang_ref: &str = &new_shebang;
new_lines[shebang_line_idx] = new_shebang_ref;
let trailing_newline = if content.ends_with('\n') { "\n" } else { "" };
let new_content = format!("{}{trailing_newline}", new_lines.join("\n"));
file::write(&exec_path, &new_content)?;
}
Ok(())
}
/// Finds the Ruby shebang line in a script.
/// Returns (line_index, line_content) or None if not found.
///
/// For regular Ruby scripts, this is line 0 with `#!...ruby...`.
/// For RubyGems polyglot scripts (starting with `#!/bin/sh`), the Ruby shebang
/// is the first `#!...ruby...` line after `=end`.
fn find_ruby_shebang<'a>(lines: &'a [&'a str]) -> Option<(usize, &'a str)> {
let first_line = lines.first()?;
// Check if first line is a Ruby shebang
if first_line.starts_with("#!") && first_line.contains("ruby") {
return Some((0, first_line));
}
// Check for polyglot format: #!/bin/sh followed by =end and then Ruby shebang
if first_line.starts_with("#!/bin/sh") {
let mut found_end = false;
for (idx, line) in lines.iter().enumerate().skip(1) {
if line.trim() == "=end" {
found_end = true;
continue;
}
if found_end && line.starts_with("#!") && line.contains("ruby") {
return Some((idx, line));
}
}
}
None
}
/// Checks if a Ruby path is within mise's installs directory.
fn is_mise_ruby_path(ruby_path: &str) -> bool {
let ruby_installs = env::MISE_INSTALLS_DIR.join("ruby");
Path::new(ruby_path).starts_with(&ruby_installs)
}
/// Converts a full version Ruby shebang to use the minor version symlink.
/// e.g., `/home/user/.mise/installs/ruby/3.1.0/bin/ruby` → `/home/user/.mise/installs/ruby/3.1/bin/ruby`
fn to_minor_version_shebang(ruby_path: &str) -> Option<String> {
let ruby_installs = env::MISE_INSTALLS_DIR.join("ruby");
let ruby_installs_str = ruby_installs.to_string_lossy();
// Check if path matches pattern: {installs}/ruby/{version}/bin/ruby
let path = Path::new(ruby_path);
let rel_path = path.strip_prefix(&ruby_installs).ok()?;
let mut components = rel_path.components();
// First component should be the version (e.g., "3.1.0")
let version_component = components.next()?.as_os_str().to_string_lossy();
let version_str = version_component.as_ref();
// Extract minor version (e.g., "3.1.0" → "3.1")
let minor_version = extract_minor_version(version_str)?;
// Reconstruct the path with minor version
let remaining: std::path::PathBuf = components.collect();
Some(format!(
"{}/{}/{}",
ruby_installs_str,
minor_version,
remaining.display()
))
}
/// Extracts major.minor from a version string.
/// e.g., "3.1.0" → "3.1", "3.2.1-preview1" → "3.2"
fn extract_minor_version(version: &str) -> Option<String> {
let parts: Vec<&str> = version.split('.').collect();
if parts.len() >= 2 {
Some(format!("{}.{}", parts[0], parts[1]))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_minor_version() {
assert_eq!(extract_minor_version("3.1.0"), Some("3.1".to_string()));
assert_eq!(extract_minor_version("3.2.1"), Some("3.2".to_string()));
assert_eq!(
extract_minor_version("3.1.0-preview1"),
Some("3.1".to_string())
);
assert_eq!(extract_minor_version("2.7.8"), Some("2.7".to_string()));
assert_eq!(extract_minor_version("3"), None);
assert_eq!(extract_minor_version("latest"), None);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/version_list.rs | src/backend/version_list.rs | /// Version list parsing utilities for fetching remote versions from URLs.
///
/// Supports multiple formats:
/// - Single version (plain text)
/// - Line-separated versions
/// - JSON arrays of strings
/// - JSON arrays of objects with version fields
/// - JSON objects with nested version arrays
///
/// Options:
/// - `version_list_url`: URL to fetch version list from
/// - `version_regex`: Regex pattern to extract versions (first capturing group or full match)
/// - `version_json_path`: JQ-like path to extract versions from JSON (e.g., `.[].version`)
use crate::backend::jq;
use eyre::Result;
use regex::Regex;
use std::collections::HashSet;
/// Fetch and parse versions from a version list URL
pub async fn fetch_versions(
version_list_url: &str,
version_regex: Option<&str>,
version_json_path: Option<&str>,
) -> Result<Vec<String>> {
use crate::http::HTTP;
// Fetch the content
let response = HTTP.get_text(version_list_url).await?;
let content = response.trim();
// Parse versions based on format
parse_version_list(content, version_regex, version_json_path)
}
/// Parse version list from content using optional regex pattern or JSON path
pub fn parse_version_list(
content: &str,
version_regex: Option<&str>,
version_json_path: Option<&str>,
) -> Result<Vec<String>> {
let mut versions = Vec::new();
let trimmed = content.trim();
// If a JSON path is provided (like ".[].version" or ".versions"), try to use it
// but fall back to text parsing if JSON parsing fails
if let Some(json_path) = version_json_path {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(trimmed)
&& let Ok(extracted) = jq::extract(&json, json_path)
{
versions = extracted;
}
// If JSON parsing failed or path extraction failed, fall through to text parsing below
}
// If a regex is provided, use it to extract versions
else if let Some(pattern) = version_regex {
let re = Regex::new(pattern)?;
for cap in re.captures_iter(content) {
// Use the first capturing group if present, otherwise the whole match
let version = cap
.get(1)
.or_else(|| cap.get(0))
.map(|m| m.as_str().to_string());
if let Some(v) = version {
let v = v.trim();
if !v.is_empty() {
versions.push(v.to_string());
}
}
}
} else {
// Try to detect the format automatically
// Check if it looks like JSON array or object
if trimmed.starts_with('[') || trimmed.starts_with('{') {
// Try to parse as JSON
if let Ok(json) = serde_json::from_str::<serde_json::Value>(trimmed) {
versions = jq::extract_auto(&json);
}
}
}
// If no versions extracted yet, treat as line-separated or single version
// This provides fallback for all cases including failed JSON parsing
if versions.is_empty() {
for line in trimmed.lines() {
let line = line.trim();
// Skip empty lines and comments
if !line.is_empty() && !line.starts_with('#') {
// Strip common version prefixes
let version = line.trim_start_matches('v');
versions.push(version.to_string());
}
}
}
// Remove duplicates while preserving order
let mut seen = HashSet::new();
versions.retain(|v| seen.insert(v.clone()));
Ok(versions)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_single_version() {
let content = "2.0.53";
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["2.0.53"]);
}
#[test]
fn test_parse_single_version_with_v_prefix() {
let content = "v2.0.53";
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["2.0.53"]);
}
#[test]
fn test_parse_line_separated_versions() {
let content = "1.0.0\n1.1.0\n2.0.0";
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "1.1.0", "2.0.0"]);
}
#[test]
fn test_parse_line_separated_with_comments() {
let content = "# Latest versions\n1.0.0\n# Stable\n2.0.0";
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_json_array_of_strings() {
let content = r#"["1.0.0", "1.1.0", "2.0.0"]"#;
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "1.1.0", "2.0.0"]);
}
#[test]
fn test_parse_json_array_with_v_prefix() {
let content = r#"["v1.0.0", "v1.1.0", "v2.0.0"]"#;
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "1.1.0", "2.0.0"]);
}
#[test]
fn test_parse_json_array_of_objects_with_version() {
let content = r#"[{"version": "1.0.0"}, {"version": "2.0.0"}]"#;
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_json_array_of_objects_with_tag_name() {
let content = r#"[{"tag_name": "v1.0.0"}, {"tag_name": "v2.0.0"}]"#;
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_json_object_with_versions_array() {
let content = r#"{"versions": ["1.0.0", "2.0.0"]}"#;
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_with_regex() {
let content = "version 1.0.0\nversion 2.0.0\nother stuff";
let versions = parse_version_list(content, Some(r"version (\d+\.\d+\.\d+)"), None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_with_json_path_array_field() {
let content = r#"{"data": {"versions": ["1.0.0", "2.0.0"]}}"#;
let versions = parse_version_list(content, None, Some(".data.versions[]")).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_with_json_path_object_array() {
let content = r#"[{"version": "1.0.0"}, {"version": "2.0.0"}]"#;
let versions = parse_version_list(content, None, Some(".[].version")).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_with_json_path_nested() {
let content =
r#"{"releases": [{"info": {"version": "1.0.0"}}, {"info": {"version": "2.0.0"}}]}"#;
let versions = parse_version_list(content, None, Some(".releases[].info.version")).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_removes_duplicates() {
let content = "1.0.0\n1.0.0\n2.0.0\n2.0.0";
let versions = parse_version_list(content, None, None).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_empty_content() {
let content = "";
let versions = parse_version_list(content, None, None).unwrap();
assert!(versions.is_empty());
}
#[test]
fn test_parse_whitespace_only() {
let content = " \n\n ";
let versions = parse_version_list(content, None, None).unwrap();
assert!(versions.is_empty());
}
#[test]
fn test_parse_json_path_with_invalid_json_falls_back_to_text() {
// When version_json_path is provided but content is not valid JSON,
// it should gracefully fall back to text parsing
let content = "1.0.0\n2.0.0";
let versions = parse_version_list(content, None, Some(".[].version")).unwrap();
assert_eq!(versions, vec!["1.0.0", "2.0.0"]);
}
#[test]
fn test_parse_json_path_with_wrong_path_falls_back_to_text() {
// When version_json_path doesn't match the JSON structure,
// it should fall back to text parsing
let content = r#"{"other": "data"}"#;
let versions = parse_version_list(content, None, Some(".[].version")).unwrap();
// Falls back to treating JSON as a single line of text
assert_eq!(versions, vec![r#"{"other": "data"}"#]);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/conda.rs | src/backend/conda.rs | use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::cli::args::BackendArg;
use crate::cli::version::{ARCH, OS};
use crate::config::Config;
use crate::config::Settings;
use crate::file::{self, TarOptions};
use crate::http::HTTP_FETCH;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::ToolVersion;
use crate::{backend::Backend, dirs, hash, http::HTTP, parallel};
use async_trait::async_trait;
use eyre::{Result, bail};
use itertools::Itertools;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use versions::Versioning;
/// Conda backend requires experimental mode to be enabled
pub const EXPERIMENTAL: bool = true;
#[derive(Debug)]
pub struct CondaBackend {
ba: Arc<BackendArg>,
}
/// Map OS/arch pair to conda subdir format
fn platform_to_conda_subdir(os: &str, arch: &str) -> &'static str {
match (os, arch) {
("linux", "x64") => "linux-64",
("linux", "arm64") => "linux-aarch64",
("macos", "x64") => "osx-64",
("macos", "arm64") => "osx-arm64",
("windows", "x64") => "win-64",
_ => "noarch",
}
}
impl CondaBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
/// Get the conda channel from settings or tool options
fn channel(&self) -> String {
self.ba
.opts()
.get("channel")
.cloned()
.unwrap_or_else(|| Settings::get().conda.channel.clone())
}
/// Map mise OS/ARCH to conda subdir
fn conda_subdir() -> &'static str {
platform_to_conda_subdir(OS.as_str(), ARCH.as_str())
}
/// Map PlatformTarget to conda subdir for lockfile resolution
fn conda_subdir_for_platform(target: &PlatformTarget) -> &'static str {
platform_to_conda_subdir(target.os_name(), target.arch_name())
}
/// Build a proper download URL from the API response
fn build_download_url(download_url: &str) -> String {
if download_url.starts_with("//") {
format!("https:{}", download_url)
} else if download_url.starts_with('/') {
format!("https://conda.anaconda.org{}", download_url)
} else {
download_url.to_string()
}
}
/// Fetch package files from the anaconda.org API for a given package
async fn fetch_package_files_for(&self, package_name: &str) -> Result<Vec<CondaPackageFile>> {
let channel = self.channel();
let url = format!(
"https://api.anaconda.org/package/{}/{}/files",
channel, package_name
);
let files: Vec<CondaPackageFile> = HTTP_FETCH.json(&url).await?;
Ok(files)
}
/// Fetch package files from the anaconda.org API for this tool
async fn fetch_package_files(&self) -> Result<Vec<CondaPackageFile>> {
self.fetch_package_files_for(&self.tool_name()).await
}
/// Find the best package file for a given version and platform
/// Prefers platform-specific packages over noarch, and .conda format over .tar.bz2
fn find_package_file<'a>(
files: &'a [CondaPackageFile],
version: Option<&str>,
subdir: &str,
) -> Option<&'a CondaPackageFile> {
// Try platform-specific packages first, then fall back to noarch
Self::find_package_file_for_subdir(files, version, subdir)
.or_else(|| Self::find_package_file_for_subdir(files, version, "noarch"))
}
/// Find the best package file for a given version and specific subdir
/// Prefers .conda format over .tar.bz2 (newer, faster)
fn find_package_file_for_subdir<'a>(
files: &'a [CondaPackageFile],
version: Option<&str>,
subdir: &str,
) -> Option<&'a CondaPackageFile> {
// Filter by exact platform match
let platform_files: Vec<_> = files.iter().filter(|f| f.attrs.subdir == subdir).collect();
if platform_files.is_empty() {
return None;
}
// Find files matching the version spec
let matching: Vec<_> = if let Some(ver) = version {
platform_files
.iter()
.filter(|f| Self::version_matches(&f.version, ver))
.copied()
.collect()
} else {
// No version spec - get latest
let latest = platform_files
.iter()
.max_by_key(|f| Versioning::new(&f.version))?;
platform_files
.iter()
.filter(|f| f.version == latest.version)
.copied()
.collect()
};
if matching.is_empty() {
return None;
}
// Prefer .conda format over .tar.bz2
// Among matches, pick the latest version
let best_version = matching
.iter()
.max_by_key(|f| Versioning::new(&f.version))?;
matching
.iter()
.filter(|f| f.version == best_version.version)
.find(|f| f.basename.ends_with(".conda"))
.or_else(|| {
matching
.iter()
.filter(|f| f.version == best_version.version)
.find(|f| f.basename.ends_with(".tar.bz2"))
})
.copied()
}
/// Check if a version matches a conda version spec
/// Supports: exact match, prefix match, wildcard (*), and comparison operators
fn version_matches(version: &str, spec: &str) -> bool {
// Exact match
if version == spec {
return true;
}
// Wildcard pattern like "6.9.*" -> matches "6.9.anything"
if let Some(prefix) = spec.strip_suffix(".*")
&& version.starts_with(prefix)
&& version
.chars()
.nth(prefix.len())
.map(|c| c == '.')
.unwrap_or(false)
{
return true;
}
// Single wildcard like "6.*" matches "6.anything"
if let Some(prefix) = spec.strip_suffix('*')
&& version.starts_with(prefix)
{
return true;
}
// Prefix match (e.g., "1.7" matches "1.7.1")
if version.starts_with(spec)
&& version
.chars()
.nth(spec.len())
.map(|c| c == '.')
.unwrap_or(false)
{
return true;
}
// Handle compound specs like ">=1.0,<2.0" by splitting on comma
if spec.contains(',') {
return spec
.split(',')
.all(|part| Self::version_matches(version, part.trim()));
}
// Comparison operators (>=, <=, >, <, ==, !=)
Self::check_version_constraint(version, spec)
}
/// Check a single version constraint like ">=1.0" or "<2.0"
fn check_version_constraint(version: &str, constraint: &str) -> bool {
let v = match Versioning::new(version) {
Some(v) => v,
None => return false,
};
if let Some(spec_ver) = constraint.strip_prefix(">=") {
if let Some(s) = Versioning::new(spec_ver) {
return v >= s;
}
} else if let Some(spec_ver) = constraint.strip_prefix("<=") {
if let Some(s) = Versioning::new(spec_ver) {
return v <= s;
}
} else if let Some(spec_ver) = constraint.strip_prefix("==") {
if let Some(s) = Versioning::new(spec_ver) {
return v == s;
}
} else if let Some(spec_ver) = constraint.strip_prefix("!=") {
if let Some(s) = Versioning::new(spec_ver) {
return v != s;
}
} else if let Some(spec_ver) = constraint.strip_prefix('>') {
if let Some(s) = Versioning::new(spec_ver) {
return v > s;
}
} else if let Some(spec_ver) = constraint.strip_prefix('<')
&& let Some(s) = Versioning::new(spec_ver)
{
return v < s;
}
false
}
/// Extract a conda package (.conda or .tar.bz2) to the install path
fn extract_conda_package(
&self,
ctx: &InstallContext,
tarball_path: &std::path::Path,
install_path: &std::path::Path,
) -> Result<()> {
let filename = tarball_path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
if filename.ends_with(".conda") {
// .conda format: ZIP containing pkg-*.tar.zst
self.extract_conda_format(ctx, tarball_path, install_path)?;
} else if filename.ends_with(".tar.bz2") {
// Legacy format: plain tar.bz2
ctx.pr.set_message(format!("extract {filename}"));
let tar_opts = TarOptions {
format: file::TarFormat::TarBz2,
pr: Some(ctx.pr.as_ref()),
..Default::default()
};
file::untar(tarball_path, install_path, &tar_opts)?;
} else {
bail!("unsupported conda package format: {}", filename);
}
Ok(())
}
/// Extract .conda format (ZIP with inner tar.zst)
fn extract_conda_format(
&self,
ctx: &InstallContext,
conda_path: &std::path::Path,
install_path: &std::path::Path,
) -> Result<()> {
let filename = conda_path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("package.conda");
ctx.pr.set_message(format!("extract {filename}"));
// Create a unique temp directory for extraction to avoid race conditions
// when multiple processes extract different packages simultaneously
let parent_dir = conda_path.parent().unwrap();
let temp_dir = tempfile::tempdir_in(parent_dir)?;
// Unzip the .conda file
file::unzip(conda_path, temp_dir.path(), &Default::default())?;
// Find and extract pkg-*.tar.zst
let pkg_tar = std::fs::read_dir(temp_dir.path())?
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("pkg-") && n.ends_with(".tar.zst"))
});
if let Some(pkg_tar_path) = pkg_tar {
let tar_opts = TarOptions {
format: file::TarFormat::TarZst,
pr: Some(ctx.pr.as_ref()),
..Default::default()
};
file::untar(&pkg_tar_path, install_path, &tar_opts)?;
} else {
bail!("could not find pkg-*.tar.zst in .conda archive");
}
// temp_dir is automatically cleaned up when dropped
Ok(())
}
/// Verify SHA256 checksum if available
fn verify_checksum(tarball_path: &Path, expected_sha256: Option<&str>) -> Result<()> {
if let Some(expected) = expected_sha256 {
hash::ensure_checksum(tarball_path, expected, None, "sha256")?;
}
Ok(())
}
/// Get the shared conda package data directory
/// All conda packages (main + deps) are stored here for sharing across tools
fn conda_data_dir() -> PathBuf {
dirs::DATA.join("conda-packages")
}
/// Get path for a specific package file in the data directory
/// Uses basename which includes version+build: "clang-21.1.7-default_h489deba_0.conda"
fn package_path(basename: &str) -> PathBuf {
let filename = Path::new(basename)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(basename);
Self::conda_data_dir().join(filename)
}
/// Recursively resolve dependencies for a package
async fn resolve_dependencies(
&self,
pkg_file: &CondaPackageFile,
subdir: &str,
resolved: &mut HashMap<String, ResolvedPackage>,
visited: &mut HashSet<String>,
) -> Result<()> {
for dep in &pkg_file.attrs.depends {
let Some((name, version_spec)) = parse_dependency(dep) else {
continue;
};
// Skip if already resolved or being visited (circular dep protection)
if resolved.contains_key(&name) || visited.contains(&name) {
continue;
}
visited.insert(name.clone());
// Fetch dependency package files
let dep_files = match self.fetch_package_files_for(&name).await {
Ok(files) => files,
Err(e) => {
bail!("failed to fetch dependency '{}': {}", name, e);
}
};
// Find best matching version for this platform
let Some(matched) =
Self::find_package_file(&dep_files, version_spec.as_deref(), subdir)
else {
// Skip dependencies not available for this platform
// This is common - many conda packages have platform-specific deps
debug!(
"skipping dependency '{}' (spec: {:?}) - not available for platform {}",
name, version_spec, subdir
);
continue;
};
resolved.insert(name.clone(), matched.to_resolved_package(&name));
// Recurse into this dependency's dependencies
Box::pin(self.resolve_dependencies(matched, subdir, resolved, visited)).await?;
}
Ok(())
}
/// Download a conda package to shared data directory (standalone for parallel::parallel)
async fn download_package(pkg: ResolvedPackage) -> Result<PathBuf> {
use eyre::WrapErr;
let data_dir = Self::conda_data_dir();
file::create_dir_all(&data_dir)
.wrap_err_with(|| format!("failed to create conda data dir for {}", pkg.name))?;
let tarball_path = Self::package_path(&pkg.basename);
// Check if file already exists with valid checksum
if tarball_path.exists() {
if Self::verify_checksum(&tarball_path, pkg.sha256.as_deref()).is_ok() {
return Ok(tarball_path);
}
// Corrupted file - delete it
let _ = std::fs::remove_file(&tarball_path);
}
// Download to a temp file first, then rename after verification
// This ensures the final path never contains a corrupted file
let temp_path = tarball_path.with_extension(format!(
"{}.tmp.{}",
tarball_path
.extension()
.and_then(|e| e.to_str())
.unwrap_or(""),
std::process::id()
));
// Clean up any stale temp file from previous runs
let _ = std::fs::remove_file(&temp_path);
HTTP.download_file(&pkg.download_url, &temp_path, None)
.await
.wrap_err_with(|| format!("failed to download {}", pkg.download_url))?;
// Verify checksum of downloaded file
let file_size = std::fs::metadata(&temp_path).map(|m| m.len()).unwrap_or(0);
Self::verify_checksum(&temp_path, pkg.sha256.as_deref()).wrap_err_with(|| {
format!(
"checksum verification failed for {} (file size: {} bytes)",
pkg.name, file_size
)
})?;
// Rename temp file to final path (atomic on most filesystems)
std::fs::rename(&temp_path, &tarball_path)
.wrap_err_with(|| format!("failed to rename temp file for {}", pkg.name))?;
Ok(tarball_path)
}
}
#[async_trait]
impl Backend for CondaBackend {
fn get_type(&self) -> BackendType {
BackendType::Conda
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let files = self.fetch_package_files().await?;
let subdir = Self::conda_subdir();
// Filter by current platform and group by version to get the latest upload time per version
let mut version_times: std::collections::HashMap<String, Option<String>> =
std::collections::HashMap::new();
for f in files
.iter()
.filter(|f| f.attrs.subdir == subdir || f.attrs.subdir == "noarch")
{
version_times
.entry(f.version.clone())
.and_modify(|existing| {
// Keep the latest upload time for each version
if let Some(new_time) = &f.upload_time
&& (existing.is_none() || existing.as_ref().is_some_and(|e| new_time > e))
{
*existing = Some(new_time.clone());
}
})
.or_insert_with(|| f.upload_time.clone());
}
// Convert to VersionInfo and sort by version
let versions: Vec<VersionInfo> = version_times
.into_iter()
.map(|(version, created_at)| VersionInfo {
version,
created_at,
..Default::default()
})
.sorted_by_cached_key(|v| Versioning::new(&v.version))
.collect();
Ok(versions)
}
/// Override to bypass the shared remote_versions cache since conda's
/// channel option affects which versions are available.
async fn list_remote_versions_with_info(
&self,
config: &Arc<Config>,
) -> Result<Vec<VersionInfo>> {
self._list_remote_versions(config).await
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
Settings::get().ensure_experimental("conda backend")?;
let files = self.fetch_package_files().await?;
let subdir = Self::conda_subdir();
// Find the package file for this version (prefers platform-specific over noarch)
let pkg_file = Self::find_package_file(&files, Some(&tv.version), subdir);
let pkg_file = match pkg_file {
Some(f) => f,
None => bail!(
"conda package {}@{} not found for platform {}",
self.tool_name(),
tv.version,
subdir
),
};
// Resolve all dependencies
ctx.pr.set_message("resolving dependencies".to_string());
let mut resolved = HashMap::new();
let mut visited = HashSet::new();
// Add main package to visited to prevent circular resolution back to it
visited.insert(self.tool_name());
self.resolve_dependencies(pkg_file, subdir, &mut resolved, &mut visited)
.await?;
// Build main package info
let main_pkg = pkg_file.to_resolved_package(&self.tool_name());
// Build list of all packages to download (deps + main)
let mut all_packages: Vec<ResolvedPackage> = resolved.values().cloned().collect();
all_packages.push(main_pkg.clone());
// Download all packages in parallel
ctx.pr
.set_message(format!("downloading {} packages", all_packages.len()));
let downloaded_paths =
parallel::parallel(all_packages.clone(), Self::download_package).await?;
// Create map of package name -> downloaded path
let path_map: HashMap<String, PathBuf> = all_packages
.iter()
.zip(downloaded_paths.iter())
.map(|(pkg, path)| (pkg.name.clone(), path.clone()))
.collect();
let install_path = tv.install_path();
file::remove_all(&install_path)?;
file::create_dir_all(&install_path)?;
// Extract dependencies first (sequential to avoid conflicts)
for name in resolved.keys() {
let tarball_path = &path_map[name];
ctx.pr.set_message(format!("extract {name}"));
self.extract_conda_package(ctx, tarball_path, &install_path)?;
}
// Extract main package last (so its files take precedence)
let main_tarball = &path_map[&main_pkg.name];
ctx.pr.set_message(format!("extract {}", self.tool_name()));
self.extract_conda_package(ctx, main_tarball, &install_path)?;
// Store lockfile info
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(main_pkg.download_url.clone());
if let Some(sha256) = &main_pkg.sha256 {
platform_info.checksum = Some(format!("sha256:{}", sha256));
}
// Make binaries executable (use same path logic as list_bin_paths)
let bin_path = if cfg!(windows) {
install_path.join("Library").join("bin")
} else {
install_path.join("bin")
};
if bin_path.exists() {
for entry in std::fs::read_dir(&bin_path)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
file::make_executable(&path)?;
}
}
}
Ok(tv)
}
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let files = self.fetch_package_files().await?;
let subdir = Self::conda_subdir_for_platform(target);
// Find the package file for this version and platform (prefers platform-specific over noarch)
let pkg_file = Self::find_package_file(&files, Some(&tv.version), subdir);
match pkg_file {
Some(pkg_file) => {
let download_url = Self::build_download_url(&pkg_file.download_url);
Ok(PlatformInfo {
url: Some(download_url),
checksum: pkg_file.sha256.as_ref().map(|s| format!("sha256:{}", s)),
size: None,
url_api: None,
})
}
None => {
// No package available for this platform
Ok(PlatformInfo {
url: None,
checksum: None,
size: None,
url_api: None,
})
}
}
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<PathBuf>> {
let install_path = tv.install_path();
if cfg!(windows) {
// Windows conda packages put binaries in Library/bin
Ok(vec![install_path.join("Library").join("bin")])
} else {
// Unix conda packages put binaries in bin
Ok(vec![install_path.join("bin")])
}
}
}
/// Represents a conda package file from the anaconda.org API
#[derive(Debug, Deserialize)]
struct CondaPackageFile {
version: String,
basename: String,
download_url: String,
sha256: Option<String>,
upload_time: Option<String>,
#[serde(default)]
attrs: CondaPackageAttrs,
}
impl CondaPackageFile {
/// Convert to a ResolvedPackage with the given name
fn to_resolved_package(&self, name: &str) -> ResolvedPackage {
ResolvedPackage {
name: name.to_string(),
download_url: CondaBackend::build_download_url(&self.download_url),
// Filter out empty strings - API sometimes returns "" instead of null
sha256: self.sha256.as_ref().filter(|s| !s.is_empty()).cloned(),
basename: self.basename.clone(),
}
}
}
/// Package attributes including platform info
#[derive(Debug, Default, Deserialize)]
struct CondaPackageAttrs {
#[serde(default)]
subdir: String,
#[serde(default)]
depends: Vec<String>,
}
/// Resolved package ready for download
#[derive(Debug, Clone)]
struct ResolvedPackage {
name: String,
download_url: String,
sha256: Option<String>,
basename: String,
}
/// Packages to skip during dependency resolution
/// - Virtual packages (__osx, __glibc, etc.) represent system requirements
/// - Runtime dependencies (python, ruby) are typically not needed for standalone tools
/// - System-provided libraries (gcc, vc runtime) should be installed separately
const SKIP_PACKAGES: &[&str] = &[
"python",
"python_abi",
"ruby",
"perl",
"r-base",
// Linux system libraries (provided by distro)
"libgcc-ng",
"libstdcxx-ng",
// Windows Visual C++ runtime (requires Visual Studio or VC++ redistributable)
"ucrt",
"vc",
"vc14_runtime",
"vs2015_runtime",
];
/// Parse a conda dependency specification
/// Returns (package_name, optional_version_spec) or None if should be skipped
fn parse_dependency(dep: &str) -> Option<(String, Option<String>)> {
// Skip virtual packages (start with __)
if dep.starts_with("__") {
return None;
}
// Parse "package_name [version_spec] [build_spec]"
let parts: Vec<&str> = dep.split_whitespace().collect();
let name = parts.first()?.to_string();
// Skip runtime dependencies that are typically not needed for standalone tools
if SKIP_PACKAGES.contains(&name.as_str()) {
return None;
}
// Get version spec if present (ignore build spec)
let version = parts.get(1).map(|s| s.to_string());
Some((name, version))
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/platform_target.rs | src/backend/platform_target.rs | use crate::platform::Platform;
/// Represents a target platform for lockfile metadata fetching
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlatformTarget {
pub platform: Platform,
}
impl PlatformTarget {
pub fn new(platform: Platform) -> Self {
Self { platform }
}
pub fn from_current() -> Self {
Self::new(Platform::current())
}
pub fn os_name(&self) -> &str {
&self.platform.os
}
pub fn arch_name(&self) -> &str {
&self.platform.arch
}
pub fn qualifier(&self) -> Option<&str> {
self.platform.qualifier.as_deref()
}
pub fn to_key(&self) -> String {
self.platform.to_key()
}
/// Returns true if this target matches the current platform
pub fn is_current(&self) -> bool {
self.platform == Platform::current()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_platform_target_creation() {
let platform = Platform::parse("linux-x64").unwrap();
let target = PlatformTarget::new(platform.clone());
assert_eq!(target.platform, platform);
assert_eq!(target.os_name(), "linux");
assert_eq!(target.arch_name(), "x64");
assert_eq!(target.qualifier(), None);
assert_eq!(target.to_key(), "linux-x64");
}
#[test]
fn test_platform_target_with_qualifier() {
let platform = Platform::parse("linux-x64-musl").unwrap();
let target = PlatformTarget::new(platform);
assert_eq!(target.os_name(), "linux");
assert_eq!(target.arch_name(), "x64");
assert_eq!(target.qualifier(), Some("musl"));
assert_eq!(target.to_key(), "linux-x64-musl");
}
#[test]
fn test_from_current() {
let target = PlatformTarget::from_current();
let current_platform = Platform::current();
assert_eq!(target.platform, current_platform);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/mod.rs | src/backend/mod.rs | use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsString;
use std::fmt::{Debug, Display, Formatter};
use std::fs::File;
use std::hash::Hash;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tokio::sync::Mutex as TokioMutex;
use jiff::Timestamp;
use crate::cli::args::{BackendArg, ToolVersionType};
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::file::{display_path, remove_all, remove_all_with_warning};
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::platform::Platform;
use crate::plugins::core::CORE_PLUGINS;
use crate::plugins::{PluginType, VERSION_REGEX};
use crate::registry::{REGISTRY, full_to_url, normalize_remote, tool_enabled};
use crate::runtime_symlinks::is_runtime_symlink;
use crate::toolset::outdated_info::OutdatedInfo;
use crate::toolset::{
ResolveOptions, ToolRequest, ToolVersion, Toolset, install_state, is_outdated_version,
};
use crate::ui::progress_report::SingleReport;
use crate::{
cache::{CacheManager, CacheManagerBuilder},
plugins::PluginEnum,
};
use crate::{dirs, env, file, hash, lock_file, plugins, versions_host};
use async_trait::async_trait;
use backend_type::BackendType;
use console::style;
use eyre::{Result, WrapErr, bail, eyre};
use indexmap::IndexSet;
use itertools::Itertools;
use platform_target::PlatformTarget;
use regex::Regex;
use std::sync::LazyLock as Lazy;
pub mod aqua;
pub mod asdf;
pub mod asset_matcher;
pub mod backend_type;
pub mod cargo;
pub mod conda;
pub mod dotnet;
mod external_plugin_cache;
pub mod gem;
pub mod github;
pub mod go;
pub mod http;
pub mod jq;
pub mod npm;
pub mod pipx;
pub mod platform_target;
pub mod spm;
pub mod static_helpers;
pub mod ubi;
pub mod version_list;
pub mod vfox;
pub type ABackend = Arc<dyn Backend>;
pub type BackendMap = BTreeMap<String, ABackend>;
pub type BackendList = Vec<ABackend>;
pub type VersionCacheManager = CacheManager<Vec<VersionInfo>>;
/// Information about a GitHub/GitLab release for platform-specific tools
#[derive(Debug, Clone)]
pub struct GitHubReleaseInfo {
pub repo: String,
pub asset_pattern: Option<String>,
pub api_url: Option<String>,
pub release_type: ReleaseType,
}
#[derive(Debug, Clone)]
pub enum ReleaseType {
GitHub,
GitLab,
}
/// Information about a tool version including optional metadata like creation time
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct VersionInfo {
pub version: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub created_at: Option<String>,
/// URL to the release page (e.g., GitHub/GitLab release page)
#[serde(skip_serializing_if = "Option::is_none", default)]
pub release_url: Option<String>,
}
impl VersionInfo {
/// Filter versions to only include those released before the given timestamp.
/// Versions without a created_at timestamp are included by default.
pub fn filter_by_date(versions: Vec<Self>, before: Timestamp) -> Vec<Self> {
use crate::duration::parse_into_timestamp;
versions
.into_iter()
.filter(|v| {
match &v.created_at {
Some(ts) => {
// Parse the timestamp using parse_into_timestamp which handles
// RFC3339, date-only (YYYY-MM-DD), and other formats
match parse_into_timestamp(ts) {
Ok(created) => created < before,
Err(_) => {
// If we can't parse the timestamp, include the version
trace!("Failed to parse timestamp: {}", ts);
true
}
}
}
// Include versions without timestamps
None => true,
}
})
.collect()
}
}
/// Security feature information for a tool
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SecurityFeature {
Checksum {
#[serde(skip_serializing_if = "Option::is_none")]
algorithm: Option<String>,
},
GithubAttestations {
#[serde(skip_serializing_if = "Option::is_none")]
signer_workflow: Option<String>,
},
Slsa {
#[serde(skip_serializing_if = "Option::is_none")]
level: Option<u8>,
},
Cosign,
Minisign {
#[serde(skip_serializing_if = "Option::is_none")]
public_key: Option<String>,
},
Gpg,
}
static TOOLS: Mutex<Option<Arc<BackendMap>>> = Mutex::new(None);
pub async fn load_tools() -> Result<Arc<BackendMap>> {
if let Some(memo_tools) = TOOLS.lock().unwrap().clone() {
return Ok(memo_tools);
}
install_state::init().await?;
time!("load_tools start");
let core_tools = CORE_PLUGINS.values().cloned().collect::<Vec<ABackend>>();
let mut tools = core_tools;
// add tools with idiomatic files so they get parsed even if no versions are installed
tools.extend(
REGISTRY
.values()
.filter(|rt| !rt.idiomatic_files.is_empty() && rt.is_supported_os())
.filter_map(|rt| arg_to_backend(rt.short.into())),
);
time!("load_tools core");
tools.extend(
install_state::list_tools()
.values()
.filter(|ist| ist.full.is_some())
.flat_map(|ist| arg_to_backend(ist.clone().into())),
);
time!("load_tools install_state");
tools.retain(|backend| {
tool_enabled(
&Settings::get().enable_tools(),
&Settings::get().disable_tools(),
&backend.id().to_string(),
)
});
tools.retain(|backend| {
!Settings::get()
.disable_backends
.contains(&backend.get_type().to_string())
});
let tools: BackendMap = tools
.into_iter()
.map(|backend| (backend.ba().short.clone(), backend))
.collect();
let tools = Arc::new(tools);
*TOOLS.lock().unwrap() = Some(tools.clone());
time!("load_tools done");
Ok(tools)
}
pub fn list() -> BackendList {
TOOLS
.lock()
.unwrap()
.as_ref()
.unwrap()
.values()
.cloned()
.collect()
}
pub fn get(ba: &BackendArg) -> Option<ABackend> {
let mut tools = TOOLS.lock().unwrap();
let tools_ = tools.as_ref().unwrap();
if let Some(backend) = tools_.get(&ba.short) {
Some(backend.clone())
} else if let Some(backend) = arg_to_backend(ba.clone()) {
let mut tools_ = tools_.deref().clone();
tools_.insert(ba.short.clone(), backend.clone());
*tools = Some(Arc::new(tools_));
Some(backend)
} else {
None
}
}
pub fn remove(short: &str) {
let mut tools = TOOLS.lock().unwrap();
let mut tools_ = tools.as_ref().unwrap().deref().clone();
tools_.remove(short);
*tools = Some(Arc::new(tools_));
}
pub fn arg_to_backend(ba: BackendArg) -> Option<ABackend> {
match ba.backend_type() {
BackendType::Core => {
CORE_PLUGINS
.get(&ba.short)
.or_else(|| {
// this can happen if something like "corenode" is aliased to "core:node"
ba.full()
.strip_prefix("core:")
.and_then(|short| CORE_PLUGINS.get(short))
})
.cloned()
}
BackendType::Aqua => Some(Arc::new(aqua::AquaBackend::from_arg(ba))),
BackendType::Asdf => Some(Arc::new(asdf::AsdfBackend::from_arg(ba))),
BackendType::Cargo => Some(Arc::new(cargo::CargoBackend::from_arg(ba))),
BackendType::Conda => Some(Arc::new(conda::CondaBackend::from_arg(ba))),
BackendType::Dotnet => Some(Arc::new(dotnet::DotnetBackend::from_arg(ba))),
BackendType::Npm => Some(Arc::new(npm::NPMBackend::from_arg(ba))),
BackendType::Gem => Some(Arc::new(gem::GemBackend::from_arg(ba))),
BackendType::Github => Some(Arc::new(github::UnifiedGitBackend::from_arg(ba))),
BackendType::Gitlab => Some(Arc::new(github::UnifiedGitBackend::from_arg(ba))),
BackendType::Go => Some(Arc::new(go::GoBackend::from_arg(ba))),
BackendType::Pipx => Some(Arc::new(pipx::PIPXBackend::from_arg(ba))),
BackendType::Spm => Some(Arc::new(spm::SPMBackend::from_arg(ba))),
BackendType::Http => Some(Arc::new(http::HttpBackend::from_arg(ba))),
BackendType::Ubi => Some(Arc::new(ubi::UbiBackend::from_arg(ba))),
BackendType::Vfox => Some(Arc::new(vfox::VfoxBackend::from_arg(ba, None))),
BackendType::VfoxBackend(plugin_name) => Some(Arc::new(vfox::VfoxBackend::from_arg(
ba,
Some(plugin_name.to_string()),
))),
BackendType::Unknown => None,
}
}
/// Returns install-time-only option keys for a backend type.
/// These are options that only affect installation/download, not post-install behavior.
/// Used to filter cached options when config provides its own options.
pub fn install_time_option_keys_for_type(backend_type: &BackendType) -> Vec<String> {
match backend_type {
BackendType::Http => http::install_time_option_keys(),
BackendType::Github | BackendType::Gitlab => github::install_time_option_keys(),
BackendType::Ubi => ubi::install_time_option_keys(),
BackendType::Cargo => cargo::install_time_option_keys(),
BackendType::Go => go::install_time_option_keys(),
BackendType::Pipx => pipx::install_time_option_keys(),
_ => vec![],
}
}
#[async_trait]
pub trait Backend: Debug + Send + Sync {
fn id(&self) -> &str {
&self.ba().short
}
fn tool_name(&self) -> String {
self.ba().tool_name()
}
fn get_type(&self) -> BackendType {
BackendType::Core
}
fn ba(&self) -> &Arc<BackendArg>;
/// Generates a platform key for lockfile storage.
/// Default implementation uses os-arch format, but backends can override for more specific keys.
fn get_platform_key(&self) -> String {
let settings = Settings::get();
let os = settings.os();
let arch = settings.arch();
format!("{os}-{arch}")
}
/// Resolves the lockfile options for a tool request on a target platform.
/// These options affect artifact identity and must match exactly for lockfile lookup.
///
/// For the current platform: resolves from Settings and ToolRequest options
/// For other platforms (cross-platform mise lock): uses sensible defaults
///
/// Backends should override this to return options that affect which artifact is downloaded.
fn resolve_lockfile_options(
&self,
_request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
BTreeMap::new() // Default: no options affect artifact identity
}
/// Returns all platform variants that should be locked for a given base platform.
///
/// Some tools have compile-time variants (e.g., bun has baseline/musl variants)
/// that result in different download URLs and checksums. This method allows
/// backends to declare all variants so `mise lock` can fetch checksums for each.
///
/// Default returns just the base platform. Backends should override this to
/// return additional variants when applicable.
///
/// Example: For bun on linux-x64, this might return:
/// - linux-x64 (default, AVX2)
/// - linux-x64-baseline (no AVX2)
/// - linux-x64-musl (musl libc)
/// - linux-x64-musl-baseline (musl + no AVX2)
fn platform_variants(&self, platform: &Platform) -> Vec<Platform> {
vec![platform.clone()] // Default: just the base platform
}
async fn description(&self) -> Option<String> {
None
}
async fn security_info(&self) -> Vec<SecurityFeature> {
vec![]
}
fn get_plugin_type(&self) -> Option<PluginType> {
None
}
/// If any of these tools are installing in parallel, we should wait for them to finish
/// before installing this tool.
fn get_dependencies(&self) -> Result<Vec<&str>> {
Ok(vec![])
}
/// dependencies which wait for install but do not warn, like cargo-binstall
fn get_optional_dependencies(&self) -> Result<Vec<&str>> {
Ok(vec![])
}
fn get_all_dependencies(&self, optional: bool) -> Result<IndexSet<BackendArg>> {
let all_fulls = self.ba().all_fulls();
if all_fulls.is_empty() {
// this can happen on windows where we won't be able to install this os/arch so
// the fact there might be dependencies is meaningless
return Ok(Default::default());
}
let mut deps: Vec<&str> = self.get_dependencies()?;
if optional {
deps.extend(self.get_optional_dependencies()?);
}
let mut deps: IndexSet<_> = deps.into_iter().map(BackendArg::from).collect();
if let Some(rt) = REGISTRY.get(self.ba().short.as_str()) {
// add dependencies from registry.toml
deps.extend(rt.depends.iter().map(BackendArg::from));
}
deps.retain(|ba| &**self.ba() != ba);
deps.retain(|ba| !all_fulls.contains(&ba.full()));
for ba in deps.clone() {
if let Ok(backend) = ba.backend() {
deps.extend(backend.get_all_dependencies(optional)?);
}
}
Ok(deps)
}
async fn list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<String>> {
Ok(self
.list_remote_versions_with_info(config)
.await?
.into_iter()
.map(|v| v.version)
.collect())
}
/// List remote versions with additional metadata like created_at timestamps.
/// Results are cached. Backends can override `_list_remote_versions_with_info`
/// to provide timestamp information.
///
/// This method first tries the versions host (mise-versions.jdx.dev) which provides
/// version info with created_at timestamps. If that fails, it falls back to the
/// backend's `_list_remote_versions_with_info` implementation.
async fn list_remote_versions_with_info(
&self,
config: &Arc<Config>,
) -> eyre::Result<Vec<VersionInfo>> {
let remote_versions = self.get_remote_version_cache();
let remote_versions = remote_versions.lock().await;
let ba = self.ba().clone();
let id = self.id();
// Check if this is an external plugin with a custom remote - skip versions host if so
let use_versions_host = if let Some(plugin) = self.plugin()
&& let Ok(Some(remote_url)) = plugin.get_remote_url()
{
// Check if remote matches the registry default
let normalized_remote =
normalize_remote(&remote_url).unwrap_or_else(|_| "INVALID_URL".into());
let shorthand_remote = REGISTRY
.get(plugin.name())
.and_then(|rt| rt.backends().first().map(|b| full_to_url(b)))
.unwrap_or_default();
let matches =
normalized_remote == normalize_remote(&shorthand_remote).unwrap_or_default();
if !matches {
trace!(
"Skipping versions host for {} because it has a non-default remote",
ba.short
);
}
matches
} else {
true // Core plugins and plugins without remote URLs can use versions host
};
let versions = remote_versions
.get_or_try_init_async(|| async {
trace!("Listing remote versions for {}", ba.to_string());
// Try versions host first (now returns VersionInfo with timestamps)
if use_versions_host {
match versions_host::list_versions(&ba.short).await {
Ok(Some(versions)) => {
trace!(
"Got {} versions from versions host for {}",
versions.len(),
ba.to_string()
);
return Ok(versions);
}
Ok(None) => {}
Err(e) => {
debug!("Error getting versions from versions host: {:#}", e);
}
}
}
trace!(
"Calling backend to list remote versions for {}",
ba.to_string()
);
let versions = self
._list_remote_versions(config)
.await?
.into_iter()
.filter(|v| match v.version.parse::<ToolVersionType>() {
Ok(ToolVersionType::Version(_)) => true,
_ => {
warn!("Invalid version: {id}@{}", v.version);
false
}
})
.collect_vec();
if versions.is_empty() && self.get_type() != BackendType::Http {
warn!("No versions found for {id}");
}
Ok(versions)
})
.await?;
Ok(versions.clone())
}
/// Backend implementation for fetching remote versions with metadata.
/// Override this to provide version listing with optional timestamp information.
/// Return `VersionInfo` with `created_at: None` if timestamps are not available.
async fn _list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>>;
async fn latest_stable_version(&self, config: &Arc<Config>) -> eyre::Result<Option<String>> {
self.latest_version(config, Some("latest".into())).await
}
fn list_installed_versions(&self) -> Vec<String> {
install_state::list_versions(&self.ba().short)
}
fn is_version_installed(
&self,
config: &Arc<Config>,
tv: &ToolVersion,
check_symlink: bool,
) -> bool {
let check_path = |install_path: &Path, check_symlink: bool| {
let is_installed = install_path.exists();
let is_not_incomplete = !self.incomplete_file_path(tv).exists();
let is_valid_symlink = !check_symlink || !is_runtime_symlink(install_path);
let installed = is_installed && is_not_incomplete && is_valid_symlink;
if log::log_enabled!(log::Level::Trace) && !installed {
let mut msg = format!(
"{} is not installed, path: {}",
self.ba(),
display_path(install_path)
);
if !is_installed {
msg += " (not installed)";
}
if !is_not_incomplete {
msg += " (incomplete)";
}
if !is_valid_symlink {
msg += " (runtime symlink)";
}
trace!("{}", msg);
}
installed
};
match tv.request {
ToolRequest::System { .. } => true,
_ => {
if let Some(install_path) = tv.request.install_path(config)
&& check_path(&install_path, true)
{
return true;
}
check_path(&tv.install_path(), check_symlink)
}
}
}
async fn is_version_outdated(&self, config: &Arc<Config>, tv: &ToolVersion) -> bool {
let latest = match tv.latest_version(config).await {
Ok(latest) => latest,
Err(e) => {
warn!(
"Error getting latest version for {}: {:#}",
self.ba().to_string(),
e
);
return false;
}
};
!self.is_version_installed(config, tv, true) || is_outdated_version(&tv.version, &latest)
}
fn symlink_path(&self, tv: &ToolVersion) -> Option<PathBuf> {
match tv.install_path() {
path if path.is_symlink() && !is_runtime_symlink(&path) => Some(path),
_ => None,
}
}
fn create_symlink(&self, version: &str, target: &Path) -> Result<Option<(PathBuf, PathBuf)>> {
let link = self.ba().installs_path.join(version);
if link.exists() {
return Ok(None);
}
file::create_dir_all(link.parent().unwrap())?;
let link = file::make_symlink(target, &link)?;
Ok(Some(link))
}
fn list_installed_versions_matching(&self, query: &str) -> Vec<String> {
let versions = self.list_installed_versions();
self.fuzzy_match_filter(versions, query)
}
async fn list_versions_matching(
&self,
config: &Arc<Config>,
query: &str,
) -> eyre::Result<Vec<String>> {
let versions = self.list_remote_versions(config).await?;
Ok(self.fuzzy_match_filter(versions, query))
}
/// List versions matching a query, optionally filtered by release date.
/// Use this when you have a `before_date` from ResolveOptions.
async fn list_versions_matching_with_opts(
&self,
config: &Arc<Config>,
query: &str,
before_date: Option<Timestamp>,
) -> eyre::Result<Vec<String>> {
let versions = match before_date {
Some(before) => {
// Use version info to filter by date
let versions_with_info = self.list_remote_versions_with_info(config).await?;
let filtered = VersionInfo::filter_by_date(versions_with_info, before);
// Warn if no versions have timestamps
if filtered.iter().all(|v| v.created_at.is_none()) && !filtered.is_empty() {
debug!(
"Backend {} does not provide release dates; --before filter may not work as expected",
self.id()
);
}
filtered.into_iter().map(|v| v.version).collect()
}
None => self.list_remote_versions(config).await?,
};
Ok(self.fuzzy_match_filter(versions, query))
}
async fn latest_version(
&self,
config: &Arc<Config>,
query: Option<String>,
) -> eyre::Result<Option<String>> {
match query {
Some(query) => {
let mut matches = self.list_versions_matching(config, &query).await?;
if matches.is_empty() && query == "latest" {
matches = self.list_remote_versions(config).await?;
}
Ok(find_match_in_list(&matches, &query))
}
None => self.latest_stable_version(config).await,
}
}
/// Get the latest version, optionally filtered by release date.
/// Use this when you have a `before_date` from ResolveOptions.
async fn latest_version_with_opts(
&self,
config: &Arc<Config>,
query: Option<String>,
before_date: Option<Timestamp>,
) -> eyre::Result<Option<String>> {
match query {
Some(query) => {
let mut matches = self
.list_versions_matching_with_opts(config, &query, before_date)
.await?;
if matches.is_empty() && query == "latest" {
// Fall back to all versions if no match
matches = match before_date {
Some(before) => {
let versions_with_info =
self.list_remote_versions_with_info(config).await?;
VersionInfo::filter_by_date(versions_with_info, before)
.into_iter()
.map(|v| v.version)
.collect()
}
None => self.list_remote_versions(config).await?,
};
}
Ok(find_match_in_list(&matches, &query))
}
None => {
// For stable version, apply date filter if provided
match before_date {
Some(before) => {
let versions_with_info =
self.list_remote_versions_with_info(config).await?;
let filtered = VersionInfo::filter_by_date(versions_with_info, before);
let versions: Vec<String> =
filtered.into_iter().map(|v| v.version).collect();
Ok(find_match_in_list(&versions, "latest"))
}
None => self.latest_stable_version(config).await,
}
}
}
}
fn latest_installed_version(&self, query: Option<String>) -> eyre::Result<Option<String>> {
match query {
Some(query) => {
let matches = self.list_installed_versions_matching(&query);
Ok(find_match_in_list(&matches, &query))
}
None => {
let installed_symlink = self.ba().installs_path.join("latest");
if installed_symlink.exists() {
let Some(target) = file::resolve_symlink(&installed_symlink)? else {
return Ok(Some("latest".to_string()));
};
let version = target
.file_name()
.ok_or_else(|| eyre!("Invalid symlink target"))?
.to_string_lossy()
.to_string();
Ok(Some(version))
} else {
Ok(None)
}
}
}
}
async fn warn_if_dependencies_missing(&self, config: &Arc<Config>) -> eyre::Result<()> {
let deps = self
.get_all_dependencies(false)?
.into_iter()
.filter(|ba| &**self.ba() != ba)
.map(|ba| ba.short)
.collect::<HashSet<_>>();
if !deps.is_empty() {
trace!("Ensuring dependencies installed for {}", self.id());
let ts = config.get_tool_request_set().await?.filter_by_tool(deps);
let missing = ts.missing_tools(config).await;
if !missing.is_empty() {
warn_once!(
"missing dependency: {}",
missing.iter().map(|d| d.to_string()).join(", "),
);
}
}
Ok(())
}
fn purge(&self, pr: &dyn SingleReport) -> eyre::Result<()> {
rmdir(&self.ba().installs_path, pr)?;
rmdir(&self.ba().cache_path, pr)?;
rmdir(&self.ba().downloads_path, pr)?;
Ok(())
}
fn get_aliases(&self) -> eyre::Result<BTreeMap<String, String>> {
Ok(BTreeMap::new())
}
async fn idiomatic_filenames(&self) -> Result<Vec<String>> {
Ok(REGISTRY
.get(self.id())
.map(|rt| rt.idiomatic_files.iter().map(|s| s.to_string()).collect())
.unwrap_or_default())
}
async fn parse_idiomatic_file(&self, path: &Path) -> eyre::Result<String> {
let contents = file::read_to_string(path)?;
Ok(contents.trim().to_string())
}
fn plugin(&self) -> Option<&PluginEnum> {
None
}
async fn install_version(
&self,
ctx: InstallContext,
tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
// Handle dry-run mode early to avoid plugin installation
if ctx.dry_run {
use crate::ui::progress_report::ProgressIcon;
if self.is_version_installed(&ctx.config, &tv, true) {
ctx.pr
.finish_with_icon("already installed".into(), ProgressIcon::Skipped);
} else {
ctx.pr
.finish_with_icon("would install".into(), ProgressIcon::Skipped);
}
return Ok(tv);
}
if let Some(plugin) = self.plugin() {
plugin.is_installed_err()?;
}
if self.is_version_installed(&ctx.config, &tv, true) {
if ctx.force {
self.uninstall_version(&ctx.config, &tv, ctx.pr.as_ref(), false)
.await?;
} else {
return Ok(tv);
}
}
// Check for --locked mode: if enabled and no lockfile URL exists, fail early
if ctx.locked {
let platform_key = self.get_platform_key();
let has_lockfile_url = tv
.lock_platforms
.get(&platform_key)
.and_then(|p| p.url.as_ref())
.is_some();
if !has_lockfile_url {
bail!(
"No lockfile URL found for {} on platform {} (--locked mode)\n\
hint: Run `mise lock` to generate lockfile URLs, or disable locked mode",
tv.style(),
platform_key
);
}
}
// Track the installation asynchronously (fire-and-forget)
// Do this before install so the request has time to complete during installation
versions_host::track_install(tv.short(), &tv.ba().full(), &tv.version);
ctx.pr.set_message("install".into());
let _lock = lock_file::get(&tv.install_path(), ctx.force)?;
// Double-checked (locking) that it wasn't installed while we were waiting for the lock
if self.is_version_installed(&ctx.config, &tv, true) && !ctx.force {
return Ok(tv);
}
self.create_install_dirs(&tv)?;
let old_tv = tv.clone();
let tv = match self.install_version_(&ctx, tv).await {
Ok(tv) => tv,
Err(e) => {
self.cleanup_install_dirs_on_error(&old_tv);
// Pass through the error - it will be wrapped at a higher level
return Err(e);
}
};
if tv.install_path().starts_with(*dirs::INSTALLS) {
// this will be false only for `install-into`
install_state::write_backend_meta(self.ba())?;
}
self.cleanup_install_dirs(&tv);
// attempt to touch all the .tool-version files to trigger updates in hook-env
let mut touch_dirs = vec![dirs::DATA.to_path_buf()];
touch_dirs.extend(ctx.config.config_files.keys().cloned());
for path in touch_dirs {
let err = file::touch_dir(&path);
if let Err(err) = err {
trace!("error touching config file: {:?} {:?}", path, err);
}
}
let incomplete_path = self.incomplete_file_path(&tv);
if let Err(err) = file::remove_file(&incomplete_path) {
debug!("error removing incomplete file: {:?}", err);
} else {
// Sync parent directory to ensure file removal is immediately visible
if let Some(parent) = incomplete_path.parent()
&& let Err(err) = file::sync_dir(parent)
{
debug!("error syncing incomplete file parent directory: {:?}", err);
}
}
if let Some(script) = tv.request.options().get("postinstall") {
ctx.pr
.finish_with_message("running custom postinstall hook".to_string());
self.run_postinstall_hook(&ctx, &tv, script).await?;
}
ctx.pr.finish_with_message("installed".to_string());
Ok(tv)
}
async fn run_postinstall_hook(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
script: &str,
) -> eyre::Result<()> {
// Get pre-tools environment variables from config
let mut env_vars = self.exec_env(&ctx.config, &ctx.ts, tv).await?;
// Add pre-tools environment variables from config if available
if let Some(config_env) = ctx.config.env_maybe() {
for (k, v) in config_env {
env_vars.entry(k).or_insert(v);
}
}
CmdLineRunner::new(&*env::SHELL)
.env(&*env::PATH_KEY, plugins::core::path_env_with_tv_path(tv)?)
.env("MISE_TOOL_INSTALL_PATH", tv.install_path())
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/asset_matcher.rs | src/backend/asset_matcher.rs | //! Unified asset matching for backend tool installation
//!
//! This module provides a high-level `AssetMatcher` that uses platform heuristics
//! to score and rank assets for finding the best download for the target platform.
//!
//! # Example
//!
//! ```ignore
//! use crate::backend::asset_matcher::{AssetMatcher, detect_asset_for_target};
//!
//! // Auto-detect best asset for a target platform
//! let asset = detect_asset_for_target(&assets, &target)?;
//!
//! // Or use the builder
//! let asset = AssetMatcher::new()
//! .for_target(&target)
//! .pick_from(&assets)?;
//! ```
use eyre::{Result, bail};
use regex::Regex;
use std::sync::LazyLock;
use super::platform_target::PlatformTarget;
use super::static_helpers::get_filename_from_url;
use crate::http::HTTP;
// ========== Platform Detection Types (from asset_detector) ==========
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AssetOs {
Linux,
Macos,
Windows,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AssetArch {
X64,
Arm64,
X86,
Arm,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AssetLibc {
Gnu,
Musl,
Msvc,
}
impl AssetOs {
pub fn matches_target(&self, target: &str) -> bool {
match self {
AssetOs::Linux => target == "linux",
AssetOs::Macos => target == "macos" || target == "darwin",
AssetOs::Windows => target == "windows",
}
}
}
impl AssetArch {
pub fn matches_target(&self, target: &str) -> bool {
match self {
AssetArch::X64 => target == "x86_64" || target == "amd64" || target == "x64",
AssetArch::Arm64 => target == "aarch64" || target == "arm64",
AssetArch::X86 => target == "x86" || target == "i386" || target == "i686",
AssetArch::Arm => target == "arm",
}
}
}
impl AssetLibc {
pub fn matches_target(&self, target: &str) -> bool {
match self {
AssetLibc::Gnu => target == "gnu",
AssetLibc::Musl => target == "musl",
AssetLibc::Msvc => target == "msvc",
}
}
}
/// Detected platform information from a URL
#[derive(Debug, Clone)]
pub struct DetectedPlatform {
pub os: AssetOs,
pub arch: AssetArch,
#[allow(unused)]
pub libc: Option<AssetLibc>,
}
impl DetectedPlatform {
/// Convert to mise's platform string format (e.g., "linux-x64", "macos-arm64")
pub fn to_platform_string(&self) -> String {
let os_str = match self.os {
AssetOs::Linux => "linux",
AssetOs::Macos => "macos",
AssetOs::Windows => "windows",
};
let arch_str = match self.arch {
AssetArch::X64 => "x64",
AssetArch::Arm64 => "arm64",
AssetArch::X86 => "x86",
AssetArch::Arm => "arm",
};
format!("{os_str}-{arch_str}")
}
}
// Platform detection patterns
static OS_PATTERNS: LazyLock<Vec<(AssetOs, Regex)>> = LazyLock::new(|| {
vec![
(
AssetOs::Linux,
Regex::new(r"(?i)(?:\b|_)(?:linux|ubuntu|debian|fedora|centos|rhel|alpine|arch)(?:\b|_|32|64|-)")
.unwrap(),
),
(
AssetOs::Macos,
Regex::new(r"(?i)(?:\b|_)(?:darwin|mac(?:osx?)?|osx)(?:\b|_)").unwrap(),
),
(
AssetOs::Windows,
Regex::new(r"(?i)(?:\b|_)win(?:32|64|dows)?(?:\b|_)").unwrap(),
),
]
});
static ARCH_PATTERNS: LazyLock<Vec<(AssetArch, Regex)>> = LazyLock::new(|| {
vec![
(
AssetArch::X64,
Regex::new(r"(?i)(?:\b|_)(?:x86[_-]64|x64|amd64)(?:\b|_)").unwrap(),
),
(
AssetArch::Arm64,
Regex::new(r"(?i)(?:\b|_)(?:aarch_?64|arm_?64)(?:\b|_)").unwrap(),
),
(
AssetArch::X86,
Regex::new(r"(?i)(?:\b|_)(?:x86|i386|i686)(?:\b|_)").unwrap(),
),
(
AssetArch::Arm,
Regex::new(r"(?i)(?:\b|_)arm(?:v[0-7])?(?:\b|_)").unwrap(),
),
]
});
static LIBC_PATTERNS: LazyLock<Vec<(AssetLibc, Regex)>> = LazyLock::new(|| {
vec![
(
AssetLibc::Msvc,
Regex::new(r"(?i)(?:\b|_)(?:msvc)(?:\b|_)").unwrap(),
),
(
AssetLibc::Gnu,
Regex::new(r"(?i)(?:\b|_)(?:gnu|glibc)(?:\b|_)").unwrap(),
),
(
AssetLibc::Musl,
Regex::new(r"(?i)(?:\b|_)(?:musl)(?:\b|_)").unwrap(),
),
]
});
static ARCHIVE_EXTENSIONS: &[&str] = &[
".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tgz", ".tbz2", ".txz", ".tzst", ".zip", ".7z",
".tar",
];
// ========== AssetPicker (from asset_detector) ==========
/// Automatically detects the best asset for the current platform
pub struct AssetPicker {
target_os: String,
target_arch: String,
target_libc: String,
}
impl AssetPicker {
/// Create an AssetPicker with an explicit libc setting
pub fn with_libc(target_os: String, target_arch: String, libc: Option<String>) -> Self {
let target_libc = libc.unwrap_or_else(|| {
if target_os == "windows" {
"msvc".to_string()
} else if cfg!(target_env = "musl") {
"musl".to_string()
} else {
"gnu".to_string()
}
});
Self {
target_os,
target_arch,
target_libc,
}
}
/// Picks the best asset from available options
pub fn pick_best_asset(&self, assets: &[String]) -> Option<String> {
let candidates = self.filter_archive_assets(assets);
let mut scored_assets = self.score_all_assets(&candidates);
scored_assets.sort_by(|a, b| b.0.cmp(&a.0));
scored_assets
.first()
.filter(|(score, _)| *score > 0)
.map(|(_, asset)| asset.clone())
}
fn filter_archive_assets(&self, assets: &[String]) -> Vec<String> {
let archive_assets: Vec<String> = assets
.iter()
.filter(|name| ARCHIVE_EXTENSIONS.iter().any(|ext| name.ends_with(ext)))
.cloned()
.collect();
if archive_assets.is_empty() {
assets.to_vec()
} else {
archive_assets
}
}
fn score_all_assets(&self, assets: &[String]) -> Vec<(i32, String)> {
assets
.iter()
.map(|asset| (self.score_asset(asset), asset.clone()))
.collect()
}
/// Scores a single asset based on platform compatibility
pub fn score_asset(&self, asset: &str) -> i32 {
let mut score = 0;
score += self.score_os_match(asset);
score += self.score_arch_match(asset);
if self.target_os == "linux" || self.target_os == "windows" {
score += self.score_libc_match(asset);
}
score += self.score_format_preferences(asset);
score += self.score_build_penalties(asset);
score
}
fn score_os_match(&self, asset: &str) -> i32 {
for (os, pattern) in OS_PATTERNS.iter() {
if pattern.is_match(asset) {
return if os.matches_target(&self.target_os) {
100
} else {
-100
};
}
}
0
}
fn score_arch_match(&self, asset: &str) -> i32 {
for (arch, pattern) in ARCH_PATTERNS.iter() {
if pattern.is_match(asset) {
return if arch.matches_target(&self.target_arch) {
50
} else {
-25
};
}
}
0
}
fn score_libc_match(&self, asset: &str) -> i32 {
for (libc, pattern) in LIBC_PATTERNS.iter() {
if pattern.is_match(asset) {
return if libc.matches_target(&self.target_libc) {
25
} else {
-10
};
}
}
0
}
fn score_format_preferences(&self, asset: &str) -> i32 {
if ARCHIVE_EXTENSIONS.iter().any(|ext| asset.ends_with(ext)) {
10
} else {
0
}
}
fn score_build_penalties(&self, asset: &str) -> i32 {
let mut penalty = 0;
if asset.contains("debug") || asset.contains("test") {
penalty -= 20;
}
if asset.contains(".artifactbundle") {
penalty -= 30;
}
penalty
}
}
/// Detects platform information from a URL
pub fn detect_platform_from_url(url: &str) -> Option<DetectedPlatform> {
let mut detected_os = None;
let mut detected_arch = None;
let mut detected_libc = None;
let filename = get_filename_from_url(url);
for (os, pattern) in OS_PATTERNS.iter() {
if pattern.is_match(&filename) {
detected_os = Some(*os);
break;
}
}
for (arch, pattern) in ARCH_PATTERNS.iter() {
if pattern.is_match(&filename) {
detected_arch = Some(*arch);
break;
}
}
if detected_os == Some(AssetOs::Linux) || detected_os == Some(AssetOs::Windows) {
for (libc, pattern) in LIBC_PATTERNS.iter() {
if pattern.is_match(&filename) {
detected_libc = Some(*libc);
break;
}
}
}
if let (Some(os), Some(arch)) = (detected_os, detected_arch) {
Some(DetectedPlatform {
os,
arch,
libc: detected_libc,
})
} else {
None
}
}
/// Common checksum file extensions
static CHECKSUM_EXTENSIONS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
vec![
".sha256",
".sha256sum",
".sha256sums",
".SHA256",
".SHA256SUM",
".SHA256SUMS",
".sha512",
".sha512sum",
".sha512sums",
".SHA512",
".SHA512SUM",
".SHA512SUMS",
".md5",
".md5sum",
".checksums",
".CHECKSUMS",
]
});
/// Common checksum filename patterns
static CHECKSUM_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
vec![
Regex::new(r"(?i)^sha256sums?\.txt$").unwrap(),
Regex::new(r"(?i)^sha512sums?\.txt$").unwrap(),
Regex::new(r"(?i)^checksums?\.txt$").unwrap(),
Regex::new(r"(?i)^SHASUMS").unwrap(),
Regex::new(r"(?i)checksums?\.sha256$").unwrap(),
]
});
/// Represents a matched asset with metadata
#[derive(Debug, Clone)]
pub struct MatchedAsset {
/// The asset name/filename
pub name: String,
}
/// Builder for matching assets
#[derive(Debug, Default)]
pub struct AssetMatcher {
/// Target OS (e.g., "linux", "macos", "windows")
target_os: Option<String>,
/// Target architecture (e.g., "x86_64", "aarch64")
target_arch: Option<String>,
/// Target libc variant (e.g., "gnu", "musl")
target_libc: Option<String>,
}
impl AssetMatcher {
/// Create a new AssetMatcher with default settings
pub fn new() -> Self {
Self::default()
}
/// Configure for a specific target platform
pub fn for_target(mut self, target: &PlatformTarget) -> Self {
self.target_os = Some(target.os_name().to_string());
self.target_arch = Some(target.arch_name().to_string());
self.target_libc = target.qualifier().map(|s| s.to_string());
self
}
/// Pick the best matching asset from a list of names
pub fn pick_from(&self, assets: &[String]) -> Result<MatchedAsset> {
let filtered = self.filter_assets(assets);
if filtered.is_empty() {
bail!("No assets available after filtering");
}
self.match_by_auto_detection(&filtered)
}
/// Find checksum file for a given asset
pub fn find_checksum_for(&self, asset_name: &str, assets: &[String]) -> Option<String> {
let base_name = asset_name
.trim_end_matches(".tar.gz")
.trim_end_matches(".tar.xz")
.trim_end_matches(".tar.bz2")
.trim_end_matches(".zip")
.trim_end_matches(".tgz");
// Try exact match with checksum extension
for ext in CHECKSUM_EXTENSIONS.iter() {
let checksum_name = format!("{asset_name}{ext}");
if assets.iter().any(|a| a == &checksum_name) {
return Some(checksum_name);
}
let checksum_name = format!("{base_name}{ext}");
if assets.iter().any(|a| a == &checksum_name) {
return Some(checksum_name);
}
}
// Try common checksum file patterns
for pattern in CHECKSUM_PATTERNS.iter() {
for asset in assets {
if pattern.is_match(asset) {
return Some(asset.clone());
}
}
}
None
}
// ========== Internal Methods ==========
fn filter_assets(&self, assets: &[String]) -> Vec<String> {
let is_archive = |name: &str| ARCHIVE_EXTENSIONS.iter().any(|ext| name.ends_with(ext));
// Prefer archives when available
let archives: Vec<String> = assets.iter().filter(|a| is_archive(a)).cloned().collect();
if !archives.is_empty() {
return archives;
}
assets.to_vec()
}
fn create_picker(&self) -> Option<AssetPicker> {
let os = self.target_os.as_ref()?;
let arch = self.target_arch.as_ref()?;
Some(AssetPicker::with_libc(
os.clone(),
arch.clone(),
self.target_libc.clone(),
))
}
fn match_by_auto_detection(&self, assets: &[String]) -> Result<MatchedAsset> {
let picker = self
.create_picker()
.ok_or_else(|| eyre::eyre!("Target OS and arch must be set for auto-detection"))?;
let best = picker.pick_best_asset(assets).ok_or_else(|| {
let os = self.target_os.as_deref().unwrap_or("unknown");
let arch = self.target_arch.as_deref().unwrap_or("unknown");
eyre::eyre!(
"No matching asset found for platform {}-{}\nAvailable assets:\n{}",
os,
arch,
assets.join("\n")
)
})?;
Ok(MatchedAsset { name: best })
}
}
/// Convenience function to detect the best asset for a target platform
pub fn detect_asset_for_target(assets: &[String], target: &PlatformTarget) -> Result<String> {
AssetMatcher::new()
.for_target(target)
.pick_from(assets)
.map(|m| m.name)
}
// ========== Checksum Fetching Helpers ==========
/// Represents an asset with its download URL
#[derive(Debug, Clone)]
pub struct Asset {
/// The asset filename
pub name: String,
/// The download URL for the asset
pub url: String,
}
impl Asset {
pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
Self {
name: name.into(),
url: url.into(),
}
}
}
/// Result of a checksum lookup
#[derive(Debug, Clone)]
pub struct ChecksumResult {
/// Algorithm used (sha256, sha512, md5, blake3)
pub algorithm: String,
/// The hash value
pub hash: String,
/// Which checksum file this came from
pub source_file: String,
}
impl ChecksumResult {
/// Format as "algorithm:hash" string for verification
pub fn to_string_formatted(&self) -> String {
format!("{}:{}", self.algorithm, self.hash)
}
}
/// Checksum file fetcher that finds and parses checksums from release assets
pub struct ChecksumFetcher<'a> {
assets: &'a [Asset],
}
impl<'a> ChecksumFetcher<'a> {
/// Create a new checksum fetcher with the given assets
pub fn new(assets: &'a [Asset]) -> Self {
Self { assets }
}
/// Find and fetch the checksum for a specific asset
///
/// This method:
/// 1. Finds a checksum file that matches the asset name
/// 2. Fetches the checksum file
/// 3. Parses it to extract the checksum for the target file
///
/// Returns None if no checksum file is found or parsing fails.
pub async fn fetch_checksum_for(&self, asset_name: &str) -> Option<ChecksumResult> {
let asset_names: Vec<String> = self.assets.iter().map(|a| a.name.clone()).collect();
let matcher = AssetMatcher::new();
// First try to find an asset-specific checksum file (e.g., file.tar.gz.sha256)
if let Some(checksum_filename) = matcher.find_checksum_for(asset_name, &asset_names)
&& let Some(checksum_asset) = self.assets.iter().find(|a| a.name == checksum_filename)
&& let Some(result) = self
.fetch_and_parse_checksum(&checksum_asset.url, &checksum_filename, asset_name)
.await
{
return Some(result);
}
// Try common global checksum files by exact name match first
let global_patterns = [
"checksums.txt",
"SHA256SUMS",
"SHASUMS256.txt",
"sha256sums.txt",
];
for pattern in global_patterns {
if let Some(checksum_asset) = self
.assets
.iter()
.find(|a| a.name.eq_ignore_ascii_case(pattern))
&& let Some(result) = self
.fetch_and_parse_checksum(&checksum_asset.url, &checksum_asset.name, asset_name)
.await
{
return Some(result);
}
}
// Last resort: try any file with "checksum" in the name
if let Some(checksum_asset) = self
.assets
.iter()
.find(|a| a.name.to_lowercase().contains("checksum"))
&& let Some(result) = self
.fetch_and_parse_checksum(&checksum_asset.url, &checksum_asset.name, asset_name)
.await
{
return Some(result);
}
None
}
/// Fetch a checksum file and parse it for the target asset
async fn fetch_and_parse_checksum(
&self,
url: &str,
checksum_filename: &str,
target_asset: &str,
) -> Option<ChecksumResult> {
let content = match HTTP.get_text(url).await {
Ok(c) => c,
Err(e) => {
debug!("Failed to fetch checksum file {}: {}", url, e);
return None;
}
};
// Detect algorithm from filename
let algorithm = detect_checksum_algorithm(checksum_filename);
// Try to parse the checksum
parse_checksum_content(&content, target_asset, &algorithm, checksum_filename)
}
}
/// Detect the checksum algorithm from the filename
fn detect_checksum_algorithm(filename: &str) -> String {
let lower = filename.to_lowercase();
if lower.contains("sha512") || lower.ends_with(".sha512") || lower.ends_with(".sha512sum") {
"sha512".to_string()
} else if lower.contains("md5") || lower.ends_with(".md5") || lower.ends_with(".md5sum") {
"md5".to_string()
} else if lower.contains("blake3") || lower.ends_with(".b3") {
"blake3".to_string()
} else {
// Default to sha256 (most common)
"sha256".to_string()
}
}
/// Parse checksum content and extract the hash for a specific file
fn parse_checksum_content(
content: &str,
target_file: &str,
algorithm: &str,
source_file: &str,
) -> Option<ChecksumResult> {
let trimmed = content.trim();
// Check if this looks like a multi-line SHASUMS file (has lines with two parts)
let is_shasums_format = trimmed.lines().any(|line| {
let parts: Vec<&str> = line.split_whitespace().collect();
parts.len() >= 2
});
if is_shasums_format {
// Try standard SHASUMS format: "<hash> <filename>" or "<hash> *<filename>"
// Parse manually to avoid panic from hash::parse_shasums
for line in trimmed.lines() {
let mut parts = line.split_whitespace();
if let (Some(hash_str), Some(filename)) = (parts.next(), parts.next()) {
// Strip leading * or . from filename if present (some formats use this)
let clean_filename = filename.trim_start_matches(['*', '.']);
if (clean_filename == target_file || filename == target_file)
&& is_valid_hash(hash_str, algorithm)
{
return Some(ChecksumResult {
algorithm: algorithm.to_string(),
hash: hash_str.to_string(),
source_file: source_file.to_string(),
});
}
}
}
// Target file not found in SHASUMS file - return None, don't fall through
return None;
}
// Only for single-file checksum (e.g., file.tar.gz.sha256), extract just the hash
// Format is typically "<hash>" or "<hash> <filename>"
if let Some(first_word) = trimmed.split_whitespace().next() {
// Validate it looks like a hash (hex string of appropriate length)
if is_valid_hash(first_word, algorithm) {
return Some(ChecksumResult {
algorithm: algorithm.to_string(),
hash: first_word.to_string(),
source_file: source_file.to_string(),
});
}
}
None
}
/// Check if a string looks like a valid hash for the given algorithm
fn is_valid_hash(s: &str, algorithm: &str) -> bool {
let expected_len = match algorithm {
"sha256" => 64,
"sha512" => 128,
"md5" => 32,
"blake3" => 64,
_ => return s.len() >= 32, // At least 128 bits
};
s.len() == expected_len && s.chars().all(|c| c.is_ascii_hexdigit())
}
#[cfg(test)]
mod tests {
use super::*;
fn test_assets() -> Vec<String> {
vec![
"tool-1.0.0-linux-x86_64.tar.gz".to_string(),
"tool-1.0.0-linux-aarch64.tar.gz".to_string(),
"tool-1.0.0-darwin-x86_64.tar.gz".to_string(),
"tool-1.0.0-darwin-arm64.tar.gz".to_string(),
"tool-1.0.0-windows-x86_64.zip".to_string(),
"tool-1.0.0-linux-x86_64.tar.gz.sha256".to_string(),
"checksums.txt".to_string(),
]
}
#[test]
fn test_find_checksum() {
let matcher = AssetMatcher::new();
let checksum = matcher.find_checksum_for("tool-1.0.0-linux-x86_64.tar.gz", &test_assets());
assert_eq!(
checksum,
Some("tool-1.0.0-linux-x86_64.tar.gz.sha256".to_string())
);
}
#[test]
fn test_find_checksum_global() {
let matcher = AssetMatcher::new();
let assets = vec!["tool-1.0.0.tar.gz".to_string(), "checksums.txt".to_string()];
let checksum = matcher.find_checksum_for("tool-1.0.0.tar.gz", &assets);
assert_eq!(checksum, Some("checksums.txt".to_string()));
}
// ========== Checksum Helper Tests ==========
#[test]
fn test_detect_checksum_algorithm() {
assert_eq!(detect_checksum_algorithm("SHA256SUMS"), "sha256");
assert_eq!(detect_checksum_algorithm("file.sha256"), "sha256");
assert_eq!(detect_checksum_algorithm("sha256sums.txt"), "sha256");
assert_eq!(detect_checksum_algorithm("SHA512SUMS"), "sha512");
assert_eq!(detect_checksum_algorithm("file.sha512"), "sha512");
assert_eq!(detect_checksum_algorithm("file.md5"), "md5");
assert_eq!(detect_checksum_algorithm("MD5SUMS"), "md5");
assert_eq!(detect_checksum_algorithm("checksums.b3"), "blake3");
assert_eq!(detect_checksum_algorithm("checksums.txt"), "sha256"); // default
}
#[test]
fn test_is_valid_hash() {
// SHA256 (64 chars)
assert!(is_valid_hash(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"sha256"
));
assert!(!is_valid_hash("e3b0c44298fc1c149afbf4c8996fb924", "sha256")); // too short
// SHA512 (128 chars)
assert!(is_valid_hash(
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
"sha512"
));
// MD5 (32 chars)
assert!(is_valid_hash("d41d8cd98f00b204e9800998ecf8427e", "md5"));
assert!(!is_valid_hash("d41d8cd98f00b204", "md5")); // too short
// Invalid characters
assert!(!is_valid_hash(
"g3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"sha256"
));
}
#[test]
fn test_parse_checksum_content_shasums_format() {
let content = r#"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tool-1.0.0-linux-x64.tar.gz
abc123def456abc123def456abc123def456abc123def456abc123def456abcd tool-1.0.0-darwin-arm64.tar.gz"#;
let result = parse_checksum_content(
content,
"tool-1.0.0-linux-x64.tar.gz",
"sha256",
"SHA256SUMS",
);
assert!(result.is_some());
let r = result.unwrap();
assert_eq!(r.algorithm, "sha256");
assert_eq!(
r.hash,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(r.source_file, "SHA256SUMS");
}
#[test]
fn test_parse_checksum_content_single_file() {
let content = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
let result = parse_checksum_content(
content,
"tool-1.0.0-linux-x64.tar.gz",
"sha256",
"tool-1.0.0-linux-x64.tar.gz.sha256",
);
assert!(result.is_some());
let r = result.unwrap();
assert_eq!(r.algorithm, "sha256");
assert_eq!(
r.hash,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
#[test]
fn test_parse_checksum_content_with_filename_suffix() {
// Checksum file with format: "<hash> filename" should match the filename
let content =
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 tool.tar.gz";
// Should return the hash when target matches the filename
let result = parse_checksum_content(content, "tool.tar.gz", "sha256", "tool.sha256");
assert!(result.is_some());
let r = result.unwrap();
assert_eq!(
r.hash,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
// Should return None when target doesn't match the filename
let result = parse_checksum_content(content, "other-file.tar.gz", "sha256", "tool.sha256");
assert!(
result.is_none(),
"Should not return hash for wrong target file"
);
}
#[test]
fn test_checksum_result_format() {
let result = ChecksumResult {
algorithm: "sha256".to_string(),
hash: "abc123".to_string(),
source_file: "checksums.txt".to_string(),
};
assert_eq!(result.to_string_formatted(), "sha256:abc123");
}
#[test]
fn test_asset_creation() {
let asset = Asset::new("file.tar.gz", "https://example.com/file.tar.gz");
assert_eq!(asset.name, "file.tar.gz");
assert_eq!(asset.url, "https://example.com/file.tar.gz");
}
// ========== Platform Detection Tests ==========
#[test]
fn test_asset_picker_functionality() {
let picker = AssetPicker::with_libc("linux".to_string(), "x86_64".to_string(), None);
let assets = vec![
"tool-1.0.0-linux-x86_64.tar.gz".to_string(),
"tool-1.0.0-darwin-x86_64.tar.gz".to_string(),
"tool-1.0.0-windows-x86_64.zip".to_string(),
];
let picked = picker.pick_best_asset(&assets).unwrap();
assert_eq!(picked, "tool-1.0.0-linux-x86_64.tar.gz");
}
#[test]
fn test_asset_scoring() {
let picker = AssetPicker::with_libc("linux".to_string(), "x86_64".to_string(), None);
let score_linux = picker.score_asset("tool-1.0.0-linux-x86_64.tar.gz");
let score_windows = picker.score_asset("tool-1.0.0-windows-x86_64.zip");
let score_linux_arm = picker.score_asset("tool-1.0.0-linux-arm64.tar.gz");
assert!(
score_linux > score_windows,
"Linux should score higher than Windows"
);
assert!(
score_linux > score_linux_arm,
"x86_64 should score higher than arm64"
);
}
#[test]
fn test_archive_preference() {
let picker = AssetPicker::with_libc("linux".to_string(), "x86_64".to_string(), None);
let assets = vec![
"tool-1.0.0-linux-x86_64".to_string(),
"tool-1.0.0-linux-x86_64.tar.gz".to_string(),
];
let picked = picker.pick_best_asset(&assets).unwrap();
assert_eq!(picked, "tool-1.0.0-linux-x86_64.tar.gz");
}
#[test]
fn test_platform_detection_from_url() {
// Test Node.js URL
let url = "https://nodejs.org/dist/v22.17.1/node-v22.17.1-darwin-arm64.tar.gz";
let platform = detect_platform_from_url(url).unwrap();
assert_eq!(platform.os, AssetOs::Macos);
assert_eq!(platform.arch, AssetArch::Arm64);
assert_eq!(platform.to_platform_string(), "macos-arm64");
// Test Linux x64 URL
let url = "https://github.com/BurntSushi/ripgrep/releases/download/14.0.3/ripgrep-14.0.3-x86_64-unknown-linux-musl.tar.gz";
let platform = detect_platform_from_url(url).unwrap();
assert_eq!(platform.os, AssetOs::Linux);
assert_eq!(platform.arch, AssetArch::X64);
assert_eq!(platform.libc, Some(AssetLibc::Musl));
assert_eq!(platform.to_platform_string(), "linux-x64");
// Test Windows URL
let url =
"https://github.com/cli/cli/releases/download/v2.336.0/gh_2.336.0_windows_amd64.zip";
let platform = detect_platform_from_url(url).unwrap();
assert_eq!(platform.os, AssetOs::Windows);
assert_eq!(platform.arch, AssetArch::X64);
assert_eq!(platform.to_platform_string(), "windows-x64");
// Test URL without platform info
let url = "https://example.com/generic-tool.tar.gz";
let platform = detect_platform_from_url(url);
assert!(platform.is_none());
}
#[test]
fn test_platform_string_conversion() {
let platform = DetectedPlatform {
os: AssetOs::Linux,
arch: AssetArch::X64,
libc: Some(AssetLibc::Gnu),
};
assert_eq!(platform.to_platform_string(), "linux-x64");
let platform = DetectedPlatform {
os: AssetOs::Macos,
arch: AssetArch::Arm64,
libc: None,
};
assert_eq!(platform.to_platform_string(), "macos-arm64");
let platform = DetectedPlatform {
os: AssetOs::Windows,
arch: AssetArch::X86,
libc: None,
};
assert_eq!(platform.to_platform_string(), "windows-x86");
}
#[test]
fn test_windows_msvc_preference() {
let qsv_assets = vec![
"qsv-8.1.1-x86_64-pc-windows-gnu.zip".to_string(),
"qsv-8.1.1-x86_64-pc-windows-msvc.zip".to_string(),
];
let picker = AssetPicker::with_libc("windows".to_string(), "x86_64".to_string(), None);
let picked = picker.pick_best_asset(&qsv_assets).unwrap();
assert_eq!(picked, "qsv-8.1.1-x86_64-pc-windows-msvc.zip");
}
#[test]
fn test_for_target_with_libc_qualifier() {
use crate::backend::platform_target::PlatformTarget;
use crate::platform::Platform;
let assets = vec![
"tool-1.0.0-linux-x86_64-gnu.tar.gz".to_string(),
"tool-1.0.0-linux-x86_64-musl.tar.gz".to_string(),
];
// Test with musl qualifier
let platform = Platform::parse("linux-x64-musl").unwrap();
let target = PlatformTarget::new(platform);
let result = AssetMatcher::new()
.for_target(&target)
.pick_from(&assets)
.unwrap();
assert_eq!(result.name, "tool-1.0.0-linux-x86_64-musl.tar.gz");
// Test with gnu qualifier
let platform = Platform::parse("linux-x64-gnu").unwrap();
let target = PlatformTarget::new(platform);
let result = AssetMatcher::new()
.for_target(&target)
.pick_from(&assets)
.unwrap();
assert_eq!(result.name, "tool-1.0.0-linux-x86_64-gnu.tar.gz");
}
#[test]
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/github.rs | src/backend/github.rs | use crate::backend::SecurityFeature;
use crate::backend::VersionInfo;
use crate::backend::asset_matcher::{self, Asset, ChecksumFetcher};
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::{
get_filename_from_url, install_artifact, lookup_platform_key, lookup_platform_key_for_target,
template_string, try_with_v_prefix, verify_artifact,
};
use crate::cli::args::{BackendArg, ToolVersionType};
use crate::config::{Config, Settings};
use crate::env;
use crate::file;
use crate::http::HTTP;
use crate::install_context::InstallContext;
use crate::lockfile::PlatformInfo;
use crate::toolset::ToolVersionOptions;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::{backend::Backend, github, gitlab};
use async_trait::async_trait;
use eyre::Result;
use regex::Regex;
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::sync::Arc;
#[derive(Debug)]
pub struct UnifiedGitBackend {
ba: Arc<BackendArg>,
}
struct ReleaseAsset {
name: String,
url: String,
url_api: String,
digest: Option<String>,
}
const DEFAULT_GITHUB_API_BASE_URL: &str = "https://api.github.com";
const DEFAULT_GITLAB_API_BASE_URL: &str = "https://gitlab.com/api/v4";
/// Status returned from verification attempts
enum VerificationStatus {
/// No attestations or provenance found (not an error, tool may not have them)
NoAttestations,
/// An error occurred during verification
Error(String),
}
/// Returns install-time-only option keys for GitHub/GitLab backend.
pub fn install_time_option_keys() -> Vec<String> {
vec![
"asset_pattern".into(),
"url".into(),
"version_prefix".into(),
]
}
#[async_trait]
impl Backend for UnifiedGitBackend {
fn get_type(&self) -> BackendType {
if self.is_gitlab() {
BackendType::Gitlab
} else {
BackendType::Github
}
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn security_info(&self) -> Vec<SecurityFeature> {
// Only report security features for GitHub (not GitLab yet)
if self.is_gitlab() {
return vec![];
}
let mut features = vec![];
// Get the latest release to check for security assets
let repo = self.ba.tool_name();
let opts = self.ba.opts();
let api_url = self.get_api_url(&opts);
let releases = github::list_releases_from_url(api_url.as_str(), &repo)
.await
.unwrap_or_default();
let latest_release = releases.first();
// Check for checksum files in assets
if let Some(release) = latest_release {
let has_checksum = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains("sha256")
|| name.contains("checksum")
|| name.ends_with(".sha256")
|| name.ends_with(".sha512")
});
if has_checksum {
features.push(SecurityFeature::Checksum {
algorithm: Some("sha256".to_string()),
});
}
}
// Check for GitHub Attestations (assets with .sigstore.json or .sigstore extension)
if let Some(release) = latest_release {
let has_attestations = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.ends_with(".sigstore.json") || name.ends_with(".sigstore")
});
if has_attestations {
features.push(SecurityFeature::GithubAttestations {
signer_workflow: None,
});
}
}
// Check for SLSA provenance (intoto.jsonl files)
if let Some(release) = latest_release {
let has_slsa = release.assets.iter().any(|a| {
let name = a.name.to_lowercase();
name.contains(".intoto.jsonl")
|| name.contains("provenance")
|| name.ends_with(".attestation")
});
if has_slsa {
features.push(SecurityFeature::Slsa { level: None });
}
}
features
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> Result<Vec<VersionInfo>> {
let repo = self.ba.tool_name();
let id = self.ba.to_string();
let opts = self.ba.opts();
let api_url = self.get_api_url(&opts);
let version_prefix = opts.get("version_prefix");
// Derive web URL base from API URL for enterprise support
let web_url_base = if self.is_gitlab() {
if api_url == DEFAULT_GITLAB_API_BASE_URL {
format!("https://gitlab.com/{}", repo)
} else {
// Enterprise GitLab - derive web URL from API URL
let web_url = api_url.replace("/api/v4", "");
format!("{}/{}", web_url, repo)
}
} else if api_url == DEFAULT_GITHUB_API_BASE_URL {
format!("https://github.com/{}", repo)
} else {
// Enterprise GitHub - derive web URL from API URL
let web_url = api_url.replace("/api/v3", "").replace("api.", "");
format!("{}/{}", web_url, repo)
};
// Get releases with full metadata from GitHub or GitLab
let raw_versions: Vec<VersionInfo> = if self.is_gitlab() {
gitlab::list_releases_from_url(api_url.as_str(), &repo)
.await?
.into_iter()
.filter(|r| version_prefix.is_none_or(|p| r.tag_name.starts_with(p)))
.map(|r| VersionInfo {
version: self.strip_version_prefix(&r.tag_name),
created_at: r.released_at,
release_url: Some(format!("{}/-/releases/{}", web_url_base, r.tag_name)),
})
.collect()
} else {
github::list_releases_from_url(api_url.as_str(), &repo)
.await?
.into_iter()
.filter(|r| version_prefix.is_none_or(|p| r.tag_name.starts_with(p)))
.map(|r| VersionInfo {
version: self.strip_version_prefix(&r.tag_name),
created_at: Some(r.created_at),
release_url: Some(format!("{}/releases/tag/{}", web_url_base, r.tag_name)),
})
.collect()
};
// Apply common validation and reverse order
let versions = raw_versions
.into_iter()
.filter(|v| match v.version.parse::<ToolVersionType>() {
Ok(ToolVersionType::Version(_)) => true,
_ => {
warn!("Invalid version: {id}@{}", v.version);
false
}
})
.rev()
.collect();
Ok(versions)
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> Result<ToolVersion> {
let repo = self.repo();
let opts = tv.request.options();
let api_url = self.get_api_url(&opts);
// Check if URL already exists in lockfile platforms first
let platform_key = self.get_platform_key();
let asset = if let Some(existing_platform) = tv.lock_platforms.get(&platform_key)
&& existing_platform.url.is_some()
{
debug!(
"Using existing URL from lockfile for platform {}: {}",
platform_key,
existing_platform.url.clone().unwrap_or_default()
);
ReleaseAsset {
name: get_filename_from_url(existing_platform.url.as_deref().unwrap_or("")),
url: existing_platform.url.clone().unwrap_or_default(),
url_api: existing_platform.url_api.clone().unwrap_or_default(),
digest: None, // Don't use old digest from lockfile, will be fetched fresh if needed
}
} else {
// Find the asset URL for this specific version
self.resolve_asset_url(&tv, &opts, &repo, &api_url).await?
};
// Download and install
self.download_and_install(ctx, &mut tv, &asset, &opts)
.await?;
Ok(tv)
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> Result<Vec<std::path::PathBuf>> {
if self.get_filter_bins(tv).is_some() {
return Ok(vec![tv.install_path().join(".mise-bins")]);
}
self.discover_bin_paths(tv)
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// These options affect which artifact is downloaded
for key in ["asset_pattern", "url", "version_prefix"] {
if let Some(value) = opts.get(key) {
result.insert(key.to_string(), value.clone());
}
}
result
}
/// Resolve platform-specific lock information for cross-platform lockfile generation.
/// This fetches release asset metadata including SHA256 digests from GitHub/GitLab API.
async fn resolve_lock_info(
&self,
tv: &ToolVersion,
target: &PlatformTarget,
) -> Result<PlatformInfo> {
let repo = self.repo();
let opts = tv.request.options();
let api_url = self.get_api_url(&opts);
// Resolve asset for the target platform
let asset = self
.resolve_asset_url_for_target(tv, &opts, &repo, &api_url, target)
.await;
match asset {
Ok(asset) => Ok(PlatformInfo {
url: Some(asset.url),
url_api: Some(asset.url_api),
checksum: asset.digest,
size: None,
}),
Err(e) => {
debug!(
"Failed to resolve asset for {} on {}: {}",
self.ba.full(),
target.to_key(),
e
);
Ok(PlatformInfo::default())
}
}
}
}
impl UnifiedGitBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
fn is_gitlab(&self) -> bool {
self.ba.backend_type() == BackendType::Gitlab
}
fn repo(&self) -> String {
// Use tool_name() method to properly resolve aliases
// This ensures that when an alias like "test-edit = github:microsoft/edit" is used,
// the repository name is correctly extracted as "microsoft/edit"
self.ba.tool_name()
}
// Helper to format asset names for error messages
fn format_asset_list<'a, I>(assets: I) -> String
where
I: Iterator<Item = &'a String>,
{
assets.cloned().collect::<Vec<_>>().join(", ")
}
fn get_api_url(&self, opts: &ToolVersionOptions) -> String {
opts.get("api_url")
.map(|s| s.as_str())
.unwrap_or(if self.is_gitlab() {
DEFAULT_GITLAB_API_BASE_URL
} else {
DEFAULT_GITHUB_API_BASE_URL
})
.to_string()
}
/// Downloads and installs the asset
async fn download_and_install(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
asset: &ReleaseAsset,
opts: &ToolVersionOptions,
) -> Result<()> {
let filename = asset.name.clone();
let file_path = tv.download_path().join(&filename);
// Count operations dynamically:
// 1. Download (always)
// 2. Verify checksum (if checksum option present)
// 3. Extract/install (if file needs extraction)
let mut op_count = 1; // download
// Check if we'll verify checksum
let has_checksum = lookup_platform_key(opts, "checksum")
.or_else(|| opts.get("checksum").cloned())
.is_some();
if has_checksum {
op_count += 1;
}
// Check if we'll extract (archives need extraction)
let needs_extraction = filename.ends_with(".tar.gz")
|| filename.ends_with(".tar.xz")
|| filename.ends_with(".tar.bz2")
|| filename.ends_with(".tar.zst")
|| filename.ends_with(".tgz")
|| filename.ends_with(".txz")
|| filename.ends_with(".tbz2")
|| filename.ends_with(".zip");
if needs_extraction {
op_count += 1;
}
ctx.pr.start_operations(op_count);
// Store the asset URL and digest (if available) in the tool version
let platform_key = self.get_platform_key();
let platform_info = tv.lock_platforms.entry(platform_key).or_default();
platform_info.url = Some(asset.url.clone());
platform_info.url_api = Some(asset.url_api.clone());
if let Some(digest) = &asset.digest {
debug!("using GitHub API digest for checksum verification");
platform_info.checksum = Some(digest.clone());
}
let url = match asset.url_api.starts_with(DEFAULT_GITHUB_API_BASE_URL)
|| asset.url_api.starts_with(DEFAULT_GITLAB_API_BASE_URL)
{
// check if url is reachable, 404 might indicate a private repo or asset.
// This is needed, because private repos and assets cannot be downloaded
// via browser url, therefore a fallback to api_url is needed in such cases.
true => match HTTP.head(asset.url.clone()).await {
Ok(_) => asset.url.clone(),
Err(_) => asset.url_api.clone(),
},
// Custom API URLs usually imply that a custom GitHub/GitLab instance is used.
// Often times such instances do not allow browser URL downloads, e.g. due to
// upstream company SSOs. Therefore, using the api_url for downloading is the safer approach.
false => {
debug!(
"Since the tool resides on a custom GitHub/GitLab API ({:?}), the asset download will be performed using the given API instead of browser URL download",
asset.url_api
);
asset.url_api.clone()
}
};
let headers = if self.is_gitlab() {
gitlab::get_headers(&url)
} else {
github::get_headers(&url)
};
ctx.pr.set_message(format!("download {filename}"));
HTTP.download_file_with_headers(url, &file_path, &headers, Some(ctx.pr.as_ref()))
.await?;
// Verify and install
verify_artifact(tv, &file_path, opts, Some(ctx.pr.as_ref()))?;
self.verify_checksum(ctx, tv, &file_path)?;
// Verify attestations or SLSA (check attestations first, fall back to SLSA)
self.verify_attestations_or_slsa(ctx, tv, &file_path)
.await?;
install_artifact(tv, &file_path, opts, Some(ctx.pr.as_ref()))?;
if let Some(bins) = self.get_filter_bins(tv) {
self.create_symlink_bin_dir(tv, bins)?;
}
Ok(())
}
/// Discovers bin paths in the installation directory
fn discover_bin_paths(&self, tv: &ToolVersion) -> Result<Vec<std::path::PathBuf>> {
let opts = tv.request.options();
if let Some(bin_path_template) =
lookup_platform_key(&opts, "bin_path").or_else(|| opts.get("bin_path").cloned())
{
let bin_path = template_string(&bin_path_template, tv);
return Ok(vec![tv.install_path().join(&bin_path)]);
}
let bin_path = tv.install_path().join("bin");
if bin_path.exists() {
return Ok(vec![bin_path]);
}
// Check if the root directory contains an executable file
// If so, use the root directory as a bin path
if let Ok(entries) = std::fs::read_dir(tv.install_path()) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && file::is_executable(&path) {
return Ok(vec![tv.install_path()]);
}
}
}
// Look for bin directory or executables in subdirectories (for extracted archives)
let mut paths = Vec::new();
if let Ok(entries) = std::fs::read_dir(tv.install_path()) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
// Check for {subdir}/bin
let sub_bin_path = path.join("bin");
if sub_bin_path.exists() {
paths.push(sub_bin_path);
} else {
// Check for executables directly in subdir (e.g., tusd_darwin_arm64/tusd)
if let Ok(sub_entries) = std::fs::read_dir(&path) {
for sub_entry in sub_entries.flatten() {
let sub_path = sub_entry.path();
if sub_path.is_file() && file::is_executable(&sub_path) {
paths.push(path.clone());
break;
}
}
}
}
}
}
}
if paths.is_empty() {
Ok(vec![tv.install_path()])
} else {
Ok(paths)
}
}
/// Resolves the asset URL using either explicit patterns or auto-detection.
/// Delegates to resolve_asset_url_for_target with the current platform.
async fn resolve_asset_url(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
) -> Result<ReleaseAsset> {
let current_platform = PlatformTarget::from_current();
self.resolve_asset_url_for_target(tv, opts, repo, api_url, ¤t_platform)
.await
}
/// Resolves asset URL for a specific target platform (for cross-platform lockfile generation)
async fn resolve_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
// Check for direct platform-specific URLs first
if let Some(direct_url) = lookup_platform_key_for_target(opts, "url", target) {
return Ok(ReleaseAsset {
name: get_filename_from_url(&direct_url),
url: direct_url.clone(),
url_api: direct_url.clone(),
digest: None, // Direct URLs don't have API digest
});
}
let version = &tv.version;
let version_prefix = opts.get("version_prefix").map(|s| s.as_str());
if self.is_gitlab() {
try_with_v_prefix(version, version_prefix, |candidate| async move {
self.resolve_gitlab_asset_url_for_target(
tv, opts, repo, api_url, &candidate, target,
)
.await
})
.await
} else {
try_with_v_prefix(version, version_prefix, |candidate| async move {
self.resolve_github_asset_url_for_target(
tv, opts, repo, api_url, &candidate, target,
)
.await
})
.await
}
}
/// Resolves GitHub asset URL for a specific target platform
async fn resolve_github_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
version: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
let release = github::get_release_for_url(api_url, repo, version).await?;
let available_assets: Vec<String> = release.assets.iter().map(|a| a.name.clone()).collect();
// Build asset list with URLs for checksum fetching
let assets_with_urls: Vec<Asset> = release
.assets
.iter()
.map(|a| Asset::new(&a.name, &a.browser_download_url))
.collect();
// Try explicit pattern first
if let Some(pattern) = lookup_platform_key_for_target(opts, "asset_pattern", target)
.or_else(|| opts.get("asset_pattern").cloned())
{
// Template the pattern for the target platform
let templated_pattern = template_string_for_target(&pattern, tv, target);
let asset = release
.assets
.into_iter()
.find(|a| self.matches_pattern(&a.name, &templated_pattern))
.ok_or_else(|| {
eyre::eyre!(
"No matching asset found for pattern: {}\nAvailable assets: {}",
templated_pattern,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = if asset.digest.is_some() {
asset.digest
} else {
self.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await
};
return Ok(ReleaseAsset {
name: asset.name,
url: asset.browser_download_url,
url_api: asset.url,
digest,
});
}
// Fall back to auto-detection for target platform
let asset_name = asset_matcher::detect_asset_for_target(&available_assets, target)?;
let asset = self
.find_asset_case_insensitive(&release.assets, &asset_name, |a| &a.name)
.ok_or_else(|| {
eyre::eyre!(
"Auto-detected asset not found: {}\nAvailable assets: {}",
asset_name,
Self::format_asset_list(available_assets.iter())
)
})?;
// Try to get checksum from API digest or fetch from release assets
let digest = if asset.digest.is_some() {
asset.digest.clone()
} else {
self.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await
};
Ok(ReleaseAsset {
name: asset.name.clone(),
url: asset.browser_download_url.clone(),
url_api: asset.url.clone(),
digest,
})
}
/// Resolves GitLab asset URL for a specific target platform
async fn resolve_gitlab_asset_url_for_target(
&self,
tv: &ToolVersion,
opts: &ToolVersionOptions,
repo: &str,
api_url: &str,
version: &str,
target: &PlatformTarget,
) -> Result<ReleaseAsset> {
let release = gitlab::get_release_for_url(api_url, repo, version).await?;
let available_assets: Vec<String> = release
.assets
.links
.iter()
.map(|a| a.name.clone())
.collect();
// Build asset list with URLs for checksum fetching
let assets_with_urls: Vec<Asset> = release
.assets
.links
.iter()
.map(|a| Asset::new(&a.name, &a.direct_asset_url))
.collect();
// Try explicit pattern first
if let Some(pattern) = lookup_platform_key_for_target(opts, "asset_pattern", target)
.or_else(|| opts.get("asset_pattern").cloned())
{
// Template the pattern for the target platform
let templated_pattern = template_string_for_target(&pattern, tv, target);
let asset = release
.assets
.links
.into_iter()
.find(|a| self.matches_pattern(&a.name, &templated_pattern))
.ok_or_else(|| {
eyre::eyre!(
"No matching asset found for pattern: {}\nAvailable assets: {}",
templated_pattern,
Self::format_asset_list(available_assets.iter())
)
})?;
// GitLab doesn't provide digests, so try fetching from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
return Ok(ReleaseAsset {
name: asset.name,
url: asset.direct_asset_url.clone(),
url_api: asset.url,
digest,
});
}
// Fall back to auto-detection for target platform
let asset_name = asset_matcher::detect_asset_for_target(&available_assets, target)?;
let asset = self
.find_asset_case_insensitive(&release.assets.links, &asset_name, |a| &a.name)
.ok_or_else(|| {
eyre::eyre!(
"Auto-detected asset not found: {}\nAvailable assets: {}",
asset_name,
Self::format_asset_list(available_assets.iter())
)
})?;
// GitLab doesn't provide digests, so try fetching from release assets
let digest = self
.try_fetch_checksum_from_assets(&assets_with_urls, &asset.name)
.await;
Ok(ReleaseAsset {
name: asset.name.clone(),
url: asset.direct_asset_url.clone(),
url_api: asset.url.clone(),
digest,
})
}
fn find_asset_case_insensitive<'a, T>(
&self,
assets: &'a [T],
target_name: &str,
get_name: impl Fn(&T) -> &str,
) -> Option<&'a T> {
// First try exact match, then case-insensitive
assets
.iter()
.find(|a| get_name(a) == target_name)
.or_else(|| {
let target_lower = target_name.to_lowercase();
assets
.iter()
.find(|a| get_name(a).to_lowercase() == target_lower)
})
}
fn matches_pattern(&self, asset_name: &str, pattern: &str) -> bool {
// Simple pattern matching - convert glob-like pattern to regex
let regex_pattern = pattern
.replace(".", "\\.")
.replace("*", ".*")
.replace("?", ".");
if let Ok(re) = Regex::new(&format!("^{regex_pattern}$")) {
re.is_match(asset_name)
} else {
// Fallback to simple contains check
asset_name.contains(pattern)
}
}
fn strip_version_prefix(&self, tag_name: &str) -> String {
let opts = self.ba.opts();
// If a custom version_prefix is configured, strip it first
if let Some(prefix) = opts.get("version_prefix")
&& let Some(stripped) = tag_name.strip_prefix(prefix)
{
return stripped.to_string();
}
// Fall back to stripping 'v' prefix
if tag_name.starts_with('v') {
tag_name.trim_start_matches('v').to_string()
} else {
tag_name.to_string()
}
}
/// Tries to fetch a checksum for an asset from release checksum files.
///
/// This method looks for checksum files (SHA256SUMS, *.sha256, etc.) in the release
/// assets and attempts to extract the checksum for the target asset.
///
/// Returns the checksum in "sha256:hash" format if found, None otherwise.
async fn try_fetch_checksum_from_assets(
&self,
assets: &[Asset],
asset_name: &str,
) -> Option<String> {
let fetcher = ChecksumFetcher::new(assets);
match fetcher.fetch_checksum_for(asset_name).await {
Some(result) => {
debug!(
"Found checksum for {} from {}: {}",
asset_name,
result.source_file,
result.to_string_formatted()
);
Some(result.to_string_formatted())
}
None => {
trace!("No checksum file found for {}", asset_name);
None
}
}
}
fn get_filter_bins(&self, tv: &ToolVersion) -> Option<Vec<String>> {
let opts = tv.request.options();
let filter_bins = lookup_platform_key(&opts, "filter_bins")
.or_else(|| opts.get("filter_bins").cloned())?;
Some(
filter_bins
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
)
}
/// Creates a `.mise-bins` directory with symlinks only to the binaries specified in filter_bins.
fn create_symlink_bin_dir(&self, tv: &ToolVersion, bins: Vec<String>) -> Result<()> {
let symlink_dir = tv.install_path().join(".mise-bins");
file::create_dir_all(&symlink_dir)?;
// Find where the actual binaries are
let install_path = tv.install_path();
let bin_paths = self.discover_bin_paths(tv)?;
// Collect all possible source directories (install root + discovered bin paths)
let mut src_dirs = bin_paths;
if !src_dirs.contains(&install_path) {
src_dirs.push(install_path);
}
for bin_name in bins {
// Find the binary in any of the source directories
let mut found = false;
for dir in &src_dirs {
let src = dir.join(&bin_name);
if src.exists() {
let dst = symlink_dir.join(&bin_name);
if !dst.exists() {
file::make_symlink_or_copy(&src, &dst)?;
}
found = true;
break;
}
}
if !found {
warn!(
"Could not find binary '{}' in install directories. Available paths: {:?}",
bin_name, src_dirs
);
}
}
Ok(())
}
/// Verify artifact using GitHub attestations or SLSA provenance.
/// Tries attestations first, falls back to SLSA if no attestations found.
/// If verification is attempted and fails, it's a hard error.
async fn verify_attestations_or_slsa(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
file_path: &std::path::Path,
) -> Result<()> {
let settings = Settings::get();
// Only verify for GitHub repos (not GitLab)
if self.is_gitlab() {
return Ok(());
}
// Try GitHub attestations first (if enabled globally and for github backend)
if settings.github_attestations && settings.github.github_attestations {
match self
.try_verify_github_attestations(ctx, tv, file_path)
.await
{
Ok(true) => return Ok(()), // Verified successfully
Ok(false) => {
// Attestations exist but verification failed - hard error
return Err(eyre::eyre!(
"GitHub attestations verification failed for {tv}"
));
}
Err(VerificationStatus::NoAttestations) => {
// No attestations - fall through to try SLSA
debug!("No GitHub attestations found for {tv}, trying SLSA");
}
Err(VerificationStatus::Error(e)) => {
// Error during verification - hard error
return Err(eyre::eyre!(
"GitHub attestations verification error for {tv}: {e}"
));
}
}
}
// Fall back to SLSA provenance (if enabled globally and for github backend)
if settings.slsa && settings.github.slsa {
match self.try_verify_slsa(ctx, tv, file_path).await {
Ok(true) => return Ok(()), // Verified successfully
Ok(false) => {
// Provenance exists but verification failed - hard error
return Err(eyre::eyre!("SLSA provenance verification failed for {tv}"));
}
Err(VerificationStatus::NoAttestations) => {
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/cargo.rs | src/backend/cargo.rs | use std::collections::BTreeMap;
use std::{fmt::Debug, sync::Arc};
use async_trait::async_trait;
use color_eyre::Section;
use eyre::{bail, eyre};
use url::Url;
use crate::Result;
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::lookup_platform_key;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::env::GITHUB_TOKEN;
use crate::http::HTTP_FETCH;
use crate::install_context::InstallContext;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::{env, file};
#[derive(Debug)]
pub struct CargoBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for CargoBackend {
fn get_type(&self) -> BackendType {
BackendType::Cargo
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["rust"])
}
fn get_optional_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["cargo-binstall", "sccache"])
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
if self.git_url().is_some() {
// TODO: maybe fetch tags/branches from git?
return Ok(vec![VersionInfo {
version: "HEAD".into(),
..Default::default()
}]);
}
// Use crates.io API which includes created_at timestamps
let url = format!(
"https://crates.io/api/v1/crates/{}/versions",
self.tool_name()
);
let response: CratesIoVersionsResponse = HTTP_FETCH.json(&url).await?;
let versions = response
.versions
.into_iter()
.filter(|v| !v.yanked)
.map(|v| VersionInfo {
version: v.num,
created_at: Some(v.created_at),
..Default::default()
})
.rev() // API returns newest first, we want oldest first
.collect();
Ok(versions)
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
// Check if cargo is available
self.warn_if_dependency_missing(
&ctx.config,
"cargo",
"To use cargo packages with mise, you need to install Rust first:\n\
mise use rust@latest\n\n\
Or install Rust via https://rustup.rs/",
)
.await;
let config = ctx.config.clone();
let install_arg = format!("{}@{}", self.tool_name(), tv.version);
let registry_name = &Settings::get().cargo.registry_name;
let cmd = CmdLineRunner::new("cargo").arg("install");
let mut cmd = if let Some(url) = self.git_url() {
let mut cmd = cmd.arg(format!("--git={url}"));
if let Some(rev) = tv.version.strip_prefix("rev:") {
cmd = cmd.arg(format!("--rev={rev}"));
} else if let Some(branch) = tv.version.strip_prefix("branch:") {
cmd = cmd.arg(format!("--branch={branch}"));
} else if let Some(tag) = tv.version.strip_prefix("tag:") {
cmd = cmd.arg(format!("--tag={tag}"));
} else if tv.version != "HEAD" {
Err(eyre!("Invalid cargo git version: {}", tv.version).note(
r#"You can specify "rev:", "branch:", or "tag:", e.g.:
* mise use cargo:eza-community/eza@tag:v0.18.0
* mise use cargo:eza-community/eza@branch:main"#,
))?;
}
cmd
} else if self.is_binstall_enabled(&config, &tv).await {
let mut cmd = CmdLineRunner::new("cargo-binstall").arg("-y");
if let Some(token) = &*GITHUB_TOKEN {
cmd = cmd.env("GITHUB_TOKEN", token)
}
cmd.arg(install_arg)
} else if env::var("MISE_CARGO_BINSTALL_ONLY").is_ok_and(|v| v == "1") {
bail!("cargo-binstall is not available, but MISE_CARGO_BINSTALL_ONLY is set");
} else {
cmd.arg(install_arg)
};
let opts = tv.request.options();
if let Some(bin) = lookup_platform_key(&opts, "bin").or_else(|| opts.get("bin").cloned()) {
cmd = cmd.arg(format!("--bin={bin}"));
}
if opts
.get("locked")
.is_none_or(|v| v.to_lowercase() != "false")
{
cmd = cmd.arg("--locked");
}
if let Some(features) = opts.get("features") {
cmd = cmd.arg(format!("--features={features}"));
}
if let Some(default_features) = opts.get("default-features")
&& default_features.to_lowercase() == "false"
{
cmd = cmd.arg("--no-default-features");
}
if let Some(c) = opts.get("crate") {
cmd = cmd.arg(c);
}
if let Some(registry_name) = registry_name {
cmd = cmd.arg(format!("--registry={registry_name}"));
}
cmd.arg("--root")
.arg(tv.install_path())
.with_pr(ctx.pr.as_ref())
.envs(ctx.ts.env_with_path(&ctx.config).await?)
.prepend_path(ctx.ts.list_paths(&ctx.config).await)?
.prepend_path(
self.dependency_toolset(&ctx.config)
.await?
.list_paths(&ctx.config)
.await,
)?
.execute()?;
Ok(tv.clone())
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// These options affect what gets compiled/installed
for key in ["features", "default-features", "bin"] {
if let Some(value) = opts.get(key) {
result.insert(key.to_string(), value.clone());
}
}
result
}
}
/// Returns install-time-only option keys for Cargo backend.
pub fn install_time_option_keys() -> Vec<String> {
vec!["features".into(), "default-features".into(), "bin".into()]
}
impl CargoBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
async fn is_binstall_enabled(&self, config: &Arc<Config>, tv: &ToolVersion) -> bool {
if !Settings::get().cargo.binstall {
return false;
}
if file::which_non_pristine("cargo-binstall").is_none() {
match self.dependency_toolset(config).await {
Ok(ts) => {
if ts.which(config, "cargo-binstall").await.is_none() {
return false;
}
}
Err(_e) => {
return false;
}
}
}
let opts = tv.request.options();
if opts.contains_key("features") || opts.contains_key("default-features") {
info!("not using cargo-binstall because features are specified");
return false;
}
true
}
/// if the name is a git repo, return the git url
fn git_url(&self) -> Option<Url> {
if let Ok(url) = Url::parse(&self.tool_name()) {
Some(url)
} else if let Some((user, repo)) = self.tool_name().split_once('/') {
format!("https://github.com/{user}/{repo}.git").parse().ok()
} else {
None
}
}
}
#[derive(Debug, serde::Deserialize)]
struct CratesIoVersionsResponse {
versions: Vec<CratesIoVersion>,
}
#[derive(Debug, serde::Deserialize)]
struct CratesIoVersion {
num: String,
yanked: bool,
created_at: String,
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/npm.rs | src/backend/npm.rs | use crate::Result;
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::install_context::InstallContext;
use crate::timeout;
use crate::toolset::ToolVersion;
use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashMap;
use std::{fmt::Debug, sync::Arc};
use tokio::sync::Mutex as TokioMutex;
#[derive(Debug)]
pub struct NPMBackend {
ba: Arc<BackendArg>,
// use a mutex to prevent deadlocks that occurs due to reentrant cache access
latest_version_cache: TokioMutex<CacheManager<Option<String>>>,
}
const NPM_PROGRAM: &str = if cfg!(windows) { "npm.cmd" } else { "npm" };
#[async_trait]
impl Backend for NPMBackend {
fn get_type(&self) -> BackendType {
BackendType::Npm
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["node", "bun", "pnpm"])
}
async fn _list_remote_versions(&self, config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
// Use npm CLI to respect custom registry configurations
self.ensure_npm_for_version_check(config).await;
timeout::run_with_timeout_async(
async || {
let env = self.dependency_env(config).await?;
// Fetch versions and timestamps in parallel
let versions_raw =
cmd!(NPM_PROGRAM, "view", self.tool_name(), "versions", "--json")
.full_env(&env)
.read()?;
let time_raw = cmd!(NPM_PROGRAM, "view", self.tool_name(), "time", "--json")
.full_env(&env)
.read()?;
let versions: Vec<String> = serde_json::from_str(&versions_raw)?;
let time: HashMap<String, String> = serde_json::from_str(&time_raw)?;
let version_info = versions
.into_iter()
.map(|version| {
let created_at = time.get(&version).cloned();
VersionInfo {
version,
created_at,
..Default::default()
}
})
.collect();
Ok(version_info)
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
}
async fn latest_stable_version(&self, config: &Arc<Config>) -> eyre::Result<Option<String>> {
// TODO: Add bun support for getting latest version without npm
// See TODO in _list_remote_versions for details
self.ensure_npm_for_version_check(config).await;
let cache = self.latest_version_cache.lock().await;
let this = self;
timeout::run_with_timeout_async(
async || {
cache
.get_or_try_init_async(async || {
// Always use npm for getting version info since bun info requires package.json
// bun is only used for actual package installation
let raw =
cmd!(NPM_PROGRAM, "view", this.tool_name(), "dist-tags", "--json")
.full_env(this.dependency_env(config).await?)
.read()?;
let dist_tags: Value = serde_json::from_str(&raw)?;
match dist_tags["latest"] {
Value::String(ref s) => Ok(Some(s.clone())),
_ => this.latest_version(config, Some("latest".into())).await,
}
})
.await
},
Settings::get().fetch_remote_versions_timeout(),
)
.await
.cloned()
}
async fn install_version_(&self, ctx: &InstallContext, tv: ToolVersion) -> Result<ToolVersion> {
self.check_install_deps(&ctx.config).await;
match Settings::get().npm.package_manager.as_str() {
"bun" => {
CmdLineRunner::new("bun")
.arg("install")
.arg(format!("{}@{}", self.tool_name(), tv.version))
.arg("--global")
.arg("--trust")
.with_pr(ctx.pr.as_ref())
.envs(ctx.ts.env_with_path(&ctx.config).await?)
.env("BUN_INSTALL_GLOBAL_DIR", tv.install_path())
.env("BUN_INSTALL_BIN", tv.install_path().join("bin"))
.prepend_path(ctx.ts.list_paths(&ctx.config).await)?
.prepend_path(
self.dependency_toolset(&ctx.config)
.await?
.list_paths(&ctx.config)
.await,
)?
.current_dir(tv.install_path())
.execute()?;
}
"pnpm" => {
let bin_dir = tv.install_path().join("bin");
crate::file::create_dir_all(&bin_dir)?;
CmdLineRunner::new("pnpm")
.arg("add")
.arg("--global")
.arg(format!("{}@{}", self.tool_name(), tv.version))
.arg("--global-dir")
.arg(tv.install_path())
.arg("--global-bin-dir")
.arg(&bin_dir)
.with_pr(ctx.pr.as_ref())
.envs(ctx.ts.env_with_path(&ctx.config).await?)
.prepend_path(ctx.ts.list_paths(&ctx.config).await)?
.prepend_path(
self.dependency_toolset(&ctx.config)
.await?
.list_paths(&ctx.config)
.await,
)?
// required to avoid pnpm error "global bin dir isn't in PATH"
// https://github.com/pnpm/pnpm/issues/9333
.prepend_path(vec![bin_dir])?
.execute()?;
}
_ => {
CmdLineRunner::new(NPM_PROGRAM)
.arg("install")
.arg("-g")
.arg(format!("{}@{}", self.tool_name(), tv.version))
.arg("--prefix")
.arg(tv.install_path())
.with_pr(ctx.pr.as_ref())
.envs(ctx.ts.env_with_path(&ctx.config).await?)
.prepend_path(ctx.ts.list_paths(&ctx.config).await)?
.prepend_path(
self.dependency_toolset(&ctx.config)
.await?
.list_paths(&ctx.config)
.await,
)?
.execute()?;
}
}
Ok(tv)
}
#[cfg(windows)]
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &crate::toolset::ToolVersion,
) -> eyre::Result<Vec<std::path::PathBuf>> {
if Settings::get().npm.package_manager == "npm" {
Ok(vec![tv.install_path()])
} else {
Ok(vec![tv.install_path().join("bin")])
}
}
}
impl NPMBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self {
latest_version_cache: TokioMutex::new(
CacheManagerBuilder::new(ba.cache_path.join("latest_version.msgpack.z"))
.with_fresh_duration(Settings::get().fetch_remote_versions_cache())
.build(),
),
ba: Arc::new(ba),
}
}
/// Check dependencies for version checking (always needs npm)
async fn ensure_npm_for_version_check(&self, config: &Arc<Config>) {
// We always need npm for querying package versions
// TODO: Once bun supports querying packages without package.json, this can be updated
self.warn_if_dependency_missing(
config,
"npm", // Use "npm" for dependency check, which will check npm.cmd on Windows
"To use npm packages with mise, you need to install Node.js first:\n\
mise use node@latest\n\n\
Note: npm is required for querying package information, even when using bun for installation.",
)
.await
}
/// Check dependencies for package installation (npm or bun based on settings)
async fn check_install_deps(&self, config: &Arc<Config>) {
match Settings::get().npm.package_manager.as_str() {
"bun" => {
self.warn_if_dependency_missing(
config,
"bun",
"To use npm packages with bun, you need to install bun first:\n\
mise use bun@latest\n\n\
Or switch back to npm by setting:\n\
mise settings npm.package_manager=npm",
)
.await
}
"pnpm" => {
self.warn_if_dependency_missing(
config,
"pnpm",
"To use npm packages with pnpm, you need to install pnpm first:\n\
mise use pnpm@latest\n\n\
Or switch back to npm by setting:\n\
mise settings npm.package_manager=npm",
)
.await
}
_ => {
self.warn_if_dependency_missing(
config,
"npm",
"To use npm packages with mise, you need to install Node.js first:\n\
mise use node@latest\n\n\
Alternatively, you can use bun or pnpm instead of npm by setting:\n\
mise settings npm.package_manager=bun",
)
.await
}
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/backend_type.rs | src/backend/backend_type.rs | use std::fmt::{Display, Formatter};
#[derive(
Debug,
PartialEq,
Eq,
Hash,
Clone,
strum::EnumString,
strum::EnumIter,
strum::AsRefStr,
Ord,
PartialOrd,
)]
#[strum(serialize_all = "snake_case")]
pub enum BackendType {
Aqua,
Asdf,
Cargo,
Conda,
Core,
Dotnet,
Gem,
Github,
Gitlab,
Go,
Npm,
Pipx,
Spm,
Http,
Ubi,
Vfox,
VfoxBackend(String),
Unknown,
}
impl Display for BackendType {
fn fmt(&self, formatter: &mut Formatter) -> std::fmt::Result {
match self {
BackendType::VfoxBackend(plugin_name) => write!(formatter, "{plugin_name}"),
_ => write!(formatter, "{}", format!("{self:?}").to_lowercase()),
}
}
}
impl BackendType {
pub fn guess(s: &str) -> BackendType {
let prefix = s.split(':').next().unwrap_or(s);
match prefix {
"aqua" => BackendType::Aqua,
"asdf" => BackendType::Asdf,
"cargo" => BackendType::Cargo,
"conda" => BackendType::Conda,
"core" => BackendType::Core,
"dotnet" => BackendType::Dotnet,
"gem" => BackendType::Gem,
"github" => BackendType::Github,
"gitlab" => BackendType::Gitlab,
"go" => BackendType::Go,
"npm" => BackendType::Npm,
"pipx" => BackendType::Pipx,
"spm" => BackendType::Spm,
"http" => BackendType::Http,
"ubi" => BackendType::Ubi,
"vfox" => BackendType::Vfox,
_ => BackendType::Unknown,
}
}
/// Returns true if this backend requires experimental mode to be enabled
pub fn is_experimental(&self) -> bool {
use super::{conda, dotnet, spm};
match self {
BackendType::Conda => conda::EXPERIMENTAL,
BackendType::Spm => spm::EXPERIMENTAL,
BackendType::Dotnet => dotnet::EXPERIMENTAL,
_ => false,
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/spm.rs | src/backend/spm.rs | use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::git::{CloneOptions, Git};
use crate::install_context::InstallContext;
use crate::toolset::ToolVersion;
use crate::{dirs, file, github, gitlab};
use async_trait::async_trait;
use eyre::WrapErr;
use serde::Deserializer;
use serde::de::{MapAccess, Visitor};
use serde_derive::Deserialize;
use std::path::PathBuf;
use std::{
fmt::{self, Debug},
sync::Arc,
};
use strum::{AsRefStr, EnumString, VariantNames};
use url::Url;
use xx::regex;
/// SPM backend requires experimental mode to be enabled
pub const EXPERIMENTAL: bool = true;
#[derive(Debug)]
pub struct SPMBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for SPMBackend {
fn get_type(&self) -> BackendType {
BackendType::Spm
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["swift"])
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
let provider = GitProvider::from_ba(&self.ba);
let repo = SwiftPackageRepo::new(&self.tool_name(), &provider)?;
let versions = match provider.kind {
GitProviderKind::GitLab => {
gitlab::list_releases_from_url(&provider.api_url, repo.shorthand.as_str())
.await?
.into_iter()
.map(|r| VersionInfo {
version: r.tag_name,
created_at: r.released_at,
..Default::default()
})
.rev()
.collect()
}
_ => github::list_releases_from_url(&provider.api_url, repo.shorthand.as_str())
.await?
.into_iter()
.map(|r| VersionInfo {
version: r.tag_name,
created_at: Some(r.created_at),
..Default::default()
})
.rev()
.collect(),
};
Ok(versions)
}
async fn install_version_(
&self,
ctx: &InstallContext,
tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
let settings = Settings::get();
settings.ensure_experimental("spm backend")?;
// Check if swift is available
self.warn_if_dependency_missing(
&ctx.config,
"swift",
"To use Swift Package Manager (spm) tools with mise, you need to install Swift first:\n\
mise use swift@latest\n\n\
Or install Swift via https://swift.org/download/",
)
.await;
let provider = GitProvider::from_ba(&self.ba);
let repo = SwiftPackageRepo::new(&self.tool_name(), &provider)?;
let revision = if tv.version == "latest" {
self.latest_stable_version(&ctx.config)
.await?
.ok_or_else(|| eyre::eyre!("No stable versions found"))?
} else {
tv.version.clone()
};
let repo_dir = self.clone_package_repo(ctx, &tv, &repo, &revision)?;
let executables = self.get_executable_names(ctx, &repo_dir, &tv).await?;
if executables.is_empty() {
return Err(eyre::eyre!("No executables found in the package"));
}
let bin_path = tv.install_path().join("bin");
file::create_dir_all(&bin_path)?;
for executable in executables {
let exe_path = self
.build_executable(&executable, &repo_dir, ctx, &tv)
.await?;
file::make_symlink(&exe_path, &bin_path.join(executable))?;
}
// delete (huge) intermediate artifacts
file::remove_all(tv.install_path().join("repositories"))?;
file::remove_all(tv.cache_path())?;
Ok(tv)
}
}
impl SPMBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
fn clone_package_repo(
&self,
ctx: &InstallContext,
tv: &ToolVersion,
package_repo: &SwiftPackageRepo,
revision: &str,
) -> Result<PathBuf, eyre::Error> {
let repo = Git::new(tv.cache_path().join("repo"));
if !repo.exists() {
debug!(
"Cloning swift package repo {} to {}",
package_repo.url.as_str(),
repo.dir.display(),
);
repo.clone(
package_repo.url.as_str(),
CloneOptions::default().pr(ctx.pr.as_ref()),
)?;
}
debug!("Checking out revision: {revision}");
repo.update_tag(revision.to_string())?;
// Updates submodules ensuring they match the checked-out revision
repo.update_submodules()?;
Ok(repo.dir)
}
async fn get_executable_names(
&self,
ctx: &InstallContext,
repo_dir: &PathBuf,
tv: &ToolVersion,
) -> Result<Vec<String>, eyre::Error> {
let package_json = cmd!(
"swift",
"package",
"dump-package",
"--package-path",
&repo_dir,
"--scratch-path",
tv.install_path(),
"--cache-path",
dirs::CACHE.join("spm"),
)
.full_env(self.dependency_env(&ctx.config).await?)
.read()?;
let executables = serde_json::from_str::<PackageDescription>(&package_json)
.wrap_err("Failed to parse package description")?
.products
.iter()
.filter(|p| p.r#type.is_executable())
.map(|p| p.name.clone())
.collect::<Vec<String>>();
debug!("Found executables: {:?}", executables);
Ok(executables)
}
async fn build_executable(
&self,
executable: &str,
repo_dir: &PathBuf,
ctx: &InstallContext,
tv: &ToolVersion,
) -> Result<PathBuf, eyre::Error> {
debug!("Building swift package");
CmdLineRunner::new("swift")
.arg("build")
.arg("--configuration")
.arg("release")
.arg("--product")
.arg(executable)
.arg("--scratch-path")
.arg(tv.install_path())
.arg("--package-path")
.arg(repo_dir)
.arg("--cache-path")
.arg(dirs::CACHE.join("spm"))
.with_pr(ctx.pr.as_ref())
.prepend_path(
self.dependency_toolset(&ctx.config)
.await?
.list_paths(&ctx.config)
.await,
)?
.execute()?;
let bin_path = cmd!(
"swift",
"build",
"--configuration",
"release",
"--product",
&executable,
"--package-path",
&repo_dir,
"--scratch-path",
tv.install_path(),
"--cache-path",
dirs::CACHE.join("spm"),
"--show-bin-path"
)
.full_env(self.dependency_env(&ctx.config).await?)
.read()?;
Ok(PathBuf::from(bin_path.trim().to_string()).join(executable))
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GitProvider {
pub api_url: String,
pub kind: GitProviderKind,
}
impl Default for GitProvider {
fn default() -> Self {
Self {
api_url: github::API_URL.to_string(),
kind: GitProviderKind::GitHub,
}
}
}
#[derive(AsRefStr, Clone, Debug, Eq, PartialEq, EnumString, VariantNames)]
pub enum GitProviderKind {
#[strum(serialize = "github")]
GitHub,
#[strum(serialize = "gitlab")]
GitLab,
}
impl GitProvider {
fn from_ba(ba: &BackendArg) -> Self {
let opts = ba.opts();
let default_provider = GitProviderKind::GitHub.as_ref().to_string();
let provider = opts.get("provider").unwrap_or(&default_provider);
let kind = if ba.tool_name.contains("gitlab.com") {
GitProviderKind::GitLab
} else {
match provider.to_lowercase().as_str() {
"gitlab" => GitProviderKind::GitLab,
_ => GitProviderKind::GitHub,
}
};
let api_url = match opts.get("api_url") {
Some(api_url) => api_url.trim_end_matches('/').to_string(),
None => match kind {
GitProviderKind::GitHub => github::API_URL.to_string(),
GitProviderKind::GitLab => gitlab::API_URL.to_string(),
},
};
Self { api_url, kind }
}
}
#[derive(Debug)]
struct SwiftPackageRepo {
/// https://github.com/owner/repo.git
url: Url,
/// owner/repo_name
shorthand: String,
}
impl SwiftPackageRepo {
/// Parse the slug or the full URL of a GitHub package repository.
fn new(name: &str, provider: &GitProvider) -> Result<Self, eyre::Error> {
let name = name.strip_prefix("spm:").unwrap_or(name);
let shorthand_regex = regex!(r"^(?:[a-zA-Z0-9_-]+/)+[a-zA-Z0-9._-]+$");
let shorthand_in_url_regex = regex!(
r"^https://(?P<domain>[^/]+)/(?P<shorthand>(?:[a-zA-Z0-9_-]+/)+[a-zA-Z0-9._-]+)\.git"
);
let (shorthand, url) = if let Some(caps) = shorthand_in_url_regex.captures(name) {
let shorthand = caps.name("shorthand").unwrap().as_str();
let url = Url::parse(name)?;
(shorthand, url)
} else if shorthand_regex.is_match(name) {
let host = match provider.kind {
GitProviderKind::GitHub => "github.com",
GitProviderKind::GitLab => "gitlab.com",
};
let url_str = format!("https://{}/{}.git", host, name);
let url = Url::parse(&url_str)?;
(name, url)
} else {
Err(eyre::eyre!(
"Invalid Swift package repository: {}. The repository should either be a repository slug (owner/name), or the complete URL (e.g. https://github.com/owner/name.git).",
name
))?
};
Ok(Self {
url,
shorthand: shorthand.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use crate::{config::Config, toolset::ToolVersionOptions};
use super::*;
use indexmap::indexmap;
use pretty_assertions::assert_str_eq;
#[tokio::test]
async fn test_git_provider_from_ba() {
// Example of defining a capture (closure) in Rust:
let get_ba = |tool: String, opts: Option<ToolVersionOptions>| {
BackendArg::new_raw("spm".to_string(), Some(tool.clone()), tool, opts)
};
assert_eq!(
GitProvider::from_ba(&get_ba("tool".to_string(), None)),
GitProvider {
api_url: github::API_URL.to_string(),
kind: GitProviderKind::GitHub
}
);
assert_eq!(
GitProvider::from_ba(&get_ba(
"tool".to_string(),
Some(ToolVersionOptions {
opts: indexmap![
"provider".to_string() => "gitlab".to_string()
],
..Default::default()
})
)),
GitProvider {
api_url: gitlab::API_URL.to_string(),
kind: GitProviderKind::GitLab
}
);
assert_eq!(
GitProvider::from_ba(&get_ba(
"tool".to_string(),
Some(ToolVersionOptions {
opts: indexmap![
"api_url".to_string() => "https://gitlab.acme.com/api/v4".to_string(),
"provider".to_string() => "gitlab".to_string(),
],
..Default::default()
})
)),
GitProvider {
api_url: "https://gitlab.acme.com/api/v4".to_string(),
kind: GitProviderKind::GitLab
}
);
}
#[tokio::test]
async fn test_spm_repo_init_by_shorthand() {
let _config = Config::get().await.unwrap();
let package_repo =
SwiftPackageRepo::new("nicklockwood/SwiftFormat", &GitProvider::default()).unwrap();
assert_str_eq!(
package_repo.url.as_str(),
"https://github.com/nicklockwood/SwiftFormat.git"
);
assert_str_eq!(package_repo.shorthand, "nicklockwood/SwiftFormat");
let package_repo = SwiftPackageRepo::new(
"acme/nicklockwood/SwiftFormat",
&GitProvider {
api_url: gitlab::API_URL.to_string(),
kind: GitProviderKind::GitLab,
},
)
.unwrap();
assert_str_eq!(
package_repo.url.as_str(),
"https://gitlab.com/acme/nicklockwood/SwiftFormat.git"
);
assert_str_eq!(package_repo.shorthand, "acme/nicklockwood/SwiftFormat");
}
#[tokio::test]
async fn test_spm_repo_init_name() {
let _config = Config::get().await.unwrap();
assert!(
SwiftPackageRepo::new("owner/name.swift", &GitProvider::default()).is_ok(),
"name part can contain ."
);
assert!(
SwiftPackageRepo::new("owner/name_swift", &GitProvider::default()).is_ok(),
"name part can contain _"
);
assert!(
SwiftPackageRepo::new("owner/name-swift", &GitProvider::default()).is_ok(),
"name part can contain -"
);
assert!(
SwiftPackageRepo::new("owner/name$swift", &GitProvider::default()).is_err(),
"name part cannot contain characters other than a-zA-Z0-9._-"
);
}
#[tokio::test]
async fn test_spm_repo_init_by_url() {
let package_repo = SwiftPackageRepo::new(
"https://github.com/nicklockwood/SwiftFormat.git",
&GitProvider::default(),
)
.unwrap();
assert_str_eq!(
package_repo.url.as_str(),
"https://github.com/nicklockwood/SwiftFormat.git"
);
assert_str_eq!(package_repo.shorthand, "nicklockwood/SwiftFormat");
let package_repo = SwiftPackageRepo::new(
"https://gitlab.acme.com/acme/someuser/SwiftTool.git",
&GitProvider {
api_url: "https://api.gitlab.acme.com/api/v4".to_string(),
kind: GitProviderKind::GitLab,
},
)
.unwrap();
assert_str_eq!(
package_repo.url.as_str(),
"https://gitlab.acme.com/acme/someuser/SwiftTool.git"
);
assert_str_eq!(package_repo.shorthand, "acme/someuser/SwiftTool");
}
}
/// https://developer.apple.com/documentation/packagedescription
#[derive(Deserialize)]
struct PackageDescription {
products: Vec<PackageDescriptionProduct>,
}
#[derive(Deserialize)]
struct PackageDescriptionProduct {
name: String,
#[serde(deserialize_with = "PackageDescriptionProductType::deserialize_product_type_field")]
r#type: PackageDescriptionProductType,
}
#[derive(Deserialize)]
enum PackageDescriptionProductType {
Executable,
Other,
}
impl PackageDescriptionProductType {
fn is_executable(&self) -> bool {
matches!(self, Self::Executable)
}
/// Swift determines the toolchain to use with a given package using a comment in the Package.swift file at the top.
/// For example:
/// // swift-tools-version: 6.0
///
/// The version of the toolchain can be older than the Swift version used to build the package. This versioning gives
/// Apple the flexibility to introduce and flag breaking changes in the toolchain.
///
/// How to determine the product type is something that might change across different versions of Swift.
///
/// ## Swift 5.x
///
/// Product type is a key in the map with an undocumented value that we are not interested in and can be easily skipped.
///
/// Example:
/// ```json
/// "type" : {
/// "executable" : null
/// }
/// ```
/// or
/// ```json
/// "type" : {
/// "library" : [
/// "automatic"
/// ]
/// }
/// ```
///
/// ## Swift 6.x
///
/// The product type is directly the value under the key "type"
///
/// Example:
///
/// ```json
/// "type": "executable"
/// ```
///
fn deserialize_product_type_field<'de, D>(
deserializer: D,
) -> Result<PackageDescriptionProductType, D::Error>
where
D: Deserializer<'de>,
{
struct TypeFieldVisitor;
impl<'de> Visitor<'de> for TypeFieldVisitor {
type Value = PackageDescriptionProductType;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a map with a key 'executable' or other types")
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
if let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"type" => {
let value: String = map.next_value()?;
if value == "executable" {
Ok(PackageDescriptionProductType::Executable)
} else {
Ok(PackageDescriptionProductType::Other)
}
}
"executable" => {
// Skip the value by reading it into a dummy serde_json::Value
let _value: serde_json::Value = map.next_value()?;
Ok(PackageDescriptionProductType::Executable)
}
_ => {
let _value: serde_json::Value = map.next_value()?;
Ok(PackageDescriptionProductType::Other)
}
}
} else {
Err(serde::de::Error::custom("missing key"))
}
}
}
deserializer.deserialize_map(TypeFieldVisitor)
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/dotnet.rs | src/backend/dotnet.rs | use std::sync::Arc;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::Settings;
use crate::http::HTTP_FETCH;
use crate::{backend::Backend, config::Config};
use async_trait::async_trait;
use eyre::eyre;
/// Dotnet backend requires experimental mode to be enabled
pub const EXPERIMENTAL: bool = true;
#[derive(Debug)]
pub struct DotnetBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for DotnetBackend {
fn get_type(&self) -> BackendType {
BackendType::Dotnet
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
Ok(vec!["dotnet"])
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
let feed_url = self.get_search_url().await?;
let feed: NugetFeedSearch = HTTP_FETCH
.json(format!(
"{}?q={}&packageType=dotnettool&take=1&prerelease={}",
feed_url,
&self.tool_name(),
Settings::get()
.dotnet
.package_flags
.contains(&"prerelease".to_string())
))
.await?;
if feed.total_hits == 0 {
return Err(eyre!("No tool found"));
}
let data = feed.data.first().ok_or_else(|| eyre!("No data found"))?;
// Because the nuget API is a search API we need to check name of the tool we are looking for
if data.id.to_lowercase() != self.tool_name().to_lowercase() {
return Err(eyre!("Tool {} not found", &self.tool_name()));
}
Ok(data
.versions
.iter()
.map(|x| VersionInfo {
version: x.version.clone(),
..Default::default()
})
.collect())
}
async fn install_version_(
&self,
ctx: &crate::install_context::InstallContext,
tv: crate::toolset::ToolVersion,
) -> eyre::Result<crate::toolset::ToolVersion> {
Settings::get().ensure_experimental("dotnet backend")?;
// Check if dotnet is available
self.warn_if_dependency_missing(
&ctx.config,
"dotnet",
"To use dotnet tools with mise, you need to install .NET SDK first:\n\
mise use dotnet@latest\n\n\
Or install .NET SDK via https://dotnet.microsoft.com/download",
)
.await;
let mut cli = CmdLineRunner::new("dotnet")
.arg("tool")
.arg("install")
.arg(self.tool_name())
.arg("--tool-path")
.arg(tv.install_path().join("bin"));
if &tv.version != "latest" {
cli = cli.arg("--version").arg(&tv.version);
}
cli.with_pr(ctx.pr.as_ref())
.envs(self.dependency_env(&ctx.config).await?)
.execute()?;
Ok(tv)
}
}
impl DotnetBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
async fn get_search_url(&self) -> eyre::Result<String> {
let settings = Settings::get();
let nuget_registry = settings.dotnet.registry_url.as_str();
let services: NugetFeed = HTTP_FETCH.json(nuget_registry).await?;
let feed = services
.resources
.iter()
.find(|x| x.service_type == "SearchQueryService/3.5.0")
.or_else(|| {
services
.resources
.iter()
.find(|x| x.service_type == "SearchQueryService")
})
.ok_or_else(|| eyre!("No SearchQueryService found"))?;
Ok(feed.id.clone())
}
}
#[derive(serde::Deserialize)]
struct NugetFeed {
resources: Vec<NugetFeedResource>,
}
#[derive(serde::Deserialize)]
struct NugetFeedResource {
#[serde(rename = "@id")]
id: String,
#[serde(rename = "@type")]
service_type: String,
}
#[derive(serde::Deserialize)]
struct NugetFeedSearch {
#[serde(rename = "totalHits")]
total_hits: i32,
data: Vec<NugetFeedSearchData>,
}
#[derive(serde::Deserialize)]
struct NugetFeedSearchData {
id: String,
versions: Vec<NugetFeedSearchDataVersion>,
}
#[derive(serde::Deserialize)]
struct NugetFeedSearchDataVersion {
version: String,
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/backend/ubi.rs | src/backend/ubi.rs | use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::backend::platform_target::PlatformTarget;
use crate::backend::static_helpers::{lookup_platform_key, try_with_v_prefix};
use crate::cli::args::BackendArg;
use crate::config::{Config, Settings};
use crate::env::{
GITHUB_TOKEN, GITLAB_TOKEN, MISE_GITHUB_ENTERPRISE_TOKEN, MISE_GITLAB_ENTERPRISE_TOKEN,
};
use crate::install_context::InstallContext;
use crate::plugins::VERSION_REGEX;
use crate::toolset::{ToolRequest, ToolVersion};
use crate::{backend::Backend, toolset::ToolVersionOptions};
use crate::{file, github, gitlab, hash};
use async_trait::async_trait;
use eyre::bail;
use regex::Regex;
use std::collections::BTreeMap;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::OnceLock;
use std::{fmt::Debug, sync::LazyLock};
use ubi::{ForgeType, UbiBuilder};
use xx::regex;
#[derive(Debug)]
pub struct UbiBackend {
ba: Arc<BackendArg>,
}
#[async_trait]
impl Backend for UbiBackend {
fn get_type(&self) -> BackendType {
BackendType::Ubi
}
fn ba(&self) -> &Arc<BackendArg> {
&self.ba
}
async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
if name_is_url(&self.tool_name()) {
Ok(vec![VersionInfo {
version: "latest".to_string(),
created_at: None,
release_url: None,
}])
} else {
let opts = self.ba.opts();
let forge = match opts.get("provider") {
Some(forge) => ForgeType::from_str(forge)?,
None => ForgeType::default(),
};
let api_url = match opts.get("api_url") {
Some(api_url) => api_url.strip_suffix("/").unwrap_or(api_url),
None => match forge {
ForgeType::GitHub => github::API_URL,
ForgeType::GitLab => gitlab::API_URL,
_ => bail!("Unsupported forge type {:?}", forge),
},
};
let tag_regex_cell = OnceLock::new();
// Build release URL base based on forge type and api_url
let release_url_base = match forge {
ForgeType::GitHub => {
if api_url == github::API_URL {
format!("https://github.com/{}", self.tool_name())
} else {
// Enterprise GitHub - derive web URL from API URL
let web_url = api_url.replace("/api/v3", "").replace("api.", "");
format!("{}/{}", web_url, self.tool_name())
}
}
ForgeType::GitLab => {
if api_url == gitlab::API_URL {
format!("https://gitlab.com/{}", self.tool_name())
} else {
// Enterprise GitLab - derive web URL from API URL
let web_url = api_url.replace("/api/v4", "");
format!("{}/{}", web_url, self.tool_name())
}
}
_ => bail!("Unsupported forge type {:?}", forge),
};
// Helper to check if tag matches tag_regex (if provided)
let matches_tag_regex = |tag: &str| -> bool {
if let Some(re_str) = opts.get("tag_regex") {
let re = tag_regex_cell.get_or_init(|| Regex::new(re_str).unwrap());
re.is_match(tag)
} else {
true
}
};
// Helper to strip 'v' prefix from version
let strip_v_prefix = |tag: &str| -> String {
if regex!(r"^v[0-9]").is_match(tag) {
tag[1..].to_string()
} else {
tag.to_string()
}
};
let mut version_infos: Vec<VersionInfo> = match forge {
ForgeType::GitHub => {
let releases =
github::list_releases_from_url(api_url, &self.tool_name()).await?;
if releases.is_empty() {
// Fall back to tags (no created_at available)
github::list_tags_from_url(api_url, &self.tool_name())
.await?
.into_iter()
.filter(|tag| matches_tag_regex(tag))
.map(|tag| {
let release_url =
format!("{}/releases/tag/{}", release_url_base, tag);
VersionInfo {
version: strip_v_prefix(&tag),
created_at: None,
release_url: Some(release_url),
}
})
.collect()
} else {
releases
.into_iter()
.filter(|r| matches_tag_regex(&r.tag_name))
.map(|r| {
let release_url =
format!("{}/releases/tag/{}", release_url_base, r.tag_name);
VersionInfo {
version: strip_v_prefix(&r.tag_name),
created_at: Some(r.created_at),
release_url: Some(release_url),
}
})
.collect()
}
}
ForgeType::GitLab => {
let releases =
gitlab::list_releases_from_url(api_url, &self.tool_name()).await?;
if releases.is_empty() {
// Fall back to tags (no created_at available)
gitlab::list_tags_from_url(api_url, &self.tool_name())
.await?
.into_iter()
.filter(|tag| matches_tag_regex(tag))
.map(|tag| {
// Use /-/tags/ for tag-only URLs (no release exists)
let release_url = format!("{}/-/tags/{}", release_url_base, tag);
VersionInfo {
version: strip_v_prefix(&tag),
created_at: None,
release_url: Some(release_url),
}
})
.collect()
} else {
releases
.into_iter()
.filter(|r| matches_tag_regex(&r.tag_name))
.map(|r| {
let release_url =
format!("{}/-/releases/{}", release_url_base, r.tag_name);
VersionInfo {
version: strip_v_prefix(&r.tag_name),
created_at: r.released_at,
release_url: Some(release_url),
}
})
.collect()
}
}
_ => bail!("Unsupported forge type {:?}", forge),
};
// Sort: versions starting with digits first, then reverse
version_infos.sort_by_cached_key(|vi| !regex!(r"^[0-9]").is_match(&vi.version));
version_infos.reverse();
Ok(version_infos)
}
}
async fn install_version_(
&self,
ctx: &InstallContext,
mut tv: ToolVersion,
) -> eyre::Result<ToolVersion> {
deprecated!(
"ubi",
"The ubi backend is deprecated. Use the github backend instead (e.g., github:owner/repo)"
);
// Check if lockfile has URL for this platform
let platform_key = self.get_platform_key();
let lockfile_url = tv
.lock_platforms
.get(&platform_key)
.and_then(|p| p.url.clone());
let v = tv.version.to_string();
let opts = tv.request.options();
let bin_path = lookup_platform_key(&opts, "bin_path")
.or_else(|| opts.get("bin_path").cloned())
.unwrap_or_else(|| "bin".to_string());
let extract_all = opts.get("extract_all").is_some_and(|v| v == "true");
let bin_dir = tv.install_path();
// Use lockfile URL if available, otherwise fall back to standard resolution
if let Some(url) = &lockfile_url {
install(url, &v, &bin_dir, extract_all, &opts)
.await
.map_err(|e| eyre::eyre!(e))?;
} else if name_is_url(&self.tool_name()) {
install(&self.tool_name(), &v, &bin_dir, extract_all, &opts)
.await
.map_err(|e| eyre::eyre!(e))?;
} else {
try_with_v_prefix(&v, None, |candidate| {
let opts = opts.clone();
let bin_dir = bin_dir.clone();
async move {
install(
&self.tool_name(),
&candidate,
&bin_dir,
extract_all,
&opts,
)
.await
}
})
.await?;
}
let mut possible_exes = vec![
tv.request
.options()
.get("exe")
.cloned()
.unwrap_or(tv.ba().short.to_string()),
];
if cfg!(windows) {
possible_exes.push(format!("{}.exe", possible_exes[0]));
}
let full_binary_path = if let Some(bin_file) = possible_exes
.into_iter()
.map(|e| bin_dir.join(e))
.find(|f| f.exists())
{
bin_file
} else {
let mut bin_dir = bin_dir.to_path_buf();
if extract_all && bin_dir.join(&bin_path).exists() {
bin_dir = bin_dir.join(&bin_path);
}
file::ls(&bin_dir)?
.into_iter()
.find(|f| {
!f.file_name()
.is_some_and(|f| f.to_string_lossy().starts_with("."))
})
.unwrap()
};
self.verify_checksum(ctx, &mut tv, &full_binary_path)?;
Ok(tv)
}
fn fuzzy_match_filter(&self, versions: Vec<String>, query: &str) -> Vec<String> {
let escaped_query = regex::escape(query);
let query = if query == "latest" {
"\\D*[0-9].*"
} else {
&escaped_query
};
let query_regex = Regex::new(&format!("^{query}([-.].+)?$")).unwrap();
versions
.into_iter()
.filter(|v| {
if query == v {
return true;
}
if VERSION_REGEX.is_match(v) {
return false;
}
query_regex.is_match(v)
})
.collect()
}
fn verify_checksum(
&self,
ctx: &InstallContext,
tv: &mut ToolVersion,
file: &Path,
) -> eyre::Result<()> {
// For ubi backend, generate a more specific platform key that includes tool-specific options
let mut platform_key = self.get_platform_key();
let filename = file.file_name().unwrap().to_string_lossy().to_string();
if let Some(exe) = tv.request.options().get("exe") {
platform_key = format!("{platform_key}-{exe}");
}
if let Some(matching) = tv.request.options().get("matching") {
platform_key = format!("{platform_key}-{matching}");
}
// Include filename to distinguish different downloads for the same platform
platform_key = format!("{platform_key}-{filename}");
// Get or create platform info for this platform key
let platform_info = tv.lock_platforms.entry(platform_key.clone()).or_default();
if let Some(checksum) = &platform_info.checksum {
ctx.pr
.set_message(format!("checksum verify {platform_key}"));
if let Some((algo, check)) = checksum.split_once(':') {
hash::ensure_checksum(file, check, Some(ctx.pr.as_ref()), algo)?;
} else {
bail!("Invalid checksum: {platform_key}");
}
} else if Settings::get().lockfile && Settings::get().experimental {
ctx.pr
.set_message(format!("checksum generate {platform_key}"));
let hash = hash::file_hash_blake3(file, Some(ctx.pr.as_ref()))?;
platform_info.checksum = Some(format!("blake3:{hash}"));
}
Ok(())
}
async fn list_bin_paths(
&self,
_config: &Arc<Config>,
tv: &ToolVersion,
) -> eyre::Result<Vec<std::path::PathBuf>> {
let opts = tv.request.options();
if let Some(bin_path) =
lookup_platform_key(&opts, "bin_path").or_else(|| opts.get("bin_path").cloned())
{
// bin_path should always point to a directory containing binaries
Ok(vec![tv.install_path().join(&bin_path)])
} else if opts.get("extract_all").is_some_and(|v| v == "true") {
Ok(vec![tv.install_path()])
} else {
let bin_path = tv.install_path().join("bin");
if bin_path.exists() {
Ok(vec![bin_path])
} else {
Ok(vec![tv.install_path()])
}
}
}
fn resolve_lockfile_options(
&self,
request: &ToolRequest,
_target: &PlatformTarget,
) -> BTreeMap<String, String> {
let opts = request.options();
let mut result = BTreeMap::new();
// These options affect which artifact is downloaded
for key in ["exe", "matching", "matching_regex", "provider"] {
if let Some(value) = opts.get(key) {
result.insert(key.to_string(), value.clone());
}
}
result
}
}
/// Returns install-time-only option keys for UBI backend.
pub fn install_time_option_keys() -> Vec<String> {
vec![
"exe".into(),
"matching".into(),
"matching_regex".into(),
"provider".into(),
]
}
impl UbiBackend {
pub fn from_arg(ba: BackendArg) -> Self {
Self { ba: Arc::new(ba) }
}
}
fn name_is_url(n: &str) -> bool {
n.starts_with("http")
}
fn set_token<'a>(mut builder: UbiBuilder<'a>, forge: &ForgeType) -> UbiBuilder<'a> {
match forge {
ForgeType::GitHub => {
if let Some(token) = &*GITHUB_TOKEN {
builder = builder.token(token)
}
builder
}
ForgeType::GitLab => {
if let Some(token) = &*GITLAB_TOKEN {
builder = builder.token(token)
}
builder
}
_ => builder,
}
}
fn set_enterprise_token<'a>(mut builder: UbiBuilder<'a>, forge: &ForgeType) -> UbiBuilder<'a> {
match forge {
ForgeType::GitHub => {
if let Some(token) = &*MISE_GITHUB_ENTERPRISE_TOKEN {
builder = builder.token(token);
}
builder
}
ForgeType::GitLab => {
if let Some(token) = &*MISE_GITLAB_ENTERPRISE_TOKEN {
builder = builder.token(token);
}
builder
}
_ => builder,
}
}
async fn install(
name: &str,
v: &str,
bin_dir: &Path,
extract_all: bool,
opts: &ToolVersionOptions,
) -> anyhow::Result<()> {
let mut builder = UbiBuilder::new().install_dir(bin_dir);
if name_is_url(name) {
builder = builder.url(name);
} else {
builder = builder.project(name);
builder = builder.tag(v);
}
if extract_all {
builder = builder.extract_all();
} else {
if let Some(exe) = opts.get("exe") {
builder = builder.exe(exe);
}
if let Some(rename_exe) = opts.get("rename_exe") {
builder = builder.rename_exe_to(rename_exe)
}
}
if let Some(matching) = opts.get("matching") {
builder = builder.matching(matching);
}
if let Some(matching_regex) = opts.get("matching_regex") {
builder = builder.matching_regex(matching_regex);
}
let forge = match opts.get("provider") {
Some(forge) => ForgeType::from_str(forge)?,
None => ForgeType::default(),
};
builder = builder.forge(forge.clone());
builder = set_token(builder, &forge);
if let Some(api_url) = opts.get("api_url")
&& !api_url.contains("github.com")
&& !api_url.contains("gitlab.com")
{
builder = builder.api_base_url(api_url.strip_suffix("/").unwrap_or(api_url));
builder = set_enterprise_token(builder, &forge);
}
let mut ubi = builder.build()?;
// TODO: hacky but does not compile without it
tokio::task::block_in_place(|| {
static RT: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
});
RT.block_on(async { ubi.install_binary().await })
})
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/settings.rs | src/config/settings.rs | use crate::cli::Cli;
use crate::config::ALL_TOML_CONFIG_FILES;
use crate::duration;
use crate::file::FindUp;
use crate::{dirs, env, file};
#[allow(unused_imports)]
use confique::env::parse::{list_by_colon, list_by_comma};
use confique::{Config, Partial};
use eyre::{Result, bail};
use indexmap::{IndexMap, indexmap};
use itertools::Itertools;
use serde::ser::Error;
use serde::{Deserialize, Deserializer};
use serde_derive::Serialize;
use std::env::consts::{ARCH, OS};
use std::fmt::{Debug, Display, Formatter};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::LazyLock as Lazy;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use std::{
collections::{BTreeSet, HashSet},
sync::atomic::Ordering,
};
use url::Url;
// settings are generated from settings.toml in the project root
// make sure you run `mise run render` after updating settings.toml
include!(concat!(env!("OUT_DIR"), "/settings.rs"));
pub enum SettingsType {
Bool,
String,
Integer,
Duration,
Path,
Url,
ListString,
ListPath,
SetString,
IndexMap,
}
pub struct SettingsMeta {
// pub key: String,
pub type_: SettingsType,
pub description: &'static str,
}
#[derive(
Debug,
Clone,
Copy,
Serialize,
Deserialize,
Default,
strum::EnumString,
strum::Display,
PartialEq,
Eq,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum SettingsStatusMissingTools {
/// never show the warning
Never,
/// hide this warning if the user hasn't installed at least 1 version of the tool before
#[default]
IfOtherVersionsInstalled,
/// always show the warning if tools are missing
Always,
}
pub type SettingsPartial = <Settings as Config>::Partial;
static BASE_SETTINGS: RwLock<Option<Arc<Settings>>> = RwLock::new(None);
static CLI_SETTINGS: Mutex<Option<SettingsPartial>> = Mutex::new(None);
static DEFAULT_SETTINGS: Lazy<SettingsPartial> = Lazy::new(|| {
let mut s = SettingsPartial::empty();
s.python.default_packages_file = Some(env::HOME.join(".default-python-packages"));
if let Some("alpine" | "nixos") = env::LINUX_DISTRO.as_ref().map(|s| s.as_str())
&& !cfg!(test)
{
s.all_compile = Some(true);
}
s
});
pub fn is_loaded() -> bool {
BASE_SETTINGS.read().unwrap().is_some()
}
#[derive(Serialize, Deserialize)]
pub struct SettingsFile {
#[serde(default)]
pub settings: SettingsPartial,
}
impl Settings {
pub fn get() -> Arc<Self> {
Self::try_get().unwrap()
}
pub fn try_get() -> Result<Arc<Self>> {
if let Some(settings) = BASE_SETTINGS.read().unwrap().as_ref() {
return Ok(settings.clone());
}
time!("try_get");
// Initial pass to obtain cd option
let mut sb = Self::builder()
.preloaded(CLI_SETTINGS.lock().unwrap().clone().unwrap_or_default())
.env();
let mut settings = sb.load()?;
if let Some(mut cd) = settings.cd {
static ORIG_PATH: Lazy<std::io::Result<PathBuf>> = Lazy::new(env::current_dir);
if cd.is_relative() {
cd = ORIG_PATH.as_ref()?.join(cd);
}
env::set_current_dir(cd)?;
}
// Reload settings after current directory option processed
sb = Self::builder()
.preloaded(CLI_SETTINGS.lock().unwrap().clone().unwrap_or_default())
.env();
for file in Self::all_settings_files() {
sb = sb.preloaded(file);
}
sb = sb.preloaded(DEFAULT_SETTINGS.clone());
settings = sb.load()?;
if !settings.legacy_version_file {
settings.idiomatic_version_file = Some(false);
}
if settings.raw {
settings.jobs = 1;
}
// Handle NO_COLOR environment variable
if *env::NO_COLOR {
settings.color = false;
}
if settings.debug {
settings.log_level = "debug".to_string();
}
if settings.trace {
settings.log_level = "trace".to_string();
}
if settings.quiet {
settings.log_level = "error".to_string();
}
if settings.log_level == "trace" || settings.log_level == "debug" {
settings.verbose = true;
settings.debug = true;
if settings.log_level == "trace" {
settings.trace = true;
}
}
let args = env::args().collect_vec();
// handle the special case of `mise -v` which should show version, not set verbose
if settings.verbose && !(args.len() == 2 && args[1] == "-v") {
settings.quiet = false;
if settings.log_level != "trace" {
settings.log_level = "debug".to_string();
}
}
if !settings.color {
console::set_colors_enabled(false);
console::set_colors_enabled_stderr(false);
} else if *env::CLICOLOR_FORCE == Some(true) {
console::set_colors_enabled(true);
console::set_colors_enabled_stderr(true);
} else if *env::CLICOLOR == Some(false) {
console::set_colors_enabled(false);
console::set_colors_enabled_stderr(false);
} else if ci_info::is_ci() && !cfg!(test) {
console::set_colors_enabled_stderr(true);
}
if settings.ci {
settings.yes = true;
}
if settings.all_compile {
if settings.node.compile.is_none() {
settings.node.compile = Some(true);
}
if settings.python.compile.is_none() {
settings.python.compile = Some(true);
}
if settings.erlang.compile.is_none() {
settings.erlang.compile = Some(true);
}
if settings.ruby.compile.is_none() {
settings.ruby.compile = Some(true);
}
}
if settings.gpg_verify.is_some() {
settings.node.gpg_verify = settings.node.gpg_verify.or(settings.gpg_verify);
settings.swift.gpg_verify = settings.swift.gpg_verify.or(settings.gpg_verify);
}
settings.set_hidden_configs();
if cfg!(test) {
settings.experimental = true;
}
let settings = Arc::new(settings);
*BASE_SETTINGS.write().unwrap() = Some(settings.clone());
time!("try_get done");
trace!("Settings: {:#?}", settings);
Ok(settings)
}
/// Sets deprecated settings to new names
fn set_hidden_configs(&mut self) {
if !self.auto_install {
self.exec_auto_install = false;
self.not_found_auto_install = false;
self.task_run_auto_install = false;
}
if let Some(false) = self.asdf {
self.disable_backends.push("asdf".to_string());
}
if let Some(false) = self.vfox {
self.disable_backends.push("vfox".to_string());
}
if let Some(disable_default_shorthands) = self.disable_default_shorthands {
self.disable_default_registry = disable_default_shorthands;
}
if let Some(cargo_binstall) = self.cargo_binstall {
self.cargo.binstall = cargo_binstall;
}
if let Some(pipx_uvx) = self.pipx_uvx {
self.pipx.uvx = Some(pipx_uvx);
}
if let Some(python_compile) = self.python_compile {
self.python.compile = Some(python_compile);
}
if let Some(python_default_packages_file) = &self.python_default_packages_file {
self.python.default_packages_file = Some(python_default_packages_file.clone());
}
if let Some(python_patch_url) = &self.python_patch_url {
self.python.patch_url = Some(python_patch_url.clone());
}
if let Some(python_patches_directory) = &self.python_patches_directory {
self.python.patches_directory = Some(python_patches_directory.clone());
}
if let Some(python_precompiled_arch) = &self.python_precompiled_arch {
self.python.precompiled_arch = Some(python_precompiled_arch.clone());
}
if let Some(python_precompiled_os) = &self.python_precompiled_os {
self.python.precompiled_os = Some(python_precompiled_os.clone());
}
if let Some(python_pyenv_repo) = &self.python_pyenv_repo {
self.python.pyenv_repo = python_pyenv_repo.clone();
}
if let Some(python_venv_stdlib) = self.python_venv_stdlib {
self.python.venv_stdlib = python_venv_stdlib;
}
if let Some(python_venv_auto_create) = self.python_venv_auto_create {
self.python.venv_auto_create = python_venv_auto_create;
}
if self.npm.bun {
self.npm.package_manager = "bun".to_string();
}
}
pub fn add_cli_matches(cli: &Cli) {
let mut s = SettingsPartial::empty();
// Don't process mise-specific flags when running as a shim
if *crate::env::IS_RUNNING_AS_SHIM {
Self::reset(Some(s));
return;
}
if cli.raw {
s.raw = Some(true);
}
if cli.locked {
s.locked = Some(true);
}
if let Some(cd) = &cli.cd {
s.cd = Some(cd.clone());
}
if cli.profile.is_some() {
s.env = cli.profile.clone();
}
if cli.env.is_some() {
s.env = cli.env.clone();
}
if cli.yes {
s.yes = Some(true);
}
if cli.quiet {
s.quiet = Some(true);
}
if cli.trace {
s.log_level = Some("trace".to_string());
}
if cli.debug {
s.log_level = Some("debug".to_string());
}
if let Some(log_level) = &cli.log_level {
s.log_level = Some(log_level.to_string());
}
if cli.verbose > 0 {
s.verbose = Some(true);
}
if cli.verbose > 1 {
s.log_level = Some("trace".to_string());
}
Self::reset(Some(s));
}
pub fn parse_settings_file(path: &Path) -> Result<SettingsPartial> {
let raw = file::read_to_string(path)?;
let settings_file: SettingsFile = toml::from_str(&raw)?;
Ok(settings_file.settings)
}
fn all_settings_files() -> Vec<SettingsPartial> {
ALL_TOML_CONFIG_FILES
.iter()
.map(|p| Self::parse_settings_file(p))
.filter_map(|cfg| match cfg {
Ok(cfg) => Some(cfg),
Err(e) => {
eprintln!("Error loading settings file: {e}");
None
}
})
.collect()
}
pub fn hidden_configs() -> &'static HashSet<&'static str> {
static HIDDEN_CONFIGS: Lazy<HashSet<&'static str>> = Lazy::new(|| {
[
"ci",
"cd",
"debug",
"env_file",
"trace",
"log_level",
"python_venv_auto_create",
]
.into()
});
&HIDDEN_CONFIGS
}
pub fn reset(cli_settings: Option<SettingsPartial>) {
*CLI_SETTINGS.lock().unwrap() = cli_settings;
*BASE_SETTINGS.write().unwrap() = None;
// Clear caches that depend on settings and environment
crate::config::config_file::config_root::reset();
}
pub fn ensure_experimental(&self, what: &str) -> Result<()> {
if !self.experimental {
bail!("{what} is experimental. Enable it with `mise settings experimental=true`");
}
Ok(())
}
pub fn trusted_config_paths(&self) -> impl Iterator<Item = PathBuf> + '_ {
self.trusted_config_paths
.iter()
.filter(|p| !p.to_string_lossy().is_empty())
.map(file::replace_path)
.filter_map(|p| p.canonicalize().ok())
}
pub fn global_tools_file(&self) -> PathBuf {
env::var_path("MISE_GLOBAL_CONFIG_FILE")
.or_else(|| env::var_path("MISE_CONFIG_FILE"))
.unwrap_or_else(|| {
if self.asdf_compat {
env::HOME.join(&*env::MISE_DEFAULT_TOOL_VERSIONS_FILENAME)
} else {
dirs::CONFIG.join("config.toml")
}
})
}
pub fn env_files(&self) -> Vec<PathBuf> {
let mut files = vec![];
if let Some(cwd) = &*dirs::CWD
&& let Some(env_file) = &self.env_file
{
let env_file = env_file.to_string_lossy().to_string();
for p in FindUp::new(cwd, &[env_file]) {
files.push(p);
}
}
files.into_iter().rev().collect()
}
pub fn as_dict(&self) -> eyre::Result<toml::Table> {
let s = toml::to_string(self)?;
let table = toml::from_str(&s)?;
Ok(table)
}
pub fn cache_prune_age_duration(&self) -> Option<Duration> {
let age = duration::parse_duration(&self.cache_prune_age).unwrap();
if age.as_secs() == 0 { None } else { Some(age) }
}
pub fn fetch_remote_versions_timeout(&self) -> Duration {
duration::parse_duration(&self.fetch_remote_versions_timeout).unwrap()
}
/// duration that remote version cache is kept for
/// for "fast" commands (represented by PREFER_OFFLINE), these are always
/// cached. For "slow" commands like `mise ls-remote` or `mise install`:
/// - if MISE_FETCH_REMOTE_VERSIONS_CACHE is set, use that
/// - if MISE_FETCH_REMOTE_VERSIONS_CACHE is not set, use HOURLY
pub fn fetch_remote_versions_cache(&self) -> Option<Duration> {
if env::PREFER_OFFLINE.load(Ordering::Relaxed) {
None
} else {
Some(duration::parse_duration(&self.fetch_remote_versions_cache).unwrap())
}
}
pub fn http_timeout(&self) -> Duration {
duration::parse_duration(&self.http_timeout).unwrap()
}
pub fn task_timeout_duration(&self) -> Option<Duration> {
self.task_timeout
.as_ref()
.and_then(|s| duration::parse_duration(s).ok())
}
pub fn log_level(&self) -> log::LevelFilter {
self.log_level.parse().unwrap_or(log::LevelFilter::Info)
}
pub fn disable_tools(&self) -> BTreeSet<String> {
self.disable_tools
.iter()
.map(|t| t.trim().to_string())
.collect()
}
pub fn enable_tools(&self) -> BTreeSet<String> {
self.enable_tools
.iter()
.map(|t| t.trim().to_string())
.collect()
}
pub fn partial_as_dict(partial: &SettingsPartial) -> eyre::Result<toml::Table> {
let s = toml::to_string(partial)?;
let table = toml::from_str(&s)?;
Ok(table)
}
pub fn default_inline_shell(&self) -> Result<Vec<String>> {
let sa = if cfg!(windows) {
&self.windows_default_inline_shell_args
} else {
&self.unix_default_inline_shell_args
};
Ok(shell_words::split(sa)?)
}
pub fn default_file_shell(&self) -> Result<Vec<String>> {
let sa = if cfg!(windows) {
&self.windows_default_file_shell_args
} else {
&self.unix_default_file_shell_args
};
Ok(shell_words::split(sa)?)
}
pub fn os(&self) -> &str {
match self.os.as_deref().unwrap_or(OS) {
"darwin" | "macos" => "macos",
"linux" => "linux",
"windows" => "windows",
other => other,
}
}
pub fn arch(&self) -> &str {
match self.arch.as_deref().unwrap_or(ARCH) {
"x86_64" | "amd64" => "x64",
"aarch64" | "arm64" => "arm64",
other => other,
}
}
pub fn no_config() -> bool {
*env::MISE_NO_CONFIG
|| !*crate::env::IS_RUNNING_AS_SHIM
&& env::ARGS
.read()
.unwrap()
.iter()
.take_while(|a| *a != "--")
.any(|a| a == "--no-config")
}
}
impl Display for Settings {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match toml::to_string_pretty(self) {
Ok(s) => write!(f, "{s}"),
Err(e) => Err(std::fmt::Error::custom(e)),
}
}
}
pub const DEFAULT_NODE_MIRROR_URL: &str = "https://nodejs.org/dist/";
impl SettingsNode {
pub fn mirror_url(&self) -> Url {
let s = self
.mirror_url
.clone()
.or(env::var("NODE_BUILD_MIRROR_URL").ok())
.unwrap_or_else(|| DEFAULT_NODE_MIRROR_URL.to_string());
Url::parse(&s).unwrap()
}
}
impl SettingsStatus {
pub fn missing_tools(&self) -> SettingsStatusMissingTools {
SettingsStatusMissingTools::from_str(&self.missing_tools).unwrap()
}
}
/// Deserialize a string to a boolean, accepting "false", "no", "0"
/// and their case-insensitive variants as `false`. Any other value (incl. "") is considered `true`.
fn bool_string<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"false" | "no" | "0" => Ok(false),
_ => Ok(true),
}
}
fn set_by_comma<T, C>(input: &str) -> Result<C, <T as FromStr>::Err>
where
T: FromStr + Eq + Ord,
C: FromIterator<T>,
{
input
.split(',')
// Filter out empty strings
.filter_map(|s| {
let trimmed = s.trim();
if !trimmed.is_empty() {
Some(T::from_str(trimmed))
} else {
None
}
})
// collect into BTreeSet to remove duplicates
.collect::<Result<BTreeSet<_>, _>>()
.map(|set| set.into_iter().collect())
}
/// Parse URL replacements from JSON string format
/// Expected format: {"source_domain": "replacement_domain", ...}
pub fn parse_url_replacements(input: &str) -> Result<IndexMap<String, String>, serde_json::Error> {
serde_json::from_str(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_set_by_comma_empty_string() {
let result: Result<BTreeSet<String>, _> = set_by_comma("");
assert!(result.is_ok());
assert_eq!(result.unwrap(), BTreeSet::new());
}
#[test]
fn test_set_by_comma_whitespace_only() {
let result: Result<BTreeSet<String>, _> = set_by_comma(" ");
assert!(result.is_ok());
assert_eq!(result.unwrap(), BTreeSet::new());
}
#[test]
fn test_set_by_comma_single_value() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo");
assert!(result.is_ok());
let expected: BTreeSet<String> = ["foo".to_string()].into_iter().collect();
assert_eq!(result.unwrap(), expected);
}
#[test]
fn test_set_by_comma_multiple_values() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo,bar,baz");
assert!(result.is_ok());
let expected: BTreeSet<String> = ["foo".to_string(), "bar".to_string(), "baz".to_string()]
.into_iter()
.collect();
assert_eq!(result.unwrap(), expected);
}
#[test]
fn test_set_by_comma_with_whitespace() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo, bar, baz");
assert!(result.is_ok());
let expected: BTreeSet<String> = ["foo".to_string(), "bar".to_string(), "baz".to_string()]
.into_iter()
.collect();
assert_eq!(result.unwrap(), expected);
}
#[test]
fn test_set_by_comma_trailing_comma() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo,bar,");
assert!(result.is_ok());
let expected: BTreeSet<String> =
["foo".to_string(), "bar".to_string()].into_iter().collect();
assert_eq!(result.unwrap(), expected);
}
#[test]
fn test_set_by_comma_duplicate_values() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo,bar,foo");
assert!(result.is_ok());
let expected: BTreeSet<String> =
["foo".to_string(), "bar".to_string()].into_iter().collect();
assert_eq!(result.unwrap(), expected);
}
#[test]
fn test_set_by_comma_empty_elements() {
let result: Result<BTreeSet<String>, _> = set_by_comma("foo,,bar");
assert!(result.is_ok());
let expected: BTreeSet<String> =
["foo".to_string(), "bar".to_string()].into_iter().collect();
assert_eq!(result.unwrap(), expected);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/mod.rs | src/config/mod.rs | use dashmap::DashMap;
use eyre::{Context, Result, bail, eyre};
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
pub use settings::Settings;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::{Debug, Formatter};
use std::iter::once;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::LazyLock as Lazy;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use tokio::{sync::OnceCell, task::JoinSet};
use walkdir::WalkDir;
use crate::backend::ABackend;
use crate::cli::version;
use crate::config::config_file::idiomatic_version::IdiomaticVersionFile;
use crate::config::config_file::min_version::MinVersionSpec;
use crate::config::config_file::mise_toml::{MiseToml, Tasks};
use crate::config::config_file::{ConfigFile, config_trust_root};
use crate::config::env_directive::{EnvResolveOptions, EnvResults, ToolsFilter};
use crate::config::tracking::Tracker;
use crate::env::{MISE_DEFAULT_CONFIG_FILENAME, MISE_DEFAULT_TOOL_VERSIONS_FILENAME};
use crate::file::display_path;
use crate::shorthands::{Shorthands, get_shorthands};
use crate::task::Task;
use crate::toolset::{ToolRequestSet, ToolRequestSetBuilder, ToolVersion, Toolset, install_state};
use crate::ui::style;
use crate::{backend, dirs, env, file, lockfile, registry, runtime_symlinks, shims, timeout};
pub mod config_file;
pub mod env_directive;
pub mod settings;
pub mod tracking;
use crate::env_diff::EnvMap;
use crate::hook_env::WatchFilePattern;
use crate::hooks::Hook;
use crate::plugins::PluginType;
use crate::tera::BASE_CONTEXT;
use crate::watch_files::WatchFile;
use crate::wildcard::Wildcard;
type AliasMap = IndexMap<String, Alias>;
type ConfigMap = IndexMap<PathBuf, Arc<dyn ConfigFile>>;
pub type EnvWithSources = IndexMap<String, (String, PathBuf)>;
pub struct Config {
pub config_files: ConfigMap,
pub project_root: Option<PathBuf>,
pub all_aliases: AliasMap,
pub repo_urls: HashMap<String, String>,
pub vars: IndexMap<String, String>,
pub tera_ctx: tera::Context,
pub shorthands: Shorthands,
pub shell_aliases: EnvWithSources,
aliases: AliasMap,
env: OnceCell<EnvResults>,
env_with_sources: OnceCell<EnvWithSources>,
hooks: OnceCell<Vec<(PathBuf, Hook)>>,
tasks_cache: Arc<DashMap<crate::task::TaskLoadContext, Arc<BTreeMap<String, Task>>>>,
tool_request_set: OnceCell<ToolRequestSet>,
toolset: OnceCell<Toolset>,
vars_loader: Option<Arc<Config>>,
vars_results: OnceCell<EnvResults>,
}
#[derive(Debug, Clone, Default)]
pub struct Alias {
pub backend: Option<String>,
pub versions: IndexMap<String, String>,
}
static _CONFIG: RwLock<Option<Arc<Config>>> = RwLock::new(None);
static _REDACTIONS: Lazy<Mutex<Arc<IndexSet<String>>>> = Lazy::new(Default::default);
pub fn is_loaded() -> bool {
_CONFIG.read().unwrap().is_some()
}
impl Config {
pub async fn get() -> Result<Arc<Self>> {
if let Some(config) = &*_CONFIG.read().unwrap() {
return Ok(config.clone());
}
measure!("load config", { Self::load().await })
}
pub fn maybe_get() -> Option<Arc<Self>> {
_CONFIG.read().unwrap().as_ref().cloned()
}
pub fn get_() -> Arc<Self> {
(*_CONFIG.read().unwrap()).clone().unwrap()
}
pub async fn reset() -> Result<Arc<Self>> {
backend::reset().await?;
timeout::run_with_timeout_async(
async || {
_CONFIG.write().unwrap().take();
*GLOBAL_CONFIG_FILES.lock().unwrap() = None;
*SYSTEM_CONFIG_FILES.lock().unwrap() = None;
GLOB_RESULTS.lock().unwrap().clear();
Ok(())
},
Duration::from_secs(5),
)
.await?;
Config::load().await
}
#[async_backtrace::framed]
pub async fn load() -> Result<Arc<Self>> {
backend::load_tools().await?;
let idiomatic_files = measure!("config::load idiomatic_files", {
load_idiomatic_files().await
});
let config_filenames = idiomatic_files
.keys()
.chain(DEFAULT_CONFIG_FILENAMES.iter())
.cloned()
.collect_vec();
let config_paths = measure!("config::load config_paths", {
load_config_paths(&config_filenames, false)
});
trace!("config_paths: {config_paths:?}");
let config_files = measure!("config::load config_files", {
load_all_config_files(&config_paths, &idiomatic_files).await?
});
let mut config = Self {
tera_ctx: BASE_CONTEXT.clone(),
config_files,
env: OnceCell::new(),
env_with_sources: OnceCell::new(),
shorthands: get_shorthands(&Settings::get()),
hooks: OnceCell::new(),
tasks_cache: Arc::new(DashMap::new()),
tool_request_set: OnceCell::new(),
toolset: OnceCell::new(),
all_aliases: Default::default(),
aliases: Default::default(),
project_root: Default::default(),
repo_urls: Default::default(),
shell_aliases: Default::default(),
vars: Default::default(),
vars_loader: None,
vars_results: OnceCell::new(),
};
let vars_config = Arc::new(Self {
tera_ctx: config.tera_ctx.clone(),
config_files: config.config_files.clone(),
env: OnceCell::new(),
env_with_sources: OnceCell::new(),
shorthands: config.shorthands.clone(),
hooks: OnceCell::new(),
tasks_cache: Arc::new(DashMap::new()),
tool_request_set: OnceCell::new(),
toolset: OnceCell::new(),
all_aliases: config.all_aliases.clone(),
aliases: config.aliases.clone(),
project_root: config.project_root.clone(),
repo_urls: config.repo_urls.clone(),
shell_aliases: config.shell_aliases.clone(),
vars: config.vars.clone(),
vars_loader: None,
vars_results: OnceCell::new(),
});
let vars_results = measure!("config::load vars_results", {
let results = load_vars(&vars_config).await?;
vars_config.vars_results.set(results.clone()).ok();
config.vars_results.set(results.clone()).ok();
config.vars_loader = Some(vars_config.clone());
results
});
let vars: IndexMap<String, String> = vars_results
.vars
.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect();
config.tera_ctx.insert("vars", &vars);
config.vars = vars;
config.aliases = load_aliases(&config.config_files)?;
config.shell_aliases = load_shell_aliases(&config.config_files)?;
config.project_root = get_project_root(&config.config_files);
config.repo_urls = load_plugins(&config.config_files)?;
measure!("config::load validate", {
config.validate()?;
});
config.all_aliases = measure!("config::load all_aliases", { config.load_all_aliases() });
measure!("config::load redactions", {
config.add_redactions(
config.redaction_keys(),
&config.vars.clone().into_iter().collect(),
);
});
if log::log_enabled!(log::Level::Trace) {
trace!("config: {config:#?}");
} else if log::log_enabled!(log::Level::Debug) {
for p in config.config_files.keys() {
debug!("config: {}", display_path(p));
}
}
time!("load done");
measure!("config::load install_state", {
for (plugin, url) in &config.repo_urls {
// check plugin type, fallback to asdf
let (mut plugin_type, has_explicit_prefix) = match plugin {
p if p.starts_with("vfox:") => (PluginType::Vfox, true),
p if p.starts_with("vfox-backend:") => (PluginType::VfoxBackend, true),
p if p.starts_with("asdf:") => (PluginType::Asdf, true),
_ => (PluginType::Asdf, false),
};
// keep backward compatibility for vfox plugins, but only if no explicit prefix
if !has_explicit_prefix && url.contains("vfox-") {
plugin_type = PluginType::Vfox;
}
let plugin = plugin
.strip_prefix("vfox:")
.or_else(|| plugin.strip_prefix("vfox-backend:"))
.or_else(|| plugin.strip_prefix("asdf:"))
.unwrap_or(plugin);
install_state::add_plugin(plugin, plugin_type).await?;
}
});
measure!("config::load remove_aliased_tools", {
for short in config
.all_aliases
.iter()
.filter(|(_, a)| a.backend.is_some())
.map(|(s, _)| s)
.chain(config.repo_urls.keys())
{
// we need to remove aliased tools so they get re-added with updated "full" values
backend::remove(short);
}
});
let config = Arc::new(config);
*_CONFIG.write().unwrap() = Some(config.clone());
Ok(config)
}
pub fn env_maybe(&self) -> Option<IndexMap<String, String>> {
self.env_with_sources.get().map(|env| {
env.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect()
})
}
pub async fn env(self: &Arc<Self>) -> eyre::Result<IndexMap<String, String>> {
Ok(self
.env_with_sources()
.await?
.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect())
}
pub async fn env_with_sources(self: &Arc<Self>) -> eyre::Result<&EnvWithSources> {
self.env_with_sources
.get_or_try_init(async || {
let mut env = self.env_results().await?.env.clone();
for env_file in Settings::get().env_files() {
match dotenvy::from_path_iter(&env_file) {
Ok(iter) => {
for item in iter {
let (k, v) = item.unwrap_or_else(|err| {
warn!("env_file: {err}");
Default::default()
});
env.insert(k, (v, env_file.clone()));
}
}
Err(err) => trace!("env_file: {err}"),
}
}
Ok(env)
})
.await
}
pub async fn env_results(self: &Arc<Self>) -> Result<&EnvResults> {
self.env
.get_or_try_init(|| async { self.load_env().await })
.await
}
pub async fn vars_results(self: &Arc<Self>) -> Result<&EnvResults> {
if let Some(loader) = &self.vars_loader
&& let Some(results) = loader.vars_results.get()
{
return Ok(results);
}
self.vars_results
.get_or_try_init(|| async move { load_vars(self).await })
.await
}
pub fn vars_results_cached(&self) -> Option<&EnvResults> {
self.vars_results.get()
}
pub async fn path_dirs(self: &Arc<Self>) -> eyre::Result<&Vec<PathBuf>> {
Ok(&self.env_results().await?.env_paths)
}
pub async fn get_tool_request_set(&self) -> eyre::Result<&ToolRequestSet> {
self.tool_request_set
.get_or_try_init(async || ToolRequestSetBuilder::new().build(self).await)
.await
}
pub async fn get_toolset(self: &Arc<Self>) -> Result<&Toolset> {
self.toolset
.get_or_try_init(|| async {
let mut ts = Toolset::from(self.get_tool_request_set().await?.clone());
ts.resolve(self).await?;
Ok(ts)
})
.await
}
pub fn get_repo_url(&self, plugin_name: &str) -> Option<String> {
let plugin_name = self
.all_aliases
.get(plugin_name)
.and_then(|a| a.backend.clone())
.or_else(|| self.repo_urls.get(plugin_name).cloned())
.unwrap_or(plugin_name.to_string());
let plugin_name = plugin_name.strip_prefix("asdf:").unwrap_or(&plugin_name);
let plugin_name = plugin_name.strip_prefix("vfox:").unwrap_or(plugin_name);
if let Some(url) = self
.repo_urls
.keys()
.find(|k| k.ends_with(&format!(":{plugin_name}")))
.and_then(|k| self.repo_urls.get(k))
{
return Some(url.clone());
}
self.shorthands
.get(plugin_name)
.map(|full| registry::full_to_url(&full[0]))
.or_else(|| {
if plugin_name.starts_with("https://") || plugin_name.split('/').count() == 2 {
Some(registry::full_to_url(plugin_name))
} else {
None
}
})
}
pub fn is_monorepo(&self) -> bool {
find_monorepo_root(&self.config_files).is_some()
}
pub async fn tasks(&self) -> Result<Arc<BTreeMap<String, Task>>> {
self.tasks_with_context(None).await
}
pub async fn tasks_with_context(
&self,
ctx: Option<&crate::task::TaskLoadContext>,
) -> Result<Arc<BTreeMap<String, Task>>> {
// Use the entire context as cache key
// Default context (None) becomes TaskLoadContext::default()
let cache_key = ctx.cloned().unwrap_or_default();
// Check if already cached
if let Some(cached) = self.tasks_cache.get(&cache_key) {
return Ok(cached.value().clone());
}
// Not cached, load tasks
let tasks = measure!("config::load_all_tasks_with_context", {
self.load_all_tasks_with_context(ctx).await?
});
let tasks_arc = Arc::new(tasks);
// Insert into cache
self.tasks_cache.insert(cache_key, tasks_arc.clone());
Ok(tasks_arc)
}
pub async fn tasks_with_aliases(&self) -> Result<BTreeMap<String, Task>> {
let tasks = self.tasks().await?;
Ok(tasks
.iter()
.flat_map(|(_, t)| {
t.aliases
.iter()
.map(|a| (a.to_string(), t.clone()))
.chain(once((t.name.clone(), t.clone())))
.collect::<Vec<_>>()
})
.collect())
}
pub async fn resolve_alias(&self, backend: &ABackend, v: &str) -> Result<String> {
if let Some(plugin_aliases) = self.all_aliases.get(&backend.ba().short)
&& let Some(alias) = plugin_aliases.versions.get(v)
{
return Ok(alias.clone());
}
if let Some(alias) = backend.get_aliases()?.get(v) {
return Ok(alias.clone());
}
Ok(v.to_string())
}
fn load_all_aliases(&self) -> AliasMap {
let mut aliases: AliasMap = self.aliases.clone();
let plugin_aliases: Vec<_> = backend::list()
.into_iter()
.map(|backend| {
let aliases = backend.get_aliases().unwrap_or_else(|err| {
warn!("get_aliases: {err}");
BTreeMap::new()
});
(backend.ba().clone(), aliases)
})
.collect();
for (ba, plugin_aliases) in plugin_aliases {
for (from, to) in plugin_aliases {
aliases
.entry(ba.short.to_string())
.or_default()
.versions
.insert(from, to);
}
}
for (short, plugin_aliases) in &self.aliases {
let alias = aliases.entry(short.clone()).or_default();
if let Some(full) = &plugin_aliases.backend {
alias.backend = Some(full.clone());
}
for (from, to) in &plugin_aliases.versions {
alias.versions.insert(from.clone(), to.clone());
}
}
aliases
}
async fn load_all_tasks_with_context(
&self,
ctx: Option<&crate::task::TaskLoadContext>,
) -> Result<BTreeMap<String, Task>> {
let config = Config::get().await?;
time!("load_all_tasks");
let local_tasks = load_local_tasks_with_context(&config, ctx).await?;
let global_tasks = load_global_tasks(&config).await?;
let mut tasks: BTreeMap<String, Task> = local_tasks
.into_iter()
.chain(global_tasks)
.rev()
.inspect(|t| {
trace!(
"loaded task {} – {}",
&t.name,
display_path(&t.config_source)
)
})
.map(|t| (t.name.clone(), t))
.collect();
let all_tasks = tasks.clone();
for task in tasks.values_mut() {
task.display_name = task.display_name(&all_tasks);
}
time!("load_all_tasks {count}", count = tasks.len(),);
Ok(tasks)
}
pub async fn get_tracked_config_files(&self) -> Result<ConfigMap> {
let mut config_files: ConfigMap = ConfigMap::default();
for path in Tracker::list_all()?.into_iter() {
match config_file::parse(&path).await {
Ok(cf) => {
config_files.insert(path, cf);
}
Err(err) => {
error!("Error loading config file: {:?}", err);
}
}
}
Ok(config_files)
}
pub fn global_config(&self) -> Result<MiseToml> {
let settings_path = global_config_path();
match settings_path.exists() {
false => {
trace!("settings does not exist {:?}", settings_path);
Ok(MiseToml::init(&settings_path))
}
true => MiseToml::from_file(&settings_path)
.wrap_err_with(|| eyre!("Error parsing {}", display_path(&settings_path))),
}
}
fn validate(&self) -> eyre::Result<()> {
self.validate_versions()?;
Ok(())
}
fn validate_versions(&self) -> eyre::Result<()> {
for cf in self.config_files.values() {
if let Some(spec) = cf.min_version() {
Self::enforce_min_version_spec(spec)?;
}
}
Ok(())
}
pub fn enforce_min_version_spec(spec: &MinVersionSpec) -> eyre::Result<()> {
let cur = &*version::V;
if let Some(required) = spec.hard_violation(cur) {
let min = style::eyellow(required);
let cur = style::eyellow(cur);
let msg = format!("mise version {min} is required, but you are using {cur}");
bail!(crate::cli::self_update::append_self_update_instructions(
msg
));
} else if let Some(recommended) = spec.soft_violation(cur) {
let min = style::eyellow(recommended);
let cur = style::eyellow(cur);
let msg = format!("mise version {min} is recommended, but you are using {cur}");
warn!(
"{}",
crate::cli::self_update::append_self_update_instructions(msg)
);
}
Ok(())
}
async fn load_env(self: &Arc<Self>) -> Result<EnvResults> {
time!("load_env start");
let entries = self
.config_files
.iter()
.rev()
.map(|(source, cf)| {
cf.env_entries()
.map(|ee| ee.into_iter().map(|e| (e, source.clone())))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect();
// trace!("load_env: entries: {:#?}", entries);
let env_results = EnvResults::resolve(
self,
self.tera_ctx.clone(),
&env::PRISTINE_ENV,
entries,
EnvResolveOptions {
vars: false,
tools: ToolsFilter::NonToolsOnly,
warn_on_missing_required: *env::WARN_ON_MISSING_REQUIRED_ENV,
},
)
.await?;
let redact_keys = self
.redaction_keys()
.into_iter()
.chain(env_results.redactions.clone())
.collect_vec();
self.add_redactions(
redact_keys,
&env_results
.env
.iter()
.map(|(k, v)| (k.clone(), v.0.clone()))
.collect(),
);
if log::log_enabled!(log::Level::Trace) {
trace!("{env_results:#?}");
} else if !env_results.is_empty() {
debug!("{env_results:?}");
}
Ok(env_results)
}
pub async fn hooks(&self) -> Result<&Vec<(PathBuf, Hook)>> {
self.hooks
.get_or_try_init(|| async {
self.config_files
.values()
.map(|cf| Ok((cf.project_root(), cf.hooks()?)))
.filter_map_ok(|(root, hooks)| root.map(|r| (r.to_path_buf(), hooks)))
.map_ok(|(root, hooks)| {
hooks
.into_iter()
.map(|h| (root.clone(), h))
.collect::<Vec<_>>()
})
.flatten_ok()
.collect()
})
.await
}
pub fn watch_file_hooks(&self) -> Result<IndexSet<(PathBuf, WatchFile)>> {
Ok(self
.config_files
.values()
.map(|cf| Ok((cf.project_root(), cf.watch_files()?)))
.collect::<Result<Vec<_>>>()?
.into_iter()
.filter_map(|(root, watch_files)| root.map(|r| (r.to_path_buf(), watch_files)))
.flat_map(|(root, watch_files)| {
watch_files
.iter()
.map(|wf| (root.clone(), wf.clone()))
.collect::<Vec<_>>()
})
.collect())
}
pub async fn watch_files(self: &Arc<Self>) -> Result<BTreeSet<WatchFilePattern>> {
let env_results = self.env_results().await?;
Ok(self
.config_files
.iter()
.map(|(p, cf)| {
let mut watch_files: Vec<WatchFilePattern> = vec![p.as_path().into()];
if let Some(parent) = p.parent() {
watch_files.push(parent.join("mise.lock").into());
}
watch_files.extend(cf.watch_files()?.iter().map(|wf| WatchFilePattern {
root: cf.project_root().map(|pr| pr.to_path_buf()),
patterns: wf.patterns.clone(),
}));
Ok(watch_files)
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.chain(env_results.env_files.iter().map(|p| p.as_path().into()))
.chain(env_results.env_scripts.iter().map(|p| p.as_path().into()))
.chain(
Settings::get()
.env_files()
.iter()
.map(|p| p.as_path().into()),
)
.collect())
}
pub fn redaction_keys(&self) -> Vec<String> {
self.config_files
.values()
.flat_map(|cf| cf.redactions().0.iter())
.cloned()
.collect()
}
pub fn add_redactions(&self, redactions: impl IntoIterator<Item = String>, env: &EnvMap) {
let mut r = _REDACTIONS.lock().unwrap();
let redactions = redactions.into_iter().flat_map(|r| {
let matcher = Wildcard::new(vec![r]);
env.iter()
.filter(|(k, _)| matcher.match_any(k))
.map(|(_, v)| v.clone())
.collect::<Vec<_>>()
});
*r = Arc::new(r.iter().cloned().chain(redactions).collect());
}
pub fn redactions(&self) -> Arc<IndexSet<String>> {
let r = _REDACTIONS.lock().unwrap();
r.deref().clone()
// self.redactions.get_or_try_init(|| {
// let mut redactions = Redactions::default();
// for cf in self.config_files.values() {
// let r = cf.redactions();
// if !r.is_empty() {
// let mut r = r.clone();
// let (tera, ctx) = self.tera(&cf.config_root());
// r.render(&mut tera.clone(), &ctx)?;
// redactions.merge(r);
// }
// }
// if redactions.is_empty() {
// return Ok(Default::default());
// }
//
// let ts = self.get_toolset()?;
// let env = ts.full_env()?;
//
// let env_matcher = Wildcard::new(redactions.env.clone());
// let var_matcher = Wildcard::new(redactions.vars.clone());
//
// let env_vals = env
// .into_iter()
// .filter(|(k, _)| env_matcher.match_any(k))
// .map(|(_, v)| v);
// let var_vals = self
// .vars
// .iter()
// .filter(|(k, _)| var_matcher.match_any(k))
// .map(|(_, v)| v.to_string());
// Ok(env_vals.chain(var_vals).collect())
// })
}
pub fn redact(&self, mut input: String) -> String {
for redaction in self.redactions().deref() {
input = input.replace(redaction, "[redacted]");
}
input
}
}
fn configs_at_root<'a>(dir: &Path, config_files: &'a ConfigMap) -> Vec<&'a Arc<dyn ConfigFile>> {
let mut configs: Vec<&'a Arc<dyn ConfigFile>> = DEFAULT_CONFIG_FILENAMES
.iter()
.rev()
.flat_map(|f| {
if f.contains('*') {
// Handle glob patterns by matching against actual config file paths
glob(dir, f)
.unwrap_or_default()
.into_iter()
.filter_map(|path| config_files.get(&path))
.collect::<Vec<_>>()
} else {
// Handle regular filenames
config_files
.get(&dir.join(f))
.into_iter()
.collect::<Vec<_>>()
}
})
.collect();
// Remove duplicates while preserving order
let mut seen = std::collections::HashSet::new();
configs.retain(|cf| seen.insert(cf.get_path().to_path_buf()));
configs
}
fn get_project_root(config_files: &ConfigMap) -> Option<PathBuf> {
let project_root = config_files
.values()
.find_map(|cf| cf.project_root())
.map(|pr| pr.to_path_buf());
trace!("project_root: {project_root:?}");
project_root
}
fn find_monorepo_root(config_files: &ConfigMap) -> Option<PathBuf> {
// Find the config file that has experimental_monorepo_root = true
// This feature requires experimental mode
if !Settings::get().experimental {
return None;
}
config_files
.values()
.find(|cf| cf.experimental_monorepo_root() == Some(true))
.and_then(|cf| cf.project_root().map(|p| p.to_path_buf()))
}
async fn load_idiomatic_files() -> BTreeMap<String, Vec<String>> {
let enable_tools = Settings::get().idiomatic_version_file_enable_tools.clone();
if enable_tools.is_empty() {
return BTreeMap::new();
}
if !Settings::get()
.idiomatic_version_file_disable_tools
.is_empty()
{
deprecated!(
"idiomatic_version_file_disable_tools",
"is deprecated, use idiomatic_version_file_enable_tools instead"
);
}
let mut jset = JoinSet::new();
for tool in backend::list() {
let enable_tools = enable_tools.clone();
jset.spawn(async move {
if !enable_tools.contains(tool.id()) {
return vec![];
}
match tool.idiomatic_filenames().await {
Ok(filenames) => filenames
.iter()
.map(|f| (f.to_string(), tool.id().to_string()))
.collect::<Vec<_>>(),
Err(err) => {
eprintln!("Error: {err}");
vec![]
}
}
});
}
let idiomatic = jset
.join_all()
.await
.into_iter()
.flatten()
.collect::<Vec<_>>();
let mut idiomatic_filenames = BTreeMap::new();
for (filename, plugin) in idiomatic {
idiomatic_filenames
.entry(filename)
.or_insert_with(Vec::new)
.push(plugin);
}
idiomatic_filenames
}
static LOCAL_CONFIG_FILENAMES: Lazy<IndexSet<&'static str>> = Lazy::new(|| {
let mut paths: IndexSet<&'static str> = IndexSet::new();
if let Some(o) = &*env::MISE_OVERRIDE_TOOL_VERSIONS_FILENAMES {
paths.extend(o.iter().map(|s| s.as_str()));
} else {
paths.extend([
".tool-versions",
&*env::MISE_DEFAULT_TOOL_VERSIONS_FILENAME, // .tool-versions
]);
}
if !env::MISE_OVERRIDE_CONFIG_FILENAMES.is_empty() {
paths.extend(
env::MISE_OVERRIDE_CONFIG_FILENAMES
.iter()
.map(|s| s.as_str()),
)
} else {
paths.extend([
".config/mise/conf.d/*.toml",
".config/mise/config.toml",
".config/mise/mise.toml",
".config/mise.toml",
".mise/config.toml",
"mise/config.toml",
".rtx.toml",
"mise.toml",
&*env::MISE_DEFAULT_CONFIG_FILENAME, // mise.toml
".mise.toml",
".config/mise/config.local.toml",
".config/mise/mise.local.toml",
".config/mise.local.toml",
".mise/config.local.toml",
"mise/config.local.toml",
".rtx.local.toml",
"mise.local.toml",
".mise.local.toml",
]);
}
paths
});
pub static DEFAULT_CONFIG_FILENAMES: Lazy<Vec<String>> = Lazy::new(|| {
let mut filenames = LOCAL_CONFIG_FILENAMES
.iter()
.map(|f| f.to_string())
.collect_vec();
for env in &*env::MISE_ENV {
filenames.push(format!(".config/mise/config.{env}.toml"));
filenames.push(format!(".config/mise.{env}.toml"));
filenames.push(format!("mise/config.{env}.toml"));
filenames.push(format!("mise.{env}.toml"));
filenames.push(format!(".mise/config.{env}.toml"));
filenames.push(format!(".mise.{env}.toml"));
filenames.push(format!(".config/mise/config.{env}.local.toml"));
filenames.push(format!(".config/mise.{env}.local.toml"));
filenames.push(format!("mise/config.{env}.local.toml"));
filenames.push(format!("mise.{env}.local.toml"));
filenames.push(format!(".mise/config.{env}.local.toml"));
filenames.push(format!(".mise.{env}.local.toml"));
}
filenames
});
static TOML_CONFIG_FILENAMES: Lazy<Vec<String>> = Lazy::new(|| {
DEFAULT_CONFIG_FILENAMES
.iter()
.filter(|s| s.ends_with(".toml"))
.map(|s| s.to_string())
.collect()
});
pub static ALL_CONFIG_FILES: Lazy<IndexSet<PathBuf>> = Lazy::new(|| {
load_config_paths(&DEFAULT_CONFIG_FILENAMES, false)
.into_iter()
.collect()
});
pub static IGNORED_CONFIG_FILES: Lazy<IndexSet<PathBuf>> = Lazy::new(|| {
load_config_paths(&DEFAULT_CONFIG_FILENAMES, true)
.into_iter()
.filter(|p| config_file::is_ignored(&config_trust_root(p)) || config_file::is_ignored(p))
.collect()
});
// pub static LOCAL_CONFIG_FILES: Lazy<Vec<PathBuf>> = Lazy::new(|| {
// ALL_CONFIG_FILES
// .iter()
// .filter(|cf| !is_global_config(cf))
// .cloned()
// .collect()
// });
type GlobResults = HashMap<(PathBuf, String), Vec<PathBuf>>;
static GLOB_RESULTS: Lazy<Mutex<GlobResults>> = Lazy::new(Default::default);
pub fn glob(dir: &Path, pattern: &str) -> Result<Vec<PathBuf>> {
let mut results = GLOB_RESULTS.lock().unwrap();
let key = (dir.to_path_buf(), pattern.to_string());
if let Some(glob) = results.get(&key) {
return Ok(glob.clone());
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/tracking.rs | src/config/tracking.rs | use std::fs;
use std::fs::{read_dir, remove_file};
use std::path::{Path, PathBuf};
use eyre::Result;
use crate::dirs::TRACKED_CONFIGS;
use crate::file::{create_dir_all, make_symlink_or_file};
use crate::hash::hash_to_str;
pub struct Tracker {}
impl Tracker {
pub fn track(path: &Path) -> Result<()> {
let tracking_path = TRACKED_CONFIGS.join(hash_to_str(&path));
if !tracking_path.exists() {
create_dir_all(&*TRACKED_CONFIGS)?;
make_symlink_or_file(path, &tracking_path)?;
}
Ok(())
}
pub fn list_all() -> Result<Vec<PathBuf>> {
let mut output = vec![];
if !TRACKED_CONFIGS.exists() {
return Ok(output);
}
for path in read_dir(&*TRACKED_CONFIGS)? {
let mut path = path?.path();
if path.is_symlink() {
path = fs::read_link(path)?;
} else if cfg!(target_os = "windows") {
path = PathBuf::from(fs::read_to_string(&path)?.trim());
} else {
continue;
}
if path.exists() {
output.push(path);
}
}
Ok(output)
}
pub fn clean() -> Result<()> {
if TRACKED_CONFIGS.is_dir() {
for path in read_dir(&*TRACKED_CONFIGS)? {
let path = path?.path();
if !path.exists() {
remove_file(&path)?;
}
}
}
Ok(())
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/venv.rs | src/config/env_directive/venv.rs | use crate::Result;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::config_file::trust_check;
use crate::config::env_directive::EnvResults;
use crate::config::{Config, Settings};
use crate::env_diff::EnvMap;
use crate::file::{display_path, which_non_pristine};
use crate::lock_file::LockFile;
use crate::toolset::ToolsetBuilder;
use crate::{backend, plugins};
use indexmap::IndexMap;
use std::{
path::{Path, PathBuf},
sync::Arc,
};
impl EnvResults {
#[allow(clippy::too_many_arguments)]
pub async fn venv(
config: &Arc<Config>,
ctx: &mut tera::Context,
tera: &mut tera::Tera,
env: &mut IndexMap<String, (String, Option<PathBuf>)>,
r: &mut EnvResults,
normalize_path: fn(&Path, PathBuf) -> PathBuf,
source: &Path,
config_root: &Path,
env_vars: EnvMap,
path: String,
create: bool,
python: Option<String>,
uv_create_args: Option<Vec<String>>,
python_create_args: Option<Vec<String>>,
) -> Result<()> {
trace!("python venv: {} create={create}", display_path(&path));
trust_check(source)?;
let venv = r.parse_template(ctx, tera, source, &path)?;
let venv = normalize_path(config_root, venv.into());
let venv_lock = LockFile::new(&venv).lock()?;
if !venv.exists() && create {
// TODO: the toolset stuff doesn't feel like it's in the right place here
// TODO: in fact this should probably be moved to execute at the same time as src/uv.rs runs in ts.env() instead of config.env()
let ts = Box::pin(ToolsetBuilder::new().build(config)).await?;
let ba = BackendArg::from("python");
let tv = ts.versions.get(&ba).and_then(|tv| {
// if a python version is specified, check if that version is installed
// otherwise use the first since that's what `python3` will refer to
if let Some(v) = &python {
tv.versions.iter().find(|t| t.version.starts_with(v))
} else {
tv.versions.first()
}
});
let python_path = tv.map(|tv| {
plugins::core::python::python_path(tv)
.to_string_lossy()
.to_string()
});
let installed = if let Some(tv) = tv {
let backend = backend::get(&ba).unwrap();
backend.is_version_installed(config, tv, false)
} else {
// if no version is specified, we're assuming python3 is provided outside of mise so return "true" here
true
};
if !installed {
warn!(
"no venv found at: {p}\n\n\
mise will automatically create the venv once all requested python versions are installed.\n\
To install the missing python versions and create the venv, please run:\n\
mise install",
p = display_path(&venv)
);
} else {
let uv_bin = ts
.which_bin(config, "uv")
.await
.or_else(|| which_non_pristine("uv"));
let use_uv = !Settings::get().python.venv_stdlib && uv_bin.is_some();
let cmd = if use_uv {
info!("creating venv with uv at: {}", display_path(&venv));
let extra = Settings::get()
.python
.uv_venv_create_args
.clone()
.or(uv_create_args)
.unwrap_or_default();
let mut cmd =
CmdLineRunner::new(uv_bin.unwrap()).args(["venv", &venv.to_string_lossy()]);
cmd = match (python_path, python) {
// The selected mise managed python tool path from env._.python.venv.python or first in list
(Some(python_path), _) => cmd.args(["--python", &python_path]),
// User specified in env._.python.venv.python but it's not in mise tools, so pass version number to uv
(_, Some(python)) => cmd.args(["--python", &python]),
// Default to whatever uv wants to use
_ => cmd,
};
cmd.args(extra)
} else {
info!("creating venv with stdlib at: {}", display_path(&venv));
let extra = Settings::get()
.python
.venv_create_args
.clone()
.or(python_create_args)
.unwrap_or_default();
let bin = match (python_path, python) {
// The selected mise managed python tool path from env._.python.venv.python or first in list
(Some(python_path), _) => python_path,
// User specified in env._.python.venv.python but it's not in mise tools, so try to find it on path
(_, Some(python)) => format!("python{python}"),
// Default to whatever python3 points to on path
_ => "python3".to_string(),
};
CmdLineRunner::new(bin)
.args(["-m", "venv", &venv.to_string_lossy()])
.args(extra)
}
.envs(env_vars);
cmd.execute()?;
}
}
drop(venv_lock);
if venv.exists() {
r.env_paths
.insert(0, venv.join(if cfg!(windows) { "Scripts" } else { "bin" }));
env.insert(
"VIRTUAL_ENV".into(),
(
venv.to_string_lossy().to_string(),
Some(source.to_path_buf()),
),
);
} else if !create {
// The create "no venv found" warning is handled elsewhere
warn!(
"no venv found at: {p}
To create a virtualenv manually, run:
python -m venv {p}",
p = display_path(&venv)
);
}
Ok(())
}
}
#[cfg(test)]
#[cfg(unix)]
mod tests {
use super::*;
use crate::config::env_directive::{
EnvDirective, EnvDirectiveOptions, EnvResolveOptions, ToolsFilter,
};
use crate::tera::BASE_CONTEXT;
use crate::test::replace_path;
use insta::assert_debug_snapshot;
#[tokio::test]
async fn test_venv_path() {
let env = EnvMap::new();
let config = Config::get().await.unwrap();
let results = EnvResults::resolve(
&config,
BASE_CONTEXT.clone(),
&env,
vec![
(
EnvDirective::PythonVenv {
path: "/".into(),
create: false,
python: None,
uv_create_args: None,
python_create_args: None,
options: EnvDirectiveOptions {
tools: true,
redact: Some(false),
required: crate::config::env_directive::RequiredValue::False,
},
},
Default::default(),
),
(
EnvDirective::PythonVenv {
path: "./".into(),
create: false,
python: None,
uv_create_args: None,
python_create_args: None,
options: EnvDirectiveOptions {
tools: true,
redact: Some(false),
required: crate::config::env_directive::RequiredValue::False,
},
},
Default::default(),
),
],
EnvResolveOptions {
vars: false,
tools: ToolsFilter::ToolsOnly,
warn_on_missing_required: false,
},
)
.await
.unwrap();
// expect order to be reversed as it processes directives from global to dir specific
assert_debug_snapshot!(
results.env_paths.into_iter().map(|p| replace_path(&p.display().to_string())).collect::<Vec<_>>(),
@r#"
[
"~/bin",
]
"#
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/path.rs | src/config/env_directive/path.rs | use crate::config::env_directive::EnvResults;
use crate::result;
use std::path::{Path, PathBuf};
impl EnvResults {
pub async fn path(
ctx: &mut tera::Context,
tera: &mut tera::Tera,
r: &mut EnvResults,
source: &Path,
input: String,
) -> result::Result<PathBuf> {
r.parse_template(ctx, tera, source, &input)
.map(PathBuf::from)
}
}
#[cfg(test)]
#[cfg(unix)]
mod tests {
use super::*;
use crate::config::{
Config,
env_directive::{EnvDirective, EnvResolveOptions, ToolsFilter},
};
use crate::env_diff::EnvMap;
use crate::tera::BASE_CONTEXT;
use crate::test::replace_path;
use insta::assert_debug_snapshot;
#[tokio::test]
async fn test_env_path() {
let mut env = EnvMap::new();
env.insert("A".to_string(), "1".to_string());
env.insert("B".to_string(), "2".to_string());
let config = Config::get().await.unwrap();
let results = EnvResults::resolve(
&config,
BASE_CONTEXT.clone(),
&env,
vec![
(
EnvDirective::Path("/path/1".into(), Default::default()),
PathBuf::from("/config"),
),
(
EnvDirective::Path("/path/2".into(), Default::default()),
PathBuf::from("/config"),
),
(
EnvDirective::Path("~/foo/{{ env.A }}".into(), Default::default()),
Default::default(),
),
(
EnvDirective::Path(
"./rel/{{ env.A }}:./rel2/{{env.B}}".into(),
Default::default(),
),
Default::default(),
),
],
EnvResolveOptions {
vars: false,
tools: ToolsFilter::NonToolsOnly,
warn_on_missing_required: false,
},
)
.await
.unwrap();
assert_debug_snapshot!(
results.env_paths.into_iter().map(|p| replace_path(&p.display().to_string())).collect::<Vec<_>>(),
@r#"
[
"~/foo/1",
"~/rel2/2",
"~/rel/1",
"/path/1",
"/path/2",
]
"#
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/source.rs | src/config/env_directive/source.rs | use crate::Result;
use crate::config::env_directive::EnvResults;
use crate::env;
use crate::env_diff::{EnvDiff, EnvDiffOperation, EnvDiffOptions, EnvMap};
use indexmap::IndexMap;
use std::path::{Path, PathBuf};
impl EnvResults {
#[allow(clippy::too_many_arguments)]
pub fn source(
ctx: &mut tera::Context,
tera: &mut tera::Tera,
paths: &mut Vec<(PathBuf, PathBuf)>,
r: &mut EnvResults,
normalize_path: fn(&Path, PathBuf) -> PathBuf,
source: &Path,
config_root: &Path,
env_vars: &EnvMap,
input: String,
) -> Result<IndexMap<PathBuf, IndexMap<String, String>>> {
let mut out = IndexMap::new();
let s = r.parse_template(ctx, tera, source, &input)?;
let orig_path = env_vars.get(&*env::PATH_KEY).cloned().unwrap_or_default();
let mut env_diff_opts = EnvDiffOptions::default();
env_diff_opts.ignore_keys.shift_remove(&*env::PATH_KEY); // allow modifying PATH
for p in xx::file::glob(normalize_path(config_root, s.into())).unwrap_or_default() {
if !p.exists() {
continue;
}
let env = out.entry(p.clone()).or_insert_with(IndexMap::new);
let env_diff =
EnvDiff::from_bash_script(&p, config_root, env_vars.clone(), &env_diff_opts)?;
for p in env_diff.to_patches() {
match p {
EnvDiffOperation::Add(k, v) | EnvDiffOperation::Change(k, v) => {
if k == *env::PATH_KEY {
// TODO: perhaps deal with path removals as well
if let Some(new_path) = v.strip_suffix(&orig_path) {
for p in env::split_paths(new_path) {
paths.push((p, source.to_path_buf()));
}
}
} else {
r.env_remove.remove(&k);
env.insert(k.clone(), v.clone());
}
}
EnvDiffOperation::Remove(k) => {
env.shift_remove(&k);
r.env_remove.insert(k);
}
}
}
}
Ok(out)
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/module.rs | src/config/env_directive/module.rs | use crate::Result;
use crate::config::env_directive::EnvResults;
use crate::dirs;
use crate::plugins::vfox_plugin::VfoxPlugin;
use heck::ToKebabCase;
use std::path::PathBuf;
use toml::Value;
impl EnvResults {
pub async fn module(
r: &mut EnvResults,
source: PathBuf,
name: String,
value: &Value,
redact: bool,
) -> Result<()> {
let path = dirs::PLUGINS.join(name.to_kebab_case());
let plugin = VfoxPlugin::new(name, path);
if let Some(env) = plugin.mise_env(value).await? {
for (k, v) in env {
if redact {
r.redactions.push(k.clone());
}
r.env.insert(k, (v, source.clone()));
}
}
if let Some(path) = plugin.mise_path(value).await? {
for p in path {
r.env_paths.push(p.into());
}
}
Ok(())
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/file.rs | src/config/env_directive/file.rs | use crate::config::{Config, env_directive::EnvResults};
use crate::file::display_path;
use crate::{Result, file, sops};
use eyre::{WrapErr, bail, eyre};
use indexmap::IndexMap;
use rops::file::format::{JsonFileFormat, YamlFileFormat};
use std::{
path::{Path, PathBuf},
sync::Arc,
};
// use indexmap so source is after value for `mise env --json` output
type EnvMap = IndexMap<String, String>;
#[derive(serde::Serialize, serde::Deserialize)]
struct Env<V> {
#[serde(default = "IndexMap::new")]
sops: IndexMap<String, V>,
#[serde(flatten)]
env: IndexMap<String, V>,
}
impl EnvResults {
#[allow(clippy::too_many_arguments)]
pub async fn file(
config: &Arc<Config>,
ctx: &mut tera::Context,
tera: &mut tera::Tera,
r: &mut EnvResults,
normalize_path: fn(&Path, PathBuf) -> PathBuf,
source: &Path,
config_root: &Path,
input: String,
) -> Result<IndexMap<PathBuf, EnvMap>> {
let mut out = IndexMap::new();
let s = r.parse_template(ctx, tera, source, &input)?;
for p in xx::file::glob(normalize_path(config_root, s.into())).unwrap_or_default() {
let env = out.entry(p.clone()).or_insert_with(IndexMap::new);
let parse_template = |s: String| r.parse_template(ctx, tera, source, &s);
let ext = p
.extension()
.map(|e| e.to_string_lossy().to_string())
.unwrap_or_default();
*env = match ext.as_str() {
"json" => Self::json(config, &p, parse_template).await?,
"yaml" => Self::yaml(config, &p, parse_template).await?,
"toml" => Self::toml(&p).await?,
_ => Self::dotenv(&p).await?,
};
}
Ok(out)
}
async fn json<PT>(config: &Arc<Config>, p: &Path, parse_template: PT) -> Result<EnvMap>
where
PT: FnMut(String) -> Result<String>,
{
let errfn = || eyre!("failed to parse json file: {}", display_path(p));
if let Ok(raw) = file::read_to_string(p) {
let mut f: Env<serde_json::Value> = serde_json::from_str(&raw).wrap_err_with(errfn)?;
if !f.sops.is_empty() {
let decrypted =
sops::decrypt::<_, JsonFileFormat>(config, &raw, parse_template, "json")
.await?;
if !decrypted.is_empty() {
f = serde_json::from_str(&decrypted).wrap_err_with(errfn)?;
} else {
return Ok(EnvMap::new());
}
}
f.env
.into_iter()
.map(|(k, v)| {
Ok((
k,
match v {
serde_json::Value::String(s) => s,
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::Bool(b) => b.to_string(),
_ => bail!("unsupported json value: {v:?}"),
},
))
})
.collect()
} else {
Ok(EnvMap::new())
}
}
async fn yaml<PT>(config: &Arc<Config>, p: &Path, parse_template: PT) -> Result<EnvMap>
where
PT: FnMut(String) -> Result<String>,
{
let errfn = || eyre!("failed to parse yaml file: {}", display_path(p));
if let Ok(raw) = file::read_to_string(p) {
let mut f: Env<serde_yaml::Value> = serde_yaml::from_str(&raw).wrap_err_with(errfn)?;
if !f.sops.is_empty() {
let decrypted =
sops::decrypt::<_, YamlFileFormat>(config, &raw, parse_template, "yaml")
.await?;
if !decrypted.is_empty() {
f = serde_yaml::from_str(&decrypted).wrap_err_with(errfn)?;
} else {
return Ok(EnvMap::new());
}
}
f.env
.into_iter()
.map(|(k, v)| {
Ok((
k,
match v {
serde_yaml::Value::String(s) => s,
serde_yaml::Value::Number(n) => n.to_string(),
serde_yaml::Value::Bool(b) => b.to_string(),
_ => bail!("unsupported yaml value: {v:?}"),
},
))
})
.collect()
} else {
Ok(EnvMap::new())
}
}
async fn toml(p: &Path) -> Result<EnvMap> {
let errfn = || eyre!("failed to parse toml file: {}", display_path(p));
// sops does not support toml yet, so no need to parse sops
if let Ok(raw) = file::read_to_string(p) {
toml::from_str::<Env<toml::Value>>(&raw)
.wrap_err_with(errfn)?
.env
.into_iter()
.map(|(k, v)| {
Ok((
k,
match v {
toml::Value::String(s) => s,
toml::Value::Integer(n) => n.to_string(),
toml::Value::Boolean(b) => b.to_string(),
_ => bail!("unsupported toml value: {v:?}"),
},
))
})
.collect()
} else {
Ok(EnvMap::new())
}
}
async fn dotenv(p: &Path) -> Result<EnvMap> {
let errfn = || eyre!("failed to parse dotenv file: {}", display_path(p));
let mut env = EnvMap::new();
if let Ok(dotenv) = dotenvy::from_path_iter(p) {
for item in dotenv {
let (k, v) = item.wrap_err_with(errfn)?;
env.insert(k, v);
}
}
Ok(env)
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/env_directive/mod.rs | src/config/env_directive/mod.rs | use crate::config::config_file::trust_check;
use crate::dirs;
use crate::env;
use crate::env_diff::EnvMap;
use crate::file::display_path;
use crate::tera::{get_tera, tera_exec};
use eyre::{Context, eyre};
use indexmap::IndexMap;
use itertools::Itertools;
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::fmt::{Debug, Display, Formatter};
use std::path::{Path, PathBuf};
use std::{cmp::PartialEq, sync::Arc};
use super::{Config, Settings};
mod file;
mod module;
mod path;
mod source;
mod venv;
#[derive(Debug, Clone, Default, PartialEq)]
pub enum RequiredValue {
#[default]
False,
True,
Help(String),
}
impl RequiredValue {
pub fn is_required(&self) -> bool {
!matches!(self, RequiredValue::False)
}
pub fn help_text(&self) -> Option<&str> {
match self {
RequiredValue::Help(text) => Some(text.as_str()),
_ => None,
}
}
}
impl<'de> serde::Deserialize<'de> for RequiredValue {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, Visitor};
use std::fmt;
struct RequiredVisitor;
impl<'de> Visitor<'de> for RequiredVisitor {
type Value = RequiredValue;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a boolean or a string")
}
fn visit_bool<E>(self, value: bool) -> Result<RequiredValue, E>
where
E: de::Error,
{
Ok(if value {
RequiredValue::True
} else {
RequiredValue::False
})
}
fn visit_str<E>(self, value: &str) -> Result<RequiredValue, E>
where
E: de::Error,
{
Ok(RequiredValue::Help(value.to_string()))
}
fn visit_string<E>(self, value: String) -> Result<RequiredValue, E>
where
E: de::Error,
{
Ok(RequiredValue::Help(value))
}
}
deserializer.deserialize_any(RequiredVisitor)
}
}
impl serde::Serialize for RequiredValue {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
RequiredValue::False => serializer.serialize_bool(false),
RequiredValue::True => serializer.serialize_bool(true),
RequiredValue::Help(text) => serializer.serialize_str(text),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct EnvDirectiveOptions {
#[serde(default)]
pub(crate) tools: bool,
#[serde(default)]
pub(crate) redact: Option<bool>,
#[serde(default)]
pub(crate) required: RequiredValue,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum EnvDirective {
/// simple key/value pair
Val(String, String, EnvDirectiveOptions),
/// remove a key
Rm(String, EnvDirectiveOptions),
/// Required variable that must be defined elsewhere
Required(String, EnvDirectiveOptions),
/// dotenv file
File(String, EnvDirectiveOptions),
/// add a path to the PATH
Path(String, EnvDirectiveOptions),
/// run a bash script and apply the resulting env diff
Source(String, EnvDirectiveOptions),
/// [experimental] age-encrypted value
Age {
key: String,
value: String,
format: Option<AgeFormat>,
options: EnvDirectiveOptions,
},
PythonVenv {
path: String,
create: bool,
python: Option<String>,
uv_create_args: Option<Vec<String>>,
python_create_args: Option<Vec<String>>,
options: EnvDirectiveOptions,
},
Module(String, toml::Value, EnvDirectiveOptions),
}
impl EnvDirective {
pub fn options(&self) -> &EnvDirectiveOptions {
match self {
EnvDirective::Val(_, _, opts)
| EnvDirective::Rm(_, opts)
| EnvDirective::Required(_, opts)
| EnvDirective::File(_, opts)
| EnvDirective::Path(_, opts)
| EnvDirective::Source(_, opts)
| EnvDirective::Age { options: opts, .. }
| EnvDirective::PythonVenv { options: opts, .. }
| EnvDirective::Module(_, _, opts) => opts,
}
}
}
impl From<(String, String)> for EnvDirective {
fn from((k, v): (String, String)) -> Self {
Self::Val(k, v, Default::default())
}
}
impl From<(String, i64)> for EnvDirective {
fn from((k, v): (String, i64)) -> Self {
(k, v.to_string()).into()
}
}
impl Display for EnvDirective {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EnvDirective::Val(k, v, _) => write!(f, "{k}={v}"),
EnvDirective::Rm(k, _) => write!(f, "unset {k}"),
EnvDirective::Required(k, _) => write!(f, "{k} (required)"),
EnvDirective::File(path, _) => write!(f, "_.file = \"{}\"", display_path(path)),
EnvDirective::Path(path, _) => write!(f, "_.path = \"{}\"", display_path(path)),
EnvDirective::Source(path, _) => write!(f, "_.source = \"{}\"", display_path(path)),
EnvDirective::Age { key, format, .. } => {
write!(f, "{key} (age-encrypted")?;
if let Some(fmt) = format {
let fmt_str = match fmt {
AgeFormat::Zstd => "zstd",
AgeFormat::Raw => "raw",
};
write!(f, ", {fmt_str}")?;
}
write!(f, ")")
}
EnvDirective::Module(name, _, _) => write!(f, "module {name}"),
EnvDirective::PythonVenv {
path,
create,
python,
uv_create_args,
python_create_args,
..
} => {
write!(f, "python venv path={}", display_path(path))?;
if *create {
write!(f, " create")?;
}
if let Some(python) = python {
write!(f, " python={python}")?;
}
if let Some(args) = uv_create_args {
write!(f, " uv_create_args={args:?}")?;
}
if let Some(args) = python_create_args {
write!(f, " python_create_args={args:?}")?;
}
Ok(())
}
}
}
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub enum AgeFormat {
#[serde(rename = "zstd")]
Zstd,
#[serde(rename = "raw")]
#[default]
Raw,
}
#[derive(Default, Clone)]
pub struct EnvResults {
pub env: IndexMap<String, (String, PathBuf)>,
pub vars: IndexMap<String, (String, PathBuf)>,
pub env_remove: BTreeSet<String>,
pub env_files: Vec<PathBuf>,
pub env_paths: Vec<PathBuf>,
pub env_scripts: Vec<PathBuf>,
pub redactions: Vec<String>,
pub tool_add_paths: Vec<PathBuf>,
}
#[derive(Debug, Clone, Default)]
pub enum ToolsFilter {
ToolsOnly,
#[default]
NonToolsOnly,
Both,
}
pub struct EnvResolveOptions {
pub vars: bool,
pub tools: ToolsFilter,
pub warn_on_missing_required: bool,
}
impl EnvResults {
pub async fn resolve(
config: &Arc<Config>,
mut ctx: tera::Context,
initial: &EnvMap,
input: Vec<(EnvDirective, PathBuf)>,
resolve_opts: EnvResolveOptions,
) -> eyre::Result<Self> {
// trace!("resolve: input: {:#?}", &input);
let mut env = initial
.iter()
.map(|(k, v)| (k.clone(), (v.clone(), None)))
.collect::<IndexMap<_, _>>();
let mut r = Self {
env: Default::default(),
vars: Default::default(),
env_remove: BTreeSet::new(),
env_files: Vec::new(),
env_paths: Vec::new(),
env_scripts: Vec::new(),
redactions: Vec::new(),
tool_add_paths: Vec::new(),
};
let normalize_path = |config_root: &Path, p: PathBuf| {
let p = p.strip_prefix("./").unwrap_or(&p);
match p.strip_prefix("~/") {
Ok(p) => dirs::HOME.join(p),
_ if p.is_relative() => config_root.join(p),
_ => p.to_path_buf(),
}
};
let mut paths: Vec<(PathBuf, PathBuf)> = Vec::new();
let last_python_venv = input.iter().rev().find_map(|(d, _)| match d {
EnvDirective::PythonVenv { .. } => Some(d),
_ => None,
});
let filtered_input = input
.iter()
.fold(Vec::new(), |mut acc, (directive, source)| {
// Filter directives based on tools setting
let should_include = match &resolve_opts.tools {
ToolsFilter::ToolsOnly => directive.options().tools,
ToolsFilter::NonToolsOnly => !directive.options().tools,
ToolsFilter::Both => true,
};
if !should_include {
return acc;
}
if let Some(d) = &last_python_venv
&& matches!(directive, EnvDirective::PythonVenv { .. })
&& **d != *directive
{
// skip venv directives if it's not the last one
return acc;
}
acc.push((directive.clone(), source.clone()));
acc
});
// Save filtered_input for validation after processing
let filtered_input_for_validation = filtered_input.clone();
for (directive, source) in filtered_input {
let mut tera = get_tera(source.parent());
tera.register_function(
"exec",
tera_exec(
source.parent().map(|d| d.to_path_buf()),
env.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect(),
),
);
// trace!(
// "resolve: directive: {:?}, source: {:?}",
// &directive,
// &source
// );
let config_root = crate::config::config_file::config_root::config_root(&source);
ctx.insert("cwd", &*dirs::CWD);
ctx.insert("config_root", &config_root);
let env_vars = env
.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect::<EnvMap>();
ctx.insert("env", &env_vars);
let mut vars: EnvMap = if let Some(Value::Object(existing_vars)) = ctx.get("vars") {
existing_vars
.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect()
} else {
EnvMap::new()
};
vars.extend(r.vars.iter().map(|(k, (v, _))| (k.clone(), v.clone())));
ctx.insert("vars", &vars);
let redact = directive.options().redact;
// trace!("resolve: ctx.get('env'): {:#?}", &ctx.get("env"));
match directive {
EnvDirective::Val(k, v, _opts) => {
let v = r.parse_template(&ctx, &mut tera, &source, &v)?;
if resolve_opts.vars {
r.vars.insert(k, (v, source.clone()));
} else {
r.env_remove.remove(&k);
// trace!("resolve: inserting {:?}={:?} from {:?}", &k, &v, &source);
if redact.unwrap_or(false) {
r.redactions.push(k.clone());
}
env.insert(k, (v, Some(source.clone())));
}
}
EnvDirective::Rm(k, _opts) => {
env.shift_remove(&k);
r.env_remove.insert(k);
}
EnvDirective::Required(_k, _opts) => {
// Required directives don't set any value - they only validate during validation phase
// The actual value must come from the initial environment or a later config file
}
EnvDirective::Age {
key: ref k,
ref options,
..
} => {
// Decrypt age-encrypted value
let res = crate::agecrypt::decrypt_age_directive(&directive).await;
let decrypted_v = match res {
Ok(decrypted_v) => {
// Parse as template after decryption
r.parse_template(&ctx, &mut tera, &source, &decrypted_v)?
}
Err(e) if Settings::get().age.strict => {
return Err(e)
.wrap_err(eyre!("[experimental] Failed to decrypt {}", k));
}
Err(e) => {
debug!(
"[experimental] Age decryption failed for {} but continuing in non-strict mode: {}",
k, e
);
// continue to the next directive
continue;
}
};
if resolve_opts.vars {
r.vars.insert(k.clone(), (decrypted_v, source.clone()));
} else {
r.env_remove.remove(k);
// Handle redaction for age-encrypted values
// We're already in the EnvDirective::Age match arm, so we know this is an Age directive
// For age-encrypted values, we default to redacting for security
// With nullable redact, we can now distinguish between:
// - None: not specified (default for age is to redact for security)
// - Some(true): explicitly redact
// - Some(false): explicitly don't redact
debug!("Age directive {}: redact = {:?}", k, options.redact);
match options.redact {
Some(false) => {
// User explicitly set redact = false - don't redact
debug!(
"Age directive {}: NOT redacting (explicit redact = false)",
k
);
}
Some(true) | None => {
// Either explicitly redact or use age default (redact for security)
debug!(
"Age directive {}: redacting (redact = {:?})",
k, options.redact
);
r.redactions.push(k.clone());
}
}
env.insert(k.clone(), (decrypted_v, Some(source.clone())));
}
}
EnvDirective::Path(input_str, _opts) => {
let path = Self::path(&mut ctx, &mut tera, &mut r, &source, input_str).await?;
paths.push((path.clone(), source.clone()));
// Don't modify PATH in env - just add to env_paths
// This allows consumers to control PATH ordering
}
EnvDirective::File(input, _opts) => {
let files = Self::file(
config,
&mut ctx,
&mut tera,
&mut r,
normalize_path,
&source,
&config_root,
input,
)
.await?;
for (f, new_env) in files {
r.env_files.push(f.clone());
for (k, v) in new_env {
if resolve_opts.vars {
r.vars.insert(k, (v, f.clone()));
} else {
if redact.unwrap_or(false) {
r.redactions.push(k.clone());
}
env.insert(k, (v, Some(f.clone())));
}
}
}
}
EnvDirective::Source(input, _opts) => {
let files = Self::source(
&mut ctx,
&mut tera,
&mut paths,
&mut r,
normalize_path,
&source,
&config_root,
&env_vars,
input,
)?;
for (f, new_env) in files {
r.env_scripts.push(f.clone());
for (k, v) in new_env {
if resolve_opts.vars {
r.vars.insert(k, (v, f.clone()));
} else {
if redact.unwrap_or(false) {
r.redactions.push(k.clone());
}
env.insert(k, (v, Some(f.clone())));
}
}
}
}
EnvDirective::PythonVenv {
path,
create,
python,
uv_create_args,
python_create_args,
options: _opts,
} => {
Self::venv(
config,
&mut ctx,
&mut tera,
&mut env,
&mut r,
normalize_path,
&source,
&config_root,
env_vars,
path,
create,
python,
uv_create_args,
python_create_args,
)
.await?;
}
EnvDirective::Module(name, value, _opts) => {
Self::module(&mut r, source, name, &value, redact.unwrap_or(false)).await?;
}
};
}
let env_vars = env
.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect::<HashMap<_, _>>();
ctx.insert("env", &env_vars);
for (k, (v, source)) in env {
if let Some(source) = source {
r.env.insert(k, (v, source));
}
}
// trace!("resolve: paths: {:#?}", &paths);
// trace!("resolve: ctx.env: {:#?}", &ctx.get("env"));
for (source, paths) in &paths.iter().chunk_by(|(_, source)| source) {
// Use the computed config_root (project root for nested configs) for path resolution
// to be consistent with other env directives like _.source and _.file
let config_root = crate::config::config_file::config_root::config_root(source);
let paths = paths.map(|(p, _)| p).collect_vec();
let mut paths = paths
.iter()
.rev()
.flat_map(|path| env::split_paths(path))
.map(|s| normalize_path(&config_root, s))
.collect::<Vec<_>>();
// r.env_paths is already reversed and paths should prepend r.env_paths
paths.reverse();
paths.extend(r.env_paths);
r.env_paths = paths;
}
// Validate required environment variables
Self::validate_required_env_vars(
&filtered_input_for_validation,
initial,
&r,
resolve_opts.warn_on_missing_required,
)?;
Ok(r)
}
fn validate_required_env_vars(
input: &[(EnvDirective, PathBuf)],
initial: &EnvMap,
env_results: &EnvResults,
warn_mode: bool,
) -> eyre::Result<()> {
let mut required_vars = Vec::new();
// Collect all required environment variables with their options
for (directive, source) in input {
match directive {
EnvDirective::Val(key, _, options) if options.required.is_required() => {
required_vars.push((key.clone(), source.clone(), options.required.clone()));
}
EnvDirective::Required(key, options) => {
required_vars.push((key.clone(), source.clone(), options.required.clone()));
}
_ => {}
}
}
// Check if required variables are defined
for (var_name, declaring_source, required_value) in required_vars {
// Variable must be defined either:
// 1. In the initial environment (before mise runs), OR
// 2. In a config file processed later than the one declaring it as required
let is_predefined = initial.contains_key(&var_name);
let is_defined_later = if let Some((_, var_source)) = env_results.env.get(&var_name) {
// Check if the variable comes from a different config file
var_source != &declaring_source
} else {
false
};
if !is_predefined && !is_defined_later {
let base_message = format!(
"Required environment variable '{}' is not defined. It must be set before mise runs or in a later config file. (Required in: {})",
var_name,
display_path(declaring_source)
);
let message = if let Some(help) = required_value.help_text() {
format!("{}\nHelp: {}", base_message, help)
} else {
base_message
};
if warn_mode {
warn!("{}", message);
} else {
return Err(eyre!("{}", message));
}
}
}
Ok(())
}
fn parse_template(
&self,
ctx: &tera::Context,
tera: &mut tera::Tera,
path: &Path,
input: &str,
) -> eyre::Result<String> {
if !input.contains("{{") && !input.contains("{%") && !input.contains("{#") {
return Ok(input.to_string());
}
trust_check(path)?;
let output = tera
.render_str(input, ctx)
.wrap_err_with(|| eyre!("failed to parse template: '{input}'"))?;
Ok(output)
}
pub fn is_empty(&self) -> bool {
self.env.is_empty()
&& self.vars.is_empty()
&& self.env_remove.is_empty()
&& self.env_files.is_empty()
&& self.env_paths.is_empty()
&& self.env_scripts.is_empty()
&& self.tool_add_paths.is_empty()
}
}
impl Debug for EnvResults {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("EnvResults");
if !self.env.is_empty() {
ds.field("env", &self.env.keys().collect::<Vec<_>>());
}
if !self.vars.is_empty() {
ds.field("vars", &self.vars.keys().collect::<Vec<_>>());
}
if !self.env_remove.is_empty() {
ds.field("env_remove", &self.env_remove);
}
if !self.env_files.is_empty() {
ds.field("env_files", &self.env_files);
}
if !self.env_paths.is_empty() {
ds.field("env_paths", &self.env_paths);
}
if !self.env_scripts.is_empty() {
ds.field("env_scripts", &self.env_scripts);
}
if !self.tool_add_paths.is_empty() {
ds.field("tool_add_paths", &self.tool_add_paths);
}
ds.finish()
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/tool_versions.rs | src/config/config_file/tool_versions.rs | use std::path::{Path, PathBuf};
use std::{
fmt::{Display, Formatter},
sync::{Arc, Mutex},
};
use console::{Alignment, measure_text_width, pad_str};
use eyre::Result;
use indexmap::IndexMap;
use itertools::Itertools;
use tera::Context;
use crate::cli::args::BackendArg;
use crate::config::config_file::ConfigFile;
use crate::file;
use crate::file::display_path;
use crate::tera::{BASE_CONTEXT, get_tera};
use crate::toolset::{ToolRequest, ToolRequestSet, ToolSource};
use super::ConfigFileType;
// python 3.11.0 3.10.0
// shellcheck 0.9.0
// shfmt 3.6.0
/// represents asdf's .tool-versions file
#[derive(Debug, Default)]
pub struct ToolVersions {
context: Context,
path: PathBuf,
pre: String,
plugins: Mutex<IndexMap<BackendArg, ToolVersionPlugin>>,
tools: Mutex<ToolRequestSet>,
}
#[derive(Debug, Clone)]
struct ToolVersionPlugin {
orig_name: String,
versions: Vec<String>,
post: String,
}
impl ToolVersions {
pub fn init(filename: &Path) -> ToolVersions {
let mut context = BASE_CONTEXT.clone();
context.insert("config_root", filename.parent().unwrap().to_str().unwrap());
ToolVersions {
context,
tools: Mutex::new(ToolRequestSet::new()),
path: filename.to_path_buf(),
..Default::default()
}
}
pub fn from_file(path: &Path) -> Result<Self> {
trace!("parsing tool-versions: {}", path.display());
Self::parse_str(&file::read_to_string(path)?, path.to_path_buf())
}
pub fn parse_str(s: &str, path: PathBuf) -> Result<Self> {
let mut cf = Self::init(&path);
let dir = path.parent();
let s = get_tera(dir).render_str(s, &cf.context)?;
for line in s.lines() {
if !line.trim_start().starts_with('#') {
break;
}
cf.pre.push_str(line);
cf.pre.push('\n');
}
cf.plugins = Mutex::new(Self::parse_plugins(&s));
cf.populate_toolset()?;
trace!("{cf}");
Ok(cf)
}
fn parse_plugins(input: &str) -> IndexMap<BackendArg, ToolVersionPlugin> {
let mut plugins: IndexMap<BackendArg, ToolVersionPlugin> = IndexMap::new();
for line in input.lines() {
if line.trim_start().starts_with('#') {
if let Some(prev) = &mut plugins.values_mut().last() {
prev.post.push_str(line);
prev.post.push('\n');
}
continue;
}
let (line, post) = line.split_once('#').unwrap_or((line, ""));
let mut parts = line.split_whitespace();
if let Some(plugin) = parts.next() {
// handle invalid trailing colons in `.tool-versions` files
// note that this method will cause the colons to be removed
// permanently if saving the file again, but I think that's fine
let orig_plugin = plugin.trim_end_matches(':');
let ba = orig_plugin.into();
let tvp = ToolVersionPlugin {
orig_name: orig_plugin.to_string(),
versions: parts.map(|v| v.to_string()).collect(),
post: match post {
"" => String::from("\n"),
_ => [" #", post, "\n"].join(""),
},
};
plugins.insert(ba, tvp);
}
}
plugins
}
fn add_version(
&self,
plugins: &mut IndexMap<BackendArg, ToolVersionPlugin>,
fa: &BackendArg,
version: String,
) {
get_or_create_plugin(plugins, fa).versions.push(version);
}
fn populate_toolset(&self) -> eyre::Result<()> {
let source = ToolSource::ToolVersions(self.path.clone());
for (ba, tvp) in &*self.plugins.lock().unwrap() {
for version in &tvp.versions {
let tvr = ToolRequest::new(Arc::new(ba.clone()), version, source.clone())?;
self.tools.lock().unwrap().add_version(tvr, &source)
}
}
Ok(())
}
}
impl Display for ToolVersions {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let plugins = &self
.plugins
.lock()
.unwrap()
.iter()
.map(|(p, v)| format!("{}@{}", p, v.versions.join("|")))
.collect_vec();
write!(
f,
"ToolVersions({}): {}",
display_path(&self.path),
plugins.join(", ")
)
}
}
impl ConfigFile for ToolVersions {
fn config_type(&self) -> ConfigFileType {
ConfigFileType::ToolVersions
}
fn get_path(&self) -> &Path {
self.path.as_path()
}
fn remove_tool(&self, fa: &BackendArg) -> Result<()> {
self.plugins.lock().unwrap().shift_remove(fa);
Ok(())
}
fn replace_versions(&self, fa: &BackendArg, versions: Vec<ToolRequest>) -> eyre::Result<()> {
let mut plugins = self.plugins.lock().unwrap();
get_or_create_plugin(&mut plugins, fa).versions.clear();
for tr in versions {
if !tr.options().is_empty() {
warn!("tool options are not supported in .tool-versions files");
}
self.add_version(&mut plugins, fa, tr.version());
}
Ok(())
}
fn save(&self) -> Result<()> {
let s = self.dump()?;
file::write(&self.path, s)
}
fn dump(&self) -> eyre::Result<String> {
let mut s = self.pre.clone();
let plugins = self.plugins.lock().unwrap();
let max_plugin_len = plugins
.keys()
.map(|p| measure_text_width(&p.to_string()))
.max()
.unwrap_or_default();
for (_, tv) in &*plugins {
let mut plugin = tv.orig_name.to_string();
if plugin == "node" {
plugin = "nodejs".into();
} else if plugin == "go" {
plugin = "golang".into();
}
let plugin = pad_str(&plugin, max_plugin_len, Alignment::Left, None);
s.push_str(&format!("{} {}{}", plugin, tv.versions.join(" "), tv.post));
}
Ok(s.trim_end().to_string() + "\n")
}
fn source(&self) -> ToolSource {
ToolSource::ToolVersions(self.path.clone())
}
fn to_tool_request_set(&self) -> eyre::Result<ToolRequestSet> {
Ok(self.tools.lock().unwrap().clone())
}
}
fn get_or_create_plugin<'a>(
plugins: &'a mut IndexMap<BackendArg, ToolVersionPlugin>,
fa: &BackendArg,
) -> &'a mut ToolVersionPlugin {
plugins
.entry(fa.clone())
.or_insert_with(|| ToolVersionPlugin {
orig_name: fa.short.to_string(),
versions: vec![],
post: "".into(),
})
}
impl Clone for ToolVersions {
fn clone(&self) -> Self {
Self {
context: self.context.clone(),
path: self.path.clone(),
pre: self.pre.clone(),
plugins: Mutex::new(self.plugins.lock().unwrap().clone()),
tools: Mutex::new(self.tools.lock().unwrap().clone()),
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/min_version.rs | src/config/config_file/min_version.rs | use std::fmt;
use versions::Versioning;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MinVersionSpec {
hard: Option<Versioning>,
soft: Option<Versioning>,
}
impl MinVersionSpec {
pub fn new(hard: Option<Versioning>, soft: Option<Versioning>) -> Option<Self> {
if hard.is_none() && soft.is_none() {
None
} else {
Some(Self { hard, soft })
}
}
pub fn hard(&self) -> Option<&Versioning> {
self.hard.as_ref()
}
pub fn set_hard(&mut self, version: Versioning) {
self.hard = Some(version);
}
pub fn soft(&self) -> Option<&Versioning> {
self.soft.as_ref()
}
pub fn set_soft(&mut self, version: Versioning) {
self.soft = Some(version);
}
pub fn is_empty(&self) -> bool {
self.hard.is_none() && self.soft.is_none()
}
pub fn hard_violation(&self, current: &Versioning) -> Option<&Versioning> {
self.hard().filter(|required| current < *required)
}
pub fn soft_violation(&self, current: &Versioning) -> Option<&Versioning> {
self.soft().filter(|recommended| current < *recommended)
}
pub fn merge_with(&mut self, other: &Self) {
if self.hard.is_none() {
self.hard = other.hard.clone();
}
if self.soft.is_none() {
self.soft = other.soft.clone();
}
}
}
impl fmt::Display for MinVersionSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.hard.as_ref(), self.soft.as_ref()) {
(Some(h), None) => write!(f, "{}", h),
(None, Some(s)) => write!(f, "{}", s),
(Some(h), Some(s)) => write!(f, "hard={}, soft={}", h, s),
(None, None) => write!(f, ""),
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/mod.rs | src/config/config_file/mod.rs | use std::ffi::OsStr;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Once};
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use crate::cli::args::{BackendArg, ToolArg};
use crate::config::config_file::min_version::MinVersionSpec;
use crate::config::config_file::mise_toml::MiseToml;
use crate::config::env_directive::EnvDirective;
use crate::config::{AliasMap, Settings, settings};
use crate::errors::Error::UntrustedConfig;
use crate::file::display_path;
use crate::hash::hash_to_str;
use crate::hooks::Hook;
use crate::prepare::PrepareConfig;
use crate::redactions::Redactions;
use crate::task::Task;
use crate::toolset::{ToolRequest, ToolRequestSet, ToolSource, ToolVersionList, Toolset};
use crate::ui::{prompt, style};
use crate::watch_files::WatchFile;
use crate::{backend, config, dirs, env, file, hash};
use eyre::{Result, eyre};
use idiomatic_version::IdiomaticVersionFile;
use indexmap::IndexMap;
use serde_derive::Deserialize;
use std::sync::LazyLock as Lazy;
use tool_versions::ToolVersions;
use super::Config;
pub mod config_root;
pub mod idiomatic_version;
pub mod min_version;
pub mod mise_toml;
pub mod toml;
pub mod tool_versions;
#[derive(Debug, PartialEq)]
pub enum ConfigFileType {
MiseToml,
ToolVersions,
IdiomaticVersion,
}
pub trait ConfigFile: Debug + Send + Sync {
fn get_path(&self) -> &Path;
fn min_version(&self) -> Option<&MinVersionSpec> {
None
}
/// gets the project directory for the config
/// if it's a global/system config, returns None
/// files like ~/src/foo/.mise/config.toml will return ~/src/foo
/// and ~/src/foo/.mise.config.toml will return None
fn project_root(&self) -> Option<PathBuf> {
let p = self.get_path();
if config::is_global_config(p) {
return None;
}
match p.parent() {
Some(dir) => match dir {
dir if dir.starts_with(*dirs::CONFIG) => None,
dir if dir.starts_with(*dirs::SYSTEM) => None,
dir if dir == *dirs::HOME => None,
_ => Some(config_root::config_root(p)),
},
None => None,
}
}
fn config_type(&self) -> ConfigFileType;
fn config_root(&self) -> PathBuf {
config_root::config_root(self.get_path())
}
fn plugins(&self) -> Result<HashMap<String, String>> {
Ok(Default::default())
}
fn env_entries(&self) -> Result<Vec<EnvDirective>> {
Ok(Default::default())
}
fn vars_entries(&self) -> Result<Vec<EnvDirective>> {
Ok(Default::default())
}
fn tasks(&self) -> Vec<&Task> {
Default::default()
}
fn remove_tool(&self, ba: &BackendArg) -> eyre::Result<()>;
fn replace_versions(&self, ba: &BackendArg, versions: Vec<ToolRequest>) -> eyre::Result<()>;
fn save(&self) -> eyre::Result<()>;
fn dump(&self) -> eyre::Result<String>;
fn source(&self) -> ToolSource;
fn to_toolset(&self) -> eyre::Result<Toolset> {
Ok(self.to_tool_request_set()?.into())
}
fn to_tool_request_set(&self) -> eyre::Result<ToolRequestSet>;
fn aliases(&self) -> eyre::Result<AliasMap> {
Ok(Default::default())
}
fn shell_aliases(&self) -> eyre::Result<IndexMap<String, String>> {
Ok(Default::default())
}
fn task_config(&self) -> &TaskConfig {
static DEFAULT_TASK_CONFIG: Lazy<TaskConfig> = Lazy::new(TaskConfig::default);
&DEFAULT_TASK_CONFIG
}
fn experimental_monorepo_root(&self) -> Option<bool> {
None
}
fn redactions(&self) -> &Redactions {
static DEFAULT_REDACTIONS: Lazy<Redactions> = Lazy::new(Redactions::default);
&DEFAULT_REDACTIONS
}
fn watch_files(&self) -> Result<Vec<WatchFile>> {
Ok(Default::default())
}
fn hooks(&self) -> Result<Vec<Hook>> {
Ok(Default::default())
}
fn prepare_config(&self) -> Option<PrepareConfig> {
None
}
}
impl dyn ConfigFile {
pub async fn add_runtimes(
&self,
config: &Arc<Config>,
tools: &[ToolArg],
pin: bool,
) -> eyre::Result<()> {
// TODO: this has become a complete mess and could probably be greatly simplified
let mut ts = self.to_toolset()?.to_owned();
ts.resolve(config).await?;
trace!("resolved toolset");
let mut plugins_to_update = HashMap::new();
for ta in tools {
if let Some(tv) = &ta.tvr {
plugins_to_update
.entry(ta.ba.clone())
.or_insert_with(Vec::new)
.push(tv);
}
}
trace!("plugins to update: {plugins_to_update:?}");
for (ba, versions) in &plugins_to_update {
let mut tvl = ToolVersionList::new(
ba.clone(),
ts.source.clone().unwrap_or(ToolSource::Argument),
);
for tv in versions {
tvl.requests.push((*tv).clone());
}
ts.versions.insert(ba.clone(), tvl);
}
trace!("resolving toolset 2");
ts.resolve(config).await?;
trace!("resolved toolset 2");
for (ba, versions) in plugins_to_update {
let mut new = vec![];
for tr in versions {
let mut tr = tr.clone();
if pin {
let tv = tr.resolve(config, &Default::default()).await?;
if let ToolRequest::Version {
version: _version,
source,
options,
backend,
} = tr
{
tr = ToolRequest::Version {
version: tv.version,
source,
options,
backend,
};
}
}
new.push(tr);
}
trace!("replacing versions {new:?}");
self.replace_versions(&ba, new)?;
}
trace!("done adding runtimes");
Ok(())
}
/// this is for `mise local|global TOOL` which will display the version instead of setting it
/// it's only valid to use a single tool in this case
/// returns "true" if the tool was displayed which means the CLI should exit
pub fn display_runtime(&self, runtimes: &[ToolArg]) -> eyre::Result<bool> {
// in this situation we just print the current version in the config file
if runtimes.len() == 1 && runtimes[0].tvr.is_none() {
let fa = &runtimes[0].ba;
let tvl = self
.to_toolset()?
.versions
.get(fa)
.ok_or_else(|| {
eyre!(
"no version set for {} in {}",
fa.to_string(),
display_path(self.get_path())
)
})?
.requests
.iter()
.map(|tvr| tvr.version())
.collect::<Vec<_>>();
miseprintln!("{}", tvl.join(" "));
return Ok(true);
}
// check for something like `mise local node python@latest` which is invalid
if runtimes.iter().any(|r| r.tvr.is_none()) {
return Err(eyre!(
"invalid input, specify a version for each tool. Or just specify one tool to print the current version"
));
}
Ok(false)
}
}
async fn init(path: &Path) -> Arc<dyn ConfigFile> {
match detect_config_file_type(path).await {
Some(ConfigFileType::MiseToml) => Arc::new(MiseToml::init(path)),
Some(ConfigFileType::ToolVersions) => Arc::new(ToolVersions::init(path)),
Some(ConfigFileType::IdiomaticVersion) => {
Arc::new(IdiomaticVersionFile::init(path.to_path_buf()))
}
_ => panic!("Unknown config file type: {}", path.display()),
}
}
pub async fn parse_or_init(path: &Path) -> eyre::Result<Arc<dyn ConfigFile>> {
let path = if path.is_dir() {
path.join(&*env::MISE_DEFAULT_CONFIG_FILENAME)
} else {
path.into()
};
let cf = match path.exists() {
true => parse(&path).await?,
false => init(&path).await,
};
Ok(cf)
}
pub async fn parse(path: &Path) -> Result<Arc<dyn ConfigFile>> {
if let Ok(settings) = Settings::try_get()
&& settings.paranoid
{
trust_check(path)?;
}
match detect_config_file_type(path).await {
Some(ConfigFileType::MiseToml) => Ok(Arc::new(MiseToml::from_file(path)?)),
Some(ConfigFileType::ToolVersions) => Ok(Arc::new(ToolVersions::from_file(path)?)),
Some(ConfigFileType::IdiomaticVersion) => {
Ok(Arc::new(IdiomaticVersionFile::from_file(path).await?))
}
#[allow(clippy::box_default)]
_ => Ok(Arc::new(MiseToml::default())),
}
}
pub fn config_trust_root(path: &Path) -> PathBuf {
if settings::is_loaded() && Settings::get().paranoid {
path.to_path_buf()
} else {
config_root::config_root(path)
}
}
pub fn trust_check(path: &Path) -> eyre::Result<()> {
static MUTEX: Mutex<()> = Mutex::new(());
let _lock = MUTEX.lock().unwrap(); // Prevent multiple checks at once so we don't prompt multiple times for the same path
let config_root = config_trust_root(path);
let default_cmd = String::new();
let args = env::ARGS.read().unwrap();
let cmd = args.get(1).unwrap_or(&default_cmd).as_str();
if is_trusted(&config_root) || is_trusted(path) || cmd == "trust" || cfg!(test) {
return Ok(());
}
if cmd != "hook-env" && !is_ignored(&config_root) && !is_ignored(path) {
let ans = prompt::confirm_with_all(format!(
"{} config files in {} are not trusted. Trust them?",
style::eyellow("mise"),
style::epath(&config_root)
))?;
if ans {
trust(&config_root)?;
return Ok(());
} else if console::user_attended_stderr() {
add_ignored(config_root.to_path_buf())?;
}
}
Err(UntrustedConfig(path.into()))?
}
pub fn is_trusted(path: &Path) -> bool {
let canonicalized_path = match path.canonicalize() {
Ok(p) => p,
Err(err) => {
debug!("trust canonicalize: {err}");
return false;
}
};
if is_ignored(canonicalized_path.as_path()) {
return false;
}
if IS_TRUSTED
.lock()
.unwrap()
.contains(canonicalized_path.as_path())
{
return true;
}
if config::is_global_config(path) {
add_trusted(canonicalized_path.to_path_buf());
return true;
}
let settings = Settings::get();
for p in settings.trusted_config_paths() {
if canonicalized_path.starts_with(p) {
add_trusted(canonicalized_path.to_path_buf());
return true;
}
}
// Check if this path is within a trusted monorepo root
// Monorepo roots are marked with a special marker file when trusted
if settings.experimental
&& let Some(parent) = canonicalized_path.parent()
{
let mut current = parent;
while let Some(dir) = current.parent() {
let monorepo_marker = trust_path(dir).with_extension("monorepo");
if monorepo_marker.exists() {
add_trusted(canonicalized_path.to_path_buf());
return true;
}
current = dir;
}
}
if settings.paranoid {
let trusted = trust_file_hash(path).unwrap_or_else(|e| {
warn!("trust_file_hash: {e}");
false
});
if !trusted {
return false;
}
} else if cfg!(test) || ci_info::is_ci() {
// in tests/CI we trust everything
return true;
} else if !trust_path(path).exists() {
// the file isn't trusted, and we're not on a CI system where we generally assume we can
// trust config files
return false;
}
add_trusted(canonicalized_path.to_path_buf());
true
}
static IS_TRUSTED: Lazy<Mutex<HashSet<PathBuf>>> = Lazy::new(|| Mutex::new(HashSet::new()));
static IS_IGNORED: Lazy<Mutex<HashSet<PathBuf>>> = Lazy::new(|| Mutex::new(HashSet::new()));
fn add_trusted(path: PathBuf) {
IS_TRUSTED.lock().unwrap().insert(path);
}
pub fn add_ignored(path: PathBuf) -> Result<()> {
let path = path.canonicalize()?;
file::create_dir_all(&*dirs::IGNORED_CONFIGS)?;
file::make_symlink_or_file(&path, &ignore_path(&path))?;
IS_IGNORED.lock().unwrap().insert(path);
Ok(())
}
pub fn rm_ignored(path: PathBuf) -> Result<()> {
let path = path.canonicalize()?;
let ignore_path = ignore_path(&path);
if ignore_path.exists() {
file::remove_file(&ignore_path)?;
}
IS_IGNORED.lock().unwrap().remove(&path);
Ok(())
}
pub fn is_ignored(path: &Path) -> bool {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
if !dirs::IGNORED_CONFIGS.exists() {
return;
}
let mut is_ignored = IS_IGNORED.lock().unwrap();
for entry in file::ls(&dirs::IGNORED_CONFIGS).unwrap_or_default() {
if let Ok(canonicalized_path) = entry.canonicalize() {
is_ignored.insert(canonicalized_path);
}
}
});
if let Ok(path) = path.canonicalize() {
env::MISE_IGNORED_CONFIG_PATHS
.iter()
.any(|p| path.starts_with(p))
|| IS_IGNORED.lock().unwrap().contains(&path)
} else {
debug!("is_ignored: path canonicalize failed");
true
}
}
pub fn trust(path: &Path) -> Result<()> {
rm_ignored(path.to_path_buf())?;
let hashed_path = trust_path(path);
if !hashed_path.exists() {
file::create_dir_all(hashed_path.parent().unwrap())?;
file::make_symlink_or_file(path.canonicalize()?.as_path(), &hashed_path)?;
}
if Settings::get().paranoid {
let trust_hash_path = hashed_path.with_extension("hash");
let hash = hash::file_hash_sha256(path, None)?;
file::write(trust_hash_path, hash)?;
}
Ok(())
}
/// Marks a trusted config as a monorepo root, allowing all descendant configs to be trusted
pub fn mark_as_monorepo_root(path: &Path) -> Result<()> {
let config_root = config_trust_root(path);
let hashed_path = trust_path(&config_root);
let monorepo_marker = hashed_path.with_extension("monorepo");
if !monorepo_marker.exists() {
file::create_dir_all(monorepo_marker.parent().unwrap())?;
file::write(&monorepo_marker, "")?;
}
Ok(())
}
pub fn untrust(path: &Path) -> eyre::Result<()> {
rm_ignored(path.to_path_buf())?;
let hashed_path = trust_path(path);
if hashed_path.exists() {
file::remove_file(hashed_path)?;
}
Ok(())
}
/// generates a path like ~/.mise/trusted-configs/dir-file-3e8b8c44c3.toml
fn trust_path(path: &Path) -> PathBuf {
dirs::TRUSTED_CONFIGS.join(hashed_path_filename(path))
}
fn ignore_path(path: &Path) -> PathBuf {
dirs::IGNORED_CONFIGS.join(hashed_path_filename(path))
}
/// creates the filename portion of trust/ignore files, e.g.:
fn hashed_path_filename(path: &Path) -> String {
let canonicalized_path = path.canonicalize().unwrap();
let hash = hash_to_str(&canonicalized_path);
let trunc_str = |s: &OsStr| {
let mut s = s.to_str().unwrap().to_string();
s = s.chars().take(20).collect();
s
};
let trust_path = dirs::TRUSTED_CONFIGS.join(hash_to_str(&hash));
if trust_path.exists() {
return trust_path
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
}
let parent = canonicalized_path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default()
.file_name()
.map(trunc_str);
let filename = canonicalized_path.file_name().map(trunc_str);
[parent, filename, Some(hash)]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join("-")
}
fn trust_file_hash(path: &Path) -> eyre::Result<bool> {
let trust_path = trust_path(path);
let trust_hash_path = trust_path.with_extension("hash");
if !trust_hash_path.exists() {
return Ok(false);
}
let hash = file::read_to_string(&trust_hash_path)?;
let actual = hash::file_hash_sha256(path, None)?;
Ok(hash == actual)
}
async fn filename_is_idiomatic(file_name: String) -> bool {
for b in backend::list() {
match b.idiomatic_filenames().await {
Ok(filenames) => {
if filenames.contains(&file_name) {
return true;
}
}
Err(e) => {
debug!("idiomatic_filenames failed for {}: {:?}", b, e);
}
}
}
false
}
async fn detect_config_file_type(path: &Path) -> Option<ConfigFileType> {
match path
.file_name()
.and_then(|f| f.to_str())
.unwrap_or("mise.toml")
{
f if filename_is_idiomatic(f.to_string()).await => Some(ConfigFileType::IdiomaticVersion),
f if env::MISE_OVERRIDE_TOOL_VERSIONS_FILENAMES
.as_ref()
.is_some_and(|o| o.contains(f)) =>
{
Some(ConfigFileType::ToolVersions)
}
f if env::MISE_DEFAULT_TOOL_VERSIONS_FILENAME.as_str() == f => {
Some(ConfigFileType::ToolVersions)
}
f if f.ends_with(".toml") => Some(ConfigFileType::MiseToml),
f if env::MISE_OVERRIDE_CONFIG_FILENAMES.contains(f) => Some(ConfigFileType::MiseToml),
f if env::MISE_DEFAULT_CONFIG_FILENAME.as_str() == f => Some(ConfigFileType::MiseToml),
_ => None,
}
}
impl Display for dyn ConfigFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let toolset = self.to_toolset().unwrap().to_string();
write!(f, "{}: {toolset}", &display_path(self.get_path()))
}
}
impl PartialEq for dyn ConfigFile {
fn eq(&self, other: &Self) -> bool {
self.get_path() == other.get_path()
}
}
impl Eq for dyn ConfigFile {}
impl Hash for dyn ConfigFile {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.get_path().hash(state);
}
}
#[derive(Clone, Debug, Default, Deserialize)]
pub struct TaskConfig {
pub includes: Option<Vec<PathBuf>>,
pub dir: Option<String>,
}
#[cfg(test)]
#[cfg(unix)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[tokio::test]
async fn test_detect_config_file_type() {
env::set_var("MISE_EXPERIMENTAL", "true");
assert_eq!(
detect_config_file_type(Path::new("/foo/bar/.nvmrc")).await,
Some(ConfigFileType::IdiomaticVersion)
);
assert_eq!(
detect_config_file_type(Path::new("/foo/bar/.ruby-version")).await,
Some(ConfigFileType::IdiomaticVersion)
);
assert_eq!(
detect_config_file_type(Path::new("/foo/bar/.test-tool-versions")).await,
Some(ConfigFileType::ToolVersions)
);
assert_eq!(
detect_config_file_type(Path::new("/foo/bar/mise.toml")).await,
Some(ConfigFileType::MiseToml)
);
assert_eq!(
detect_config_file_type(Path::new("/foo/bar/rust-toolchain.toml")).await,
Some(ConfigFileType::IdiomaticVersion)
);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/idiomatic_version.rs | src/config/config_file/idiomatic_version.rs | use std::path::{Path, PathBuf};
use std::sync::Arc;
use eyre::Result;
use crate::backend::{self, Backend, BackendList};
use crate::cli::args::BackendArg;
use crate::config::config_file::ConfigFile;
use crate::toolset::{ToolRequest, ToolRequestSet, ToolSource};
use super::ConfigFileType;
#[derive(Debug, Clone)]
pub struct IdiomaticVersionFile {
path: PathBuf,
tools: ToolRequestSet,
}
impl IdiomaticVersionFile {
pub fn init(path: PathBuf) -> Self {
Self {
path,
tools: ToolRequestSet::new(),
}
}
pub async fn parse(path: PathBuf, plugins: BackendList) -> Result<Self> {
let source = ToolSource::IdiomaticVersionFile(path.clone());
let mut tools = ToolRequestSet::new();
for plugin in plugins {
let version = plugin.parse_idiomatic_file(&path).await?;
for version in version.split_whitespace() {
let tr = ToolRequest::new(plugin.ba().clone(), version, source.clone())?;
tools.add_version(tr, &source);
}
}
Ok(Self { tools, path })
}
pub async fn from_file(path: &Path) -> Result<Self> {
trace!("parsing idiomatic version: {}", path.display());
let file_name = &path.file_name().unwrap().to_string_lossy().to_string();
let mut tools: Vec<Arc<dyn Backend>> = vec![];
for b in backend::list().into_iter() {
if b.idiomatic_filenames()
.await
.is_ok_and(|f| f.contains(file_name))
{
tools.push(b);
}
}
Self::parse(path.to_path_buf(), tools).await
}
}
impl ConfigFile for IdiomaticVersionFile {
fn config_type(&self) -> ConfigFileType {
ConfigFileType::IdiomaticVersion
}
fn get_path(&self) -> &Path {
self.path.as_path()
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn remove_tool(&self, _fa: &BackendArg) -> Result<()> {
unimplemented!()
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn replace_versions(
&self,
_plugin_name: &BackendArg,
_versions: Vec<ToolRequest>,
) -> Result<()> {
unimplemented!()
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn save(&self) -> Result<()> {
unimplemented!()
}
#[cfg_attr(coverage_nightly, coverage(off))]
fn dump(&self) -> Result<String> {
unimplemented!()
}
fn source(&self) -> ToolSource {
ToolSource::IdiomaticVersionFile(self.path.clone())
}
fn to_tool_request_set(&self) -> Result<ToolRequestSet> {
Ok(self.tools.clone())
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/mise_toml.rs | src/config/config_file/mise_toml.rs | use eyre::{WrapErr, eyre};
use indexmap::IndexMap;
use itertools::Itertools;
use once_cell::sync::OnceCell;
use serde::de::Visitor;
use serde::{Deserializer, de};
use serde_derive::Deserialize;
use std::fmt::{Debug, Formatter};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{
collections::{BTreeMap, HashMap},
sync::{Mutex, MutexGuard},
};
use tera::Context as TeraContext;
use toml_edit::{Array, DocumentMut, InlineTable, Item, Key, Value, table, value};
use versions::Versioning;
use crate::cli::args::{BackendArg, ToolVersionType};
use crate::config::config_file::{ConfigFile, TaskConfig, config_trust_root, trust, trust_check};
use crate::config::config_file::{config_root, toml::deserialize_arr};
use crate::config::env_directive::{AgeFormat, EnvDirective, EnvDirectiveOptions, RequiredValue};
use crate::config::settings::SettingsPartial;
use crate::config::{Alias, AliasMap, Config};
use crate::env_diff::EnvMap;
use crate::file::{create_dir_all, display_path};
use crate::hooks::{Hook, Hooks};
use crate::prepare::PrepareConfig;
use crate::redactions::Redactions;
use crate::registry::REGISTRY;
use crate::task::Task;
use crate::tera::{BASE_CONTEXT, get_tera};
use crate::toolset::{ToolRequest, ToolRequestSet, ToolSource, ToolVersionOptions};
use crate::watch_files::WatchFile;
use crate::{env, file};
use super::{ConfigFileType, min_version::MinVersionSpec};
#[derive(Default, Deserialize)]
pub struct MiseToml {
#[serde(rename = "_")]
custom: Option<toml::Value>,
#[serde(default, deserialize_with = "deserialize_min_version")]
min_version: Option<MinVersionSpec>,
#[serde(skip)]
context: TeraContext,
#[serde(skip)]
path: PathBuf,
#[serde(default, alias = "dotenv", deserialize_with = "deserialize_arr")]
env_file: Vec<String>,
#[serde(default)]
env: EnvList,
#[serde(default, deserialize_with = "deserialize_arr")]
env_path: Vec<String>,
#[serde(default)]
alias: AliasMap,
#[serde(default)]
tool_alias: AliasMap,
#[serde(default)]
shell_alias: IndexMap<String, String>,
#[serde(skip)]
doc: Mutex<OnceCell<DocumentMut>>,
#[serde(default)]
hooks: IndexMap<Hooks, toml::Value>,
#[serde(default)]
tools: Mutex<IndexMap<BackendArg, MiseTomlToolList>>,
#[serde(default)]
plugins: HashMap<String, String>,
#[serde(default)]
redactions: Redactions,
#[serde(default)]
task_config: TaskConfig,
#[serde(default)]
tasks: Tasks,
#[serde(default)]
watch_files: Vec<WatchFile>,
#[serde(default)]
prepare: Option<PrepareConfig>,
#[serde(default)]
vars: EnvList,
#[serde(default)]
settings: SettingsPartial,
/// Marks this config as a monorepo root, enabling target path syntax for tasks
#[serde(default)]
experimental_monorepo_root: Option<bool>,
}
#[derive(Debug, Default, Clone)]
pub struct MiseTomlToolList(Vec<MiseTomlTool>);
#[derive(Debug, Clone)]
pub struct MiseTomlTool {
pub tt: ToolVersionType,
pub options: Option<ToolVersionOptions>,
}
#[derive(Debug, Default, Clone)]
pub struct Tasks(pub BTreeMap<String, Task>);
#[derive(Debug, Default, Clone)]
pub struct EnvList(pub(crate) Vec<EnvDirective>);
impl EnvList {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl MiseToml {
fn enforce_min_version_fallback(body: &str) -> eyre::Result<()> {
if let Ok(val) = toml::from_str::<toml::Value>(body)
&& let Some(min_val) = val.get("min_version")
{
let mut hard_req: Option<versions::Versioning> = None;
let mut soft_req: Option<versions::Versioning> = None;
match min_val {
toml::Value::String(s) => {
hard_req = versions::Versioning::new(s);
}
toml::Value::Table(t) => {
if let Some(toml::Value::String(s)) = t.get("hard") {
hard_req = versions::Versioning::new(s);
}
if let Some(toml::Value::String(s)) = t.get("soft") {
soft_req = versions::Versioning::new(s);
}
}
_ => {}
}
if let Some(spec) =
crate::config::config_file::min_version::MinVersionSpec::new(hard_req, soft_req)
{
crate::config::Config::enforce_min_version_spec(&spec)?;
}
}
Ok(())
}
fn contains_template_syntax(input: &str) -> bool {
input.contains("{{") || input.contains("{%") || input.contains("{#")
}
pub fn init(path: &Path) -> Self {
let mut context = BASE_CONTEXT.clone();
context.insert(
"config_root",
config_root::config_root(path).to_str().unwrap(),
);
let mut rf = Self {
path: path.to_path_buf(),
context,
..Default::default()
};
rf.update_context_env(env::PRISTINE_ENV.clone());
rf
}
pub fn from_file(path: &Path) -> eyre::Result<Self> {
let body = file::read_to_string(path)?;
Self::from_str(&body, path)
}
pub fn from_str(body: &str, path: &Path) -> eyre::Result<Self> {
trust_check(path)?;
trace!("parsing: {}", display_path(path));
let des = toml::Deserializer::new(body);
let de_res = serde_ignored::deserialize(des, |p| {
warn!("unknown field in {}: {p}", display_path(path));
});
let mut rf: MiseToml = match de_res {
Ok(rf) => rf,
Err(err) => {
Self::enforce_min_version_fallback(body)?;
return Err(err.into());
}
};
rf.context = BASE_CONTEXT.clone();
rf.context.insert(
"config_root",
config_root::config_root(path).to_str().unwrap(),
);
rf.update_context_env(env::PRISTINE_ENV.clone());
rf.path = path.to_path_buf();
let project_root = rf.project_root().map(|p| p.to_path_buf());
for task in rf.tasks.0.values_mut() {
task.config_source.clone_from(&rf.path);
task.config_root = project_root.clone();
}
// trace!("{}", rf.dump()?);
Ok(rf)
}
fn doc(&self) -> eyre::Result<DocumentMut> {
self.doc
.lock()
.unwrap()
.get_or_try_init(|| {
let body = file::read_to_string(&self.path).unwrap_or_default();
Ok(body.parse()?)
})
.cloned()
}
fn doc_mut(&self) -> eyre::Result<MutexGuard<'_, OnceCell<DocumentMut>>> {
self.doc()?;
Ok(self.doc.lock().unwrap())
}
pub fn set_backend_alias(&mut self, fa: &BackendArg, to: &str) -> eyre::Result<()> {
self.doc_mut()?
.get_mut()
.unwrap()
.entry("tool_alias")
.or_insert_with(table)
.as_table_like_mut()
.unwrap()
.insert(&fa.short, value(to));
Ok(())
}
pub fn set_alias(&mut self, fa: &BackendArg, from: &str, to: &str) -> eyre::Result<()> {
self.tool_alias
.entry(fa.short.to_string())
.or_default()
.versions
.insert(from.into(), to.into());
self.doc_mut()?
.get_mut()
.unwrap()
.entry("tool_alias")
.or_insert_with(table)
.as_table_like_mut()
.unwrap()
.entry(&fa.to_string())
.or_insert_with(table)
.as_table_like_mut()
.unwrap()
.entry("versions")
.or_insert_with(table)
.as_table_like_mut()
.unwrap()
.insert(from, value(to));
Ok(())
}
pub fn remove_backend_alias(&mut self, fa: &BackendArg) -> eyre::Result<()> {
let mut doc = self.doc_mut()?;
let doc = doc.get_mut().unwrap();
// Remove from both tool_alias and deprecated alias sections
for section in ["tool_alias", "alias"] {
if let Some(aliases) = doc.get_mut(section).and_then(|v| v.as_table_mut()) {
aliases.remove(&fa.short);
if aliases.is_empty() {
doc.as_table_mut().remove(section);
}
}
}
Ok(())
}
pub fn remove_alias(&mut self, fa: &BackendArg, from: &str) -> eyre::Result<()> {
// Remove from both tool_alias and deprecated alias in memory
for alias_map in [&mut self.tool_alias, &mut self.alias] {
if let Some(aliases) = alias_map.get_mut(&fa.short) {
aliases.versions.shift_remove(from);
if aliases.versions.is_empty() && aliases.backend.is_none() {
alias_map.shift_remove(&fa.short);
}
}
}
let mut doc = self.doc_mut()?;
let doc = doc.get_mut().unwrap();
// Remove from both tool_alias and deprecated alias sections in doc
for section in ["tool_alias", "alias"] {
if let Some(aliases) = doc.get_mut(section).and_then(|v| v.as_table_mut()) {
if let Some(alias) = aliases
.get_mut(&fa.to_string())
.and_then(|v| v.as_table_mut())
{
if let Some(versions) = alias.get_mut("versions").and_then(|v| v.as_table_mut())
{
versions.remove(from);
if versions.is_empty() {
alias.remove("versions");
}
}
if alias.is_empty() {
aliases.remove(&fa.to_string());
}
}
if aliases.is_empty() {
doc.as_table_mut().remove(section);
}
}
}
Ok(())
}
pub fn set_shell_alias(&mut self, name: &str, command: &str) -> eyre::Result<()> {
self.shell_alias.insert(name.into(), command.into());
self.doc_mut()?
.get_mut()
.unwrap()
.entry("shell_alias")
.or_insert_with(table)
.as_table_like_mut()
.unwrap()
.insert(name, value(command));
Ok(())
}
pub fn remove_shell_alias(&mut self, name: &str) -> eyre::Result<()> {
self.shell_alias.shift_remove(name);
let mut doc = self.doc_mut()?;
let doc = doc.get_mut().unwrap();
if let Some(shell_alias) = doc.get_mut("shell_alias").and_then(|v| v.as_table_mut()) {
shell_alias.remove(name);
if shell_alias.is_empty() {
doc.as_table_mut().remove("shell_alias");
}
}
Ok(())
}
pub fn update_env<V: Into<Value>>(&mut self, key: &str, value: V) -> eyre::Result<()> {
let mut doc = self.doc_mut()?;
let mut env_tbl = doc
.get_mut()
.unwrap()
.entry("env")
.or_insert_with(table)
.as_table_mut()
.unwrap();
let key_parts = key.split('.').collect_vec();
for (i, k) in key_parts.iter().enumerate() {
if i == key_parts.len() - 1 {
let k = get_key_with_decor(env_tbl, k);
env_tbl.insert_formatted(&k, toml_edit::value(value));
break;
} else if !env_tbl.contains_key(k) {
env_tbl.insert_formatted(&Key::from(*k), toml_edit::table());
}
env_tbl = env_tbl.get_mut(k).unwrap().as_table_mut().unwrap();
}
Ok(())
}
pub fn update_env_age(
&mut self,
key: &str,
value: &str,
format: Option<AgeFormat>,
) -> eyre::Result<()> {
let mut doc = self.doc_mut()?;
let mut env_tbl = doc
.get_mut()
.unwrap()
.entry("env")
.or_insert_with(table)
.as_table_mut()
.unwrap();
// Create the age inline table
let mut outer_table = InlineTable::new();
// Check if we need the complex format or can use simplified form
match format {
Some(AgeFormat::Zstd) => {
// Non-default format, use full form: {age = {value = "...", format = "zstd"}}
let mut age_table = InlineTable::new();
age_table.insert("value", value.into());
age_table.insert("format", "zstd".into());
outer_table.insert("age", Value::InlineTable(age_table));
}
Some(AgeFormat::Raw) | None => {
// Default format or no format, use simplified form: {age = "..."}
outer_table.insert("age", value.into());
}
}
let key_parts = key.split('.').collect_vec();
for (i, k) in key_parts.iter().enumerate() {
if i == key_parts.len() - 1 {
let k = get_key_with_decor(env_tbl, k);
env_tbl
.insert_formatted(&k, toml_edit::Item::Value(Value::InlineTable(outer_table)));
break;
} else if !env_tbl.contains_key(k) {
env_tbl.insert_formatted(&Key::from(*k), toml_edit::table());
}
env_tbl = env_tbl.get_mut(k).unwrap().as_table_mut().unwrap();
}
Ok(())
}
pub fn remove_env(&mut self, key: &str) -> eyre::Result<()> {
let mut doc = self.doc_mut()?;
let env_tbl = doc
.get_mut()
.unwrap()
.entry("env")
.or_insert_with(table)
.as_table_mut()
.unwrap();
env_tbl.remove(key);
Ok(())
}
// Merge base OS env vars with env sections from this file,
// so they are available for templating.
// Note this only merges regular key-value variables; referenced files are not resolved.
fn update_context_env(&mut self, mut base_env: EnvMap) {
let env_vars = self
.env
.0
.iter()
.filter_map(|e| match e {
EnvDirective::Val(key, value, _) => Some((key.clone(), value.clone())),
_ => None,
})
.collect::<IndexMap<_, _>>();
base_env.extend(env_vars);
self.context.insert("env", &base_env);
}
fn parse_template(&self, input: &str) -> eyre::Result<String> {
self.parse_template_with_context(&self.context, input)
}
fn parse_template_with_context(
&self,
context: &TeraContext,
input: &str,
) -> eyre::Result<String> {
if !Self::contains_template_syntax(input) {
return Ok(input.to_string());
}
let dir = self.path.parent();
let output = get_tera(dir).render_str(input, context).wrap_err_with(|| {
let p = display_path(&self.path);
eyre!("failed to parse template {input} in {p}")
})?;
Ok(output)
}
}
impl ConfigFile for MiseToml {
fn config_type(&self) -> ConfigFileType {
ConfigFileType::MiseToml
}
fn get_path(&self) -> &Path {
self.path.as_path()
}
fn min_version(&self) -> Option<&MinVersionSpec> {
self.min_version.as_ref()
}
fn plugins(&self) -> eyre::Result<HashMap<String, String>> {
self.plugins
.clone()
.into_iter()
.map(|(k, v)| {
let v = self.parse_template(&v)?;
Ok((k, v))
})
.collect()
}
fn env_entries(&self) -> eyre::Result<Vec<EnvDirective>> {
let env_entries = self.env.0.iter().cloned();
let path_entries = self
.env_path
.iter()
.map(|p| EnvDirective::Path(p.clone(), Default::default()))
.collect_vec();
let env_files = self
.env_file
.iter()
.map(|p| EnvDirective::File(p.clone(), Default::default()))
.collect_vec();
let all = path_entries
.into_iter()
.chain(env_files)
.chain(env_entries)
.collect::<Vec<_>>();
Ok(all)
}
fn vars_entries(&self) -> eyre::Result<Vec<EnvDirective>> {
Ok(self.vars.0.clone())
}
fn tasks(&self) -> Vec<&Task> {
self.tasks.0.values().collect()
}
fn remove_tool(&self, fa: &BackendArg) -> eyre::Result<()> {
let mut tools = self.tools.lock().unwrap();
tools.shift_remove(fa);
let mut doc = self.doc_mut()?;
let doc = doc.get_mut().unwrap();
if let Some(tools) = doc.get_mut("tools")
&& let Some(tools) = tools.as_table_like_mut()
{
tools.remove(&fa.to_string());
if tools.is_empty() {
doc.as_table_mut().remove("tools");
}
}
Ok(())
}
fn replace_versions(&self, ba: &BackendArg, versions: Vec<ToolRequest>) -> eyre::Result<()> {
trace!("replacing versions {ba:?} {versions:?}");
let mut tools = self.tools.lock().unwrap();
let is_tools_sorted = is_tools_sorted(&tools); // was it previously sorted (if so we'll keep it sorted)
let existing = tools.entry(ba.clone()).or_default();
let output_empty_opts = |opts: &ToolVersionOptions| {
if opts.os.is_some() || !opts.install_env.is_empty() {
return false;
}
if let Some(reg_ba) = REGISTRY.get(ba.short.as_str()).and_then(|b| b.ba())
&& reg_ba.opts.as_ref().is_some_and(|o| o == opts)
{
// in this case the options specified are the same as in the registry so output no options and rely on the defaults
return true;
}
opts.is_empty()
};
existing.0 = versions
.iter()
.map(|tr| MiseTomlTool::from(tr.clone()))
.collect();
trace!("done replacing versions");
let mut doc = self.doc_mut()?;
trace!("got doc");
let tools = doc
.get_mut()
.unwrap()
.entry("tools")
.or_insert_with(table)
.as_table_mut()
.unwrap();
// create a key from the short name preserving any decorations like prefix/suffix if the key already exists
let key = get_key_with_decor(tools, ba.short.as_str());
// if a short name is used like "node", make sure we remove any long names like "core:node"
if ba.short != ba.full() {
tools.remove(&ba.full());
}
if versions.len() == 1 {
let options = versions[0].options();
if output_empty_opts(&options) {
tools.insert_formatted(&key, value(versions[0].version()));
} else {
let mut table = InlineTable::new();
table.insert("version", versions[0].version().into());
for (k, v) in options.opts {
table.insert(k, v.into());
}
if let Some(os) = options.os {
let mut arr = Array::new();
for o in os {
arr.push(Value::from(o));
}
table.insert("os", Value::Array(arr));
}
if !options.install_env.is_empty() {
let mut env = InlineTable::new();
for (k, v) in options.install_env {
env.insert(k, v.into());
}
table.insert("install_env", env.into());
}
tools.insert_formatted(&key, table.into());
}
} else {
let mut arr = Array::new();
for tr in versions {
let v = tr.version();
if output_empty_opts(&tr.options()) {
arr.push(v.to_string());
} else {
let mut table = InlineTable::new();
table.insert("version", v.to_string().into());
for (k, v) in tr.options().opts {
table.insert(k, v.clone().into());
}
arr.push(table);
}
}
tools.insert_formatted(&key, Item::Value(Value::Array(arr)));
}
if is_tools_sorted {
tools.sort_values();
}
Ok(())
}
fn save(&self) -> eyre::Result<()> {
let contents = self.dump()?;
if let Some(parent) = self.path.parent() {
create_dir_all(parent)?;
}
file::write(&self.path, contents)?;
trust(&config_trust_root(&self.path))?;
Ok(())
}
fn dump(&self) -> eyre::Result<String> {
Ok(self.doc()?.to_string())
}
fn source(&self) -> ToolSource {
ToolSource::MiseToml(self.path.clone())
}
fn to_tool_request_set(&self) -> eyre::Result<ToolRequestSet> {
let source = ToolSource::MiseToml(self.path.clone());
let mut trs = ToolRequestSet::new();
let tools = self.tools.lock().unwrap();
let mut context = self.context.clone();
if context.get("vars").is_none()
&& let Some(config) = Config::maybe_get()
{
if let Some(vars_results) = config.vars_results_cached() {
let vars = vars_results
.vars
.iter()
.map(|(k, (v, _))| (k.clone(), v.clone()))
.collect::<IndexMap<_, _>>();
context.insert("vars", &vars);
} else if !config.vars.is_empty() {
context.insert("vars", &config.vars);
}
}
for (ba, tvp) in tools.iter() {
for tool in &tvp.0 {
let version = self.parse_template_with_context(&context, &tool.tt.to_string())?;
let tvr = if let Some(mut options) = tool.options.clone() {
for v in options.opts.values_mut() {
*v = self.parse_template_with_context(&context, v)?;
}
let mut ba = ba.clone();
// Start with cached options but filter out install-time-only options
// when config provides its own options. This allows:
// - Changing url/asset_pattern/checksum without reinstall issues
// - Preserving post-install options like bin_path for binary discovery
let mut ba_opts = ba.opts().clone();
let install_time_keys =
crate::backend::install_time_option_keys_for_type(&ba.backend_type());
if !install_time_keys.is_empty() {
ba_opts.opts.retain(|k, _| {
// Keep option if it's NOT an install-time-only key
// Also filter platform-specific variants (platforms.X.key)
!install_time_keys.contains(k)
&& !install_time_keys.iter().any(|itk| {
k.starts_with("platforms.") && k.ends_with(&format!(".{itk}"))
})
});
}
ba_opts.merge(&options.opts);
// Copy os and install_env from config (not cached)
ba_opts.os = options.os.clone();
ba_opts.install_env = options.install_env.clone();
ba.set_opts(Some(ba_opts.clone()));
ToolRequest::new_opts(ba.into(), &version, ba_opts, source.clone())?
} else {
ToolRequest::new(ba.clone().into(), &version, source.clone())?
};
trs.add_version(tvr, &source);
}
}
Ok(trs)
}
fn aliases(&self) -> eyre::Result<AliasMap> {
// Emit deprecation warning if [alias] is used
if !self.alias.is_empty() {
deprecated!(
"alias",
"[alias] is deprecated, use [tool_alias] instead in {}",
display_path(&self.path)
);
}
// Merge alias and tool_alias, with tool_alias taking precedence
let mut combined: AliasMap = self.alias.clone();
for (k, v) in &self.tool_alias {
combined.insert(k.clone(), v.clone());
}
combined
.iter()
.map(|(k, v)| {
let versions = v
.clone()
.versions
.into_iter()
.map(|(k, v)| {
let v = self.parse_template(&v)?;
Ok::<(String, String), eyre::Report>((k, v))
})
.collect::<eyre::Result<IndexMap<_, _>>>()?;
Ok((
k.clone(),
Alias {
backend: v.backend.clone(),
versions,
},
))
})
.collect()
}
fn shell_aliases(&self) -> eyre::Result<IndexMap<String, String>> {
self.shell_alias
.iter()
.map(|(k, v)| {
let v = self.parse_template(v)?;
Ok((k.clone(), v))
})
.collect()
}
fn task_config(&self) -> &TaskConfig {
&self.task_config
}
fn experimental_monorepo_root(&self) -> Option<bool> {
self.experimental_monorepo_root
}
fn redactions(&self) -> &Redactions {
&self.redactions
}
fn watch_files(&self) -> eyre::Result<Vec<WatchFile>> {
self.watch_files
.iter()
.map(|wf| {
Ok(WatchFile {
patterns: wf
.patterns
.iter()
.map(|p| self.parse_template(p))
.collect::<eyre::Result<Vec<String>>>()?,
run: self.parse_template(&wf.run)?,
})
})
.collect()
}
fn hooks(&self) -> eyre::Result<Vec<Hook>> {
Ok(self
.hooks
.iter()
.map(|(hook, val)| {
let mut hooks = Hook::from_toml(*hook, val.clone())?;
for hook in hooks.iter_mut() {
hook.script = self.parse_template(&hook.script)?;
if let Some(shell) = &hook.shell {
hook.shell = Some(self.parse_template(shell)?);
}
}
eyre::Ok(hooks)
})
.collect::<eyre::Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect())
}
fn prepare_config(&self) -> Option<PrepareConfig> {
self.prepare.clone()
}
}
/// Returns a [`toml_edit::Key`] from the given `key`.
/// Preserves any surrounding whitespace (e.g. comments) if the key already exists in the provided [`toml_edit::Table`].
fn get_key_with_decor(table: &toml_edit::Table, key: &str) -> Key {
let mut key = Key::from(key);
if let Some((k, _)) = table.get_key_value(&key) {
if let Some(prefix) = k.leaf_decor().prefix() {
key.leaf_decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = k.leaf_decor().suffix() {
key.leaf_decor_mut().set_suffix(suffix.clone());
}
}
key
}
impl Debug for MiseToml {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let tools = self.to_tool_request_set().unwrap().to_string();
let title = format!("MiseToml({}): {tools}", &display_path(&self.path));
let mut d = f.debug_struct(&title);
if let Some(min_version) = &self.min_version {
d.field("min_version", &min_version.to_string());
}
if !self.env_file.is_empty() {
d.field("env_file", &self.env_file);
}
if let Ok(env) = self.env_entries()
&& !env.is_empty()
{
d.field("env", &env);
}
if !self.alias.is_empty() {
d.field("alias", &self.alias);
}
if !self.plugins.is_empty() {
d.field("plugins", &self.plugins);
}
if self.task_config.includes.is_some() {
d.field("task_config", &self.task_config);
}
d.finish()
}
}
impl Clone for MiseToml {
fn clone(&self) -> Self {
Self {
custom: self.custom.clone(),
min_version: self.min_version.clone(),
context: self.context.clone(),
path: self.path.clone(),
env_file: self.env_file.clone(),
env: self.env.clone(),
env_path: self.env_path.clone(),
alias: self.alias.clone(),
tool_alias: self.tool_alias.clone(),
shell_alias: self.shell_alias.clone(),
doc: Mutex::new(self.doc.lock().unwrap().clone()),
hooks: self.hooks.clone(),
tools: Mutex::new(self.tools.lock().unwrap().clone()),
redactions: self.redactions.clone(),
plugins: self.plugins.clone(),
tasks: self.tasks.clone(),
task_config: self.task_config.clone(),
settings: self.settings.clone(),
watch_files: self.watch_files.clone(),
prepare: self.prepare.clone(),
vars: self.vars.clone(),
experimental_monorepo_root: self.experimental_monorepo_root,
}
}
}
impl From<ToolRequest> for MiseTomlTool {
fn from(tr: ToolRequest) -> Self {
match tr {
ToolRequest::Version {
version,
options,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::Version(version),
options: if options.is_empty() {
None
} else {
Some(options)
},
},
ToolRequest::Path {
path,
options,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::Path(path),
options: if options.is_empty() {
None
} else {
Some(options)
},
},
ToolRequest::Prefix {
prefix,
options,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::Prefix(prefix),
options: if options.is_empty() {
None
} else {
Some(options)
},
},
ToolRequest::Ref {
ref_,
ref_type,
options,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::Ref(ref_, ref_type),
options: if options.is_empty() {
None
} else {
Some(options)
},
},
ToolRequest::Sub {
sub,
options,
orig_version,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::Sub { sub, orig_version },
options: if options.is_empty() {
None
} else {
Some(options)
},
},
ToolRequest::System {
options,
backend: _backend,
source: _source,
} => Self {
tt: ToolVersionType::System,
options: if options.is_empty() {
None
} else {
Some(options)
},
},
}
}
}
fn deserialize_min_version<'de, D>(deserializer: D) -> Result<Option<MinVersionSpec>, D::Error>
where
D: Deserializer<'de>,
{
struct MinVersionVisitor;
impl<'de> Visitor<'de> for MinVersionVisitor {
type Value = Option<MinVersionSpec>;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | true |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/config_root.rs | src/config/config_file/config_root.rs | use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock as Lazy, Mutex};
use path_absolutize::Absolutize;
use xx::regex;
use crate::config::is_global_config;
use crate::env;
static CONFIG_ROOT_CACHE: Lazy<Mutex<HashMap<PathBuf, PathBuf>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
pub fn reset() {
CONFIG_ROOT_CACHE.lock().unwrap().clear();
}
pub fn config_root(path: &Path) -> PathBuf {
if is_global_config(path) {
return env::MISE_GLOBAL_CONFIG_ROOT.to_path_buf();
}
let path = path
.absolutize()
.map(|p| p.to_path_buf())
.unwrap_or_else(|_| path.to_path_buf());
if let Some(cached) = CONFIG_ROOT_CACHE.lock().unwrap().get(&path).cloned() {
return cached;
}
let parts = path
.components()
.map(|c| c.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>();
let filename = parts.last().map(|p| p.as_str()).unwrap_or_default();
let parent = parts
.iter()
.nth_back(1)
.map(|p| p.as_str())
.unwrap_or_default();
let grandparent = parts
.iter()
.nth_back(2)
.map(|p| p.as_str())
.unwrap_or_default();
let great_grandparent = parts
.iter()
.nth_back(3)
.map(|p| p.as_str())
.unwrap_or_default();
let parent_path = || path.parent().unwrap().to_path_buf();
let grandparent_path = || parent_path().parent().unwrap().to_path_buf();
let great_grandparent_path = || grandparent_path().parent().unwrap().to_path_buf();
let great_great_grandparent_path = || great_grandparent_path().parent().unwrap().to_path_buf();
let is_mise_dir = |d: &str| d == "mise" || d == ".mise";
let is_config_filename = |f: &str| {
f == "config.toml" || f == "config.local.toml" || regex!(r"config\..+\.toml").is_match(f)
};
let out = if parent == "conf.d" && is_mise_dir(grandparent) {
if great_grandparent == ".config" {
great_great_grandparent_path()
} else {
great_grandparent_path()
}
} else if is_mise_dir(parent) && is_config_filename(filename) {
if grandparent == ".config" {
great_grandparent_path()
} else {
grandparent_path()
}
} else if parent == ".config" {
grandparent_path()
} else {
parent_path()
};
CONFIG_ROOT_CACHE.lock().unwrap().insert(path, out.clone());
out
}
#[cfg(test)]
#[cfg(unix)]
mod tests {
use super::*;
#[test]
fn test_config_root() {
for p in &[
"/foo/bar/.config/mise/conf.d/config.toml",
"/foo/bar/.config/mise/conf.d/foo.toml",
"/foo/bar/.config/mise/config.local.toml",
"/foo/bar/.config/mise/config.toml",
"/foo/bar/.config/mise.local.toml",
"/foo/bar/.config/mise.toml",
"/foo/bar/.mise.env.toml",
"/foo/bar/.mise.local.toml",
"/foo/bar/.mise.toml",
"/foo/bar/.mise/conf.d/config.toml",
"/foo/bar/.mise/conf.d/foo.toml",
"/foo/bar/.mise/config.local.toml",
"/foo/bar/.mise/config.toml",
"/foo/bar/.tool-versions",
"/foo/bar/mise.env.toml",
"/foo/bar/mise.local.toml",
"/foo/bar/mise.toml",
"/foo/bar/mise/config.local.toml",
"/foo/bar/mise/config.toml",
"/foo/bar/.config/mise/config.env.toml",
"/foo/bar/.config/mise.env.toml",
"/foo/bar/.mise/config.env.toml",
"/foo/bar/.mise.env.toml",
] {
println!("{p}");
assert_eq!(config_root(Path::new(p)), PathBuf::from("/foo/bar"));
}
}
#[test]
fn test_config_root_mise_dir() {
for p in &[
"/foo/mise/.config/mise/conf.d/config.toml",
"/foo/mise/.config/mise/conf.d/foo.toml",
"/foo/mise/.config/mise/config.local.toml",
"/foo/mise/.config/mise/config.toml",
"/foo/mise/.config/mise.local.toml",
"/foo/mise/.config/mise.toml",
"/foo/mise/.mise.env.toml",
"/foo/mise/.mise.local.toml",
"/foo/mise/.mise.toml",
"/foo/mise/.mise/conf.d/config.toml",
"/foo/mise/.mise/conf.d/foo.toml",
"/foo/mise/.mise/config.local.toml",
"/foo/mise/.mise/config.toml",
"/foo/mise/.tool-versions",
"/foo/mise/mise.env.toml",
"/foo/mise/mise.local.toml",
"/foo/mise/mise.toml",
"/foo/mise/mise/config.local.toml",
"/foo/mise/mise/config.toml",
"/foo/mise/.config/mise/config.env.toml",
"/foo/mise/.config/mise.env.toml",
"/foo/mise/.mise/config.env.toml",
"/foo/mise/.mise.env.toml",
] {
println!("{p}");
assert_eq!(config_root(Path::new(p)), PathBuf::from("/foo/mise"));
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/config/config_file/toml.rs | src/config/config_file/toml.rs | use crate::Result;
use std::collections::BTreeMap;
use std::fmt::Formatter;
use std::str::FromStr;
use serde::{Deserialize, de};
use crate::config::config_file::mise_toml::EnvList;
pub struct TomlParser<'a> {
table: &'a toml::Value,
}
impl<'a> TomlParser<'a> {
pub fn new(table: &'a toml::Value) -> Self {
Self { table }
}
pub fn parse_str<T>(&self, key: &str) -> Option<T>
where
T: From<String>,
{
self.table
.get(key)
.and_then(|value| value.as_str())
.map(|value| value.to_string().into())
}
pub fn parse_bool(&self, key: &str) -> Option<bool> {
self.table.get(key).and_then(|value| value.as_bool())
}
pub fn parse_array<T>(&self, key: &str) -> Option<Vec<T>>
where
T: From<String>,
{
self.table
.get(key)
.and_then(|value| value.as_array())
.map(|array| {
array
.iter()
.filter_map(|value| value.as_str().map(|v| v.to_string().into()))
.collect::<Vec<T>>()
})
}
pub fn parse_table(&self, key: &str) -> Option<BTreeMap<String, toml::Value>> {
self.table
.get(key)
.and_then(|value| value.as_table())
.map(|table| {
table
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect::<BTreeMap<String, toml::Value>>()
})
}
pub fn parse_env(&self, key: &str) -> Result<Option<EnvList>> {
self.table
.get(key)
.map(|value| {
EnvList::deserialize(value.clone())
.map_err(|e| eyre::eyre!("failed to parse env: {}", e))
})
.transpose()
}
}
pub fn deserialize_arr<'de, D, C, T>(deserializer: D) -> std::result::Result<C, D::Error>
where
D: de::Deserializer<'de>,
C: FromIterator<T> + Deserialize<'de>,
T: FromStr + Deserialize<'de>,
<T as FromStr>::Err: std::fmt::Display,
{
struct ArrVisitor<C, T>(std::marker::PhantomData<(C, T)>);
impl<'de, C, T> de::Visitor<'de> for ArrVisitor<C, T>
where
C: FromIterator<T> + Deserialize<'de>,
T: FromStr + Deserialize<'de>,
<T as FromStr>::Err: std::fmt::Display,
{
type Value = C;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
formatter.write_str("a string, a map, or a list of strings/maps")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where
E: de::Error,
{
let v = v.parse().map_err(de::Error::custom)?;
Ok(std::iter::once(v).collect())
}
fn visit_map<M>(self, map: M) -> std::result::Result<Self::Value, M::Error>
where
M: de::MapAccess<'de>,
{
let item = T::deserialize(de::value::MapAccessDeserializer::new(map))?;
Ok(std::iter::once(item).collect())
}
fn visit_seq<S>(self, seq: S) -> std::result::Result<Self::Value, S::Error>
where
S: de::SeqAccess<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrValue<T> {
String(String),
Value(T),
}
let mut seq = seq;
std::iter::from_fn(|| seq.next_element::<StringOrValue<T>>().transpose())
.map(|element| match element {
Ok(StringOrValue::String(s)) => s.parse().map_err(de::Error::custom),
Ok(StringOrValue::Value(v)) => Ok(v),
Err(e) => Err(e),
})
.collect()
}
}
deserializer.deserialize_any(ArrVisitor(std::marker::PhantomData))
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
use std::str::FromStr;
#[test]
fn test_parse_arr() {
let toml = r#"arr = ["1", "2", "3"]"#;
let table = toml::from_str(toml).unwrap();
let parser = TomlParser::new(&table);
let arr = parser.parse_array::<String>("arr");
assert_eq!(arr.unwrap().join(":"), "1:2:3");
}
#[test]
fn test_parse_table() {
let toml = r#"table = {foo = "bar", baz = "qux", num = 123}"#;
let table = toml::from_str(toml).unwrap();
let parser = TomlParser::new(&table);
let table = parser.parse_table("table").unwrap();
assert_eq!(table.len(), 3);
assert_eq!(table.get("foo").unwrap().as_str().unwrap(), "bar");
assert_eq!(table.get("baz").unwrap().as_str().unwrap(), "qux");
assert_eq!(table.get("num").unwrap().as_integer().unwrap(), 123);
}
#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum TestItem {
String(String),
Object { a: String, b: i64 },
}
impl FromStr for TestItem {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(TestItem::String(s.to_string()))
}
}
#[derive(Deserialize, Debug, PartialEq)]
struct TestStruct {
#[serde(default, deserialize_with = "deserialize_arr")]
arr: Vec<TestItem>,
}
#[test]
fn test_deserialize_arr_string() {
let toml_str = r#"arr = "hello""#;
let expected = TestStruct {
arr: vec![TestItem::String("hello".to_string())],
};
let actual: TestStruct = toml::from_str(toml_str).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn test_deserialize_arr_string_list() {
let toml_str = r#"arr = ["hello", "world"]"#;
let expected = TestStruct {
arr: vec![
TestItem::String("hello".to_string()),
TestItem::String("world".to_string()),
],
};
let actual: TestStruct = toml::from_str(toml_str).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn test_deserialize_arr_map() {
let toml_str = r#"arr = { a = "foo", b = 123 }"#;
let expected = TestStruct {
arr: vec![TestItem::Object {
a: "foo".to_string(),
b: 123,
}],
};
let actual: TestStruct = toml::from_str(toml_str).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn test_deserialize_arr_map_list() {
let toml_str = r#"
arr = [
{ a = "foo", b = 123 },
{ a = "bar", b = 456 },
]
"#;
let expected = TestStruct {
arr: vec![
TestItem::Object {
a: "foo".to_string(),
b: 123,
},
TestItem::Object {
a: "bar".to_string(),
b: 456,
},
],
};
let actual: TestStruct = toml::from_str(toml_str).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn test_deserialize_arr_mixed_list() {
let toml_str = r#"
arr = [
"hello",
{ a = "foo", b = 123 },
]
"#;
let expected = TestStruct {
arr: vec![
TestItem::String("hello".to_string()),
TestItem::Object {
a: "foo".to_string(),
b: 123,
},
],
};
let actual: TestStruct = toml::from_str(toml_str).unwrap();
assert_eq!(actual, expected);
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/asdf.rs | src/cli/asdf.rs | use std::sync::Arc;
use clap::ValueHint::CommandWithArguments;
use eyre::Result;
use itertools::Itertools;
use crate::cli::Cli;
use crate::cli::ls_remote::LsRemote;
use crate::config::Config;
use crate::toolset::ToolsetBuilder;
/// [internal] simulates asdf for plugins that call "asdf" internally
#[derive(Debug, clap::Args)]
#[clap(hide = true, verbatim_doc_comment)]
pub struct Asdf {
/// all arguments
#[clap(allow_hyphen_values = true, value_hint = CommandWithArguments, trailing_var_arg = true)]
args: Vec<String>,
}
impl Asdf {
pub async fn run(mut self) -> Result<()> {
let config = Config::get().await?;
let mut args = vec![String::from("mise")];
args.append(&mut self.args);
match args.get(1).map(|s| s.as_str()) {
Some("reshim") => Box::pin(Cli::run(&args)).await,
Some("list") => list_versions(&config, &args).await,
Some("install") => {
if args.len() == 4 {
let version = args.pop().unwrap();
args[2] = format!("{}@{}", args[2], version);
}
Box::pin(Cli::run(&args)).await
}
_ => Box::pin(Cli::run(&args)).await,
}
}
}
async fn list_versions(config: &Arc<Config>, args: &[String]) -> Result<()> {
if args[2] == "all" {
return LsRemote {
prefix: None,
all: false,
plugin: args.get(3).map(|s| s.parse()).transpose()?,
json: false,
}
.run()
.await;
}
let ts = ToolsetBuilder::new().build(config).await?;
let mut versions = ts.list_installed_versions(config).await?;
let plugin = match args.len() {
3 => Some(&args[2]),
_ => None,
};
if let Some(plugin) = plugin {
versions.retain(|(_, v)| &v.ba().to_string() == plugin);
for (_, version) in versions {
miseprintln!("{}", version.version);
}
} else {
for (plugin, versions) in &versions.into_iter().chunk_by(|(_, v)| v.ba().clone()) {
miseprintln!("{}", plugin);
for (_, tv) in versions {
miseprintln!(" {}", tv.version);
}
}
}
Ok(())
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/external.rs | src/cli/external.rs | use clap::Command;
use eyre::Result;
use std::collections::HashMap;
use std::sync::LazyLock as Lazy;
use crate::backend;
use crate::cli::args::BackendArg;
pub static COMMANDS: Lazy<HashMap<String, Command>> = Lazy::new(|| {
backend::list()
.into_iter()
.flat_map(|b| {
if let Some(p) = b.plugin() {
return p.external_commands().unwrap_or_else(|e| {
let p = p.name();
warn!("failed to load external commands for plugin {p}: {e:#}");
vec![]
});
}
vec![]
})
.map(|cmd| (cmd.get_name().to_string(), cmd))
.collect()
});
pub fn execute(ba: &BackendArg, mut cmd: Command, args: Vec<String>) -> Result<()> {
if let Some(subcommand) = cmd.find_subcommand(&args[0]) {
let backend = ba.backend()?;
if let Some(p) = backend.plugin() {
p.execute_external_command(subcommand.get_name(), args)?;
}
} else {
cmd.print_help().unwrap();
}
Ok(())
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/prune.rs | src/cli/prune.rs | use std::collections::BTreeMap;
use std::sync::Arc;
use crate::cli::args::{BackendArg, ToolArg};
use crate::config::tracking::Tracker;
use crate::config::{Config, Settings};
use crate::runtime_symlinks;
use crate::toolset::{ToolVersion, Toolset, ToolsetBuilder};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::ui::prompt;
use crate::{backend::Backend, config};
use console::style;
use eyre::Result;
use super::trust::Trust;
/// Delete unused versions of tools
///
/// mise tracks which config files have been used in ~/.local/state/mise/tracked-configs
/// Versions which are no longer the latest specified in any of those configs are deleted.
/// Versions installed only with environment variables `MISE_<PLUGIN>_VERSION` will be deleted,
/// as will versions only referenced on the command line `mise exec <PLUGIN>@<VERSION>`.
///
/// You can list prunable tools with `mise ls --prunable`
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Prune {
/// Prune only these tools
#[clap()]
pub installed_tool: Option<Vec<ToolArg>>,
/// Do not actually delete anything
#[clap(long, short = 'n')]
pub dry_run: bool,
/// Prune only tracked and trusted configuration links that point to non-existent configurations
#[clap(long)]
pub configs: bool,
/// Prune only unused versions of tools
#[clap(long)]
pub tools: bool,
}
impl Prune {
pub async fn run(self) -> Result<()> {
let mut config = Config::get().await?;
if self.configs || !self.tools {
self.prune_configs()?;
}
if self.tools || !self.configs {
let backends = self
.installed_tool
.as_ref()
.map(|it| it.iter().map(|ta| ta.ba.as_ref()).collect());
prune(&config, backends.unwrap_or_default(), self.dry_run).await?;
config = Config::reset().await?;
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?;
}
Ok(())
}
fn prune_configs(&self) -> Result<()> {
if self.dry_run {
info!("pruned configuration links {}", style("[dryrun]").bold());
} else {
Tracker::clean()?;
Trust::clean()?;
info!("pruned configuration links");
}
Ok(())
}
}
pub async fn prunable_tools(
config: &Arc<Config>,
tools: Vec<&BackendArg>,
) -> Result<Vec<(Arc<dyn Backend>, ToolVersion)>> {
let ts = ToolsetBuilder::new().build(config).await?;
let mut to_delete = ts
.list_installed_versions(config)
.await?
.into_iter()
.map(|(p, tv)| ((tv.ba().short.to_string(), tv.tv_pathname()), (p, tv)))
.collect::<BTreeMap<(String, String), (Arc<dyn Backend>, ToolVersion)>>();
if !tools.is_empty() {
to_delete.retain(|_, (_, tv)| tools.contains(&tv.ba()));
}
for cf in config.get_tracked_config_files().await?.values() {
let mut ts = Toolset::from(cf.to_tool_request_set()?);
ts.resolve(config).await?;
for (_, tv) in ts.list_current_versions() {
to_delete.remove(&(tv.ba().short.to_string(), tv.tv_pathname()));
}
}
Ok(to_delete.into_values().collect())
}
pub async fn prune(config: &Arc<Config>, tools: Vec<&BackendArg>, dry_run: bool) -> Result<()> {
let to_delete = prunable_tools(config, tools).await?;
delete(config, dry_run, to_delete).await
}
async fn delete(
config: &Arc<Config>,
dry_run: bool,
to_delete: Vec<(Arc<dyn Backend>, ToolVersion)>,
) -> Result<()> {
let mpr = MultiProgressReport::get();
for (p, tv) in to_delete {
let mut prefix = tv.style();
if dry_run {
prefix = format!("{} {} ", prefix, style("[dryrun]").bold());
}
let pr = mpr.add(&prefix);
if dry_run || Settings::get().yes || prompt::confirm_with_all(format!("remove {} ?", &tv))?
{
p.uninstall_version(config, &tv, pr.as_ref(), dry_run)
.await?;
runtime_symlinks::remove_missing_symlinks(p)?;
pr.finish();
}
}
Ok(())
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise prune --dry-run</bold>
rm -rf ~/.local/share/mise/versions/node/20.0.0
rm -rf ~/.local/share/mise/versions/node/20.0.1
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/uninstall.rs | src/cli/uninstall.rs | use std::sync::Arc;
use console::style;
use eyre::{Result, bail, eyre};
use itertools::Itertools;
use crate::backend::Backend;
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::toolset::{ToolRequest, ToolSource, ToolVersion, ToolsetBuilder};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{config, dirs, file};
/// Removes installed tool versions
///
/// This only removes the installed version, it does not modify mise.toml.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Uninstall {
/// Tool(s) to remove
#[clap(value_name = "INSTALLED_TOOL@VERSION", required_unless_present = "all")]
installed_tool: Vec<ToolArg>,
/// Delete all installed versions
#[clap(long, short)]
all: bool,
/// Do not actually delete anything
#[clap(long, short = 'n')]
dry_run: bool,
}
impl Uninstall {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
let tool_versions = if self.installed_tool.is_empty() && self.all {
self.get_all_tool_versions(&config).await?
} else {
self.get_requested_tool_versions(&config).await?
};
let tool_versions = tool_versions
.into_iter()
.unique_by(|(_, tv)| (tv.request.ba().short.clone(), tv.version.clone()))
.collect::<Vec<_>>();
if !self.all && tool_versions.len() > self.installed_tool.len() {
bail!("multiple tools specified, use --all to uninstall all versions");
}
let mpr = MultiProgressReport::get();
for (plugin, tv) in tool_versions {
if !plugin.is_version_installed(&config, &tv, true) {
warn!("{} is not installed", tv.style());
continue;
}
let pr = mpr.add(&tv.style());
if let Err(err) = plugin
.uninstall_version(&config, &tv, pr.as_ref(), self.dry_run)
.await
{
error!("{err}");
return Err(eyre!(err).wrap_err(format!("failed to uninstall {tv}")));
}
if self.dry_run {
pr.finish_with_message("uninstalled (dry-run)".into());
} else {
pr.finish_with_message("uninstalled".into());
}
}
file::touch_dir(&dirs::DATA)?;
let config = Config::reset().await?;
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?;
Ok(())
}
async fn get_all_tool_versions(
&self,
config: &Arc<Config>,
) -> Result<Vec<(Arc<dyn Backend>, ToolVersion)>> {
let ts = ToolsetBuilder::new().build(config).await?;
let tool_versions = ts
.list_installed_versions(config)
.await?
.into_iter()
.collect::<Vec<_>>();
Ok(tool_versions)
}
async fn get_requested_tool_versions(
&self,
config: &Arc<Config>,
) -> Result<Vec<(Arc<dyn Backend>, ToolVersion)>> {
let runtimes = ToolArg::double_tool_condition(&self.installed_tool)?;
let mut tool_versions = Vec::new();
for ta in runtimes {
let backend = ta.ba.backend()?;
let query = ta.tvr.as_ref().map(|tvr| tvr.version()).unwrap_or_default();
let installed_versions = backend.list_installed_versions();
let exact_match = installed_versions.iter().find(|v| v == &&query);
let matches = match exact_match {
Some(m) => vec![m],
None => installed_versions
.iter()
.filter(|v| v.starts_with(&query))
.collect_vec(),
};
let mut tvs = matches
.into_iter()
.map(|v| {
let tvr = ToolRequest::new(backend.ba().clone(), v, ToolSource::Unknown)?;
let tv = ToolVersion::new(tvr, v.into());
Ok((backend.clone(), tv))
})
.collect::<Result<Vec<_>>>()?;
if let Some(tvr) = &ta.tvr {
tvs.push((
backend.clone(),
tvr.resolve(config, &Default::default()).await?,
));
}
if tvs.is_empty() {
warn!(
"no versions found for {}",
style(&backend).blue().for_stderr()
);
}
tool_versions.extend(tvs);
}
Ok(tool_versions)
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# will uninstall specific version
$ <bold>mise uninstall node@18.0.0</bold>
# will uninstall the current node version (if only one version is installed)
$ <bold>mise uninstall node</bold>
# will uninstall all installed versions of node
$ <bold>mise uninstall --all node@18.0.0</bold> # will uninstall all node versions
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/link.rs | src/cli/link.rs | use std::path::PathBuf;
use clap::ValueHint;
use color_eyre::eyre::{Result, eyre};
use console::style;
use eyre::bail;
use path_absolutize::Absolutize;
use crate::file::{make_symlink, remove_all};
use crate::{cli::args::ToolArg, config::Config};
use crate::{config, file};
/// Symlinks a tool version into mise
///
/// Use this for adding installs either custom compiled outside mise or built with a different tool.
#[derive(Debug, clap::Args)]
#[clap(visible_alias = "ln", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Link {
/// Tool name and version to create a symlink for
#[clap(value_name = "TOOL@VERSION")]
tool: ToolArg,
/// The local path to the tool version
/// e.g.: ~/.nvm/versions/node/v20.0.0
#[clap(value_hint = ValueHint::DirPath, verbatim_doc_comment)]
path: PathBuf,
/// Overwrite an existing tool version if it exists
#[clap(long, short = 'f')]
force: bool,
}
impl Link {
pub async fn run(self) -> Result<()> {
let version = match self.tool.tvr {
Some(ref tvr) => tvr.version(),
None => bail!("must provide a version for {}", self.tool.style()),
};
let path = self.path.absolutize()?;
if !path.exists() {
warn!(
"Target path {} does not exist",
style(path.to_string_lossy()).cyan().for_stderr()
);
}
let target = self.tool.ba.installs_path.join(version);
if target.exists() {
if self.force {
remove_all(&target)?;
} else {
return Err(eyre!(
"Tool version {} already exists, use {} to overwrite",
self.tool.style(),
style("--force").yellow().for_stderr()
));
}
}
file::create_dir_all(target.parent().unwrap())?;
make_symlink(&path, &target)?;
let config = Config::reset().await?;
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?;
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# build node-20.0.0 with node-build and link it into mise
$ <bold>node-build 20.0.0 ~/.nodes/20.0.0</bold>
$ <bold>mise link node@20.0.0 ~/.nodes/20.0.0</bold>
# have mise use the node version provided by Homebrew
$ <bold>brew install node</bold>
$ <bold>mise link node@brew $(brew --prefix node)</bold>
$ <bold>mise use node@brew</bold>
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/test_tool.rs | src/cli/test_tool.rs | use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::file::display_path;
use crate::registry::{REGISTRY, RegistryTool};
use crate::tera::get_tera;
use crate::toolset::{InstallOptions, ToolsetBuilder};
use crate::ui::time;
use crate::{dirs, env, file};
use eyre::{Result, bail, eyre};
use std::path::{Path, PathBuf};
use std::{collections::BTreeSet, sync::Arc};
/// Test a tool installs and executes
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct TestTool {
/// Tool(s) to test
#[clap(required_unless_present_any = ["all", "all_config"])]
pub tools: Option<Vec<ToolArg>>,
/// Test every tool specified in registry.toml
#[clap(long, short, conflicts_with = "tools", conflicts_with = "all_config")]
pub all: bool,
/// Number of jobs to run in parallel
/// [default: 4]
#[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)]
pub jobs: Option<usize>,
/// Test all tools specified in config files
#[clap(long, conflicts_with = "tools", conflicts_with = "all")]
pub all_config: bool,
/// Also test tools not defined in registry.toml, guessing how to test it
#[clap(long)]
pub include_non_defined: bool,
/// Directly pipe stdin/stdout/stderr from plugin to user
/// Sets --jobs=1
#[clap(long, overrides_with = "jobs")]
pub raw: bool,
}
impl TestTool {
pub async fn run(self) -> Result<()> {
let mut errored = vec![];
self.github_summary(vec![
"Tool".to_string(),
"Duration".to_string(),
"Status".to_string(),
])?;
self.github_summary(vec![
"---".to_string(),
"---".to_string(),
"---".to_string(),
])?;
let mut config = Config::get().await?;
let target_tools = self.get_target_tools(&config).await?;
for (i, (tool, rt)) in target_tools.into_iter().enumerate() {
if *env::TEST_TRANCHE_COUNT > 0 && (i % *env::TEST_TRANCHE_COUNT) != *env::TEST_TRANCHE
{
continue;
}
let (cmd, expected) = if let Some(test) = &rt.test {
(test.0.to_string(), test.1)
} else if self.include_non_defined {
(format!("{} --version", tool.short), "__TODO__")
} else {
continue;
};
let start = std::time::Instant::now();
match self.test(&mut config, &tool, &cmd, expected).await {
Ok(_) => {
info!("{}: OK", tool.short);
self.github_summary(vec![
tool.short.clone(),
time::format_duration(start.elapsed()).to_string(),
":white_check_mark:".to_string(),
])?;
}
Err(err) => {
error!("{}: {:?}", tool.short, err);
errored.push(tool.short.clone());
self.github_summary(vec![
tool.short.clone(),
time::format_duration(start.elapsed()).to_string(),
":x:".to_string(),
])?;
}
};
}
if let Ok(github_summary) = env::var("GITHUB_STEP_SUMMARY") {
let mut content: String = "\n".into();
if !errored.is_empty() {
content.push_str(&format!("**Failed Tools**: {}\n", errored.join(", ")));
}
file::append(github_summary, content)?;
}
if !errored.is_empty() {
bail!("tools failed: {}", errored.join(", "));
}
Ok(())
}
async fn get_target_tools(
&self,
config: &Arc<Config>,
) -> Result<Vec<(ToolArg, &RegistryTool)>> {
if let Some(tools) = &self.tools {
let mut targets = Vec::new();
let mut not_found = Vec::new();
for tool_arg in tools {
if let Some(rt) = REGISTRY.get(tool_arg.short.as_str()) {
targets.push((tool_arg.clone(), rt));
} else {
not_found.push(tool_arg.short.clone());
}
}
if !not_found.is_empty() {
bail!("tools not found: {}", not_found.join(", "));
}
Ok(targets)
} else if self.all {
REGISTRY
.iter()
.filter(|(short, rt)| rt.short == **short) // Filter out aliases
.map(|(short, rt)| short.parse().map(|s| (s, rt)))
.collect()
} else if self.all_config {
let ts = ToolsetBuilder::new().build(config).await?;
let config_tools = ts
.versions
.keys()
.map(|t| t.short.clone())
.collect::<BTreeSet<_>>();
let mut targets = Vec::new();
for tool in config_tools {
if let Some(rt) = REGISTRY.get(tool.as_str()) {
targets.push((tool.parse()?, rt));
}
}
Ok(targets)
} else {
unreachable!()
}
}
fn github_summary(&self, parts: Vec<String>) -> Result<()> {
if let Ok(github_summary) = env::var("GITHUB_STEP_SUMMARY") {
file::append(github_summary, format!("| {} |\n", parts.join(" | ")))?;
}
Ok(())
}
async fn test(
&self,
config: &mut Arc<Config>,
tool: &ToolArg,
cmd: &str,
expected: &str,
) -> Result<()> {
// First, clean all backend data by removing directories
let pr = crate::ui::multi_progress_report::MultiProgressReport::get()
.add(&format!("cleaning {}", tool.short));
let mut cleaned_any = false;
// Remove entire installs directory for this tool
if tool.ba.installs_path.exists() {
info!(
"Removing installs directory: {}",
tool.ba.installs_path.display()
);
file::remove_all(&tool.ba.installs_path)?;
cleaned_any = true;
}
// Clear cache directory (contains metadata)
if tool.ba.cache_path.exists() {
info!("Removing cache directory: {}", tool.ba.cache_path.display());
file::remove_all(&tool.ba.cache_path)?;
cleaned_any = true;
}
// Clear downloads directory
if tool.ba.downloads_path.exists() {
info!(
"Removing downloads directory: {}",
tool.ba.downloads_path.display()
);
file::remove_all(&tool.ba.downloads_path)?;
cleaned_any = true;
}
pr.finish();
// Reset the config to clear in-memory backend metadata caches if we cleaned anything
if cleaned_any {
*config = Config::reset().await?;
}
let mut args = vec![tool.clone()];
args.extend(
tool.ba
.backend()?
.get_all_dependencies(false)?
.into_iter()
.map(|ba| ba.to_string().parse())
.collect::<Result<Vec<ToolArg>>>()?,
);
let mut ts = ToolsetBuilder::new()
.with_args(&args)
.with_default_to_latest(true)
.build(config)
.await?;
let opts = InstallOptions {
missing_args_only: false,
jobs: self.jobs,
raw: self.raw,
..Default::default()
};
ts.install_missing_versions(config, &opts).await?;
ts.notify_if_versions_missing(config).await;
let tv = if let Some(tv) = ts
.versions
.get(tool.ba.as_ref())
.and_then(|tvl| tvl.versions.first())
{
tv.clone()
} else {
warn!("no versions found for {tool}");
return Ok(());
};
let backend = tv.backend()?;
let env = ts.env_with_path(config).await?;
let mut which_parts = cmd.split_whitespace().collect::<Vec<_>>();
let cmd = which_parts.remove(0);
let mut which_cmd = backend
.which(config, &tv, cmd)
.await?
.unwrap_or(PathBuf::from(cmd));
if cfg!(windows) && which_cmd == Path::new("which") {
which_cmd = PathBuf::from("where");
}
let cmd = format!("{} {}", which_cmd.display(), which_parts.join(" "));
info!("$ {cmd}");
let mut cmd = if cfg!(windows) {
cmd!("cmd", "/C", cmd)
} else {
cmd!("sh", "-c", cmd)
};
cmd = cmd.stdout_capture();
for (k, v) in env.iter() {
cmd = cmd.env(k, v);
}
let res = cmd.unchecked().run()?;
match res.status.code() {
Some(0) => {}
Some(code) => {
if code == 127 {
let bin_dirs = backend.list_bin_paths(config, &tv).await?;
for bin_dir in &bin_dirs {
let bins = file::ls(bin_dir)?
.into_iter()
.filter(|p| file::is_executable(p))
.map(|p| p.file_name().unwrap().to_string_lossy().to_string())
.collect::<Vec<_>>();
info!(
"available bins in {}\n{}",
display_path(bin_dir),
bins.join("\n")
);
}
}
return Err(eyre!("command failed: exit code {}", code));
}
None => return Err(eyre!("command failed: terminated by signal")),
}
let mut ctx = config.tera_ctx.clone();
ctx.insert("version", &tv.version);
let mut tera = get_tera(dirs::CWD.as_ref().map(|d| d.as_path()));
let expected = tera.render_str(expected, &ctx)?;
let stdout = String::from_utf8(res.stdout)?;
miseprintln!("{}", stdout.trim_end());
if !stdout.contains(&expected) {
return Err(eyre!(
"expected output not found: {expected}, got: {stdout}"
));
}
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise test-tool ripgrep</bold>
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/local.rs | src/cli/local.rs | use std::{
path::{Path, PathBuf},
sync::Arc,
};
use color_eyre::eyre::{ContextCompat, Result, eyre};
use console::style;
use itertools::Itertools;
use crate::config::{Settings, config_file};
use crate::env::{MISE_DEFAULT_CONFIG_FILENAME, MISE_DEFAULT_TOOL_VERSIONS_FILENAME};
use crate::file::display_path;
use crate::{
cli::args::{BackendArg, ToolArg},
config::Config,
};
use crate::{env, file};
/// Sets/gets tool version in local .tool-versions or mise.toml
///
/// Use this to set a tool's version when within a directory
/// Use `mise global` to set a tool version globally
/// This uses `.tool-version` by default unless there is a `mise.toml` file or if `MISE_USE_TOML`
/// is set. A future v2 release of mise will default to using `mise.toml`.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, hide = true, alias = "l", after_long_help = AFTER_LONG_HELP)]
pub struct Local {
/// Tool(s) to add to .tool-versions/mise.toml
/// e.g.: node@20
/// if this is a single tool with no version,
/// the current value of .tool-versions/mise.toml will be displayed
#[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)]
tool: Vec<ToolArg>,
/// Recurse up to find a .tool-versions file rather than using the current directory only
/// by default this command will only set the tool in the current directory ("$PWD/.tool-versions")
#[clap(short, long, verbatim_doc_comment)]
parent: bool,
/// Save fuzzy version to `.tool-versions`
/// e.g.: `mise local --fuzzy node@20` will save `node 20` to .tool-versions
/// This is the default behavior unless MISE_ASDF_COMPAT=1
#[clap(long, overrides_with = "pin")]
fuzzy: bool,
/// Get the path of the config file
#[clap(long)]
path: bool,
/// Save exact version to `.tool-versions`
/// e.g.: `mise local --pin node@20` will save `node 20.0.0` to .tool-versions
#[clap(long, verbatim_doc_comment, overrides_with = "fuzzy")]
pin: bool,
/// Remove the plugin(s) from .tool-versions
#[clap(long, value_name = "PLUGIN", aliases = ["rm", "unset"])]
remove: Option<Vec<BackendArg>>,
}
impl Local {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
let path = if self.parent {
get_parent_path()?
} else {
get_path()?
};
local(
&config,
&path,
self.tool,
self.remove,
self.pin,
self.fuzzy,
self.path,
)
.await
}
}
fn get_path() -> Result<PathBuf> {
let cwd = env::current_dir()?;
let mise_toml = cwd.join(MISE_DEFAULT_CONFIG_FILENAME.as_str());
let tool_versions = cwd.join(MISE_DEFAULT_TOOL_VERSIONS_FILENAME.as_str());
if mise_toml.exists() {
Ok(mise_toml)
} else if tool_versions.exists() {
Ok(tool_versions)
} else if *env::MISE_USE_TOML {
Ok(mise_toml)
} else {
Ok(tool_versions)
}
}
pub fn get_parent_path() -> Result<PathBuf> {
let mut filenames = vec![MISE_DEFAULT_CONFIG_FILENAME.as_str()];
if !*env::MISE_USE_TOML {
filenames.push(MISE_DEFAULT_TOOL_VERSIONS_FILENAME.as_str());
}
file::find_up(&env::current_dir()?, &filenames)
.wrap_err_with(|| eyre!("no {} file found", filenames.join(" or "),))
}
#[allow(clippy::too_many_arguments)]
pub async fn local(
config: &Arc<Config>,
path: &Path,
runtime: Vec<ToolArg>,
remove: Option<Vec<BackendArg>>,
pin: bool,
fuzzy: bool,
show_path: bool,
) -> Result<()> {
deprecated!(
"local",
"mise local/global are deprecated. Use `mise use` instead."
);
let settings = Settings::try_get()?;
let cf = config_file::parse_or_init(path).await?;
if show_path {
miseprintln!("{}", path.display());
return Ok(());
}
if let Some(plugins) = &remove {
for plugin in plugins {
cf.remove_tool(plugin)?;
}
let tools = plugins
.iter()
.map(|r| style(&r.short).blue().for_stderr().to_string())
.join(" ");
miseprintln!("{} {} {tools}", style("mise").dim(), display_path(path));
}
if !runtime.is_empty() {
let runtimes = ToolArg::double_tool_condition(&runtime)?;
if cf.display_runtime(&runtimes)? {
return Ok(());
}
let pin = pin || (settings.asdf_compat && !fuzzy);
cf.add_runtimes(config, &runtimes, pin).await?;
let tools = runtimes.iter().map(|t| t.style()).join(" ");
miseprintln!("{} {} {tools}", style("mise").dim(), display_path(path));
}
if !runtime.is_empty() || remove.is_some() {
trace!("saving config file {}", display_path(path));
cf.save()?;
} else {
miseprint!("{}", cf.dump()?)?;
}
Ok(())
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# set the current version of node to 20.x for the current directory
# will use a precise version (e.g.: 20.0.0) in .tool-versions file
$ <bold>mise local node@20</bold>
# set node to 20.x for the current project (recurses up to find .tool-versions)
$ <bold>mise local -p node@20</bold>
# set the current version of node to 20.x for the current directory
# will use a fuzzy version (e.g.: 20) in .tool-versions file
$ <bold>mise local --fuzzy node@20</bold>
# removes node from .tool-versions
$ <bold>mise local --remove=node</bold>
# show the current version of node in .tool-versions
$ <bold>mise local node</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/ls.rs | src/cli/ls.rs | use comfy_table::{Attribute, Cell, Color};
use eyre::{Result, ensure};
use indexmap::IndexMap;
use itertools::Itertools;
use serde_derive::Serialize;
use std::path::PathBuf;
use std::sync::Arc;
use versions::Versioning;
use crate::backend::Backend;
use crate::cli::args::BackendArg;
use crate::cli::prune;
use crate::config;
use crate::config::Config;
use crate::toolset::{ToolSource, ToolVersion, Toolset};
use crate::ui::table::MiseTable;
/// List installed and active tool versions
///
/// This command lists tools that mise "knows about".
/// These may be tools that are currently installed, or those
/// that are in a config file (active) but may or may not be installed.
///
/// It's a useful command to get the current state of your tools.
#[derive(Debug, clap::Args)]
#[clap(visible_alias = "list", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Ls {
/// Only show tool versions from [TOOL]
#[clap(conflicts_with = "tool_flag")]
installed_tool: Option<Vec<BackendArg>>,
/// Only show tool versions currently specified in a mise.toml
#[clap(long, short)]
current: bool,
/// Only show tool versions currently specified in the global mise.toml
#[clap(long, short, conflicts_with = "local")]
global: bool,
/// Only show tool versions that are installed
/// (Hides tools defined in mise.toml but not installed)
#[clap(long, short)]
installed: bool,
/// Output in JSON format
#[clap(long, short = 'J')]
json: bool,
/// Only show tool versions currently specified in the local mise.toml
#[clap(long, short, conflicts_with = "global")]
local: bool,
/// Display missing tool versions
#[clap(long, short, conflicts_with = "installed")]
missing: bool,
/// Don't fetch information such as outdated versions
#[clap(long, short, hide = true)]
offline: bool,
#[clap(long = "plugin", short = 'p', hide = true)]
tool_flag: Option<BackendArg>,
/// Don't display headers
#[clap(long, alias = "no-headers", verbatim_doc_comment, conflicts_with_all = &["json"])]
no_header: bool,
/// Display whether a version is outdated
#[clap(long)]
outdated: bool,
/// Display versions matching this prefix
#[clap(long, requires = "installed_tool")]
prefix: Option<String>,
/// List only tools that can be pruned with `mise prune`
#[clap(long)]
prunable: bool,
}
impl Ls {
pub async fn run(mut self) -> Result<()> {
let config = Config::get().await?;
self.installed_tool = self
.installed_tool
.or_else(|| self.tool_flag.clone().map(|p| vec![p]));
self.verify_plugin()?;
let mut runtimes = if self.prunable {
self.get_prunable_runtime_list(&config).await?
} else {
self.get_runtime_list(&config).await?
};
if self.current || self.global || self.local {
// TODO: global is a little weird: it will show global versions as the active ones even if
// they're overridden locally
runtimes.retain(|(_, _, _, source)| !source.is_unknown());
}
if self.installed {
let mut installed_runtimes = vec![];
for (ls, p, tv, source) in runtimes {
if p.is_version_installed(&config, &tv, true) {
installed_runtimes.push((ls, p, tv, source));
}
}
runtimes = installed_runtimes;
}
if self.missing {
let mut missing_runtimes = vec![];
for (ls, p, tv, source) in runtimes {
if !p.is_version_installed(&config, &tv, true) {
missing_runtimes.push((ls, p, tv, source));
}
}
runtimes = missing_runtimes;
}
if let Some(prefix) = &self.prefix {
runtimes.retain(|(_, _, tv, _)| tv.version.starts_with(prefix));
}
if self.json {
self.display_json(&config, runtimes).await
} else {
self.display_user(&config, runtimes).await
}
}
fn verify_plugin(&self) -> Result<()> {
if let Some(plugins) = &self.installed_tool {
for ba in plugins {
if let Some(plugin) = ba.backend()?.plugin() {
ensure!(plugin.is_installed(), "{ba} is not installed");
}
}
}
Ok(())
}
async fn display_json(
&self,
config: &Arc<Config>,
runtimes: Vec<RuntimeRow<'_>>,
) -> Result<()> {
if let Some(plugins) = &self.installed_tool {
// only runtimes for 1 plugin
let runtimes: Vec<RuntimeRow<'_>> = runtimes
.into_iter()
.filter(|(_, p, _, _)| plugins.contains(p.ba()))
.collect();
let mut r = vec![];
for row in runtimes {
r.push(json_tool_version_from(config, row).await);
}
miseprintln!("{}", serde_json::to_string_pretty(&r)?);
return Ok(());
}
let mut plugins = JSONOutput::new();
for (plugin_name, runtimes) in &runtimes
.into_iter()
.chunk_by(|(_, p, _, _)| p.id().to_string())
{
let mut r = vec![];
for (ls, p, tv, source) in runtimes {
r.push(json_tool_version_from(config, (ls, p, tv, source)).await);
}
plugins.insert(plugin_name.clone(), r);
}
miseprintln!("{}", serde_json::to_string_pretty(&plugins)?);
Ok(())
}
async fn display_user<'a>(
&'a self,
config: &Arc<Config>,
runtimes: Vec<RuntimeRow<'a>>,
) -> Result<()> {
let mut rows = vec![];
for (ls, p, tv, source) in runtimes {
rows.push(Row {
tool: p.clone(),
version: version_status_from(config, (ls, p.as_ref(), &tv, &source)).await,
requested: match source.is_unknown() {
true => None,
false => Some(tv.request.version()),
},
source: if source.is_unknown() {
None
} else {
Some(source)
},
});
}
let mut table = MiseTable::new(self.no_header, &["Tool", "Version", "Source", "Requested"]);
for r in rows {
let row = vec![
r.display_tool(),
r.display_version(),
r.display_source(),
r.display_requested(),
];
table.add_row(row);
}
table.truncate(true).print()
}
async fn get_prunable_runtime_list(&self, config: &Arc<Config>) -> Result<Vec<RuntimeRow<'_>>> {
let installed_tool = self.installed_tool.clone().unwrap_or_default();
Ok(
prune::prunable_tools(config, installed_tool.iter().collect())
.await?
.into_iter()
.map(|(p, tv)| (self, p, tv, ToolSource::Unknown))
.collect(),
)
}
async fn get_runtime_list(&self, config: &Arc<Config>) -> Result<Vec<RuntimeRow<'_>>> {
let mut trs = config.get_tool_request_set().await?.clone();
if self.global {
trs = trs
.iter()
.filter(|(.., ts)| match ts {
ToolSource::MiseToml(p) => config::is_global_config(p),
_ => false,
})
.map(|(fa, tv, ts)| (fa.clone(), tv.clone(), ts.clone()))
.collect()
} else if self.local {
trs = trs
.iter()
.filter(|(.., ts)| match ts {
ToolSource::MiseToml(p) => !config::is_global_config(p),
_ => false,
})
.map(|(fa, tv, ts)| (fa.clone(), tv.clone(), ts.clone()))
.collect()
}
let mut ts = Toolset::from(trs);
ts.resolve(config).await?;
let rvs: Vec<RuntimeRow<'_>> = ts
.list_all_versions(config)
.await?
.into_iter()
.map(|(b, tv)| ((b, tv.version.clone()), tv))
.filter(|((b, _), _)| match &self.installed_tool {
Some(p) => p.contains(b.ba()),
None => true,
})
.sorted_by_cached_key(|((plugin_name, version), _)| {
(
plugin_name.clone(),
Versioning::new(version),
version.clone(),
)
})
.map(|(k, tv)| (self, k.0, tv.clone(), tv.request.source().clone()))
// if it isn't installed and it's not specified, don't show it
.filter(|(_ls, p, tv, source)| {
!source.is_unknown() || p.is_version_installed(config, tv, true)
})
.filter(|(_ls, p, _, _)| match &self.installed_tool {
Some(backend) => backend.contains(p.ba()),
None => true,
})
.collect();
Ok(rvs)
}
}
type JSONOutput = IndexMap<String, Vec<JSONToolVersion>>;
#[derive(Serialize)]
struct JSONToolVersion {
version: String,
#[serde(skip_serializing_if = "Option::is_none")]
requested_version: Option<String>,
install_path: PathBuf,
#[serde(skip_serializing_if = "Option::is_none")]
source: Option<IndexMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
symlinked_to: Option<PathBuf>,
installed: bool,
active: bool,
}
type RuntimeRow<'a> = (&'a Ls, Arc<dyn Backend>, ToolVersion, ToolSource);
struct Row {
tool: Arc<dyn Backend>,
version: VersionStatus,
source: Option<ToolSource>,
requested: Option<String>,
}
impl Row {
fn display_tool(&self) -> Cell {
Cell::new(&self.tool).fg(Color::Blue)
}
fn display_version(&self) -> Cell {
match &self.version {
VersionStatus::Active(version, outdated) => {
if *outdated {
Cell::new(format!("{version} (outdated)"))
.fg(Color::Yellow)
.add_attribute(Attribute::Bold)
} else {
Cell::new(version).fg(Color::Green)
}
}
VersionStatus::Inactive(version) => Cell::new(version).add_attribute(Attribute::Dim),
VersionStatus::Missing(version) => Cell::new(format!("{version} (missing)"))
.fg(Color::Red)
.add_attribute(Attribute::CrossedOut),
VersionStatus::Symlink(version, active) => {
let mut cell = Cell::new(format!("{version} (symlink)"));
if !*active {
cell = cell.add_attribute(Attribute::Dim);
}
cell
}
}
}
fn display_source(&self) -> Cell {
Cell::new(match &self.source {
Some(source) => source.to_string(),
None => String::new(),
})
}
fn display_requested(&self) -> Cell {
Cell::new(match &self.requested {
Some(s) => s.clone(),
None => String::new(),
})
}
}
async fn json_tool_version_from(config: &Arc<Config>, row: RuntimeRow<'_>) -> JSONToolVersion {
let (ls, p, tv, source) = row;
let vs: VersionStatus = version_status_from(config, (ls, p.as_ref(), &tv, &source)).await;
JSONToolVersion {
symlinked_to: p.symlink_path(&tv),
install_path: tv.install_path(),
version: tv.version.clone(),
requested_version: if source.is_unknown() {
None
} else {
Some(tv.request.version())
},
source: if source.is_unknown() {
None
} else {
Some(source.as_json())
},
installed: !matches!(vs, VersionStatus::Missing(_)),
active: match vs {
VersionStatus::Active(_, _) => true,
VersionStatus::Symlink(_, active) => active,
_ => false,
},
}
}
#[derive(Debug)]
enum VersionStatus {
Active(String, bool),
Inactive(String),
Missing(String),
Symlink(String, bool),
}
async fn version_status_from(
config: &Arc<Config>,
(ls, p, tv, source): (&Ls, &dyn Backend, &ToolVersion, &ToolSource),
) -> VersionStatus {
if p.symlink_path(tv).is_some() {
VersionStatus::Symlink(tv.version.clone(), !source.is_unknown())
} else if !p.is_version_installed(config, tv, true) {
VersionStatus::Missing(tv.version.clone())
} else if !source.is_unknown() {
let outdated = if ls.outdated {
p.is_version_outdated(config, tv).await
} else {
false
};
VersionStatus::Active(tv.version.clone(), outdated)
} else {
VersionStatus::Inactive(tv.version.clone())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise ls</bold>
node 20.0.0 ~/src/myapp/.tool-versions latest
python 3.11.0 ~/.tool-versions 3.10
python 3.10.0
$ <bold>mise ls --current</bold>
node 20.0.0 ~/src/myapp/.tool-versions 20
python 3.11.0 ~/.tool-versions 3.11.0
$ <bold>mise ls --json</bold>
{
"node": [
{
"version": "20.0.0",
"install_path": "/Users/jdx/.mise/installs/node/20.0.0",
"source": {
"type": "mise.toml",
"path": "/Users/jdx/mise.toml"
}
}
],
"python": [...]
}
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/global.rs | src/cli/global.rs | use eyre::Result;
use crate::cli::local::local;
use crate::config::Settings;
use crate::{
cli::args::{BackendArg, ToolArg},
config::Config,
};
/// Sets/gets the global tool version(s)
///
/// Displays the contents of global config after writing.
/// The file is `$HOME/.config/mise/config.toml` by default. It can be changed with `$MISE_GLOBAL_CONFIG_FILE`.
/// If `$MISE_GLOBAL_CONFIG_FILE` is set to anything that ends in `.toml`, it will be parsed as `mise.toml`.
/// Otherwise, it will be parsed as a `.tool-versions` file.
///
/// Use MISE_ASDF_COMPAT=1 to default the global config to ~/.tool-versions
///
/// Use `mise local` to set a tool version locally in the current directory.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, hide = true, after_long_help = AFTER_LONG_HELP)]
pub struct Global {
/// Tool(s) to add to .tool-versions
/// e.g.: node@20
/// If this is a single tool with no version, the current value of the global
/// .tool-versions will be displayed
#[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)]
tool: Vec<ToolArg>,
/// Save fuzzy version to `~/.tool-versions`
/// e.g.: `mise global --fuzzy node@20` will save `node 20` to ~/.tool-versions
/// this is the default behavior unless MISE_ASDF_COMPAT=1
#[clap(long, verbatim_doc_comment, overrides_with = "pin")]
fuzzy: bool,
/// Get the path of the global config file
#[clap(long)]
path: bool,
/// Save exact version to `~/.tool-versions`
/// e.g.: `mise global --pin node@20` will save `node 20.0.0` to ~/.tool-versions
#[clap(long, verbatim_doc_comment, overrides_with = "fuzzy")]
pin: bool,
/// Remove the plugin(s) from ~/.tool-versions
#[clap(long, value_name = "PLUGIN", aliases = ["rm", "unset"])]
remove: Option<Vec<BackendArg>>,
}
impl Global {
pub async fn run(self) -> Result<()> {
let settings = Settings::try_get()?;
let config = Config::get().await?;
local(
&config,
&settings.global_tools_file(),
self.tool,
self.remove,
self.pin,
self.fuzzy,
self.path,
)
.await
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# set the current version of node to 20.x
# will use a fuzzy version (e.g.: 20) in .tool-versions file
$ <bold>mise global --fuzzy node@20</bold>
# set the current version of node to 20.x
# will use a precise version (e.g.: 20.0.0) in .tool-versions file
$ <bold>mise global --pin node@20</bold>
# show the current version of node in ~/.tool-versions
$ <bold>mise global node</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/trust.rs | src/cli/trust.rs | use std::path::PathBuf;
use crate::config::config_file::config_trust_root;
use crate::config::{
ALL_CONFIG_FILES, DEFAULT_CONFIG_FILENAMES, Settings, config_file, config_files_in_dir,
is_global_config,
};
use crate::file::{display_path, remove_file};
use crate::{config, dirs, env, file};
use clap::ValueHint;
use eyre::Result;
use itertools::Itertools;
/// Marks a config file as trusted
///
/// This means mise will parse the file with potentially dangerous
/// features enabled.
///
/// This includes:
/// - environment variables
/// - templates
/// - `path:` plugin versions
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Trust {
/// The config file to trust
#[clap(value_hint = ValueHint::FilePath, verbatim_doc_comment)]
config_file: Option<PathBuf>,
/// Trust all config files in the current directory and its parents
#[clap(long, short, verbatim_doc_comment, conflicts_with_all = &["ignore", "untrust"])]
all: bool,
/// Do not trust this config and ignore it in the future
#[clap(long, conflicts_with = "untrust")]
ignore: bool,
/// Show the trusted status of config files from the current directory and its parents.
/// Does not trust or untrust any files.
#[clap(long, verbatim_doc_comment)]
show: bool,
/// No longer trust this config, will prompt in the future
#[clap(long)]
untrust: bool,
}
impl Trust {
pub async fn run(mut self) -> Result<()> {
if self.show {
return self.show();
}
if self.untrust {
self.untrust()
} else if self.ignore {
self.ignore()
} else if self.all {
while let Some(p) = self.get_next_untrusted() {
self.config_file = Some(p);
self.trust()?;
}
Ok(())
} else {
self.trust()
}
}
pub fn clean() -> Result<()> {
if dirs::TRUSTED_CONFIGS.is_dir() {
for path in file::ls(&dirs::TRUSTED_CONFIGS)? {
if !path.exists() {
remove_file(&path)?;
}
}
}
if dirs::IGNORED_CONFIGS.is_dir() {
for path in file::ls(&dirs::IGNORED_CONFIGS)? {
if !path.exists() {
remove_file(&path)?;
}
}
}
Ok(())
}
fn untrust(&self) -> Result<()> {
let path = match self.config_file() {
Some(filename) => filename,
None => match self.get_next() {
Some(path) => path,
None => {
warn!("No trusted config files found.");
return Ok(());
}
},
};
let cfr = config_trust_root(&path);
config_file::untrust(&cfr)?;
let cfr = cfr.canonicalize()?;
info!("untrusted {}", cfr.display());
let trusted_via_settings = Settings::get()
.trusted_config_paths()
.any(|p| cfr.starts_with(p));
if trusted_via_settings {
warn!("{cfr:?} is trusted via settings so it will still be trusted.");
}
Ok(())
}
fn ignore(&self) -> Result<()> {
let path = match self.config_file() {
Some(filename) => filename,
None => match self.get_next() {
Some(path) => path,
None => {
warn!("No trusted config files found.");
return Ok(());
}
},
};
let cfr = config_trust_root(&path);
config_file::add_ignored(cfr.clone())?;
let cfr = cfr.canonicalize()?;
info!("ignored {}", cfr.display());
let trusted_via_settings = Settings::get()
.trusted_config_paths()
.any(|p| cfr.starts_with(p));
if trusted_via_settings {
warn!("{cfr:?} is trusted via settings so it will still be trusted.");
}
Ok(())
}
fn trust(&self) -> Result<()> {
let path = match self.config_file() {
Some(filename) => config_trust_root(&filename),
None => match self.get_next_untrusted() {
Some(path) => path,
None => {
warn!("No untrusted config files found.");
return Ok(());
}
},
};
config_file::trust(&path)?;
let cfr = path.canonicalize()?;
info!("trusted {}", cfr.display());
Ok(())
}
fn config_file(&self) -> Option<PathBuf> {
self.config_file.as_ref().map(|config_file| {
if config_file.is_dir() {
config_files_in_dir(config_file)
.last()
.cloned()
.unwrap_or(config_file.join(&*env::MISE_DEFAULT_CONFIG_FILENAME))
} else {
config_file.clone()
}
})
}
fn get_next(&self) -> Option<PathBuf> {
ALL_CONFIG_FILES.first().cloned()
}
fn get_next_untrusted(&self) -> Option<PathBuf> {
config::load_config_paths(&DEFAULT_CONFIG_FILENAMES, true)
.into_iter()
.filter(|p| !is_global_config(p))
.map(|p| config_trust_root(&p))
.unique()
.find(|ctr| !config_file::is_trusted(ctr))
}
fn show(&self) -> Result<()> {
let trusted = config::load_config_paths(&DEFAULT_CONFIG_FILENAMES, true)
.into_iter()
.filter(|p| !is_global_config(p))
.map(|p| config_trust_root(&p))
.unique()
.map(|p| (display_path(&p), config_file::is_trusted(&p)))
.rev()
.collect::<Vec<_>>();
if trusted.is_empty() {
info!("No trusted config files found.");
}
for (dp, trusted) in trusted {
if trusted {
miseprintln!("{dp}: trusted");
} else {
miseprintln!("{dp}: untrusted");
}
}
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# trusts ~/some_dir/mise.toml
$ <bold>mise trust ~/some_dir/mise.toml</bold>
# trusts mise.toml in the current or parent directory
$ <bold>mise trust</bold>
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/version.rs | src/cli/version.rs | use std::time::Duration;
use console::style;
use eyre::Result;
use std::sync::LazyLock as Lazy;
use versions::Versioning;
use crate::build_time::BUILD_TIME;
use crate::cli::self_update::SelfUpdate;
use crate::file::modified_duration;
use crate::ui::style;
use crate::{dirs, duration, env, file};
/// Display the version of mise
///
/// Displays the version, os, architecture, and the date of the build.
///
/// If the version is out of date, it will display a warning.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, visible_alias = "v", after_long_help = AFTER_LONG_HELP)]
pub struct Version {
/// Print the version information in JSON format
#[clap(short = 'J', long)]
json: bool,
}
impl Version {
pub async fn run(self) -> Result<()> {
if self.json {
self.json().await?
} else {
show_version()?;
show_latest().await;
}
Ok(())
}
async fn json(&self) -> Result<()> {
let json = serde_json::json!({
"version": *VERSION,
"latest": get_latest_version(duration::DAILY).await,
"os": *OS,
"arch": *ARCH,
"build_time": BUILD_TIME.to_string(),
});
println!("{}", serde_json::to_string_pretty(&json)?);
Ok(())
}
}
pub static OS: Lazy<String> = Lazy::new(|| env::consts::OS.into());
pub static ARCH: Lazy<String> = Lazy::new(|| {
match env::consts::ARCH {
"x86_64" => "x64",
"aarch64" => "arm64",
_ => env::consts::ARCH,
}
.to_string()
});
pub static VERSION_PLAIN: Lazy<String> = Lazy::new(|| {
let mut v = V.to_string();
if cfg!(debug_assertions) {
v.push_str("-DEBUG");
};
v
});
pub static VERSION: Lazy<String> = Lazy::new(|| {
let build_time = BUILD_TIME.format("%Y-%m-%d");
let v = &*VERSION_PLAIN;
format!("{v} {os}-{arch} ({build_time})", os = *OS, arch = *ARCH)
});
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise version</bold>
$ <bold>mise --version</bold>
$ <bold>mise -v</bold>
$ <bold>mise -V</bold>
"#
);
pub static V: Lazy<Versioning> = Lazy::new(|| Versioning::new(env!("CARGO_PKG_VERSION")).unwrap());
pub fn print_version_if_requested(args: &[String]) -> std::io::Result<bool> {
if args.len() == 2 && !*crate::env::IS_RUNNING_AS_SHIM {
let cmd = &args[1].to_lowercase();
if cmd == "version" || cmd == "-v" || cmd == "--version" || cmd == "v" {
show_version()?;
return Ok(true);
}
}
debug!("Version: {}", *VERSION);
Ok(false)
}
fn show_version() -> std::io::Result<()> {
if console::user_attended() {
let banner = style::nred(
r#"
_ __
____ ___ (_)_______ ___ ____ ____ / /___ _________
/ __ `__ \/ / ___/ _ \______/ _ \/ __ \______/ __ \/ / __ `/ ___/ _ \
/ / / / / / (__ ) __/_____/ __/ / / /_____/ /_/ / / /_/ / /__/ __/
/_/ /_/ /_/_/____/\___/ \___/_/ /_/ / .___/_/\__,_/\___/\___/
/_/"#
.trim_start_matches("\n"),
);
let jdx = style::nbright("by @jdx");
miseprintln!("{banner} {jdx}");
}
miseprintln!("{}", *VERSION);
Ok(())
}
pub async fn show_latest() {
if ci_info::is_ci() && !cfg!(test) {
return;
}
if let Some(latest) = check_for_new_version(duration::DAILY).await {
warn!("mise version {} available", latest);
if SelfUpdate::is_available() {
let cmd = style("mise self-update").bright().yellow().for_stderr();
warn!("To update, run {}", cmd);
} else if let Some(instructions) = crate::cli::self_update::upgrade_instructions_text() {
warn!("{}", instructions);
}
}
}
pub async fn check_for_new_version(cache_duration: Duration) -> Option<String> {
if let Some(latest) = get_latest_version(cache_duration)
.await
.and_then(Versioning::new)
&& *V < latest
{
return Some(latest.to_string());
}
None
}
async fn get_latest_version(duration: Duration) -> Option<String> {
let version_file_path = dirs::CACHE.join("latest-version");
if let Ok(metadata) = modified_duration(&version_file_path)
&& metadata < duration
&& let Some(version) = file::read_to_string(&version_file_path)
.ok()
.map(|s| s.trim().to_string())
.and_then(Versioning::new)
&& *V <= version
{
return Some(version.to_string());
}
let _ = file::create_dir_all(*dirs::CACHE);
let version = get_latest_version_call().await;
let _ = file::write(version_file_path, version.clone().unwrap_or_default());
version
}
#[cfg(test)]
async fn get_latest_version_call() -> Option<String> {
Some("0.0.0".to_string())
}
#[cfg(not(test))]
async fn get_latest_version_call() -> Option<String> {
let url = "https://mise.jdx.dev/VERSION";
debug!("checking mise version from {}", url);
match crate::http::HTTP_VERSION_CHECK.get_text(url).await {
Ok(text) => {
debug!("got version {text}");
Some(text.trim().to_string())
}
Err(err) => {
debug!("failed to check for version: {:#?}", err);
None
}
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/mcp.rs | src/cli/mcp.rs | use crate::Result;
use crate::config::Config;
use clap::Parser;
use rmcp::{
RoleServer, ServiceExt,
handler::server::ServerHandler,
model::{
AnnotateAble, CallToolRequestParam, CallToolResult, Content, ErrorCode, ErrorData,
Implementation, ListResourcesResult, ListToolsResult, PaginatedRequestParam,
ProtocolVersion, RawResource, ReadResourceRequestParam, ReadResourceResult,
ResourceContents, ServerCapabilities, ServerInfo,
},
service::RequestContext,
};
use serde_json::{Value, json};
use std::borrow::Cow;
use std::collections::HashMap;
/// [experimental] Run Model Context Protocol (MCP) server
///
/// This command starts an MCP server that exposes mise functionality
/// to AI assistants over stdin/stdout using JSON-RPC protocol.
///
/// The MCP server provides access to:
/// - Installed and available tools
/// - Task definitions and execution
/// - Environment variables
/// - Configuration information
///
/// Resources available:
/// - mise://tools - List all tools (use ?include_inactive=true to include inactive tools)
/// - mise://tasks - List all tasks with their configurations
/// - mise://env - List all environment variables
/// - mise://config - Show configuration files and project root
///
/// Note: This is primarily intended for integration with AI assistants like Claude,
/// Cursor, or other tools that support the Model Context Protocol.
#[derive(Debug, Parser)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Mcp {}
#[derive(Clone)]
struct MiseServer {}
impl MiseServer {
fn new() -> Self {
Self {}
}
}
impl ServerHandler for MiseServer {
fn get_info(&self) -> ServerInfo {
ServerInfo {
protocol_version: ProtocolVersion::V_2025_03_26,
capabilities: ServerCapabilities::builder()
.enable_resources()
.enable_tools()
.build(),
server_info: Implementation::from_build_env(),
instructions: Some("Mise MCP server provides access to tools, tasks, environment variables, and configuration".to_string()),
}
}
async fn list_resources(
&self,
_pagination: Option<PaginatedRequestParam>,
_context: RequestContext<RoleServer>,
) -> std::result::Result<ListResourcesResult, ErrorData> {
let resources = vec![
RawResource::new("mise://tools", "Installed Tools".to_string()).no_annotation(),
RawResource::new("mise://tasks", "Available Tasks".to_string()).no_annotation(),
RawResource::new("mise://env", "Environment Variables".to_string()).no_annotation(),
RawResource::new("mise://config", "Configuration".to_string()).no_annotation(),
];
Ok(ListResourcesResult {
resources,
next_cursor: None,
})
}
async fn read_resource(
&self,
params: ReadResourceRequestParam,
_context: RequestContext<RoleServer>,
) -> std::result::Result<ReadResourceResult, ErrorData> {
// Parse URI to extract query parameters
// Example: mise://tools?include_inactive=true
let url = url::Url::parse(¶ms.uri).map_err(|e| ErrorData {
code: ErrorCode(400),
message: Cow::Owned(format!("Invalid URI: {e}")),
data: None,
})?;
// Parse query parameters
// include_inactive=true will show all installed tools, not just active ones
let include_inactive = url
.query_pairs()
.any(|(key, value)| key == "include_inactive" && value == "true");
match (url.scheme(), url.host_str()) {
("mise", Some("tools")) => {
// Return tool information
// By default only shows active tools (those in current .mise.toml)
// With ?include_inactive=true, shows all installed tools
let config = Config::get().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load config: {e}")),
data: None,
})?;
// Get tool request set and resolve toolset
let trs = config
.get_tool_request_set()
.await
.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to get tool request set: {e}")),
data: None,
})?
.clone();
let mut ts = crate::toolset::Toolset::from(trs);
ts.resolve(&config).await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to resolve toolset: {e}")),
data: None,
})?;
// Get current versions to determine which are active
let current_versions = ts.list_current_versions();
let active_versions: std::collections::HashSet<String> = current_versions
.iter()
.map(|(backend, tv)| format!("{}@{}", backend.id(), tv.version))
.collect();
// Determine which versions to include
let versions = if include_inactive {
// Include all versions (active + installed)
ts.list_all_versions(&config).await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to list tool versions: {e}")),
data: None,
})?
} else {
// Only include active versions (current)
current_versions
};
// Group by tool and create JSON output
// Output format: { "node": [{"version": "20.11.0", "active": true, ...}], ... }
let mut tools_map: std::collections::HashMap<String, Vec<Value>> =
std::collections::HashMap::new();
for (backend, tv) in versions {
let tool_name = backend.id().to_string();
let install_path = tv.install_path();
let installed = install_path.exists();
let version_key = format!("{}@{}", backend.id(), tv.version);
let version_info = json!({
"version": tv.version.clone(),
"requested_version": tv.request.version(),
"install_path": install_path.to_string_lossy(),
"installed": installed,
"active": active_versions.contains(&version_key),
"source": tv.request.source().as_json(),
});
tools_map.entry(tool_name).or_default().push(version_info);
}
let text = serde_json::to_string_pretty(&tools_map).unwrap();
let contents = vec![ResourceContents::TextResourceContents {
uri: params.uri.clone(),
mime_type: Some("application/json".to_string()),
text,
}];
Ok(ReadResourceResult { contents })
}
("mise", Some("tasks")) => {
let config = Config::get().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load config: {e}")),
data: None,
})?;
let tasks = config.tasks().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load tasks: {e}")),
data: None,
})?;
let task_list: Vec<_> = tasks.iter().map(|(name, task)| {
json!({
"name": name,
"description": task.description.clone(),
"aliases": task.aliases,
"source": task.config_source.to_string_lossy(),
"depends": task.depends.iter().map(|d| d.task.clone()).collect::<Vec<_>>(),
"depends_post": task.depends_post.iter().map(|d| d.task.clone()).collect::<Vec<_>>(),
"wait_for": task.wait_for.iter().map(|d| d.task.clone()).collect::<Vec<_>>(),
"env": json!({}), // EnvList is not directly iterable, keeping empty for now
"dir": task.dir.clone(),
"hide": task.hide,
"raw": task.raw,
"sources": task.sources.clone(),
"outputs": task.outputs.clone(),
"shell": task.shell.clone(),
"quiet": task.quiet,
"silent": task.silent,
"tools": task.tools.clone(),
"run": task.run_script_strings(),
"usage": task.usage.clone(),
})
}).collect();
let text = serde_json::to_string_pretty(&task_list).unwrap();
let contents = vec![ResourceContents::TextResourceContents {
uri: params.uri.clone(),
mime_type: Some("application/json".to_string()),
text,
}];
Ok(ReadResourceResult { contents })
}
("mise", Some("env")) => {
let config = Config::get().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load config: {e}")),
data: None,
})?;
let env_template = config.env().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load env: {e}")),
data: None,
})?;
let mut env_map = HashMap::new();
for (k, v) in env_template.iter() {
env_map.insert(k.clone(), v.clone());
}
let text = serde_json::to_string_pretty(&env_map).unwrap();
let contents = vec![ResourceContents::TextResourceContents {
uri: params.uri.clone(),
mime_type: Some("application/json".to_string()),
text,
}];
Ok(ReadResourceResult { contents })
}
("mise", Some("config")) => {
let config = Config::get().await.map_err(|e| ErrorData {
code: ErrorCode(500),
message: Cow::Owned(format!("Failed to load config: {e}")),
data: None,
})?;
let config_info = json!({
"config_files": config.config_files.keys().collect::<Vec<_>>(),
"project_root": config.project_root.as_ref().map(|p| p.to_string_lossy()),
});
let text = serde_json::to_string_pretty(&config_info).unwrap();
let contents = vec![ResourceContents::TextResourceContents {
uri: params.uri.clone(),
mime_type: Some("application/json".to_string()),
text,
}];
Ok(ReadResourceResult { contents })
}
_ => Err(ErrorData {
code: ErrorCode(404),
message: Cow::Owned(format!("Unknown resource URI: {}", params.uri)),
data: None,
}),
}
}
async fn list_tools(
&self,
_pagination: Option<PaginatedRequestParam>,
_context: RequestContext<RoleServer>,
) -> std::result::Result<ListToolsResult, ErrorData> {
// For now, return empty tools list
Ok(ListToolsResult {
tools: vec![],
next_cursor: None,
})
}
async fn call_tool(
&self,
request: CallToolRequestParam,
_context: RequestContext<RoleServer>,
) -> std::result::Result<CallToolResult, ErrorData> {
match &request.name[..] {
"install_tool" => Ok(CallToolResult::success(vec![Content::text(
"Tool installation not yet implemented".to_string(),
)])),
"run_task" => Ok(CallToolResult::success(vec![Content::text(
"Task execution not yet implemented".to_string(),
)])),
_ => Err(ErrorData {
code: ErrorCode(404),
message: Cow::Owned(format!("Unknown tool: {}", request.name)),
data: None,
}),
}
}
}
impl Mcp {
pub async fn run(self) -> Result<()> {
let settings = crate::config::Settings::get();
settings.ensure_experimental("mcp")?;
eprintln!("Starting mise MCP server...");
let server = MiseServer::new();
// Create stdio transport and serve
let service = server
.serve(rmcp::transport::stdio())
.await
.map_err(|e| eyre::eyre!("Failed to create service: {}", e))?;
// Wait for the service to complete
service
.waiting()
.await
.map_err(|e| eyre::eyre!("Service error: {}", e))?;
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# Start the MCP server (typically used by AI assistant tools)
$ <bold>mise mcp</bold>
# Example integration with Claude Desktop (add to claude_desktop_config.json):
{
"mcpServers": {
"mise": {
"command": "mise",
"args": ["mcp"]
}
}
}
# Interactive testing with JSON-RPC commands:
$ <bold>echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | mise mcp</bold>
# Resources you can query:
- <bold>mise://tools</bold> - List active tools
- <bold>mise://tools?include_inactive=true</bold> - List all installed tools
- <bold>mise://tasks</bold> - List all tasks
- <bold>mise://env</bold> - List environment variables
- <bold>mise://config</bold> - Show configuration info
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/unuse.rs | src/cli/unuse.rs | use std::{path::PathBuf, sync::Arc};
use crate::cli::args::ToolArg;
use crate::cli::prune::prune;
use crate::config::config_file::ConfigFile;
use crate::config::{Config, config_file};
use crate::file::display_path;
use crate::{config, env};
use eyre::Result;
use itertools::Itertools;
use path_absolutize::Absolutize;
/// Removes installed tool versions from mise.toml
///
/// By default, this will use the `mise.toml` file that has the tool defined.
///
/// 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.
///
/// Will also prune the installed version if no other configurations are using it.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, visible_aliases = ["rm", "remove"], after_long_help = AFTER_LONG_HELP)]
pub struct Unuse {
/// Tool(s) to remove
#[clap(value_name = "INSTALLED_TOOL@VERSION", required = true)]
installed_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>,
/// Use the global config file (`~/.config/mise/config.toml`) instead of the local one
#[clap(short, long, overrides_with_all = & ["path", "env"])]
global: 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>,
/// Do not also prune the installed version
#[clap(long)]
no_prune: bool,
}
impl Unuse {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
let cf = self.get_config_file(&config).await?;
let tools = cf.to_tool_request_set()?.tools;
let mut removed: Vec<&ToolArg> = vec![];
for ta in &self.installed_tool {
if let Some(tool_requests) = tools.get(ta.ba.as_ref()) {
let should_remove = if let Some(v) = &ta.version {
tool_requests.iter().any(|tv| &tv.version() == v)
} else {
true
};
// TODO: this won't work properly for unusing a specific version in of multiple in a config
if should_remove {
removed.push(ta);
cf.remove_tool(&ta.ba)?;
}
}
}
if removed.is_empty() {
debug!("no tools to remove");
} else {
cf.save()?;
let removals = removed.iter().join(", ");
info!("removed: {removals} from {}", display_path(cf.get_path()));
}
if !self.no_prune {
prune(
&config,
self.installed_tool
.iter()
.map(|ta| ta.ba.as_ref())
.collect(),
false,
)
.await?;
let config = Config::reset().await?;
let ts = config.get_toolset().await?;
config::rebuild_shims_and_runtime_symlinks(&config, ts, &[]).await?;
}
Ok(())
}
async fn get_config_file(&self, config: &Config) -> Result<Arc<dyn ConfigFile>> {
let cwd = env::current_dir()?;
let path = if self.global {
config::global_config_path()
} else 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 if let Some(env) = &self.env {
let p = cwd.join(format!(".mise.{env}.toml"));
if p.exists() {
p
} else {
cwd.join(format!("mise.{env}.toml"))
}
} else if env::in_home_dir() {
config::global_config_path()
} else {
for cf in config.config_files.values() {
if cf
.to_tool_request_set()?
.tools
.keys()
.any(|ba| self.installed_tool.iter().any(|ta| &ta.ba == ba))
{
return config_file::parse(cf.get_path()).await;
}
}
config::local_toml_config_path()
};
config_file::parse_or_init(&path).await
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
# will uninstall specific version
$ <bold>mise unuse node@18.0.0</bold>
# will uninstall specific version from global config
$ <bold>mise unuse -g node@18.0.0</bold>
# will uninstall specific version from .mise.local.toml
$ <bold>mise unuse --env local node@20</bold>
# will uninstall specific version from .mise.staging.toml
$ <bold>mise unuse --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/outdated.rs | src/cli/outdated.rs | use std::collections::HashSet;
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::toolset::outdated_info::OutdatedInfo;
use crate::toolset::{ResolveOptions, ToolsetBuilder};
use crate::ui::table;
use eyre::Result;
use indexmap::IndexMap;
use tabled::settings::Remove;
use tabled::settings::location::ByColumnName;
/// Shows outdated tool versions
///
/// See `mise upgrade` to upgrade these versions.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Outdated {
/// Tool(s) to show outdated versions for
/// e.g.: node@20 python@3.10
/// If not specified, all tools in global and local configs will be shown
#[clap(value_name = "TOOL@VERSION", verbatim_doc_comment)]
pub tool: Vec<ToolArg>,
/// Output in JSON format
#[clap(short = 'J', long, verbatim_doc_comment)]
pub json: bool,
/// Compares against the latest versions available, not what matches the current config
///
/// For example, if you have `node = "20"` in your config by default `mise outdated` will only
/// show other 20.x versions, not 21.x or 22.x versions.
///
/// Using this flag, if there are 21.x or newer versions it will display those instead of 20.x.
#[clap(long, short = 'l', verbatim_doc_comment)]
pub bump: bool,
/// Don't show table header
#[clap(long)]
pub no_header: bool,
}
impl Outdated {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
let mut ts = ToolsetBuilder::new()
.with_args(&self.tool)
.build(&config)
.await?;
let tool_set = self
.tool
.iter()
.map(|t| t.ba.clone())
.collect::<HashSet<_>>();
ts.versions
.retain(|_, tvl| tool_set.is_empty() || tool_set.contains(&tvl.backend));
let outdated = ts
.list_outdated_versions(&config, self.bump, &ResolveOptions::default())
.await;
self.display(outdated).await?;
Ok(())
}
async fn display(&self, outdated: Vec<OutdatedInfo>) -> Result<()> {
match self.json {
true => self.display_json(outdated)?,
false => self.display_table(outdated)?,
}
Ok(())
}
fn display_table(&self, outdated: Vec<OutdatedInfo>) -> Result<()> {
if outdated.is_empty() {
info!("All tools are up to date");
if !self.bump {
hint!(
"outdated_bump",
r#"By default, `mise outdated` only shows versions that match your config. Use `mise outdated --bump` to see all new versions."#,
""
);
}
return Ok(());
}
let mut table = tabled::Table::new(outdated);
if !self.bump {
table.with(Remove::column(ByColumnName::new("bump")));
}
table::default_style(&mut table, self.no_header);
miseprintln!("{table}");
Ok(())
}
fn display_json(&self, outdated: Vec<OutdatedInfo>) -> Result<()> {
let mut map = IndexMap::new();
for o in outdated {
map.insert(o.name.to_string(), o);
}
miseprintln!("{}", serde_json::to_string_pretty(&map)?);
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise outdated</bold>
Plugin Requested Current Latest
python 3.11 3.11.0 3.11.1
node 20 20.0.0 20.1.0
$ <bold>mise outdated node</bold>
Plugin Requested Current Latest
node 20 20.0.0 20.1.0
$ <bold>mise outdated --json</bold>
{"python": {"requested": "3.11", "current": "3.11.0", "latest": "3.11.1"}, ...}
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/completion.rs | src/cli/completion.rs | use crate::cmd::cmd;
use crate::config::Config;
use crate::toolset::ToolsetBuilder;
use clap::ValueEnum;
use clap::builder::PossibleValue;
use eyre::Result;
use strum::EnumString;
/// Generate shell completions
#[derive(Debug, clap::Args)]
#[clap(aliases = ["complete", "completions"], verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Completion {
/// Shell type to generate completions for
#[clap(required_unless_present = "shell_type")]
shell: Option<Shell>,
/// Shell type to generate completions for
#[clap(long = "shell", short = 's', hide = true)]
shell_type: Option<Shell>,
/// Include the bash completion library in the bash completion script
///
/// This is required for completions to work in bash, but it is not included by default
/// you may source it separately or enable this flag to enable it in the script.
#[clap(long, verbatim_doc_comment)]
include_bash_completion_lib: bool,
/// Always use usage for completions.
/// Currently, usage is the default for fish and bash but not zsh since it has a few quirks
/// to work out first.
///
/// This requires the `usage` CLI to be installed.
/// https://usage.jdx.dev
#[clap(long, verbatim_doc_comment, hide = true)]
usage: bool,
}
impl Completion {
pub async fn run(self) -> Result<()> {
let shell = self.shell.or(self.shell_type).unwrap();
let script = match self.call_usage(shell).await {
Ok(script) => script,
Err(e) => {
debug!("usage command failed, falling back to prerendered completions");
debug!("error: {e:?}");
self.prerendered(shell)
}
};
miseprintln!("{}", script.trim());
Ok(())
}
async fn call_usage(&self, shell: Shell) -> Result<String> {
let config = Config::get().await?;
let toolset = ToolsetBuilder::new().build(&config).await?;
let mut args = vec![
"generate".into(),
"completion".into(),
shell.to_string(),
"mise".into(),
"--usage-cmd".into(),
"mise usage".into(),
"--cache-key".into(),
env!("CARGO_PKG_VERSION").into(),
];
if self.include_bash_completion_lib {
args.push("--include-bash-completion-lib".into());
}
let output = cmd("usage", args)
.full_env(toolset.full_env(&config).await?)
.read()?;
Ok(output)
}
fn prerendered(&self, shell: Shell) -> String {
match shell {
Shell::Bash => include_str!("../../completions/mise.bash"),
Shell::Fish => include_str!("../../completions/mise.fish"),
Shell::Zsh => include_str!("../../completions/_mise"),
}
.to_string()
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise completion bash --include-bash-completion-lib > ~/.local/share/bash-completion/completions/mise</bold>
$ <bold>mise completion zsh > /usr/local/share/zsh/site-functions/_mise</bold>
$ <bold>mise completion fish > ~/.config/fish/completions/mise.fish</bold>
"#
);
#[derive(Debug, Clone, Copy, EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
enum Shell {
Bash,
Fish,
Zsh,
}
impl ValueEnum for Shell {
fn value_variants<'a>() -> &'a [Self] {
&[Self::Bash, Self::Fish, Self::Zsh]
}
fn to_possible_value(&self) -> Option<PossibleValue> {
Some(PossibleValue::new(self.to_string()))
}
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/deactivate.rs | src/cli/deactivate.rs | use eyre::Result;
use crate::env;
use crate::shell::{build_deactivation_script, get_shell};
/// Disable mise for current shell session
///
/// This can be used to temporarily disable mise in a shell session.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Deactivate {}
impl Deactivate {
pub fn run(self) -> Result<()> {
if !env::is_activated() {
// Deactivating when not activated is safe - just show a warning
warn!(
"mise is not activated in this shell session. Already deactivated or never activated."
);
return Ok(());
}
let shell = get_shell(None).expect("no shell detected");
let mut output = build_deactivation_script(&*shell);
output.push_str(&shell.unset_env("__MISE_ORIG_PATH"));
miseprint!("{output}")?;
Ok(())
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise deactivate</bold>
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/self_update_stub.rs | src/cli/self_update_stub.rs | use std::collections::BTreeMap;
use std::fs;
use std::path::PathBuf;
use crate::env;
pub struct SelfUpdate {}
impl SelfUpdate {
pub fn is_available() -> bool {
false
}
}
#[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 {
if let Some(msg) = read_instructions_file(path) {
return Some(msg);
}
}
None
}
pub fn append_self_update_instructions(mut message: String) -> String {
if let Some(instructions) = upgrade_instructions_text() {
message.push('\n');
message.push_str(&instructions);
}
message
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/lock.rs | src/cli/lock.rs | use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use crate::backend::platform_target::PlatformTarget;
use crate::config::Config;
use crate::file::display_path;
use crate::lockfile::{self, Lockfile, PlatformInfo};
use crate::platform::Platform;
use crate::toolset::Toolset;
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{cli::args::ToolArg, config::Settings};
use console::style;
use eyre::Result;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
/// Result type for lock task: (short_name, version, backend, platform, info, options)
type LockTaskResult = (
String,
String,
String,
Platform,
Option<PlatformInfo>,
BTreeMap<String, String>,
);
/// Update lockfile checksums and URLs for all specified platforms
///
/// Updates checksums and download URLs for all platforms already specified in the lockfile.
/// If no lockfile exists, shows what would be created based on the current configuration.
/// This allows you to refresh lockfile data for platforms other than the one you're currently on.
/// Operates on the lockfile in the current config root. Use TOOL arguments to target specific tools.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Lock {
/// Tool(s) to update in lockfile
/// e.g.: node python
/// If not specified, all tools in lockfile will be updated
#[clap(value_name = "TOOL", verbatim_doc_comment)]
pub tool: Vec<ToolArg>,
/// Number of jobs to run in parallel
#[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)]
pub jobs: Option<usize>,
/// Show what would be updated without making changes
#[clap(long, short = 'n', verbatim_doc_comment)]
pub dry_run: bool,
/// Comma-separated list of platforms to target
/// e.g.: linux-x64,macos-arm64,windows-x64
/// If not specified, all platforms already in lockfile will be updated
#[clap(long, short, value_delimiter = ',', verbatim_doc_comment)]
pub platform: Vec<String>,
/// Update mise.local.lock instead of mise.lock
/// Use for tools defined in .local.toml configs
#[clap(long, verbatim_doc_comment)]
pub local: bool,
}
impl Lock {
pub async fn run(self) -> Result<()> {
let settings = Settings::get();
let config = Config::get().await?;
settings.ensure_experimental("lock")?;
// Determine lockfile path based on config root
let lockfile_path = self.get_lockfile_path(&config);
// Determine target platforms
let target_platforms = self.determine_target_platforms(&lockfile_path)?;
miseprintln!(
"{} Targeting {} platform(s): {}",
style("→").cyan(),
target_platforms.len(),
target_platforms
.iter()
.map(|p| p.to_key())
.collect::<Vec<_>>()
.join(", ")
);
// Get toolset and resolve versions
let ts = config.get_toolset().await?;
let tools = self.get_tools_to_lock(&config, ts);
if tools.is_empty() {
miseprintln!("{} No tools configured to lock", style("!").yellow());
return Ok(());
}
miseprintln!(
"{} Processing {} tool(s): {}",
style("→").cyan(),
tools.len(),
tools
.iter()
.map(|(ba, tv)| format!("{}@{}", ba.short, tv.version))
.collect::<Vec<_>>()
.join(", ")
);
if self.dry_run {
self.show_dry_run(&tools, &target_platforms)?;
return Ok(());
}
// Process tools and update lockfile
let mut lockfile = Lockfile::read(&lockfile_path)?;
let results = self
.process_tools(&settings, &tools, &target_platforms, &mut lockfile)
.await?;
// Save lockfile
lockfile.write(&lockfile_path)?;
// Print summary
let successful = results.iter().filter(|(_, _, ok)| *ok).count();
let skipped = results.len() - successful;
miseprintln!(
"{} Updated {} platform entries ({} skipped)",
style("✓").green(),
successful,
skipped
);
miseprintln!(
"{} Lockfile written to {}",
style("✓").green(),
style(display_path(&lockfile_path)).cyan()
);
Ok(())
}
fn get_lockfile_path(&self, config: &Config) -> PathBuf {
// Get lockfile path from the first config file
if let Some(config_path) = config.config_files.keys().next() {
let (lockfile_path, _) = lockfile::lockfile_path_for_config(config_path);
if self.local {
// Replace mise.lock with mise.local.lock
lockfile_path.with_file_name("mise.local.lock")
} else {
lockfile_path
}
} else {
// Fallback to current dir
let lockfile_name = if self.local {
"mise.local.lock"
} else {
"mise.lock"
};
std::env::current_dir()
.unwrap_or_default()
.join(lockfile_name)
}
}
fn determine_target_platforms(&self, lockfile_path: &PathBuf) -> Result<Vec<Platform>> {
if !self.platform.is_empty() {
// User specified platforms explicitly
return Platform::parse_multiple(&self.platform);
}
// Default: 5 common platforms + existing in lockfile + current platform
let mut platforms: BTreeSet<Platform> = Platform::common_platforms().into_iter().collect();
platforms.insert(Platform::current());
// Add any existing platforms from lockfile (only valid ones)
if let Ok(lockfile) = Lockfile::read(lockfile_path) {
for platform_key in lockfile.all_platform_keys() {
if let Ok(p) = Platform::parse(&platform_key) {
// Skip invalid platforms (e.g., tool-specific qualifiers like "wait-for-gh-rate-limit")
if p.validate().is_ok() {
platforms.insert(p);
}
}
}
}
Ok(platforms.into_iter().collect())
}
fn get_tools_to_lock(
&self,
config: &Config,
ts: &Toolset,
) -> Vec<(crate::cli::args::BackendArg, crate::toolset::ToolVersion)> {
// Calculate target lockfile directory (same logic as get_lockfile_path)
let target_lockfile_dir = config
.config_files
.keys()
.next()
.map(|p| {
let (lockfile_path, _) = lockfile::lockfile_path_for_config(p);
lockfile_path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default()
})
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
// Collect tools from config files that share the same lockfile directory
let mut all_tools: Vec<_> = Vec::new();
let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
// Helper to get lockfile directory for a config path
let get_lockfile_dir = |path: &std::path::Path| -> PathBuf {
let (lockfile_path, _) = lockfile::lockfile_path_for_config(path);
lockfile_path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default()
};
// First, get all tools from the resolved toolset (these are the "current" versions)
// but only if they come from a config file with the same lockfile directory
for (backend, tv) in ts.list_current_versions() {
// Check if this tool's source shares the same lockfile directory
if let Some(source_path) = tv.request.source().path()
&& get_lockfile_dir(source_path) != target_lockfile_dir
{
continue;
}
let key = (backend.ba().short.clone(), tv.version.clone());
if seen.insert(key) {
all_tools.push((backend.ba().as_ref().clone(), tv));
}
}
// Then, iterate config files with the same lockfile directory to find tools that may have been overridden
for (path, cf) in config.config_files.iter() {
// Skip config files that don't share the same lockfile directory
if get_lockfile_dir(path) != target_lockfile_dir {
continue;
}
if let Ok(trs) = cf.to_tool_request_set() {
for (ba, requests, _source) in trs.iter() {
for request in requests {
// Try to get a resolved version for this request
if let Ok(backend) = ba.backend() {
// Check if we already have this tool+version in toolset
if let Some(resolved_tv) = ts.versions.get(ba.as_ref()) {
for tv in &resolved_tv.versions {
if tv.request.version() == request.version() {
let key = (ba.short.clone(), tv.version.clone());
if seen.insert(key) {
all_tools.push((ba.as_ref().clone(), tv.clone()));
}
}
}
}
// For "latest" requests, find the highest installed version
if request.version() == "latest" {
let installed = backend.list_installed_versions();
if let Some(latest_version) = installed.iter().max_by(|a, b| {
versions::Versioning::new(a).cmp(&versions::Versioning::new(b))
}) {
let key = (ba.short.clone(), latest_version.clone());
if seen.insert(key.clone()) {
let tv = crate::toolset::ToolVersion::new(
request.clone(),
latest_version.clone(),
);
all_tools.push((ba.as_ref().clone(), tv));
}
}
}
}
}
}
}
}
if self.tool.is_empty() {
// Lock all tools
all_tools
} else {
// Filter to specified tools
let specified: BTreeSet<String> =
self.tool.iter().map(|t| t.ba.short.clone()).collect();
all_tools
.into_iter()
.filter(|(ba, _)| specified.contains(&ba.short))
.collect()
}
}
fn show_dry_run(
&self,
tools: &[(crate::cli::args::BackendArg, crate::toolset::ToolVersion)],
platforms: &[Platform],
) -> Result<()> {
miseprintln!("{} Dry run - would update:", style("→").yellow());
for (ba, tv) in tools {
let backend = crate::backend::get(ba);
for platform in platforms {
// Expand platform variants just like process_tools does
let variants = if let Some(ref backend) = backend {
backend.platform_variants(platform)
} else {
vec![platform.clone()]
};
for variant in variants {
miseprintln!(
" {} {}@{} for {}",
style("✓").green(),
style(&ba.short).bold(),
tv.version,
style(variant.to_key()).blue()
);
}
}
}
Ok(())
}
async fn process_tools(
&self,
settings: &Settings,
tools: &[(crate::cli::args::BackendArg, crate::toolset::ToolVersion)],
platforms: &[Platform],
lockfile: &mut Lockfile,
) -> Result<Vec<(String, String, bool)>> {
let jobs = self.jobs.unwrap_or(settings.jobs);
let semaphore = Arc::new(Semaphore::new(jobs));
let mut jset: JoinSet<LockTaskResult> = JoinSet::new();
let mut results = Vec::new();
let mpr = MultiProgressReport::get();
// Collect all platform variants for each tool/platform combination
let mut all_tasks: Vec<(
crate::cli::args::BackendArg,
crate::toolset::ToolVersion,
Platform,
)> = Vec::new();
for (ba, tv) in tools {
let backend = crate::backend::get(ba);
for platform in platforms {
// Get all variants for this platform from the backend
let variants = if let Some(ref backend) = backend {
backend.platform_variants(platform)
} else {
vec![platform.clone()]
};
for variant in variants {
all_tasks.push((ba.clone(), tv.clone(), variant));
}
}
}
let total_tasks = all_tasks.len();
let pr = mpr.add("lock");
pr.set_length(total_tasks as u64);
// Spawn tasks for each tool/platform variant combination
for (ba, tv, platform) in all_tasks {
let semaphore = semaphore.clone();
jset.spawn(async move {
let _permit = semaphore.acquire().await;
let target = PlatformTarget::new(platform.clone());
let backend = crate::backend::get(&ba);
let (info, options) = if let Some(backend) = backend {
let options = backend.resolve_lockfile_options(&tv.request, &target);
match backend.resolve_lock_info(&tv, &target).await {
Ok(info) => (Some(info), options),
Err(e) => {
warn!(
"Failed to resolve {} for {}: {}",
ba.short,
platform.to_key(),
e
);
(None, options)
}
}
} else {
warn!("Backend not found for {}", ba.short);
(None, BTreeMap::new())
};
(
ba.short.clone(),
tv.version.clone(),
ba.full(),
platform,
info,
options,
)
});
}
// Collect all results
let mut completed = 0;
while let Some(result) = jset.join_next().await {
completed += 1;
match result {
Ok((short, version, backend, platform, info, options)) => {
let platform_key = platform.to_key();
pr.set_message(format!("{}@{} {}", short, version, platform_key));
pr.set_position(completed);
let ok = info.is_some();
if let Some(info) = info {
lockfile.set_platform_info(
&short,
&version,
Some(&backend),
&options,
&platform_key,
info,
);
}
results.push((short, platform_key, ok));
}
Err(e) => {
warn!("Task failed: {}", e);
}
}
}
pr.finish_with_message(format!("{} platform entries", total_tasks));
Ok(results)
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise lock</bold> # update lockfile for all common platforms
$ <bold>mise lock node python</bold> # update only node and python
$ <bold>mise lock --platform linux-x64</bold> # update only linux-x64 platform
$ <bold>mise lock --dry-run</bold> # show what would be updated
$ <bold>mise lock --local</bold> # update mise.local.lock for local configs
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/reshim.rs | src/cli/reshim.rs | use eyre::Result;
use crate::config::Config;
use crate::shims;
use crate::toolset::ToolsetBuilder;
/// Creates new shims based on bin paths from currently installed tools.
///
/// This creates new shims in ~/.local/share/mise/shims for CLIs that have been added.
/// mise will try to do this automatically for commands like `npm i -g` but there are
/// other ways to install things (like using yarn or pnpm for node) that mise does
/// not know about and so it will be necessary to call this explicitly.
///
/// If you think mise should automatically call this for a particular command, please
/// open an issue on the mise repo. You can also setup a shell function to reshim
/// automatically (it's really fast so you don't need to worry about overhead):
///
/// npm() {
/// command npm "$@"
/// mise reshim
/// }
///
/// Note that this creates shims for _all_ installed tools, not just the ones that are
/// currently active in mise.toml.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Reshim {
#[clap(hide = true)]
pub plugin: Option<String>,
#[clap(hide = true)]
pub version: Option<String>,
/// Removes all shims before reshimming
#[clap(long, short)]
pub force: bool,
}
impl Reshim {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
let ts = ToolsetBuilder::new().build(&config).await?;
shims::reshim(&config, &ts, self.force).await
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise reshim</bold>
$ <bold>~/.local/share/mise/shims/node -v</bold>
v20.0.0
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/shell.rs | src/cli/shell.rs | use color_eyre::eyre::{Result, eyre};
use console::style;
use heck::ToShoutySnakeCase;
use indoc::formatdoc;
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::env;
use crate::shell::get_shell;
use crate::toolset::{InstallOptions, ToolSource, ToolsetBuilder};
/// Sets a tool version for the current session.
///
/// Only works in a session where mise is already activated.
///
/// This works by setting environment variables for the current shell session
/// such as `MISE_NODE_VERSION=20` which is "eval"ed as a shell function created by `mise activate`.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, visible_alias = "sh", after_long_help = AFTER_LONG_HELP)]
pub struct Shell {
/// Tool(s) to use
#[clap(value_name = "TOOL@VERSION", required = true)]
tool: Vec<ToolArg>,
/// Number of jobs to run in parallel
/// [default: 4]
#[clap(long, short, env = "MISE_JOBS", verbatim_doc_comment)]
jobs: Option<usize>,
/// Removes a previously set version
#[clap(long, short)]
unset: bool,
/// Directly pipe stdin/stdout/stderr from plugin to user
/// Sets --jobs=1
#[clap(long, overrides_with = "jobs")]
raw: bool,
}
impl Shell {
pub async fn run(self) -> Result<()> {
let mut config = Config::get().await?;
if !env::is_activated() {
err_inactive()?;
}
let shell = get_shell(None).expect("no shell detected");
if self.unset {
for ta in &self.tool {
let op = shell.unset_env(&format!(
"MISE_{}_VERSION",
ta.ba.short.to_shouty_snake_case()
));
print!("{op}");
}
return Ok(());
}
let mut ts = ToolsetBuilder::new()
.with_args(&self.tool)
.build(&config)
.await?;
let opts = InstallOptions {
force: false,
jobs: self.jobs,
raw: self.raw,
..Default::default()
};
ts.install_missing_versions(&mut config, &opts).await?;
ts.notify_if_versions_missing(&config).await;
for (p, tv) in ts.list_current_installed_versions(&config) {
let source = &ts.versions.get(p.ba().as_ref()).unwrap().source;
if matches!(source, ToolSource::Argument) {
let k = format!("MISE_{}_VERSION", p.id().to_shouty_snake_case());
let op = shell.set_env(&k, &tv.version);
print!("{op}");
}
}
Ok(())
}
}
fn err_inactive() -> Result<()> {
Err(eyre!(formatdoc!(
r#"
mise is not activated in this shell session.
Please run `{}` first in your shell rc file.
"#,
style("mise activate").yellow()
)))
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise shell node@20</bold>
$ <bold>node -v</bold>
v20.0.0
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/search.rs | src/cli/search.rs | use std::sync::LazyLock as Lazy;
use clap::ValueEnum;
use demand::DemandOption;
use demand::Select;
use eyre::Result;
use eyre::bail;
use eyre::eyre;
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use itertools::Itertools;
use xx::regex;
use crate::registry::RegistryTool;
use crate::{
config::Settings,
registry::{REGISTRY, tool_enabled},
ui::table::MiseTable,
};
static FUZZY_MATCHER: Lazy<SkimMatcherV2> =
Lazy::new(|| SkimMatcherV2::default().use_cache(true).smart_case());
#[derive(Debug, Clone, ValueEnum)]
pub enum MatchType {
Equal,
Contains,
Fuzzy,
}
/// Search for tools in the registry
///
/// This command searches a tool in the registry.
///
/// By default, it will show all tools that fuzzy match the search term. For
/// non-fuzzy matches, use the `--match-type` flag.
#[derive(Debug, clap::Args)]
#[clap(after_long_help = AFTER_LONG_HELP, verbatim_doc_comment)]
pub struct Search {
/// The tool to search for
name: Option<String>,
/// Show interactive search
#[clap(long, short, conflicts_with_all = &["match_type", "no_header"])]
interactive: bool,
/// Match type: equal, contains, or fuzzy
#[clap(long, short, value_enum, default_value = "fuzzy")]
match_type: MatchType,
/// Don't display headers
#[clap(long, alias = "no-headers")]
no_header: bool,
}
impl Search {
pub async fn run(self) -> Result<()> {
if self.interactive {
self.interactive()?;
} else {
self.display_table()?;
}
Ok(())
}
fn interactive(&self) -> Result<()> {
let tools = self.get_tools();
let theme = crate::ui::theme::get_theme();
let mut s = Select::new("Tool")
.description("Search a tool")
.filtering(true)
.filterable(true)
.theme(&theme);
for t in tools.iter() {
let short = t.0.as_str();
let description = get_description(t.1);
s = s.option(
DemandOption::new(short)
.label(short)
.description(&description),
);
}
match s.run() {
Ok(_) => Ok(()),
Err(err) => {
if err.kind() == std::io::ErrorKind::Interrupted {
// user interrupted, exit gracefully
Ok(())
} else {
Err(eyre!(err))
}
}
}
}
fn display_table(&self) -> Result<()> {
let tools = self
.get_matches()
.into_iter()
.map(|(short, description)| vec![short, description])
.collect_vec();
if tools.is_empty() {
bail!("tool {} not found in registry", self.name.as_ref().unwrap());
}
let mut table = MiseTable::new(self.no_header, &["Tool", "Description"]);
for row in tools {
table.add_row(row);
}
table.print()
}
fn get_matches(&self) -> Vec<(String, String)> {
self.get_tools()
.iter()
.filter_map(|(short, rt)| {
let name = self.name.as_deref().unwrap_or("");
if name.is_empty() {
Some((0, short, rt))
} else {
match self.match_type {
MatchType::Equal => {
if *short == name {
Some((0, short, rt))
} else {
None
}
}
MatchType::Contains => {
if short.contains(name) {
Some((0, short, rt))
} else {
None
}
}
MatchType::Fuzzy => FUZZY_MATCHER
.fuzzy_match(&short.to_lowercase(), name.to_lowercase().as_str())
.map(|score| (score, short, rt)),
}
}
})
.sorted_by_key(|(score, _short, _rt)| -1 * *score)
.map(|(_score, short, rt)| (short.to_string(), get_description(rt)))
.collect()
}
fn get_tools(&self) -> Vec<(String, &'static RegistryTool)> {
REGISTRY
.iter()
.filter(|(short, _)| filter_enabled(short))
.map(|(short, rt)| (short.to_string(), rt))
.sorted_by(|(a, _), (b, _)| a.cmp(b))
.collect_vec()
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise search jq</bold>
Tool Description
jq Command-line JSON processor. https://github.com/jqlang/jq
jqp A TUI playground to experiment with jq. https://github.com/noahgorstein/jqp
jiq jid on jq - interactive JSON query tool using jq expressions. https://github.com/fiatjaf/jiq
gojq Pure Go implementation of jq. https://github.com/itchyny/gojq
$ <bold>mise search --interactive</bold>
Tool
Search a tool
❯ jq Command-line JSON processor. https://github.com/jqlang/jq
jqp A TUI playground to experiment with jq. https://github.com/noahgorstein/jqp
jiq jid on jq - interactive JSON query tool using jq expressions. https://github.com/fiatjaf/jiq
gojq Pure Go implementation of jq. https://github.com/itchyny/gojq
/jq
esc clear filter • enter confirm
"#
);
fn filter_enabled(short: &str) -> bool {
tool_enabled(
&Settings::get().enable_tools,
&Settings::get().disable_tools,
&short.to_string(),
)
}
fn get_description(tool: &RegistryTool) -> String {
let description = tool.description.unwrap_or_default();
let backend = get_backends(tool.backends())
.iter()
.filter(|b| !Settings::get().disable_backends.contains(b))
.map(|b| b.to_string())
.next()
.unwrap_or_default();
if description.is_empty() {
backend.to_string()
} else {
format!("{description}. {backend}")
}
}
fn get_backends(backends: Vec<&'static str>) -> Vec<String> {
if backends.is_empty() {
return vec!["".to_string()];
}
backends
.iter()
.map(|backend| {
let prefix = backend.split(':').next().unwrap_or("");
let slug = backend.split(':').next_back().unwrap_or("");
let slug = regex!(r"^(.*?)\[.*\]$").replace_all(slug, "$1");
match prefix {
"core" => format!("https://mise.jdx.dev/lang/{slug}.html"),
"cargo" => format!("https://crates.io/crates/{slug}"),
"go" => format!("https://pkg.go.dev/{slug}"),
"pipx" => format!("https://pypi.org/project/{slug}"),
"npm" => format!("https://www.npmjs.com/package/{slug}"),
_ => format!("https://github.com/{slug}"),
}
})
.collect()
}
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/env.rs | src/cli/env.rs | use eyre::Result;
use std::{collections::BTreeMap, sync::Arc};
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::shell::{ShellType, get_shell};
use crate::toolset::{InstallOptions, Toolset, ToolsetBuilder};
use indexmap::IndexSet;
/// Exports env vars to activate mise a single time
///
/// Use this if you don't want to permanently install mise. It's not necessary to
/// use this if you have `mise activate` in your shell rc file.
#[derive(Debug, clap::Args)]
#[clap(visible_alias = "e", verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Env {
/// Tool(s) to use
#[clap(value_name = "TOOL@VERSION")]
tool: Vec<ToolArg>,
/// Output in dotenv format
#[clap(long, short = 'D', overrides_with = "shell")]
dotenv: bool,
/// Output in JSON format
#[clap(long, short = 'J', overrides_with = "shell")]
json: bool,
/// Shell type to generate environment variables for
#[clap(long, short, overrides_with = "json")]
shell: Option<ShellType>,
/// Output in JSON format with additional information (source, tool)
#[clap(long, overrides_with = "shell")]
json_extended: bool,
/// Only show redacted environment variables
#[clap(long)]
redacted: bool,
/// Only show values of environment variables
#[clap(long)]
values: bool,
}
impl Env {
pub async fn run(self) -> Result<()> {
let mut config = Config::get().await?;
let mut ts = ToolsetBuilder::new()
.with_args(&self.tool)
.build(&config)
.await?;
ts.install_missing_versions(&mut config, &InstallOptions::default())
.await?;
ts.notify_if_versions_missing(&config).await;
// Get redacted keys if needed
let redacted_keys = if self.redacted {
let env_results = config.env_results().await?;
let mut keys = IndexSet::new();
keys.extend(env_results.redactions.clone());
keys.extend(config.redaction_keys());
Some(keys)
} else {
None
};
if self.json {
self.output_json(&config, ts, &redacted_keys).await
} else if self.json_extended {
self.output_extended_json(&config, ts, &redacted_keys).await
} else if self.dotenv {
self.output_dotenv(&config, ts, &redacted_keys).await
} else if self.values {
self.output_values(&config, ts, &redacted_keys).await
} else {
self.output_shell(&config, ts, &redacted_keys).await
}
}
async fn output_json(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut env = ts.env_with_path(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
miseprintln!("{}", serde_json::to_string_pretty(&env)?);
Ok(())
}
async fn output_extended_json(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut res = BTreeMap::new();
ts.env_with_path(config).await?.iter().for_each(|(k, v)| {
res.insert(k.to_string(), BTreeMap::from([("value", v.to_string())]));
});
config.env_with_sources().await?.iter().for_each(|(k, v)| {
res.insert(
k.to_string(),
BTreeMap::from([
("value", v.0.to_string()),
("source", v.1.to_string_lossy().into_owned()),
]),
);
});
let tool_map: BTreeMap<String, String> = ts
.list_all_versions(config)
.await?
.into_iter()
.map(|(b, tv)| {
(
b.id().into(),
tv.request
.source()
.path()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| "".to_string()),
)
})
.collect();
ts.env_from_tools(config)
.await
.iter()
.for_each(|(name, value, tool_id)| {
res.insert(
name.to_string(),
BTreeMap::from([
("value", value.to_string()),
("tool", tool_id.to_string()),
(
"source",
tool_map
.get(tool_id)
.cloned()
.unwrap_or_else(|| "unknown_source".to_string()),
),
]),
);
});
if let Some(keys) = redacted_keys {
res.retain(|k, _| self.should_include_key(k, keys));
}
miseprintln!("{}", serde_json::to_string_pretty(&res)?);
Ok(())
}
async fn output_shell(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let default_shell = get_shell(Some(ShellType::Bash)).unwrap();
let shell = get_shell(self.shell).unwrap_or(default_shell);
let mut env = ts.env_with_path(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
for (k, v) in env {
let k = k.to_string();
let v = v.to_string();
miseprint!("{}", shell.set_env(&k, &v))?;
}
Ok(())
}
async fn output_dotenv(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let (mut env, _) = ts.final_env(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
for (k, v) in env {
let k = k.to_string();
let v = v.to_string();
miseprint!("{}={}\n", k, v)?;
}
Ok(())
}
async fn output_values(
&self,
config: &Arc<Config>,
ts: Toolset,
redacted_keys: &Option<IndexSet<String>>,
) -> Result<()> {
let mut env = ts.env_with_path(config).await?;
if let Some(keys) = redacted_keys {
env.retain(|k, _| self.should_include_key(k, keys));
}
for (_, v) in env {
miseprintln!("{}", v);
}
Ok(())
}
fn should_include_key(&self, key: &str, redacted_keys: &IndexSet<String>) -> bool {
// Check if key matches any redaction pattern (supporting wildcards)
redacted_keys.iter().any(|pattern| {
if pattern.contains('*') {
// Handle wildcard patterns
if pattern == "*" {
true
} else if let Some(prefix) = pattern.strip_suffix('*') {
key.starts_with(prefix)
} else if let Some(suffix) = pattern.strip_prefix('*') {
key.ends_with(suffix)
} else {
// Pattern has * in the middle, not supported yet
false
}
} else {
key == pattern
}
})
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>eval "$(mise env -s bash)"</bold>
$ <bold>eval "$(mise env -s zsh)"</bold>
$ <bold>mise env -s fish | source</bold>
$ <bold>execx($(mise env -s xonsh))</bold>
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
jdx/mise | https://github.com/jdx/mise/blob/3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb/src/cli/which.rs | src/cli/which.rs | use std::sync::Arc;
use crate::cli::args::ToolArg;
use crate::config::Config;
use crate::dirs::SHIMS;
use crate::file;
use crate::toolset::{Toolset, ToolsetBuilder};
use eyre::{Result, bail};
use itertools::Itertools;
/// Shows the path that a tool's bin points to.
///
/// Use this to figure out what version of a tool is currently active.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP)]
pub struct Which {
/// The bin to look up
#[clap(required_unless_present = "complete")]
pub bin_name: Option<String>,
/// Use a specific tool@version
/// e.g.: `mise which npm --tool=node@20`
#[clap(short, long, value_name = "TOOL@VERSION", verbatim_doc_comment)]
pub tool: Option<ToolArg>,
#[clap(long, hide = true)]
pub complete: bool,
/// Show the plugin name instead of the path
#[clap(long, conflicts_with = "version")]
pub plugin: bool,
/// Show the version instead of the path
#[clap(long, conflicts_with = "plugin")]
pub version: bool,
}
impl Which {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
if self.complete {
return self.complete(&config).await;
}
let ts = self.get_toolset(&config).await?;
let bin_name = self.bin_name.clone().unwrap();
match ts.which(&config, &bin_name).await {
Some((p, tv)) => {
if self.version {
miseprintln!("{}", tv.version);
} else if self.plugin {
miseprintln!("{p}");
} else {
let path = p.which(&config, &tv, &bin_name).await?;
miseprintln!("{}", path.unwrap().display());
}
Ok(())
}
None => {
if self.has_shim(&bin_name) {
bail!(
"{bin_name} is a mise bin however it is not currently active. Use `mise use` to activate it in this directory."
)
} else {
bail!("{bin_name} is not a mise bin. Perhaps you need to install it first.",)
}
}
}
}
async fn complete(&self, config: &Arc<Config>) -> Result<()> {
let ts = self.get_toolset(config).await?;
let bins = ts
.list_paths(config)
.await
.into_iter()
.flat_map(|p| file::ls(&p).unwrap_or_default())
.map(|p| p.file_name().unwrap().to_string_lossy().to_string())
.unique()
.sorted()
.collect_vec();
for bin in bins {
println!("{bin}");
}
Ok(())
}
async fn get_toolset(&self, config: &Arc<Config>) -> Result<Toolset> {
let mut tsb = ToolsetBuilder::new();
if let Some(tool) = &self.tool {
tsb = tsb.with_args(std::slice::from_ref(tool));
}
let ts = tsb.build(config).await?;
Ok(ts)
}
fn has_shim(&self, shim: &str) -> bool {
SHIMS.join(shim).exists()
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise which node</bold>
/home/username/.local/share/mise/installs/node/20.0.0/bin/node
$ <bold>mise which node --plugin</bold>
node
$ <bold>mise which node --version</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/ls_remote.rs | src/cli/ls_remote.rs | use std::sync::Arc;
use eyre::Result;
use serde::Serialize;
use crate::backend::Backend;
use crate::cli::args::ToolArg;
use crate::toolset::{ToolRequest, tool_request};
use crate::ui::multi_progress_report::MultiProgressReport;
use crate::{backend, config::Config};
/// Output struct for --all --json mode with consistent null handling
#[derive(Serialize)]
struct VersionOutputAll {
tool: String,
version: String,
#[serde(skip_serializing_if = "Option::is_none")]
created_at: Option<String>,
}
/// List runtime versions available for install.
///
/// Note that the results may be cached, run `mise cache clean` to clear the cache and get fresh results.
#[derive(Debug, clap::Args)]
#[clap(verbatim_doc_comment, after_long_help = AFTER_LONG_HELP, aliases = ["list-all", "list-remote"]
)]
pub struct LsRemote {
/// Tool to get versions for
#[clap(value_name = "TOOL@VERSION", required_unless_present = "all")]
pub plugin: Option<ToolArg>,
/// The version prefix to use when querying the latest version
/// same as the first argument after the "@"
#[clap(verbatim_doc_comment)]
pub prefix: Option<String>,
/// Show all installed plugins and versions
#[clap(long, verbatim_doc_comment, conflicts_with_all = ["plugin", "prefix"])]
pub all: bool,
/// Output in JSON format (includes version metadata like created_at timestamps when available)
#[clap(short = 'J', long, verbatim_doc_comment)]
pub json: bool,
}
impl LsRemote {
pub async fn run(self) -> Result<()> {
let config = Config::get().await?;
if let Some(plugin) = self.get_plugin(&config).await? {
self.run_single(&config, plugin).await
} else {
self.run_all(&config).await
}
}
async fn run_single(self, config: &Arc<Config>, plugin: Arc<dyn Backend>) -> Result<()> {
let prefix = match &self.plugin {
Some(tool_arg) => match &tool_arg.tvr {
Some(ToolRequest::Version { version: v, .. }) => Some(v.clone()),
Some(ToolRequest::Sub {
sub, orig_version, ..
}) => Some(tool_request::version_sub(orig_version, sub)),
_ => self.prefix.clone(),
},
_ => self.prefix.clone(),
};
let matches_prefix = |v: &str| prefix.as_ref().is_none_or(|p| v.starts_with(p));
let versions: Vec<_> = plugin
.list_remote_versions_with_info(config)
.await?
.into_iter()
.filter(|v| matches_prefix(&v.version))
.collect();
if self.json {
miseprintln!("{}", serde_json::to_string(&versions)?);
} else {
for v in versions {
miseprintln!("{}", v.version);
}
}
Ok(())
}
async fn run_all(self, config: &Arc<Config>) -> Result<()> {
let mut versions = vec![];
for b in backend::list() {
let tool = b.id().to_string();
for v in b.list_remote_versions_with_info(config).await? {
versions.push(VersionOutputAll {
tool: tool.clone(),
version: v.version,
created_at: v.created_at,
});
}
}
versions.sort_by(|a, b| a.tool.cmp(&b.tool));
if self.json {
miseprintln!("{}", serde_json::to_string(&versions)?);
} else {
for v in versions {
miseprintln!("{}@{}", v.tool, v.version);
}
}
Ok(())
}
async fn get_plugin(&self, config: &Arc<Config>) -> Result<Option<Arc<dyn Backend>>> {
match &self.plugin {
Some(tool_arg) => {
let backend = tool_arg.ba.backend()?;
let mpr = MultiProgressReport::get();
if let Some(plugin) = backend.plugin() {
plugin.ensure_installed(config, &mpr, false, false).await?;
}
Ok(Some(backend))
}
None => Ok(None),
}
}
}
static AFTER_LONG_HELP: &str = color_print::cstr!(
r#"<bold><underline>Examples:</underline></bold>
$ <bold>mise ls-remote node</bold>
18.0.0
20.0.0
$ <bold>mise ls-remote node@20</bold>
20.0.0
20.1.0
$ <bold>mise ls-remote node 20</bold>
20.0.0
20.1.0
$ <bold>mise ls-remote github:cli/cli --json</bold>
[{"version":"2.62.0","created_at":"2024-11-14T15:40:35Z"},{"version":"2.61.0","created_at":"2024-10-23T19:22:15Z"}]
"#
);
| rust | MIT | 3e382b34b6bf7d7b1a0efb8fdd8ea10c84498adb | 2026-01-04T15:39:11.175160Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.