pub use std::path::*;
use crate::dirs;
pub fn settle_display_separators(s: String) -> String {
match cfg!(windows) {
true => s.replace('/', "\\"),
false => s,
}
}
#[cfg(windows)]
fn simplify_verbatim_unc(shown: String) -> String {
const VERBATIM_UNC: &str = r"\\?\UNC\";
let Some(rest) = shown.strip_prefix(VERBATIM_UNC) else {
return shown;
};
let plain_len = 2 + rest.encode_utf16().count();
if rest.contains('/')
|| plain_len >= crate::file::MAX_PATH
|| rest
.split('\\')
.any(|c| c.ends_with('.') || c.ends_with(' '))
{
return shown;
}
format!(r"\\{rest}")
}
#[cfg(not(windows))]
fn simplify_verbatim_unc(shown: String) -> String {
shown
}
pub trait PathExt {
fn display_user(&self) -> String;
fn mount(&self, on: &Path) -> PathBuf;
fn is_empty(&self) -> bool;
}
impl PathExt for Path {
fn display_user(&self) -> String {
let path = dunce::simplified(self);
let home = dirs::HOME.to_string_lossy();
let home_str: &str = home.as_ref();
let shown = match cfg!(unix) && path.starts_with(home_str) && home != "/" {
true => path.to_string_lossy().replacen(home_str, "~", 1),
false => path.to_string_lossy().to_string(),
};
simplify_verbatim_unc(shown)
}
fn mount(&self, on: &Path) -> PathBuf {
if PathExt::is_empty(self) {
on.to_path_buf()
} else {
on.join(self)
}
}
fn is_empty(&self) -> bool {
self.as_os_str().is_empty()
}
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn program_stem(program: &Path) -> Option<String> {
let s = program.to_str()?;
let basename = s.rsplit(['/', '\\']).next().unwrap_or(s);
let stem = match basename.rsplit_once('.') {
Some((stem, ext)) if ext.eq_ignore_ascii_case("exe") => stem,
_ => basename,
};
Some(stem.to_ascii_lowercase())
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn is_posix_shell_program(program: &Path) -> bool {
const POSIX_SHELLS: &[&str] = &["bash", "sh", "zsh", "fish", "ksh", "dash", "ash"];
let Some(stem) = program_stem(program) else {
return false;
};
POSIX_SHELLS.iter().any(|name| *name == stem)
}
pub fn command_mode_script_payload(program: &Path) -> Option<&'static str> {
if program_stem(program).as_deref() == Some("fish") {
return Some("$argv");
}
is_posix_shell_program(program).then_some(r#""$0" "$@""#)
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn is_cmd_shell_program(program: &Path) -> bool {
program_stem(program).as_deref() == Some("cmd")
}
pub fn is_powershell_program(program: &Path) -> bool {
matches!(
program_stem(program).as_deref(),
Some("pwsh" | "powershell")
)
}
pub fn inject_powershell_no_profile(shell: &mut Vec<String>) {
let Some(program) = shell.first() else {
return;
};
if !is_powershell_program(Path::new(program)) {
return;
}
let already_present = shell[1..]
.iter()
.take_while(|arg| {
let token = arg.trim_start_matches(['-', '/']).to_ascii_lowercase();
!(!token.is_empty()
&& ("command".starts_with(&token)
|| "commandwithargs".starts_with(&token)
|| "file".starts_with(&token)))
})
.any(|arg| {
let token = arg.trim_start_matches(['-', '/']).to_ascii_lowercase();
token.len() >= 3 && "noprofile".starts_with(&token)
});
if !already_present {
shell.insert(1, "-NoProfile".to_string());
}
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn cmd_verbatim_args(shell_flags: &[String], script: &str, args: &[String]) -> Vec<String> {
let mut body = join_cmd_script_lines(script);
for arg in args {
body.push(' ');
body.push_str("e_arg_for_cmd_body(arg));
}
let mut out: Vec<String> = Vec::with_capacity(shell_flags.len() + 2);
if !shell_flags.iter().any(|f| f.eq_ignore_ascii_case("/s")) {
out.push("/s".to_string());
}
out.extend(shell_flags.iter().cloned());
out.push(format!("\"{body}\""));
out
}
#[cfg_attr(not(windows), allow(dead_code))]
fn join_cmd_script_lines(script: &str) -> String {
if !script.contains('\n') {
return script.to_string();
}
let script = script.trim();
if !script.contains('\n') {
return script.to_string();
}
let mut out = String::new();
let mut caret = false;
let mut open = false;
for line in script.lines() {
let trimmed = line.trim();
if caret && trimmed.is_empty() {
caret = false;
continue;
}
let lower = trimmed.to_ascii_lowercase();
let is_comment = trimmed.starts_with("::")
|| lower == "rem"
|| lower.starts_with("rem ")
|| lower.starts_with("rem\t");
if !caret && (trimmed.is_empty() || is_comment) {
continue;
}
if !out.is_empty() && !caret && !open && !trimmed.starts_with(')') {
out.push('&');
}
let carets = trimmed.len() - trimmed.trim_end_matches('^').len();
if carets % 2 == 1 {
out.push_str(&trimmed[..trimmed.len() - 1]);
caret = true;
open = false;
} else {
out.push_str(trimmed);
caret = false;
let segment = last_cmd_segment(trimmed);
let first = segment
.trim_start_matches('@')
.split_whitespace()
.next()
.unwrap_or_default()
.to_ascii_lowercase();
let introduces_block = segment == "("
|| trimmed.starts_with(')')
|| matches!(first.as_str(), "if" | "for" | "else");
open = introduces_block
&& trimmed
.strip_suffix('(')
.is_some_and(|rest| (rest.len() - rest.trim_end_matches('^').len()) % 2 == 0);
}
}
out
}
#[cfg_attr(not(windows), allow(dead_code))]
fn last_cmd_segment(line: &str) -> &str {
let mut start = 0;
let mut in_quotes = false;
let mut chars = line.char_indices();
while let Some((i, c)) = chars.next() {
match c {
'"' => in_quotes = !in_quotes,
'^' if !in_quotes => {
chars.next();
}
'&' | '|' if !in_quotes => start = i + 1,
_ => {}
}
}
line[start..].trim()
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn quote_arg_for_cmd_body(arg: &str) -> String {
if !arg.is_empty() && !arg.contains([' ', '\t', '"', '&', '|', '<', '>', '(', ')', '^']) {
return arg.to_string();
}
let mut s = String::with_capacity(arg.len() + 2);
s.push('"');
let mut backslashes = 0usize;
for c in arg.chars() {
if c == '\\' {
backslashes += 1;
} else {
if c == '"' {
for _ in 0..=backslashes {
s.push('\\');
}
}
backslashes = 0;
}
s.push(c);
}
for _ in 0..backslashes {
s.push('\\');
}
s.push('"');
s
}
pub fn escape_arg_for_cmd_line(arg: &str) -> String {
let quoted = quote_arg_for_cmd_body(arg);
if !arg.contains('"') {
if !quoted.starts_with('"') {
return quoted.replace('%', "^%");
}
let segments: Vec<String> = arg
.split('%')
.map(|segment| {
let trailing = segment.len() - segment.trim_end_matches('\\').len();
format!("{segment}{}", "\\".repeat(trailing))
})
.collect();
return format!("\"{}\"", segments.join("\"^%\""));
}
let mut escaped = String::with_capacity(quoted.len() * 2);
for c in quoted.chars() {
if matches!(c, '(' | ')' | '%' | '!' | '^' | '"' | '<' | '>' | '&' | '|') {
escaped.push('^');
}
escaped.push(c);
}
escaped
}
#[cfg(windows)]
pub fn cmd_verbatim_command(
program: &str,
flags: &[String],
body: &str,
) -> Option<std::process::Command> {
use std::os::windows::process::CommandExt;
let runs_command = flags
.iter()
.any(|f| f.eq_ignore_ascii_case("/c") || f.eq_ignore_ascii_case("/k"));
if !is_cmd_shell_program(Path::new(program)) || !runs_command {
return None;
}
let mut c = std::process::Command::new(program);
for a in cmd_verbatim_args(flags, body, &[]) {
c.raw_arg(a);
}
Some(c)
}
pub fn positional_cmd_command(args: &[String]) -> Option<(&[String], &str)> {
let (command, switches) = args.split_last()?;
let runs = switches
.last()
.is_some_and(|s| s.eq_ignore_ascii_case("/c") || s.eq_ignore_ascii_case("/k"));
(runs && switches.iter().all(|s| s.starts_with('/')) && command.contains('"'))
.then_some((switches, command.as_str()))
}
pub fn split_shell_command(s: &str) -> eyre::Result<Vec<String>> {
#[cfg(windows)]
{
split_shell_command_windows(s)
}
#[cfg(not(windows))]
{
Ok(shell_words::split(s)?)
}
}
#[cfg(windows)]
fn split_shell_command_windows(s: &str) -> eyre::Result<Vec<String>> {
let mut args: Vec<String> = Vec::new();
let mut cur = String::new();
let mut in_token = false;
let mut in_quotes = false;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '"' {
in_token = true;
if in_quotes {
if chars.peek() == Some(&'"') {
cur.push('"');
chars.next();
} else {
in_quotes = false;
}
} else {
in_quotes = true;
}
} else if c.is_whitespace() && !in_quotes {
if in_token {
args.push(std::mem::take(&mut cur));
in_token = false;
}
} else {
in_token = true;
cur.push(c);
}
}
if in_quotes {
return Err(eyre::eyre!("unbalanced quote in shell command: {s}"));
}
if in_token {
args.push(cur);
}
Ok(args)
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn unix_path_to_windows(entry: &str) -> Option<String> {
if let Some(rest) = entry.strip_prefix("//")
&& !rest.is_empty()
&& !rest.starts_with('/')
{
return Some(format!(r"\\{}", rest.replace('/', r"\")));
}
let bytes = entry.as_bytes();
if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
return Some(entry.replace('/', r"\"));
}
let unprefixed = entry.strip_prefix("/cygdrive").unwrap_or(entry);
let b = unprefixed.as_bytes();
if b.len() >= 2 && b[0] == b'/' && b[1].is_ascii_alphabetic() && (b.len() == 2 || b[2] == b'/')
{
let drive = (b[1] as char).to_ascii_uppercase();
let tail = unprefixed[2..].replace('/', r"\"); return Some(if tail == r"\" || tail.is_empty() {
format!(r"{drive}:\")
} else {
format!("{drive}:{tail}")
});
}
None
}
#[cfg(windows)]
pub fn resolve_posix_shell_program_path(
program: &std::ffi::OsStr,
env: &std::collections::BTreeMap<String, String>,
) -> Option<std::ffi::OsString> {
if !is_posix_shell_program(Path::new(program)) {
return None;
}
if program_has_directory_component(program) {
return None;
}
let is_bash = is_bash_basename(program);
if is_bash {
let override_path = env
.get("MISE_BASH_PATH")
.cloned()
.or_else(|| std::env::var("MISE_BASH_PATH").ok())
.filter(|s| !s.is_empty());
if let Some(p) = override_path {
let path = PathBuf::from(&p);
if path.is_file() {
return Some(path.into_os_string());
}
warn!("MISE_BASH_PATH={p} does not exist; falling back to other candidates");
}
}
let path_val = env.get(&*crate::env::PATH_KEY)?;
if !path_val.contains(';') && !path_val.contains('\\') {
return None;
}
if is_bash {
for candidate in bash_candidates(env) {
if candidate.is_file() {
return Some(candidate.into_os_string());
}
}
}
let cwd = std::env::current_dir().ok()?;
if is_bash {
let mut all = which::which_in_all(program, Some(path_val.as_str()), cwd).ok()?;
if let Some(p) = all.find(|p| !is_wsl_launcher_bash(p)) {
return Some(p.into_os_string());
}
warn!(
"no real POSIX bash found on PATH (only the WSL launcher) when resolving bash; \
install Git Bash or MSYS2, or set MISE_BASH_PATH to a real POSIX bash to silence this"
);
return None;
}
which::which_in(program, Some(path_val.as_str()), cwd)
.ok()
.map(|p| p.into_os_string())
}
#[cfg(windows)]
fn is_bash_basename(program: &std::ffi::OsStr) -> bool {
program_stem(Path::new(program)).as_deref() == Some("bash")
}
#[cfg(windows)]
fn program_has_directory_component(program: &std::ffi::OsStr) -> bool {
Path::new(program).components().count() > 1
}
#[cfg(windows)]
fn bash_candidates(env: &std::collections::BTreeMap<String, String>) -> Vec<PathBuf> {
let mut candidates = vec![
PathBuf::from(r"C:\Program Files\Git\bin\bash.exe"),
PathBuf::from(r"C:\Program Files (x86)\Git\bin\bash.exe"),
];
let local_appdata = env
.get("LOCALAPPDATA")
.cloned()
.or_else(|| std::env::var("LOCALAPPDATA").ok());
if let Some(local) = local_appdata.filter(|s| !s.is_empty()) {
candidates.push(PathBuf::from(local).join(r"Programs\Git\bin\bash.exe"));
}
candidates.push(PathBuf::from(r"C:\msys64\usr\bin\bash.exe"));
candidates.push(PathBuf::from(r"C:\msys32\usr\bin\bash.exe"));
candidates
}
#[cfg(windows)]
pub fn is_wsl_launcher_bash(path: &Path) -> bool {
let Some(s) = path.to_str() else {
return false;
};
let lower = s.to_ascii_lowercase().replace('/', "\\");
lower.ends_with(r"\windows\system32\bash.exe")
|| lower.contains(r"\microsoft\windowsapps\bash.exe")
}
#[cfg(test)]
mod tests;