Skip to main content

aft_base/
tool_path.rs

1//! Cross-platform tool binary resolution on PATH and well-known install dirs.
2//!
3//! PATH walking follows the same contract as cortexkit/magic-context
4//! `packages/cli/src/lib/find-on-path.ts` (PR #75): probe filesystem entries
5//! without shelling out to `which`/`where`, and on Windows try
6//! `.exe` → `.cmd` → `.bat` → `.com` per PATH directory.
7
8use std::path::{Path, PathBuf};
9
10/// Resolve `binary` on the process `PATH` (PATHEXT-aware on Windows via `which`).
11/// An Apple developer-tools launcher on a Mac without the tools counts as not
12/// found, because running it opens the install dialog.
13pub fn resolve_on_path(binary: &str) -> Option<PathBuf> {
14    which::which(binary)
15        .ok()
16        .or_else(|| find_on_path_manual(binary))
17        .filter(|path| !crate::developer_tools::is_unusable_launcher(path))
18}
19
20/// Walk `PATH` left-to-right without spawning a subprocess.
21pub(crate) fn find_on_path_manual(binary: &str) -> Option<PathBuf> {
22    let path_var = std::env::var_os("PATH")?;
23    for dir in std::env::split_paths(&path_var) {
24        if dir.as_os_str().is_empty() {
25            continue;
26        }
27        if let Some(found) = probe_tool_in_dir(&dir, binary) {
28            return Some(found);
29        }
30    }
31    None
32}
33
34fn path_looks_like_tool(path: &Path) -> bool {
35    let Ok(metadata) = std::fs::metadata(path) else {
36        return false;
37    };
38    if !metadata.is_file() {
39        return false;
40    }
41    #[cfg(unix)]
42    {
43        use std::os::unix::fs::PermissionsExt;
44        metadata.permissions().mode() & 0o111 != 0
45    }
46    #[cfg(not(unix))]
47    {
48        let _ = metadata;
49        true
50    }
51}
52
53/// On Windows, prefer `dir/<binary>.exe|.cmd|.bat|.com` over an
54/// extensionless file, which may be a colocated POSIX package-manager shim.
55pub fn probe_tool_in_dir(dir: &Path, binary: &str) -> Option<PathBuf> {
56    probe_tool_in_dir_for_platform(dir, binary, cfg!(windows))
57}
58
59fn probe_tool_in_dir_for_platform(dir: &Path, binary: &str, windows: bool) -> Option<PathBuf> {
60    if !dir.is_dir() {
61        return None;
62    }
63
64    if windows {
65        for ext in ["exe", "cmd", "bat", "com"] {
66            let candidate = dir.join(format!("{binary}.{ext}"));
67            if path_looks_like_tool(&candidate) {
68                return Some(candidate);
69            }
70        }
71    }
72
73    let direct = dir.join(binary);
74    path_looks_like_tool(&direct).then_some(direct)
75}
76
77/// Extra bin directories GUI-launched hosts often omit from `PATH`.
78#[cfg(windows)]
79pub fn well_known_windows_bin_dirs(userprofile: Option<&std::ffi::OsStr>) -> Vec<PathBuf> {
80    let mut dirs: Vec<PathBuf> = Vec::with_capacity(10);
81    dirs.push(PathBuf::from(r"C:\Go\bin"));
82    dirs.push(PathBuf::from(r"C:\Program Files\Go\bin"));
83    dirs.push(PathBuf::from(r"C:\Program Files\nodejs"));
84    if let Some(appdata) = crate::environment::non_empty_os_var("APPDATA") {
85        dirs.push(PathBuf::from(appdata).join("npm"));
86    }
87    if let Some(local) = crate::environment::non_empty_os_var("LOCALAPPDATA") {
88        let local_path = PathBuf::from(local);
89        dirs.push(local_path.join("pnpm"));
90        dirs.push(local_path.join("Programs").join("Python"));
91    }
92    if let Some(up) = userprofile {
93        let up_path = PathBuf::from(up);
94        dirs.push(up_path.join(r".cargo\bin"));
95        dirs.push(up_path.join(r"go\bin"));
96        dirs.push(up_path.join("scoop").join("shims"));
97    }
98    dirs
99}
100
101#[cfg(not(windows))]
102pub fn well_known_windows_bin_dirs(_userprofile: Option<&std::ffi::OsStr>) -> Vec<PathBuf> {
103    Vec::new()
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use std::fs;
110
111    #[test]
112    fn windows_tool_probe_prefers_runnable_wrapper_to_posix_shim() {
113        let dir = tempfile::tempdir().unwrap();
114        let shim = dir.path().join("prettier");
115        let cmd = dir.path().join("prettier.cmd");
116        for path in [&shim, &cmd] {
117            fs::write(path, "fixture").unwrap();
118            #[cfg(unix)]
119            {
120                use std::os::unix::fs::PermissionsExt;
121                fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
122            }
123        }
124        assert_eq!(
125            probe_tool_in_dir_for_platform(dir.path(), "prettier", true),
126            Some(cmd)
127        );
128        assert_eq!(
129            probe_tool_in_dir_for_platform(dir.path(), "prettier", false),
130            Some(shim)
131        );
132    }
133
134    #[test]
135    fn find_on_path_manual_returns_null_when_path_unset() {
136        let _guard = crate::test_env::process_env_lock();
137        let saved = std::env::var_os("PATH");
138        std::env::remove_var("PATH");
139        assert!(find_on_path_manual("aft-nonexistent-tool-xyzzy").is_none());
140        if let Some(path) = saved {
141            std::env::set_var("PATH", path);
142        }
143    }
144
145    #[cfg(unix)]
146    #[test]
147    fn find_on_path_manual_finds_executable_in_single_dir() {
148        let _guard = crate::test_env::process_env_lock();
149        let dir = tempfile::tempdir().unwrap();
150        let bin_path = dir.path().join("opencode-test-bin");
151        fs::write(&bin_path, "#!/bin/sh\necho ok\n").unwrap();
152        let mut perms = fs::metadata(&bin_path).unwrap().permissions();
153        use std::os::unix::fs::PermissionsExt;
154        perms.set_mode(0o755);
155        fs::set_permissions(&bin_path, perms).unwrap();
156
157        let saved = std::env::var_os("PATH");
158        std::env::set_var("PATH", dir.path());
159        let found = find_on_path_manual("opencode-test-bin");
160        if let Some(path) = saved {
161            std::env::set_var("PATH", path);
162        } else {
163            std::env::remove_var("PATH");
164        }
165
166        assert_eq!(found.as_deref(), Some(bin_path.as_path()));
167    }
168
169    #[cfg(unix)]
170    #[test]
171    fn find_on_path_manual_skips_non_executable_file() {
172        let _guard = crate::test_env::process_env_lock();
173        let dir = tempfile::tempdir().unwrap();
174        let bin_path = dir.path().join("opencode-test-bin");
175        fs::write(&bin_path, "not executable\n").unwrap();
176
177        let saved = std::env::var_os("PATH");
178        std::env::set_var("PATH", dir.path());
179        let found = find_on_path_manual("opencode-test-bin");
180        if let Some(path) = saved {
181            std::env::set_var("PATH", path);
182        } else {
183            std::env::remove_var("PATH");
184        }
185
186        assert!(found.is_none());
187    }
188
189    #[cfg(windows)]
190    #[test]
191    fn probe_tool_in_dir_finds_cmd_shim() {
192        let dir = tempfile::tempdir().unwrap();
193        let cmd_path = dir.path().join("biome.cmd");
194        fs::write(&cmd_path, "@echo off\n").unwrap();
195        assert_eq!(
196            probe_tool_in_dir(dir.path(), "biome").as_deref(),
197            Some(cmd_path.as_path())
198        );
199    }
200}