1use crate::paths;
5use std::collections::BTreeMap;
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum InstallOrigin {
11 Aube,
12 Mise,
13}
14
15impl InstallOrigin {
16 pub fn label(self) -> &'static str {
17 match self {
18 InstallOrigin::Aube => aube_util::embedder().name,
19 InstallOrigin::Mise => "mise",
20 }
21 }
22}
23
24#[derive(Debug, Clone)]
26pub struct InstalledNode {
27 pub version: node_semver::Version,
28 pub install_dir: PathBuf,
29 pub bin_dir: PathBuf,
32 pub node_bin: PathBuf,
33 pub origin: InstallOrigin,
34}
35
36pub fn list_installed() -> Vec<InstalledNode> {
40 let mut by_version: BTreeMap<node_semver::Version, InstalledNode> = BTreeMap::new();
41 if let Some(dir) = mise_node_installs_dir() {
43 for node in scan_install_dir(&dir, InstallOrigin::Mise) {
44 by_version.insert(node.version.clone(), node);
45 }
46 }
47 if let Some(dir) = paths::runtime_dir() {
48 for node in scan_install_dir(&dir, InstallOrigin::Aube) {
49 by_version.insert(node.version.clone(), node);
50 }
51 }
52 by_version.into_values().collect()
53}
54
55pub fn mise_node_installs_dir() -> Option<PathBuf> {
57 mise_tool_installs_dir("node")
58}
59
60pub fn mise_tool_installs_dir(tool: &str) -> Option<PathBuf> {
64 let installs = if let Some(dir) = std::env::var_os("MISE_INSTALLS_DIR") {
65 PathBuf::from(dir)
66 } else if let Some(dir) = std::env::var_os("MISE_DATA_DIR") {
67 PathBuf::from(dir).join("installs")
68 } else {
69 let data_home = aube_util::env::xdg_data_home()
70 .or_else(|| aube_util::env::home_dir().map(|h| h.join(".local/share")))?;
71 data_home.join("mise/installs")
72 };
73 Some(installs.join(tool))
74}
75
76fn scan_install_dir(root: &Path, origin: InstallOrigin) -> Vec<InstalledNode> {
82 let Ok(entries) = std::fs::read_dir(root) else {
83 return Vec::new();
84 };
85 let mut out = Vec::new();
86 for entry in entries.flatten() {
87 let path = entry.path();
88 let Ok(file_type) = entry.file_type() else {
89 continue;
90 };
91 if !file_type.is_dir() {
92 continue;
95 }
96 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
97 continue;
98 };
99 let Ok(version) = node_semver::Version::parse(name.trim_start_matches('v')) else {
100 continue;
101 };
102 if let Some(node) = validate_install(&path, version, origin) {
103 out.push(node);
104 }
105 }
106 out
107}
108
109pub(crate) fn validate_install(
113 dir: &Path,
114 version: node_semver::Version,
115 origin: InstallOrigin,
116) -> Option<InstalledNode> {
117 if dir.join("incomplete").exists() {
118 return None;
119 }
120 let (bin_dir, node_bin) = node_paths_in(dir);
121 if !is_executable_file(&node_bin) {
122 return None;
123 }
124 Some(InstalledNode {
125 version,
126 install_dir: dir.to_path_buf(),
127 bin_dir,
128 node_bin,
129 origin,
130 })
131}
132
133pub(crate) fn is_executable_file(path: &Path) -> bool {
138 let Ok(meta) = std::fs::metadata(path) else {
139 return false;
140 };
141 #[cfg(unix)]
142 {
143 use std::os::unix::fs::PermissionsExt;
144 meta.is_file() && meta.permissions().mode() & 0o111 != 0
145 }
146 #[cfg(not(unix))]
147 meta.is_file()
148}
149
150pub(crate) const fn node_exe_name() -> &'static str {
154 if cfg!(windows) { "node.exe" } else { "node" }
155}
156
157pub(crate) fn node_paths_in(dir: &Path) -> (PathBuf, PathBuf) {
160 let exe_name = node_exe_name();
161 if cfg!(windows) {
166 let root_exe = dir.join(exe_name);
167 if root_exe.is_file() {
168 return (dir.to_path_buf(), root_exe);
169 }
170 }
171 let bin = dir.join("bin");
172 let exe = bin.join(exe_name);
173 (bin, exe)
174}
175
176pub fn probe_path_node() -> Option<(node_semver::Version, PathBuf)> {
180 static PROBED: std::sync::OnceLock<Option<(node_semver::Version, PathBuf)>> =
181 std::sync::OnceLock::new();
182 PROBED.get_or_init(probe_path_node_uncached).clone()
183}
184
185fn probe_path_node_uncached() -> Option<(node_semver::Version, PathBuf)> {
186 let exe = find_on_path(node_exe_name())?;
187 let output = std::process::Command::new(&exe)
188 .arg("--version")
189 .output()
190 .ok()?;
191 if !output.status.success() {
192 return None;
193 }
194 let raw = String::from_utf8(output.stdout).ok()?;
195 let version = node_semver::Version::parse(raw.trim().trim_start_matches('v')).ok()?;
196 Some((version, exe))
197}
198
199pub fn node_on_path() -> Option<PathBuf> {
206 let node = find_on_path(node_exe_name())?;
207 let node = if node.is_absolute() {
213 node
214 } else {
215 std::env::current_dir().ok()?.join(node)
216 };
217 is_executable_file(&node).then_some(node)
218}
219
220pub(crate) fn find_on_path(bin_name: &str) -> Option<PathBuf> {
223 let path = std::env::var_os("PATH")?;
224 for dir in std::env::split_paths(&path) {
225 if dir.as_os_str().is_empty() {
226 continue;
227 }
228 let candidate = dir.join(bin_name);
229 if candidate.is_file() {
230 return Some(candidate);
231 }
232 #[cfg(windows)]
233 {
234 let with_exe = dir.join(format!("{bin_name}.exe"));
238 if with_exe.is_file() {
239 return Some(with_exe);
240 }
241 }
242 }
243 None
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 fn fab_install(root: &Path, version: &str) {
251 let dir = root.join(version);
252 let bin = if cfg!(windows) {
253 dir.clone()
254 } else {
255 dir.join("bin")
256 };
257 std::fs::create_dir_all(&bin).unwrap();
258 let exe = bin.join(node_exe_name());
259 std::fs::write(&exe, "#!/bin/sh\necho v0.0.0\n").unwrap();
260 #[cfg(unix)]
261 {
262 use std::os::unix::fs::PermissionsExt;
263 std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
264 }
265 }
266
267 #[cfg(unix)]
268 #[test]
269 fn non_executable_node_is_rejected() {
270 let tmp = tempfile::tempdir().unwrap();
271 fab_install(tmp.path(), "22.1.0");
272 use std::os::unix::fs::PermissionsExt;
273 let exe = tmp.path().join("22.1.0/bin/node");
274 std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o644)).unwrap();
275 assert!(scan_install_dir(tmp.path(), InstallOrigin::Aube).is_empty());
276 }
277
278 #[test]
279 fn scans_and_validates() {
280 let tmp = tempfile::tempdir().unwrap();
281 fab_install(tmp.path(), "22.1.0");
282 fab_install(tmp.path(), "24.4.1");
283 fab_install(tmp.path(), "26.0.0");
285 std::fs::write(tmp.path().join("26.0.0/incomplete"), "").unwrap();
286 std::fs::create_dir_all(tmp.path().join("20.0.0")).unwrap();
288 std::fs::create_dir_all(tmp.path().join(".downloads")).unwrap();
290
291 let found = scan_install_dir(tmp.path(), InstallOrigin::Aube);
292 let mut versions: Vec<String> = found.iter().map(|n| n.version.to_string()).collect();
293 versions.sort();
294 assert_eq!(versions, vec!["22.1.0", "24.4.1"]);
295 }
296
297 #[cfg(unix)]
298 #[test]
299 fn alias_symlinks_are_skipped() {
300 let tmp = tempfile::tempdir().unwrap();
301 fab_install(tmp.path(), "22.1.0");
302 std::os::unix::fs::symlink(tmp.path().join("22.1.0"), tmp.path().join("22")).unwrap();
303 std::os::unix::fs::symlink(tmp.path().join("22.1.0"), tmp.path().join("latest")).unwrap();
304 let found = scan_install_dir(tmp.path(), InstallOrigin::Aube);
305 assert_eq!(found.len(), 1, "{found:?}");
306 }
307}