artifactize_foundation/platform/
program.rs1use std::{
4 env,
5 ffi::{OsStr, OsString},
6 io,
7 path::{Path, PathBuf},
8};
9
10const SEARCH_PATH: &str = "PATH";
12const EXTENSIONS: &str = "PATHEXT";
14
15pub fn resolve_with(
19 program: &Path,
20 cwd: &Path,
21 variable: impl Fn(&str) -> Option<OsString>,
22) -> io::Result<PathBuf> {
23 resolve_from(
24 program,
25 cwd,
26 lookup_variable(&variable, SEARCH_PATH).as_deref(),
27 extensions(&variable).as_deref(),
28 )
29}
30
31#[cfg(unix)]
32fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
33 variable(name)
34}
35
36#[cfg(windows)]
37fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
38 let mut spelling = name.as_bytes().to_owned();
42 (0..(1 << name.len())).rev().find_map(|variant| {
43 for (bit, byte) in spelling.iter_mut().rev().enumerate() {
44 *byte = if variant & (1 << bit) == 0 {
45 byte.to_ascii_uppercase()
46 } else {
47 byte.to_ascii_lowercase()
48 };
49 }
50 variable(std::str::from_utf8(&spelling).expect("ASCII environment key"))
51 })
52}
53
54fn extensions(variable: &impl Fn(&str) -> Option<OsString>) -> Option<OsString> {
55 USES_PATHEXT
56 .then(|| lookup_variable(variable, EXTENSIONS))
57 .flatten()
58}
59
60fn resolve_from(
61 program: &Path,
62 cwd: &Path,
63 path: Option<&OsStr>,
64 pathext: Option<&OsStr>,
65) -> io::Result<PathBuf> {
66 lookup_paths(program, cwd, path, pathext)
67 .into_iter()
68 .find(|candidate| is_executable(candidate))
69 .ok_or_else(|| {
70 io::Error::new(
71 io::ErrorKind::NotFound,
72 format!(
73 "Program is unavailable: {}",
74 super::files::path_text(program)
75 ),
76 )
77 })
78}
79
80fn lookup_paths(
81 program: &Path,
82 cwd: &Path,
83 path: Option<&OsStr>,
84 pathext: Option<&OsStr>,
85) -> Vec<PathBuf> {
86 let candidates = candidates_from(program, pathext);
87 if program.has_root()
88 || program.components().count() > 1
89 || matches!(
90 program.components().next(),
91 Some(std::path::Component::Prefix(_))
92 )
93 {
94 return candidates
95 .into_iter()
96 .filter_map(|candidate| anchor(cwd, &candidate))
97 .collect();
98 }
99 path.into_iter()
100 .flat_map(env::split_paths)
101 .filter_map(|directory| anchor(cwd, &directory))
102 .flat_map(|directory| {
103 candidates
104 .iter()
105 .map(move |candidate| directory.join(candidate))
106 })
107 .collect()
108}
109
110#[cfg(unix)]
111fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
112 Some(cwd.join(path))
113}
114
115#[cfg(windows)]
116fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
117 use std::path::{Component, Prefix};
118
119 let mut components = path.components();
120 if let Some(Component::Prefix(prefix)) = components.next()
121 && !path.is_absolute()
122 {
123 let drive = |prefix| match prefix {
126 Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Some(drive.to_ascii_uppercase()),
127 _ => None,
128 };
129 let Some(Component::Prefix(base)) = cwd.components().next() else {
130 return None;
131 };
132 return (cwd.is_absolute()
133 && drive(prefix.kind()).is_some()
134 && drive(prefix.kind()) == drive(base.kind()))
135 .then(|| cwd.join(components.as_path()));
136 }
137 Some(cwd.join(path))
138}
139
140pub fn candidates(program: &Path, variable: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
143 candidates_from(program, extensions(&variable).as_deref())
144}
145
146fn candidates_from(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
147 if USES_PATHEXT && program.extension().is_none() {
148 pathext_candidates(program, pathext)
149 } else {
150 vec![program.to_owned()]
151 }
152}
153
154const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
156
157fn pathext_candidates(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
159 let pathext = pathext.unwrap_or_else(|| OsStr::new(DEFAULT_PATHEXT));
160 split_list(pathext)
163 .into_iter()
164 .filter(|extension| {
165 let bytes = extension.as_encoded_bytes();
166 bytes.first() == Some(&b'.') && !bytes.iter().any(|byte| matches!(byte, b'/' | b'\\'))
167 })
168 .map(|extension| {
169 let mut candidate = program.as_os_str().to_owned();
170 candidate.push(extension);
171 PathBuf::from(candidate)
172 })
173 .collect()
174}
175
176#[cfg(windows)]
178fn split_list(list: &OsStr) -> Vec<OsString> {
179 use std::os::windows::ffi::{OsStrExt, OsStringExt};
180 let units: Vec<u16> = list.encode_wide().collect();
181 units
182 .split(|unit| *unit == u16::from(b';'))
183 .map(OsString::from_wide)
184 .collect()
185}
186
187#[cfg(unix)]
189fn split_list(list: &OsStr) -> Vec<OsString> {
190 use std::os::unix::ffi::{OsStrExt, OsStringExt};
191 list.as_bytes()
192 .split(|byte| *byte == b';')
193 .map(|entry| OsString::from_vec(entry.to_vec()))
194 .collect()
195}
196
197#[cfg(unix)]
198const USES_PATHEXT: bool = false;
200
201#[cfg(unix)]
202fn is_executable(path: &Path) -> bool {
203 use rustix::fs::{Access, AtFlags, CWD, accessat};
204
205 path.is_file() && accessat(CWD, path, Access::EXEC_OK, AtFlags::EACCESS).is_ok()
206}
207
208#[cfg(windows)]
209const USES_PATHEXT: bool = true;
211
212#[cfg(windows)]
214fn is_executable(path: &Path) -> bool {
215 path.is_file()
216}
217
218#[cfg(test)]
219mod tests;