The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
feat(sdk): Detect mise and asdf toolchains and use the project's pinned versions (#227)
l0ng-aie537dd43a0f6
diff --git a/Cargo.lock b/Cargo.lockindex a250de15c..3f179876b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4035,6 +4035,7 @@ dependencies = ["serde_json","specta","specta-typescript",+ "tempfile","thiserror 2.0.21","tokio-util",]diff --git a/crates/ide-core/Cargo.toml b/crates/ide-core/Cargo.tomlindex 21618ba11..9daa648b4 100644--- a/crates/ide-core/Cargo.toml+++ b/crates/ide-core/Cargo.toml@@ -13,3 +13,6 @@ specta.workspace = truespecta-typescript.workspace = truethiserror.workspace = truetokio-util.workspace = true++[dev-dependencies]+tempfile.workspace = truediff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rsindex 49a31ff55..1b58ba68c 100644--- a/crates/ide-core/src/lib.rs+++ b/crates/ide-core/src/lib.rs@@ -20,6 +20,7 @@ pub mod remote_settings;pub mod settings;pub mod task;pub mod text;+pub mod version_managers;pub mod workflow_settings;pub use error::{IdeError, IdeResult};diff --git a/crates/ide-core/src/version_managers.rs b/crates/ide-core/src/version_managers.rsnew file mode 100644index 000000000..18e968b3d--- /dev/null+++ b/crates/ide-core/src/version_managers.rs@@ -0,0 +1,240 @@+//! Version managers that keep one install per tool version (mise, asdf): where their+//! installs and shims live. SDK detection lists the installs; child processes get the+//! shims on `PATH` when the manager's shell hook didn't run (an app started from the Dock,+//! `mise activate` only in an interactive rc file).++use std::ffi::{OsStr, OsString};+use std::path::{Path, PathBuf};++pub const MISE: &str = "mise";+pub const ASDF: &str = "asdf";++/// A toolchain the version managers install.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Tool {+ Java,+ Node,+ Python,+ Go,+ Maven,+ Gradle,+}++impl Tool {+ /// The tool's names in mise and asdf plugins (`nodejs`, `golang` are asdf's).+ pub fn names(self) -> &'static [&'static str] {+ match self {+ Tool::Java => &["java"],+ Tool::Node => &["node", "nodejs"],+ Tool::Python => &["python"],+ Tool::Go => &["go", "golang"],+ Tool::Maven => &["maven"],+ Tool::Gradle => &["gradle"],+ }+ }+}++/// One version manager's data directory (`installs/`, `shims/`).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Manager {+ pub name: &'static str,+ pub dir: PathBuf,+}++impl Manager {+ pub fn shims(&self) -> PathBuf {+ self.dir.join("shims")+ }++ /// `installs/<tool>/<version>` directories of `tool`, sorted. The alias links mise+ /// adds next to an install (`21 -> ./21.0.2`, `latest`) are left out; a link to an+ /// install elsewhere (`mise link`) is kept.+ pub fn installs(&self, tool: Tool) -> Vec<PathBuf> {+ let mut out = Vec::new();+ for name in tool.names() {+ let Ok(entries) = std::fs::read_dir(self.dir.join("installs").join(name)) else { continue };+ for e in entries.flatten() {+ let path = e.path();+ let alias = e.file_type().is_ok_and(|t| t.is_symlink())+ && std::fs::read_link(&path).is_ok_and(|t| t.is_relative() && t.components().count() <= 2);+ if !alias && path.is_dir() {+ out.push(path);+ }+ }+ }+ out.sort();+ out+ }++ /// The install of `tool` named `version` exactly (alias links included).+ pub fn install_named(&self, tool: Tool, version: &str) -> Option<PathBuf> {+ if version.is_empty() || version.contains(['/', '\\']) || version.starts_with('.') {+ return None;+ }+ tool.names().iter().map(|n| self.dir.join("installs").join(n).join(version)).find(|p| p.is_dir())+ }+}++/// mise's and asdf's data directories that exist, as this process's environment (and the+/// login shell's) set them.+pub fn managers() -> Vec<Manager> {+ let lookup = |k: &str| {+ crate::process::host_var_os(k)+ .or_else(|| crate::process::login_env()?.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()))+ };+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);+ managers_with(&lookup, home.as_deref()).into_iter().filter(|m| m.dir.is_dir()).collect()+}++/// mise: `MISE_DATA_DIR`, else `$XDG_DATA_HOME/mise`, else `~/.local/share/mise`+/// (`%LOCALAPPDATA%\mise` on Windows). asdf: `ASDF_DATA_DIR`, else `~/.asdf`.+pub fn managers_with(env: &dyn Fn(&str) -> Option<OsString>, home: Option<&Path>) -> Vec<Manager> {+ let var = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);+ let mise = var("MISE_DATA_DIR")+ .or_else(|| var("XDG_DATA_HOME").map(|d| d.join("mise")))+ .or_else(|| if cfg!(windows) { var("LOCALAPPDATA").map(|d| d.join("mise")) } else { None })+ .or_else(|| home.map(|h| h.join(".local/share/mise")));+ let asdf = var("ASDF_DATA_DIR").or_else(|| home.map(|h| h.join(".asdf")));+ let mut out = Vec::new();+ out.extend(mise.map(|dir| Manager { name: MISE, dir }));+ out.extend(asdf.map(|dir| Manager { name: ASDF, dir }));+ out+}++/// Every install of `tool` with the manager it came from, mise's first.+pub fn installs(tool: Tool) -> Vec<(PathBuf, &'static str)> {+ managers().iter().flat_map(|m| m.installs(tool).into_iter().map(|p| (p, m.name))).collect()+}++/// The manager whose installs `path` lies in.+pub fn manager_of(path: &Path) -> Option<&'static str> {+ manager_in(&managers(), path)+}++pub fn manager_in(managers: &[Manager], path: &Path) -> Option<&'static str> {+ managers.iter().find_map(|m| {+ let installs = m.dir.join("installs");+ let real = dunce::canonicalize(&installs).ok();+ (path.starts_with(&installs) || real.is_some_and(|r| path.starts_with(r))).then_some(m.name)+ })+}++/// Whether `path` is a version manager's shim (it picks the version by the working directory).+pub fn is_shim(path: &Path) -> bool {+ path.parent().is_some_and(is_shims_dir)+}++/// Whether `dir` is a version manager's `shims` folder.+pub fn is_shims_dir(dir: &Path) -> bool {+ managers().iter().any(|m| m.shims() == dir)+}++/// `path` (a `PATH` value) with the shims of a manager it doesn't reach yet: mise's in+/// front (a mise shim runs the next tool on `PATH` when no version is set), asdf's at the+/// end (an asdf shim fails then). A `PATH` that has a manager's shims or installs already+/// (its shell hook ran) is left as it is for that manager.+pub fn path_with_shims(managers: &[Manager], path: &OsStr) -> OsString {+ let mut dirs: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };+ let before = dirs.len();+ for m in managers {+ let shims = m.shims();+ let installs = m.dir.join("installs");+ if !shims.is_dir() || dirs.iter().any(|d| d == &shims || d.starts_with(&installs)) {+ continue;+ }+ if m.name == MISE {+ dirs.insert(0, shims);+ } else {+ dirs.push(shims);+ }+ }+ if dirs.len() == before {+ return path.to_owned();+ }+ std::env::join_paths(dirs).unwrap_or_else(|_| path.to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn mkdir(p: &Path) {+ std::fs::create_dir_all(p).unwrap();+ }++ #[test]+ fn data_dirs_follow_the_environment() {+ let home = Path::new("/home/me");+ let none = |_: &str| None;+ let dirs: Vec<_> = managers_with(&none, Some(home)).into_iter().map(|m| (m.name, m.dir)).collect();+ if !cfg!(windows) {+ assert_eq!(dirs[0], (MISE, home.join(".local/share/mise")));+ }+ assert_eq!(dirs[1], (ASDF, home.join(".asdf")));++ let xdg = |k: &str| (k == "XDG_DATA_HOME").then(|| OsString::from("/xdg"));+ assert_eq!(managers_with(&xdg, Some(home))[0].dir, Path::new("/xdg/mise"));++ let custom = |k: &str| match k {+ "MISE_DATA_DIR" => Some(OsString::from("/opt/mise")),+ "XDG_DATA_HOME" => Some(OsString::from("/xdg")),+ "ASDF_DATA_DIR" => Some(OsString::from("/opt/asdf")),+ _ => None,+ };+ let dirs: Vec<_> = managers_with(&custom, Some(home)).into_iter().map(|m| m.dir).collect();+ assert_eq!(dirs, [PathBuf::from("/opt/mise"), PathBuf::from("/opt/asdf")]);+ }++ #[cfg(unix)]+ #[test]+ fn installs_skip_alias_links() {+ let tmp = tempfile::tempdir().unwrap();+ let mise = Manager { name: MISE, dir: tmp.path().join("mise") };+ let node = mise.dir.join("installs/node");+ mkdir(&node.join("20.11.0"));+ mkdir(&node.join("22.1.0"));+ std::os::unix::fs::symlink("./22.1.0", node.join("22")).unwrap();+ std::os::unix::fs::symlink("./22.1.0", node.join("latest")).unwrap();+ let elsewhere = tmp.path().join("opt-node");+ mkdir(&elsewhere);+ std::os::unix::fs::symlink(&elsewhere, node.join("linked")).unwrap();+ std::fs::write(node.join(".mise.backend.toml"), "").unwrap();++ let names: Vec<_> =+ mise.installs(Tool::Node).iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect();+ assert_eq!(names, ["20.11.0", "22.1.0", "linked"]);+ assert_eq!(mise.install_named(Tool::Node, "22"), Some(node.join("22")));+ assert_eq!(mise.install_named(Tool::Node, "18"), None);+ assert_eq!(mise.install_named(Tool::Node, "../node"), None);++ // asdf's plugin names.+ let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };+ mkdir(&asdf.dir.join("installs/golang/1.22.1"));+ assert_eq!(asdf.installs(Tool::Go), [asdf.dir.join("installs/golang/1.22.1")]);+ assert_eq!(manager_in(&[mise.clone(), asdf.clone()], &node.join("20.11.0/bin/node")), Some(MISE));+ assert_eq!(manager_in(&[mise, asdf], tmp.path()), None);+ }++ #[cfg(unix)]+ #[test]+ fn shims_join_a_path_the_hook_did_not_set() {+ let tmp = tempfile::tempdir().unwrap();+ let mise = Manager { name: MISE, dir: tmp.path().join("mise") };+ let asdf = Manager { name: ASDF, dir: tmp.path().join("asdf") };+ let managers = [mise.clone(), asdf.clone()];+ let path = OsString::from("/usr/bin:/bin");+ assert_eq!(path_with_shims(&managers, &path), path, "no shims installed");++ mkdir(&mise.shims());+ mkdir(&asdf.shims());+ let got = path_with_shims(&managers, &path);+ let want = format!("{}:/usr/bin:/bin:{}", mise.shims().display(), asdf.shims().display());+ assert_eq!(got, OsString::from(want));+ assert_eq!(path_with_shims(&managers, &got), got, "applied once");++ // `mise activate` put an install on PATH: mise is active, only asdf's shims join.+ let active = format!("{}:/usr/bin", mise.dir.join("installs/node/22.1.0/bin").display());+ let got = path_with_shims(&managers, OsStr::new(&active));+ assert_eq!(got, OsString::from(format!("{active}:{}", asdf.shims().display())));+ }+}diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rsindex 404305f9f..c7a1d1916 100644--- a/crates/ide-sdk/src/apply.rs+++ b/crates/ide-sdk/src/apply.rs@@ -3,9 +3,10 @@use crate::discover::{project_venv_python, workspace_tsdk};use crate::exec::{path_with, search_path};-use crate::{angular, godot, vue};+use crate::{angular, godot, pinned, vue};use crate::{bin_dir, exe, venv_of};use ide_core::settings::{LanguageServerSettings, Settings};+use ide_core::version_managers::Tool;use ide_language::{LanguageConfig, LanguageServerConfig};use ide_run::RunConfig;use serde_json::{Value, json};@@ -28,14 +29,22 @@ pub fn setting_path(root: &Path, s: &str) -> Option<PathBuf> {}/// The project interpreter: the configured one, else a project virtualenv-/// (`.venv`, `venv`, …) in `dir` or the project root.+/// (`.venv`, `venv`, …) in the project root, else the Python the project pins for mise / asdf.pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {- setting_path(root, &s.languages.python.interpreter).or_else(|| project_venv_python(root))+ setting_path(root, &s.languages.python.interpreter)+ .or_else(|| project_venv_python(root))+ .or_else(|| pinned::pinned_python(root))}-/// The configured `node` executable's directory.+/// The configured `node` executable's directory, else the `bin` of the Node.js the+/// project pins for mise / asdf.pub(crate) fn node_dir(root: &Path, s: &Settings) -> Option<PathBuf> {- setting_path(root, &s.languages.node.interpreter).and_then(|p| p.parent().map(Path::to_path_buf))+ match setting_path(root, &s.languages.node.interpreter) {+ Some(p) => p.parent().map(Path::to_path_buf),+ None => pinned::pinned_install(root, Tool::Node)+ .map(|(dir, _)| dir.join("bin"))+ .filter(|bin| bin.join(exe("node")).is_file()),+ }}/// The configured Rust toolchain's `bin` directory and rustup toolchain name.@@ -54,8 +63,10 @@ pub(crate) fn rust_bin(root: &Path, s: &Settings) -> Option<(PathBuf, Option<StrSome((bin, toolchain))}+/// The configured GOROOT, else the Go the project pins for mise / asdf.pub(crate) fn goroot(root: &Path, s: &Settings) -> Option<PathBuf> {setting_path(root, &s.languages.go.goroot)+ .or_else(|| pinned::pinned_install(root, Tool::Go).and_then(|(dir, _)| pinned::goroot_in_install(&dir)))}/// A JDK setting: a JDK home, its `bin` or its `bin/java`.@@ -64,11 +75,12 @@ fn jdk_setting(root: &Path, value: &str) -> Option<Result<crate::java::Jdk, PathSome(p.ancestors().take(3).find_map(crate::java::jdk_at).ok_or(p))}-/// The project JDK (`languages.java.jdk`).+/// The project JDK (`languages.java.jdk`), else the JDK the project pins for mise / asdf.pub fn project_jdk(root: &Path, s: &Settings) -> Option<crate::java::Jdk> {- jdk_setting(root, &s.languages.java.jdk)?- .inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display()))- .ok()+ match jdk_setting(root, &s.languages.java.jdk) {+ Some(jdk) => jdk.inspect_err(|p| tracing::warn!("project JDK {} is not a JDK home", p.display())).ok(),+ None => pinned::pinned_install(root, Tool::Java).and_then(|(dir, _)| pinned::jdk_in_install(&dir)),+ }}/// The JDK chosen to run jdtls (`languages.java.jdtlsJdk`): `Ok(None)` when not@@ -85,10 +97,18 @@ pub fn jdtls_jdk(root: &Path, s: &Settings) -> Result<Option<crate::java::Jdk>,}/// `mvn` of the configured Maven home (`languages.java.maven.home`): the-/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`.+/// executable itself, `<home>/bin/mvn` or `<bin>/mvn`; else of the Maven the project+/// pins for mise / asdf when it has no Maven wrapper.pub fn maven_command(root: &Path, s: &Settings) -> Option<PathBuf> {- let p = setting_path(root, &s.languages.java.maven.home)?;let name = if cfg!(windows) { "mvn.cmd" } else { "mvn" };+ let Some(p) = setting_path(root, &s.languages.java.maven.home) else {+ if root.join("mvnw").is_file() || root.join("mvnw.cmd").is_file() {+ return None;+ }+ let (dir, _) = pinned::pinned_install(root, Tool::Maven)?;+ let homes = std::iter::once(dir.clone()).chain(std::fs::read_dir(&dir).ok()?.flatten().map(|e| e.path()));+ return homes.map(|h| h.join("bin").join(name)).find(|c| c.is_file());+ };let found = [p.clone(), p.join("bin").join(name), p.join(name)].into_iter().find(|c| c.is_file());if found.is_none() {tracing::warn!("Maven home {} has no {name}", p.display());@@ -458,6 +478,7 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settingslet jdk = project_jdk(root, s);let mvn = maven_command(root, s);let mvn_options = maven_options(root, s);+ let gradle = pinned::pinned_install(root, Tool::Gradle).map(|(dir, _)| dir.join("bin"));for c in configs.iter_mut() {resolve_run_command(c, root, s);@@ -529,6 +550,11 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settingsif let Some(jdk) = &jdk {c.env.entry("JAVA_HOME".into()).or_insert_with(|| jdk.home.to_string_lossy().into_owned());}+ if c.kind == "gradle"+ && let Some(bin) = gradle.as_ref().filter(|b| b.is_dir())+ {+ path_dirs.push(bin.clone());+ }if c.kind == "maven" && c.detected {if let Some(mvn) = &mvn {c.command = mvn.to_string_lossy().into_owned();diff --git a/crates/ide-sdk/src/discover.rs b/crates/ide-sdk/src/discover.rsindex 439971472..5aea9ea41 100644--- a/crates/ide-sdk/src/discover.rs+++ b/crates/ide-sdk/src/discover.rs@@ -1,7 +1,8 @@//! Finding installed interpreters and toolchains.use crate::exec::{query, search_path, which};-use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, venv_of};+use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};+use ide_core::version_managers::{self, Tool};use std::collections::HashSet;use std::path::{Path, PathBuf};use std::time::Duration;@@ -11,7 +12,7 @@ const VERSION_TIMEOUT: Duration = Duration::from_secs(4);/// Installed SDKs of `kind`, project-local ones (`root`) first. Blocking: runs/// `--version` queries in parallel.pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {- match kind {+ let mut out = match kind {SdkKind::Python => python(root),SdkKind::Node => node(),SdkKind::PackageManager => package_managers(),@@ -20,9 +21,34 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {SdkKind::TypeScript => typescript(root),SdkKind::Jdk => jdk(),SdkKind::Maven => maven(),+ };+ if let Some(root) = root {+ pinned_first(&mut out, kind, root);+ }+ out+}++fn tool_of(kind: SdkKind) -> Option<Tool> {+ match kind {+ SdkKind::Python => Some(Tool::Python),+ SdkKind::Node => Some(Tool::Node),+ SdkKind::Go => Some(Tool::Go),+ SdkKind::Jdk => Some(Tool::Java),+ SdkKind::Maven => Some(Tool::Maven),+ SdkKind::PackageManager | SdkKind::Rust | SdkKind::TypeScript => None,}}+/// Moves the install the project pins for mise / asdf after the project's own SDKs+/// (virtualenvs), ahead of the rest.+fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {+ let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };+ let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };+ let at = sdks.iter().take_while(|s| s.source == "venv").count().min(i);+ let sdk = sdks.remove(i);+ sdks.insert(at, sdk);+}+/// Runs `f` over `items` on scoped threads (version queries spawn processes).fn par_map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Option<R> + Sync) -> Vec<R> {std::thread::scope(|s| {@@ -99,6 +125,9 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {for v in subdirs(&home.join(".local/share/uv/python")) {found.push((v.join(bin_dir()).join(exe("python3")), "uv"));}+ for (v, manager) in version_managers::installs(Tool::Python) {+ found.extend(pinned::python_in_install(&v).map(|p| (p, manager)));+ }let mut conda_roots: Vec<PathBuf> =["miniconda3", "anaconda3", "miniforge3", "mambaforge", "micromamba", "opt/miniconda3"].iter()@@ -118,7 +147,7 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {}}for dir in std::env::split_paths(&search_path()) {- if dir.ends_with(".pyenv/shims") {+ if dir.ends_with(".pyenv/shims") || version_managers::is_shims_dir(&dir) {continue;}let mut names: Vec<String> = std::fs::read_dir(&dir)@@ -177,7 +206,7 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Optiformat!("Python {short} (conda: {})", env.unwrap_or_default())}(None, "pyenv") => format!("Python {short} (pyenv)"),- (None, "uv") => format!("Python {short} (uv)"),+ (None, tool @ ("uv" | "mise" | "asdf")) => format!("Python {short} ({tool})"),_ => format!("Python {short}"),};Some(Sdk {@@ -209,8 +238,10 @@ fn subdirs(dir: &Path) -> Vec<PathBuf> {fn node() -> Vec<Sdk> {let mut found: Vec<(PathBuf, &'static str)> = Vec::new();- if let Some(p) = which("node") {- found.push((p, "path"));+ // A mise / asdf shim picks the version by directory: its installs are listed instead.+ if let Some(p) = which("node").filter(|p| !version_managers::is_shim(p)) {+ let source = version_managers::manager_of(&p).unwrap_or("path");+ found.push((p, source));}if let Some(home) = home_dir() {for v in subdirs(&home.join(".nvm/versions/node")).into_iter().rev() {@@ -223,6 +254,9 @@ fn node() -> Vec<Sdk> {found.push((v.join("installation/bin").join(exe("node")), "fnm"));}}+ for (v, manager) in version_managers::installs(Tool::Node).into_iter().rev() {+ found.push((v.join("bin").join(exe("node")), manager));+ }for p in ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"] {found.push((PathBuf::from(p), "system"));}@@ -323,7 +357,7 @@ fn go() -> Vec<Sdk> {let path_go = which("go");let default_gopath =path_go.as_ref().and_then(|go| query(go, &["env", "GOPATH"], VERSION_TIMEOUT)).map(PathBuf::from);- if let Some(go) = &path_go+ if let Some(go) = path_go.as_ref().filter(|p| !version_managers::is_shim(p))&& let Some(root) = query(go, &["env", "GOROOT"], VERSION_TIMEOUT){roots.push((PathBuf::from(root), "path"));@@ -341,6 +375,9 @@ fn go() -> Vec<Sdk> {}}}+ for (d, manager) in version_managers::installs(Tool::Go) {+ roots.extend(pinned::goroot_in_install(&d).map(|r| (r, manager)));+ }let mut seen = HashSet::new();roots.retain(|(r, _)| {r.join("bin").join(exe("go")).is_file() && seen.insert(r.canonicalize().unwrap_or_else(|_| r.clone()))@@ -411,7 +448,7 @@ pub fn jdk_sdk(j: &crate::java::Jdk) -> Sdk {} else if crate::java::is_downloaded(&j.home) {"downloaded"} else {- "system"+ version_managers::manager_of(&j.home).unwrap_or("system")};Sdk {path: j.home.clone().into(),@@ -466,6 +503,10 @@ fn maven() -> Vec<Sdk> {for d in subdirs(&home.join(".sdkman/candidates/maven")) {found.push((d, "sdkman"));}+ for (d, manager) in version_managers::installs(Tool::Maven) {+ found.extend(subdirs(&d).into_iter().map(|s| (s, manager)));+ found.push((d, manager));+ }// Distributions the Maven wrapper downloaded: `dists/apache-maven-3.9.6-bin/<hash>/apache-maven-3.9.6`,// or since wrapper 3.3 the home itself, `dists/apache-maven-3.9.6/<hash>`.for dist in subdirs(&home.join(".m2/wrapper/dists")) {diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rsindex f72654169..55a56c090 100644--- a/crates/ide-sdk/src/java.rs+++ b/crates/ide-sdk/src/java.rs@@ -67,7 +67,7 @@ pub fn is_downloaded(home: &Path) -> bool {}/// JDK homes in the usual install locations (macOS `JavaVirtualMachines`,-/// `/usr/lib/jvm`, SDKMAN, IDEA's `~/.jdks`, Homebrew, Windows vendor+/// `/usr/lib/jvm`, SDKMAN, mise, asdf, IDEA's `~/.jdks`, Homebrew, Windows vendor/// directories, the IDE's downloads), `JAVA_HOME` first, then the `java` on `PATH`.fn scan() -> Vec<Jdk> {let mut homes: Vec<PathBuf> = Vec::new();@@ -110,6 +110,10 @@ fn scan() -> Vec<Jdk> {homes.extend([dir.join("Contents/Home"), dir.join("libexec/openjdk.jdk/Contents/Home"), dir]);}}+ // mise keeps a macOS JDK as its bundle (`<version>/Contents/Home`), asdf flattens it.+ for (dir, _) in ide_core::version_managers::installs(ide_core::version_managers::Tool::Java) {+ homes.extend([dir.join("Contents/Home"), dir]);+ }let mut out: Vec<Jdk> = Vec::new();for h in homes {if let Some(jdk) = jdk_at(&h)diff --git a/crates/ide-sdk/src/lib.rs b/crates/ide-sdk/src/lib.rsindex 885735cf8..66ebdbbf5 100644--- a/crates/ide-sdk/src/lib.rs+++ b/crates/ide-sdk/src/lib.rs@@ -16,6 +16,7 @@ pub mod libraries;pub mod locate;pub mod lombok;mod npm;+pub mod pinned;pub mod python;mod vue;diff --git a/crates/ide-sdk/src/pinned.rs b/crates/ide-sdk/src/pinned.rsnew file mode 100644index 000000000..9913a0d27--- /dev/null+++ b/crates/ide-sdk/src/pinned.rs@@ -0,0 +1,233 @@+//! Tool versions a project pins for mise / asdf (`mise.toml`, `.tool-versions`), and the+//! installs that match them.++use ide_core::version_managers::{self, Manager, Tool};+use std::path::{Path, PathBuf};++/// mise's config files in a directory, the one that wins first; `.tool-versions` (asdf's,+/// read by mise too) last.+const CONFIG_FILES: [&str; 9] = [+ "mise.local.toml",+ ".mise.local.toml",+ "mise.toml",+ ".mise.toml",+ "mise/config.toml",+ ".mise/config.toml",+ ".config/mise.toml",+ ".config/mise/config.toml",+ ".tool-versions",+];++/// The version of `tool` pinned for `root`: the closest directory from `root` up that+/// pins it, then the global config (`~/.config/mise/config.toml`).+pub fn pinned_version(root: &Path, tool: Tool) -> Option<String> {+ pinned_version_in(root, &global_configs(), tool)+}++fn pinned_version_in(root: &Path, global: &[PathBuf], tool: Tool) -> Option<String> {+ let files = root.ancestors().flat_map(|dir| CONFIG_FILES.iter().map(move |f| dir.join(f)));+ files.chain(global.iter().cloned()).find_map(|file| {+ let text = std::fs::read_to_string(&file).ok()?;+ if file.file_name().is_some_and(|n| n == ".tool-versions") {+ tool_versions_entry(&text, tool)+ } else {+ mise_toml_entry(&text, tool)+ }+ })+}++fn global_configs() -> Vec<PathBuf> {+ let var = |k: &str| ide_core::process::host_var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);+ if let Some(file) = var("MISE_GLOBAL_CONFIG_FILE") {+ return vec![file];+ }+ let dir = var("MISE_CONFIG_DIR")+ .or_else(|| var("XDG_CONFIG_HOME").map(|d| d.join("mise")))+ .or_else(|| crate::home_dir().map(|h| h.join(".config/mise")));+ dir.map(|d| vec![d.join("config.toml")]).unwrap_or_default()+}++/// The tool's key under `[tools]`: its name, or with a backend (`core:java`, `asdf:maven`).+fn is_key_for(key: &str, tool: Tool) -> bool {+ let name = key.rsplit_once(':').map_or(key, |(_, n)| n);+ let name = name.rsplit_once('/').map_or(name, |(_, n)| n);+ tool.names().contains(&name)+}++/// `node = "20"`, `python = ["3.12", "3.11"]` (the first) or `java = { version = "21" }`.+fn mise_toml_entry(text: &str, tool: Tool) -> Option<String> {+ let doc: toml::Table = toml::from_str(text).ok()?;+ let tools = doc.get("tools")?.as_table()?;+ let value = tools.iter().find(|(k, _)| is_key_for(k, tool)).map(|(_, v)| v)?;+ let first = match value {+ toml::Value::Array(a) => a.first()?,+ v => v,+ };+ let version = match first {+ toml::Value::String(s) => s.as_str(),+ toml::Value::Table(t) => t.get("version")?.as_str()?,+ _ => return None,+ };+ Some(version.trim().to_owned()).filter(|v| !v.is_empty())+}++/// `nodejs 20.11.0 18.19.0` (the first version).+fn tool_versions_entry(text: &str, tool: Tool) -> Option<String> {+ text.lines().find_map(|line| {+ let line = line.split('#').next()?;+ let mut words = line.split_whitespace();+ let name = words.next()?;+ is_key_for(name, tool).then(|| words.next().map(str::to_owned))?+ })+}++/// Numbers in a version, for ordering (`temurin-21.0.2+13` → 21, 0, 2, 13).+fn version_key(v: &str) -> Vec<u64> {+ v.split(|c: char| !c.is_ascii_digit()).filter_map(|n| n.parse().ok()).collect()+}++/// Whether the install `dir_name` is what mise resolves `version` to: the same name, or a+/// longer one it is a prefix of (`21` → `21.0.2`, `temurin-21` → `temurin-21.0.2+13.0.LTS`).+fn matches(dir_name: &str, version: &str) -> bool {+ dir_name == version || dir_name.strip_prefix(version).is_some_and(|rest| rest.starts_with(['.', '-', '+', '_']))+}++/// The install of `tool` that `version` selects among `managers`' installs.+fn install_for(managers: &[Manager], tool: Tool, version: &str) -> Option<(PathBuf, &'static str)> {+ if let Some(path) = version.strip_prefix("path:") {+ let path = PathBuf::from(path.trim());+ return path.is_dir().then_some((path, version_managers::MISE));+ }+ managers.iter().find_map(|m| {+ if let Some(exact) = m.install_named(tool, version) {+ return Some((dunce::canonicalize(&exact).unwrap_or(exact), m.name));+ }+ let installs = m.installs(tool);+ let name = |p: &PathBuf| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ let best = if version == "latest" {+ installs.into_iter().max_by_key(|p| version_key(&name(p)))+ } else {+ installs.into_iter().filter(|p| matches(&name(p), version)).max_by_key(|p| version_key(&name(p)))+ };+ best.map(|p| (p, m.name))+ })+}++/// The mise / asdf install of `tool` that `root` pins, with the manager's name.+pub fn pinned_install(root: &Path, tool: Tool) -> Option<(PathBuf, &'static str)> {+ let version = pinned_version(root, tool)?;+ install_for(&version_managers::managers(), tool, &version)+}++/// The pinned Python's executable.+pub(crate) fn pinned_python(root: &Path) -> Option<PathBuf> {+ let (dir, _) = pinned_install(root, Tool::Python)?;+ python_in_install(&dir)+}++/// `bin/python3` of a Python install (`python.exe` at its root on Windows).+pub(crate) fn python_in_install(dir: &Path) -> Option<PathBuf> {+ let candidates = if cfg!(windows) {+ vec![dir.join("python.exe")]+ } else {+ vec![dir.join("bin/python3"), dir.join("bin/python")]+ };+ candidates.into_iter().find(|p| p.is_file())+}++/// A Go install's GOROOT: the install itself (mise) or its `go` folder (asdf).+pub(crate) fn goroot_in_install(dir: &Path) -> Option<PathBuf> {+ [dir.to_path_buf(), dir.join("go")].into_iter().find(|d| d.join("bin").join(crate::exe("go")).is_file())+}++/// A JDK install's home: the install itself, or `Contents/Home` of a macOS bundle.+pub(crate) fn jdk_in_install(dir: &Path) -> Option<crate::java::Jdk> {+ [dir.join("Contents/Home"), dir.to_path_buf()].iter().find_map(|h| crate::java::jdk_at(h))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn write(path: &Path, text: &str) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, text).unwrap();+ }++ #[test]+ fn reads_mise_toml_forms() {+ let toml = r#"+ [env]+ NODE_ENV = "dev"+ [tools]+ node = "20"+ python = ["3.12", "3.11"]+ "core:java" = { version = "temurin-21", os = ["macos"] }+ "asdf:mise-plugins/mise-maven" = "3.9.6"+ "#;+ assert_eq!(mise_toml_entry(toml, Tool::Node).as_deref(), Some("20"));+ assert_eq!(mise_toml_entry(toml, Tool::Python).as_deref(), Some("3.12"));+ assert_eq!(mise_toml_entry(toml, Tool::Java).as_deref(), Some("temurin-21"));+ assert_eq!(mise_toml_entry(toml, Tool::Maven).as_deref(), None, "the plugin is mise-maven, not maven");+ assert_eq!(mise_toml_entry("[tools]\nmaven = '3.9.6'\n", Tool::Maven).as_deref(), Some("3.9.6"));+ assert_eq!(mise_toml_entry(toml, Tool::Go), None);+ assert_eq!(mise_toml_entry("not toml [", Tool::Node), None);+ }++ #[test]+ fn reads_tool_versions() {+ let text = "# pinned\nnodejs 20.11.0 18.19.0\ngolang 1.22.1 # comment\njava\n";+ assert_eq!(tool_versions_entry(text, Tool::Node).as_deref(), Some("20.11.0"));+ assert_eq!(tool_versions_entry(text, Tool::Go).as_deref(), Some("1.22.1"));+ assert_eq!(tool_versions_entry(text, Tool::Java), None);+ assert_eq!(tool_versions_entry(text, Tool::Python), None);+ }++ #[test]+ fn the_closest_config_wins_then_the_global_one() {+ let tmp = tempfile::tempdir().unwrap();+ let repo = tmp.path().join("repo");+ let app = repo.join("apps/web");+ std::fs::create_dir_all(&app).unwrap();+ let global = tmp.path().join("global/config.toml");+ write(&global, "[tools]\nnode = 'lts'\npython = '3.13'\ngo = '1.23'\n");+ write(&repo.join("mise.toml"), "[tools]\nnode = '20'\njava = '21'\n");+ write(&repo.join(".tool-versions"), "nodejs 18.0.0\npython 3.11.9\n");+ write(&app.join(".mise.toml"), "[tools]\nnode = '22'\n");+ let g = [global];+ assert_eq!(pinned_version_in(&app, &g, Tool::Node).as_deref(), Some("22"));+ assert_eq!(pinned_version_in(&repo, &g, Tool::Node).as_deref(), Some("20"), "mise.toml over .tool-versions");+ assert_eq!(pinned_version_in(&app, &g, Tool::Python).as_deref(), Some("3.11.9"));+ assert_eq!(pinned_version_in(&app, &g, Tool::Java).as_deref(), Some("21"));+ assert_eq!(pinned_version_in(&app, &g, Tool::Go).as_deref(), Some("1.23"));+ assert_eq!(pinned_version_in(&app, &g, Tool::Gradle), None);+ write(&repo.join("mise.local.toml"), "[tools]\nnode = '21'\n");+ assert_eq!(pinned_version_in(&repo, &g, Tool::Node).as_deref(), Some("21"));+ }++ #[test]+ fn prefixes_resolve_to_the_newest_matching_install() {+ assert!(matches("21.0.2", "21"));+ assert!(matches("temurin-21.0.2+13.0.LTS", "temurin-21"));+ assert!(!matches("210.0", "21"));+ assert!(!matches("3.1.0", "3.12"));+ let tmp = tempfile::tempdir().unwrap();+ let mise = Manager { name: version_managers::MISE, dir: tmp.path().join("mise") };+ let asdf = Manager { name: version_managers::ASDF, dir: tmp.path().join("asdf") };+ for v in ["20.9.0", "20.11.1", "22.1.0"] {+ std::fs::create_dir_all(mise.dir.join("installs/node").join(v)).unwrap();+ }+ std::fs::create_dir_all(asdf.dir.join("installs/nodejs/18.19.0")).unwrap();+ let managers = [mise.clone(), asdf.clone()];+ let pick = |v: &str| install_for(&managers, Tool::Node, v).map(|(p, m)| (p.file_name().unwrap().to_owned(), m));+ assert_eq!(pick("20"), Some(("20.11.1".into(), "mise")));+ assert_eq!(pick("22.1.0"), Some(("22.1.0".into(), "mise")));+ assert_eq!(pick("latest"), Some(("22.1.0".into(), "mise")));+ assert_eq!(pick("18"), Some(("18.19.0".into(), "asdf")));+ assert_eq!(pick("16"), None);+ let external = tmp.path().join("node-dev");+ std::fs::create_dir_all(&external).unwrap();+ let path = format!("path:{}", external.display());+ assert_eq!(install_for(&managers, Tool::Node, &path), Some((external, "mise")));+ }+}diff --git a/crates/ide-sdk/tests/version_managers.rs b/crates/ide-sdk/tests/version_managers.rsnew file mode 100644index 000000000..6131f14e5--- /dev/null+++ b/crates/ide-sdk/tests/version_managers.rs@@ -0,0 +1,130 @@+//! mise / asdf installs: detection and the project's pinned versions. One test in its+//! own binary: it points `MISE_DATA_DIR` / `ASDF_DATA_DIR` at a fake layout.+#![cfg(unix)]++use ide_core::settings::Settings;+use ide_run::RunConfig;+use ide_sdk::{Sdk, SdkKind, detect};+use std::collections::BTreeMap;+use std::os::unix::fs::PermissionsExt;+use std::path::{Path, PathBuf};++fn write(path: &Path, text: &str) {+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(path, text).unwrap();+}++/// An executable that prints `out` (a `--version` answer).+fn script(path: &Path, out: &str) {+ write(path, &format!("#!/bin/sh\necho '{out}'\n"));+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();+}++fn jdk(home: &Path, version: &str) {+ write(&home.join("release"), &format!("IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"{version}\"\n"));+ script(&home.join("bin/java"), version);+}++fn find<'a>(sdks: &'a [Sdk], dir: &Path) -> &'a Sdk {+ sdks.iter().find(|s| s.path.starts_with(dir)).unwrap_or_else(|| panic!("{} not in {sdks:#?}", dir.display()))+}++#[test]+fn mise_and_asdf_installs_are_detected_and_pinned_versions_used() {+ let tmp = tempfile::tempdir().unwrap();+ let tmp = dunce::canonicalize(tmp.path()).unwrap();+ let mise = tmp.join("mise");+ let asdf = tmp.join("asdf");+ // SAFETY: the only test in this binary; nothing else reads the environment yet.+ unsafe {+ std::env::set_var("HOME", tmp.join("home"));+ std::env::set_var("MISE_DATA_DIR", &mise);+ std::env::set_var("ASDF_DATA_DIR", &asdf);+ std::env::set_var("MISE_GLOBAL_CONFIG_FILE", tmp.join("no-global.toml"));+ std::env::remove_var("JAVA_HOME");+ }++ let installs = mise.join("installs");+ jdk(&installs.join("java/21.0.2/Contents/Home"), "21.0.2"); // macOS bundle+ jdk(&asdf.join("installs/java/temurin-17.0.10+7"), "17.0.10");+ for v in ["20.11.1", "22.1.0"] {+ script(&installs.join("node").join(v).join("bin/node"), &format!("v{v}"));+ }+ std::os::unix::fs::symlink("./22.1.0", installs.join("node/22")).unwrap();+ script(&installs.join("python/3.12.1/bin/python3"), "Python 3.12.1");+ let goroot = asdf.join("installs/golang/1.22.1/go");+ write(&goroot.join("VERSION"), "go1.22.1\n");+ script(&goroot.join("bin/go"), "go version go1.22.1");+ let maven = installs.join("maven/3.9.6");+ script(&maven.join("bin/mvn"), "Apache Maven 3.9.6");+ write(&maven.join("lib/maven-core-3.9.6.jar"), "");+ script(&installs.join("gradle/8.7/bin/gradle"), "Gradle 8.7");++ let project = tmp.join("project");+ write(+ &project.join("mise.toml"),+ "[tools]\njava = '21'\nnode = '20'\npython = '3.12'\nmaven = '3.9'\ngradle = '8.7'\n",+ );+ write(&project.join(".tool-versions"), "golang 1.22.1\nnodejs 22.1.0\n");++ let jdks = detect(SdkKind::Jdk, Some(&project));+ let mise_jdk = find(&jdks, &installs.join("java/21.0.2"));+ assert_eq!((mise_jdk.source.as_str(), mise_jdk.name.as_str()), ("mise", "Eclipse Adoptium 21.0.2"));+ assert_eq!(find(&jdks, &asdf.join("installs/java")).source, "asdf");+ assert_eq!(jdks[0].path, mise_jdk.path, "the pinned JDK first");++ let nodes = detect(SdkKind::Node, Some(&project));+ assert_eq!(nodes[0].path, installs.join("node/20.11.1/bin/node"), "mise.toml over .tool-versions");+ assert_eq!(find(&nodes, &installs.join("node/22.1.0")).source, "mise");+ assert_eq!(nodes.iter().filter(|s| s.source == "mise").count(), 2, "the `22` alias is not listed again");++ let pythons = detect(SdkKind::Python, Some(&project));+ assert_eq!(find(&pythons, &installs.join("python")).name, "Python 3.12 (mise)");++ let gos = detect(SdkKind::Go, Some(&project));+ let go = find(&gos, &goroot);+ assert_eq!((go.source.as_str(), go.version.as_deref()), ("asdf", Some("1.22.1")));++ let mavens = detect(SdkKind::Maven, Some(&project));+ let mvn = find(&mavens, &maven);+ assert_eq!((mvn.source.as_str(), mvn.version.as_deref()), ("mise", Some("3.9.6")));++ // Nothing configured in Settings: the pinned versions apply.+ let s = Settings::default();+ let jdk = ide_sdk::apply::project_jdk(&project, &s).expect("pinned JDK");+ assert_eq!((jdk.major, jdk.home.clone()), (21, installs.join("java/21.0.2/Contents/Home")));+ assert_eq!(ide_sdk::apply::python_interpreter(&project, &s), Some(installs.join("python/3.12.1/bin/python3")));+ assert_eq!(ide_sdk::apply::maven_command(&project, &s), Some(maven.join("bin/mvn")));++ let run = |kind: &str, command: &str| RunConfig {+ id: format!("{kind}:x"),+ name: "x".into(),+ kind: kind.into(),+ command: command.into(),+ args: vec![],+ cwd: None,+ env: BTreeMap::new(),+ detected: true,+ is_test: false,+ debug_adapter: None,+ allow_parallel: false,+ extras: Default::default(),+ };+ let mut configs = [run("npm", "npm"), run("go", "go"), run("gradle", "gradle"), run("maven", "mvn")];+ ide_sdk::apply::apply_to_run_configs(&mut configs, &project, &s);+ let path_of = |c: &RunConfig| -> Vec<PathBuf> { std::env::split_paths(&c.env["PATH"]).collect() };+ assert_eq!(path_of(&configs[0])[0], installs.join("node/20.11.1/bin"));+ assert_eq!(configs[1].command, goroot.join("bin/go").to_string_lossy());+ assert_eq!(configs[1].env["GOROOT"], goroot.to_string_lossy());+ assert_eq!(path_of(&configs[2])[0], installs.join("gradle/8.7/bin"));+ assert_eq!(configs[2].env["JAVA_HOME"], jdk.home.to_string_lossy());+ assert_eq!(configs[3].command, maven.join("bin/mvn").to_string_lossy());++ // The project's Maven wrapper keeps precedence over a pinned Maven.+ script(&project.join("mvnw"), "");+ assert_eq!(ide_sdk::apply::maven_command(&project, &s), None);++ // A version the project pins but that isn't installed: nothing is made up.+ write(&project.join("mise.toml"), "[tools]\njava = '25'\n");+ assert_eq!(ide_sdk::apply::project_jdk(&project, &s), None);+}diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rsindex 2c68f04d1..45ca09511 100644--- a/crates/ide-tools/src/lib.rs+++ b/crates/ide-tools/src/lib.rs@@ -157,8 +157,10 @@ pub fn extend_process_path(app_data: &Path) {}}-/// `path` (a `PATH` value) with [`tools_bin_dirs`] in front, those it lacks.+/// `path` (a `PATH` value) with [`tools_bin_dirs`] in front, those it lacks, and the+/// mise / asdf shims when their shell hook didn't put them there.pub fn path_with_tools(app_data: &Path, path: &std::ffi::OsStr) -> OsString {+ let path = &ide_core::version_managers::path_with_shims(&ide_core::version_managers::managers(), path);let mut dirs = tools_bin_dirs(app_data);let current: Vec<PathBuf> = if path.is_empty() { Vec::new() } else { std::env::split_paths(path).collect() };dirs.retain(|d| !current.contains(d));