use std::{
env,
ffi::{OsStr, OsString},
io,
path::{Path, PathBuf},
};
const SEARCH_PATH: &str = "PATH";
const EXTENSIONS: &str = "PATHEXT";
pub fn resolve_with(
program: &Path,
cwd: &Path,
variable: impl Fn(&str) -> Option<OsString>,
) -> io::Result<PathBuf> {
resolve_from(
program,
cwd,
lookup_variable(&variable, SEARCH_PATH).as_deref(),
extensions(&variable).as_deref(),
)
}
#[cfg(unix)]
fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
variable(name)
}
#[cfg(windows)]
fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
let mut spelling = name.as_bytes().to_owned();
(0..(1 << name.len())).rev().find_map(|variant| {
for (bit, byte) in spelling.iter_mut().rev().enumerate() {
*byte = if variant & (1 << bit) == 0 {
byte.to_ascii_uppercase()
} else {
byte.to_ascii_lowercase()
};
}
variable(std::str::from_utf8(&spelling).expect("ASCII environment key"))
})
}
fn extensions(variable: &impl Fn(&str) -> Option<OsString>) -> Option<OsString> {
USES_PATHEXT
.then(|| lookup_variable(variable, EXTENSIONS))
.flatten()
}
fn resolve_from(
program: &Path,
cwd: &Path,
path: Option<&OsStr>,
pathext: Option<&OsStr>,
) -> io::Result<PathBuf> {
lookup_paths(program, cwd, path, pathext)
.into_iter()
.find(|candidate| is_executable(candidate))
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!(
"Program is unavailable: {}",
super::files::path_text(program)
),
)
})
}
fn lookup_paths(
program: &Path,
cwd: &Path,
path: Option<&OsStr>,
pathext: Option<&OsStr>,
) -> Vec<PathBuf> {
let candidates = candidates_from(program, pathext);
if program.has_root()
|| program.components().count() > 1
|| matches!(
program.components().next(),
Some(std::path::Component::Prefix(_))
)
{
return candidates
.into_iter()
.filter_map(|candidate| anchor(cwd, &candidate))
.collect();
}
path.into_iter()
.flat_map(env::split_paths)
.filter_map(|directory| anchor(cwd, &directory))
.flat_map(|directory| {
candidates
.iter()
.map(move |candidate| directory.join(candidate))
})
.collect()
}
#[cfg(unix)]
fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
Some(cwd.join(path))
}
#[cfg(windows)]
fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
use std::path::{Component, Prefix};
let mut components = path.components();
if let Some(Component::Prefix(prefix)) = components.next()
&& !path.is_absolute()
{
let drive = |prefix| match prefix {
Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Some(drive.to_ascii_uppercase()),
_ => None,
};
let Some(Component::Prefix(base)) = cwd.components().next() else {
return None;
};
return (cwd.is_absolute()
&& drive(prefix.kind()).is_some()
&& drive(prefix.kind()) == drive(base.kind()))
.then(|| cwd.join(components.as_path()));
}
Some(cwd.join(path))
}
pub fn candidates(program: &Path, variable: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
candidates_from(program, extensions(&variable).as_deref())
}
fn candidates_from(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
if USES_PATHEXT && program.extension().is_none() {
pathext_candidates(program, pathext)
} else {
vec![program.to_owned()]
}
}
const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
fn pathext_candidates(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
let pathext = pathext.unwrap_or_else(|| OsStr::new(DEFAULT_PATHEXT));
split_list(pathext)
.into_iter()
.filter(|extension| {
let bytes = extension.as_encoded_bytes();
bytes.first() == Some(&b'.') && !bytes.iter().any(|byte| matches!(byte, b'/' | b'\\'))
})
.map(|extension| {
let mut candidate = program.as_os_str().to_owned();
candidate.push(extension);
PathBuf::from(candidate)
})
.collect()
}
#[cfg(windows)]
fn split_list(list: &OsStr) -> Vec<OsString> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
let units: Vec<u16> = list.encode_wide().collect();
units
.split(|unit| *unit == u16::from(b';'))
.map(OsString::from_wide)
.collect()
}
#[cfg(unix)]
fn split_list(list: &OsStr) -> Vec<OsString> {
use std::os::unix::ffi::{OsStrExt, OsStringExt};
list.as_bytes()
.split(|byte| *byte == b';')
.map(|entry| OsString::from_vec(entry.to_vec()))
.collect()
}
#[cfg(unix)]
const USES_PATHEXT: bool = false;
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use rustix::fs::{Access, AtFlags, CWD, accessat};
path.is_file() && accessat(CWD, path, Access::EXEC_OK, AtFlags::EACCESS).is_ok()
}
#[cfg(windows)]
const USES_PATHEXT: bool = true;
#[cfg(windows)]
fn is_executable(path: &Path) -> bool {
path.is_file()
}
#[cfg(test)]
mod tests;