diff --git a/crates/ide-core/src/process.rs b/crates/ide-core/src/process.rs index ddb2dc5912..c2ea891f8c 100644 --- a/crates/ide-core/src/process.rs +++ b/crates/ide-core/src/process.rs @@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command { cmd } +/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`, +/// `.bat`) always run through it. +#[cfg_attr(not(windows), allow(dead_code))] +const CMD_ENV_LIMIT: usize = 8191; + #[cfg(windows)] fn compact_batch_path(cmd: &mut Command) { - use std::os::windows::ffi::OsStrExt; use std::path::{Component, Prefix}; - // Rust runs these files through cmd.exe, which drops inherited variables over this limit. - const CMD_ENV_LIMIT: usize = 8191; + // Rust runs these files through cmd.exe. let extension = Path::new(cmd.get_program()).extension(); if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) { return; @@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) { Some((_, path)) => path.map(OsStr::to_owned), None => std::env::var_os("PATH"), }; - let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return }; - - // The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are - // missing now, keeping search precedence and leaving UNC and relative paths alone. - let dirs = std::env::split_paths(&path).filter(|dir| { + let Some(path) = path else { return }; + // The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing + // now, leaving UNC and relative paths alone. + let present = |dir: &Path| { let local = dir.is_absolute() && matches!(dir.components().next(), Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_))); !local || !std::fs::symlink_metadata(dir) .is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory)) - }); - if let Ok(compact) = std::env::join_paths(dirs) - && compact.encode_wide().count() <= CMD_ENV_LIMIT - { + }; + if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) { cmd.env("PATH", compact); } } +/// The 8.3 form of `dir`, when the volume has one. +#[cfg(windows)] +fn short_path(dir: &Path) -> Option { + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW; + + let wide: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); + let mut buf = vec![0u16; wide.len()]; + let len = u32::try_from(buf.len()).ok()?; + // SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated. + let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize; + // 0 is an error; a value of at least the buffer's length is the size a longer form needs. + if written == 0 || written >= buf.len() { + return None; + } + buf.truncate(written); + Some(OsString::from_wide(&buf).into()) +} + +/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later +/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping +/// the search order; when that is still too long, directories take `shorten`'s form, longest +/// first, until it fits. `None` when `path` fits already or nothing got shorter. +#[cfg_attr(not(windows), allow(dead_code))] +fn compact_path_list( + path: &OsStr, + limit: usize, + present: impl Fn(&Path) -> bool, + shorten: impl Fn(&Path) -> Option, +) -> Option { + let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count(); + let original = width(path); + if original <= limit { + return None; + } + let mut seen = std::collections::HashSet::new(); + let mut dirs: Vec = std::env::split_paths(path) + .filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d)) + .collect(); + let mut joined = std::env::join_paths(&dirs).ok()?; + if width(&joined) > limit { + let mut longest: Vec = (0..dirs.len()).collect(); + longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str()))); + let mut total = width(&joined); + for i in longest { + if total <= limit { + break; + } + if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) { + total -= width(dirs[i].as_os_str()) - width(short.as_os_str()); + dirs[i] = short; + } + } + joined = std::env::join_paths(&dirs).ok()?; + } + (width(&joined) < original).then_some(joined) +} + /// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and /// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` → /// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id. @@ -1295,6 +1353,26 @@ mod tests { assert_eq!(session, pid, "the child leads its own session"); } + #[test] + fn compacts_a_path_too_long_for_cmd() { + let sep = if cfg!(windows) { ";" } else { ":" }; + let join = |dirs: &[&str]| OsString::from(dirs.join(sep)); + let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40)); + let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone")); + let present = |d: &Path| !d.ends_with("gone"); + let never = |_: &Path| None; + // Fits already: left alone. + assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None); + // Later duplicates and missing directories go, the order stays. + let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]); + assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c]))); + // Still too long: the longest directories take their short form until it fits. + let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy()))); + let path = join(&[&a, &format!("{b}-longer"), &c]); + assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c]))); + assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"]))); + } + #[test] fn process_alive_tells_live_from_dead_pids() { assert!(process_alive(std::process::id()));