1use std::collections::BTreeSet;
4use std::ffi::OsStr;
5use std::path::{Path, PathBuf};
6use std::sync::Mutex;
7
8use super::cache;
9use super::resolve::search_folders;
10use crate::log::{Level, Logger};
11
12#[cfg(unix)]
14const UNIX_EXECUTE_BITS: u32 = 0o111;
15
16const WINDOWS_EXECUTABLE_EXTENSIONS: [&str; 4] = ["exe", "cmd", "bat", "com"];
18
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
21pub enum ToolError {
22 #[error("exec: {0:?}: not an executable file")]
24 NotExecutable(String),
25 #[error("exec: {0:?}: executable file not found in $PATH")]
27 NotFound(String),
28}
29
30pub fn find_tool(name: &str) -> Result<PathBuf, ToolError> {
42 separated(name).map_or_else(|| find_named(name), |path| given(path, name))
43}
44
45pub fn find_tool_readonly(name: &str) -> Result<PathBuf, ToolError> {
48 separated(name).map_or_else(|| find_named_readonly(name), |path| given(path, name))
49}
50
51fn separated(name: &str) -> Option<PathBuf> {
53 (name.contains('/') || name.contains(std::path::MAIN_SEPARATOR)).then(|| PathBuf::from(name))
54}
55
56fn find_named(name: &str) -> Result<PathBuf, ToolError> {
58 let path = std::env::var_os("PATH").unwrap_or_default();
59 let folders = search_folders().unwrap_or_default();
60 locate(name, &path, folders, cfg!(windows))
61 .map(|found| record(name, found))
62 .ok_or_else(|| ToolError::NotFound(name.to_string()))
63}
64
65fn find_named_readonly(name: &str) -> Result<PathBuf, ToolError> {
66 let path = std::env::var_os("PATH").unwrap_or_default();
67 let folders = search_folders().unwrap_or_default();
68 locate_with(
69 name,
70 &path,
71 folders,
72 cfg!(windows),
73 cache::cached_tool_readonly,
74 )
75 .map(Located::into_path)
76 .ok_or_else(|| ToolError::NotFound(name.to_string()))
77}
78
79#[derive(Debug, PartialEq, Eq)]
81pub(super) enum Located {
82 Path(PathBuf),
83 Cached(PathBuf),
84 Fallback(PathBuf),
85}
86
87impl Located {
88 fn into_path(self) -> PathBuf {
89 match self {
90 Self::Path(path) | Self::Cached(path) | Self::Fallback(path) => path,
91 }
92 }
93}
94
95pub(super) fn locate(
97 name: &str,
98 path: &OsStr,
99 fallback: &[PathBuf],
100 windows: bool,
101) -> Option<Located> {
102 locate_with(name, path, fallback, windows, cache::cached_tool)
103}
104
105fn locate_with(
106 name: &str,
107 path: &OsStr,
108 fallback: &[PathBuf],
109 windows: bool,
110 cached: impl FnOnce(&str) -> Option<PathBuf>,
111) -> Option<Located> {
112 search(name, path)
113 .map(Located::Path)
114 .or_else(|| cached(name).map(Located::Cached))
115 .or_else(|| in_fallback(name, fallback, windows).map(Located::Fallback))
116}
117
118pub(super) fn in_fallback(name: &str, fallback: &[PathBuf], windows: bool) -> Option<PathBuf> {
120 fallback
121 .iter()
122 .filter(|directory| directory.is_dir())
123 .flat_map(|directory| candidates(directory, name, windows))
124 .find(|candidate| is_executable(candidate))
125}
126
127pub(super) fn absolute_from(path: PathBuf, directory: &Path) -> PathBuf {
130 if path.is_absolute() {
131 path
132 } else {
133 directory.join(path)
134 }
135}
136
137fn remember(name: &str, found: &Path) {
139 let directory = std::env::current_dir().unwrap_or_default();
140 cache::remember_tool(name, &absolute_from(found.to_path_buf(), &directory));
141}
142
143static LOGGED_FALLBACK: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
144
145fn record(name: &str, found: Located) -> PathBuf {
148 match found {
149 Located::Path(path) => {
150 remember(name, &path);
151 path
152 }
153 Located::Cached(path) => path,
154 Located::Fallback(path) => {
155 remember(name, &path);
156 log_first_fallback(name, &path);
157 path
158 }
159 }
160}
161
162fn log_first_fallback(name: &str, path: &Path) {
164 let first = LOGGED_FALLBACK
165 .lock()
166 .is_ok_and(|mut logged| logged.insert(name.to_string()));
167 if first {
168 let text = path.display().to_string();
169 Logger::new("path").record(
170 Level::Info,
171 "install folder tool path used",
172 &[("tool", name), ("path", &text)],
173 );
174 }
175}
176
177fn given(path: PathBuf, name: &str) -> Result<PathBuf, ToolError> {
178 Some(path)
179 .filter(|path| is_executable(path))
180 .ok_or_else(|| ToolError::NotExecutable(name.to_string()))
181}
182
183pub(super) fn search(name: &str, path: &OsStr) -> Option<PathBuf> {
185 std::env::split_paths(path)
186 .flat_map(|directory| candidates(&directory, name, cfg!(windows)))
187 .find(|candidate| is_executable(candidate))
188}
189
190pub(super) fn candidates(directory: &Path, name: &str, windows: bool) -> Vec<PathBuf> {
195 let base = directory.join(name);
196 if !windows || has_executable_extension(&base) {
197 return vec![base];
198 }
199 WINDOWS_EXECUTABLE_EXTENSIONS
200 .iter()
201 .map(|extension| directory.join(format!("{name}.{extension}")))
202 .collect()
203}
204
205pub(super) fn is_executable(path: &Path) -> bool {
208 let Ok(metadata) = std::fs::metadata(path) else {
209 return false;
210 };
211 if !metadata.is_file() {
212 return false;
213 }
214 #[cfg(unix)]
215 {
216 use std::os::unix::fs::PermissionsExt;
217 metadata.permissions().mode() & UNIX_EXECUTE_BITS != 0
218 }
219 #[cfg(not(unix))]
220 {
221 true
222 }
223}
224
225pub(super) fn has_executable_extension(path: &Path) -> bool {
227 path.extension()
228 .and_then(OsStr::to_str)
229 .is_some_and(|extension| {
230 WINDOWS_EXECUTABLE_EXTENSIONS
231 .iter()
232 .any(|known| extension.eq_ignore_ascii_case(known))
233 })
234}
235
236pub(super) fn usable_cached(path: &Path) -> bool {
239 is_executable(path) && (!cfg!(windows) || has_executable_extension(path))
240}
241
242#[cfg(test)]
243mod tests {
244 use std::path::Path;
245 #[cfg(unix)]
246 use std::path::PathBuf;
247
248 use super::super::resolve::search_folders;
249 #[cfg(unix)]
250 use super::{Located, absolute_from, search, usable_cached};
251 use super::{
252 ToolError, candidates, find_tool, find_tool_readonly, has_executable_extension, locate,
253 };
254
255 #[cfg(unix)]
256 #[test]
257 fn only_an_existing_executable_saved_path_is_usable() {
258 use std::os::unix::fs::PermissionsExt as _;
259
260 let directory = tempfile::tempdir().unwrap();
261 let runnable = directory.path().join("az");
262 crate::executable_tests::write_executable(&runnable, "#!/bin/sh\n");
263 let plain = directory.path().join("plain");
264 std::fs::write(&plain, "text").unwrap();
265 std::fs::set_permissions(&plain, std::fs::Permissions::from_mode(0o600)).unwrap();
266 assert!(usable_cached(&runnable));
267 assert!(!usable_cached(&plain));
268 assert!(!usable_cached(&directory.path().join("missing")));
269 assert!(!usable_cached(directory.path()));
270 }
271
272 #[cfg(unix)]
273 #[test]
274 fn search_returns_the_first_executable_on_path() {
275 let first = tempfile::tempdir().unwrap();
276 let second = tempfile::tempdir().unwrap();
277 std::fs::write(first.path().join("tool"), "not executable").unwrap();
278 crate::executable_tests::write_executable(&second.path().join("tool"), "#!/bin/sh\n");
279 let path = std::env::join_paths([first.path(), second.path()]).unwrap();
280 assert_eq!(search("tool", &path), Some(second.path().join("tool")));
281 assert_eq!(search("absent", &path), None);
282 }
283
284 #[cfg(unix)]
285 #[test]
286 fn a_tool_missing_from_a_terminal_path_is_found_in_an_install_folder() {
287 use std::os::unix::fs::PermissionsExt as _;
288
289 let terminal_path = tempfile::tempdir().unwrap();
290 let install = tempfile::tempdir().unwrap();
291 let folder = install.path().to_path_buf();
292 let path = terminal_path.path().as_os_str();
293 assert_eq!(
294 locate("pi", path, std::slice::from_ref(&folder), false),
295 None
296 );
297 let pi = install.path().join("pi");
298 std::fs::write(&pi, "not executable").unwrap();
299 std::fs::set_permissions(&pi, std::fs::Permissions::from_mode(0o600)).unwrap();
300 assert_eq!(
301 locate("pi", path, std::slice::from_ref(&folder), false),
302 None
303 );
304 std::fs::remove_file(&pi).unwrap();
305 crate::executable_tests::write_executable(&pi, "#!/bin/sh\n");
306 let folders = [PathBuf::from("/fixture/missing/bin"), folder.clone()];
307 assert_eq!(
308 locate("pi", path, &folders, false),
309 Some(Located::Fallback(pi.clone()))
310 );
311 crate::executable_tests::write_executable(&terminal_path.path().join("pi"), "#!/bin/sh\n");
312 assert_eq!(
313 locate("pi", path, &[folder], false),
314 Some(Located::Path(terminal_path.path().join("pi")))
315 );
316 }
317
318 #[test]
319 fn without_the_startup_resolution_no_install_folder_is_searched() {
320 assert_eq!(search_folders(), None);
323 assert_eq!(
324 locate(
325 "subspace-fixture-absent-tool",
326 std::ffi::OsStr::new(""),
327 search_folders().unwrap_or_default(),
328 false
329 ),
330 None
331 );
332 assert_eq!(
333 find_tool("subspace-fixture-absent-tool"),
334 Err(ToolError::NotFound("subspace-fixture-absent-tool".into()))
335 );
336 assert_eq!(
337 find_tool_readonly("subspace-fixture-absent-tool"),
338 Err(ToolError::NotFound("subspace-fixture-absent-tool".into()))
339 );
340 }
341
342 #[cfg(unix)]
343 #[test]
344 fn readonly_resolution_obeys_path_cache_fallback_order() {
345 let path_dir = tempfile::tempdir().unwrap();
346 let fallback = tempfile::tempdir().unwrap();
347 let cached = tempfile::tempdir().unwrap();
348 let name = "readonly-order-fixture";
349 let cached_tool = cached.path().join(name);
350 let fallback_tool = fallback.path().join(name);
351 crate::executable_tests::write_executable(&cached_tool, "#!/bin/sh\n");
352 crate::executable_tests::write_executable(&fallback_tool, "#!/bin/sh\n");
353 let folders = [fallback.path().to_path_buf()];
354 let lookup = || {
355 super::locate_with(name, path_dir.path().as_os_str(), &folders, false, |_| {
356 Some(cached_tool.clone())
357 })
358 .map(Located::into_path)
359 };
360 assert_eq!(lookup(), Some(cached_tool.clone()));
361 let path_tool = path_dir.path().join(name);
362 crate::executable_tests::write_executable(&path_tool, "#!/bin/sh\n");
363 assert_eq!(lookup(), Some(path_tool));
364 std::fs::remove_file(path_dir.path().join(name)).unwrap();
365 assert_eq!(
366 super::locate_with(name, path_dir.path().as_os_str(), &folders, false, |_| None)
367 .map(Located::into_path),
368 Some(fallback_tool)
369 );
370 }
371
372 #[cfg(unix)]
373 #[test]
374 fn tool_paths_are_saved_absolute_without_resolving_links() {
375 let directory = Path::new("/fixture/work");
376 assert_eq!(
377 absolute_from(PathBuf::from("bin/az"), directory),
378 PathBuf::from("/fixture/work/bin/az")
379 );
380 assert_eq!(
381 absolute_from(PathBuf::from("../tools/az"), directory),
382 PathBuf::from("/fixture/work/../tools/az")
383 );
384 assert_eq!(
385 absolute_from(PathBuf::from("/opt/homebrew/bin/az"), directory),
386 PathBuf::from("/opt/homebrew/bin/az")
387 );
388 }
389
390 #[test]
391 fn windows_names_get_an_executable_extension_unless_they_have_one() {
392 let directory = Path::new("/fixture/bin");
393 assert_eq!(
394 candidates(directory, "az", true),
395 ["az.exe", "az.cmd", "az.bat", "az.com"].map(|name| directory.join(name))
396 );
397 assert_eq!(
398 candidates(directory, "Headlamp.exe", true),
399 [directory.join("Headlamp.exe")]
400 );
401 assert_eq!(candidates(directory, "az", false), [directory.join("az")]);
402 }
403
404 #[test]
405 fn windows_extensions_are_case_insensitive() {
406 assert!(has_executable_extension(Path::new(r"C:\Tools\az.CMD")));
407 assert!(has_executable_extension(Path::new("az.exe")));
408 assert!(!has_executable_extension(Path::new("az")));
409 assert!(!has_executable_extension(Path::new("az.ps1")));
410 }
411
412 #[test]
413 fn errors_keep_the_go_texts() {
414 assert_eq!(
415 ToolError::NotFound("az".into()).to_string(),
416 "exec: \"az\": executable file not found in $PATH"
417 );
418 assert_eq!(
419 ToolError::NotExecutable("/x/az".into()).to_string(),
420 "exec: \"/x/az\": not an executable file"
421 );
422 }
423}