Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

node_runtime: Expose standalone system Node discovery (#64928)

Ben Brandtafecd6d719aa
diff --git a/Cargo.lock b/Cargo.lock
index e54024c2e27..2b85384681b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11464,6 +11464,8 @@ dependencies = [
"serde",
"serde_json",
"smol",
+ "tempfile",
+ "thiserror 2.0.17",
"util",
"watch",
"which",
diff --git a/crates/node_runtime/Cargo.toml b/crates/node_runtime/Cargo.toml
index 9d2cc4f6bf9..494084b9cd6 100644
--- a/crates/node_runtime/Cargo.toml
+++ b/crates/node_runtime/Cargo.toml
@@ -29,10 +29,14 @@ semver.workspace = true
serde.workspace = true
serde_json.workspace = true
smol.workspace = true
+thiserror.workspace = true
util.workspace = true
watch.workspace = true
which.workspace = true
+[dev-dependencies]
+tempfile.workspace = true
+
[target.'cfg(windows)'.dependencies]
async-std.workspace = true
diff --git a/crates/node_runtime/src/node_runtime.rs b/crates/node_runtime/src/node_runtime.rs
index 7579789d7b2..50ffb30dc8c 100644
--- a/crates/node_runtime/src/node_runtime.rs
+++ b/crates/node_runtime/src/node_runtime.rs
@@ -13,7 +13,7 @@ use std::collections::HashMap;
use std::fmt::Display;
use std::{
env::{self, consts},
- ffi::OsString,
+ ffi::{OsStr, OsString},
io,
net::{IpAddr, Ipv4Addr},
path::{Path, PathBuf},
@@ -849,6 +849,173 @@ impl NodeRuntimeTrait for ManagedNodeRuntime {
}
}
+/// A system Node.js executable whose version has been checked.
+///
+/// Discovery does not require npm, initialize a cache, or download a runtime.
+#[derive(Debug, Clone)]
+pub struct SystemNode {
+ path: PathBuf,
+ version: Version,
+}
+
+/// A failure to locate or validate a system Node.js executable.
+#[derive(Debug, thiserror::Error)]
+pub enum NodeDiscoveryError {
+ #[error("Could not read the current directory while looking for Node.js: {0}")]
+ CurrentDirectory(#[source] io::Error),
+ #[error(
+ "Node.js executable {path:?} was not found. Install Node.js {minimum} or newer, or configure its executable path.",
+ minimum = SystemNode::MIN_VERSION,
+ )]
+ NotFound {
+ path: PathBuf,
+ #[source]
+ source: which::Error,
+ },
+ #[error(
+ "Could not run Node.js at {path:?}: {source}. Check that the configured executable can run."
+ )]
+ Probe {
+ path: PathBuf,
+ #[source]
+ source: io::Error,
+ },
+ #[error(
+ "Node.js at {path:?} failed its version check ({status}). Check the Node.js installation.\nstdout: {stdout}\nstderr: {stderr}",
+ status = .output.status,
+ stdout = String::from_utf8_lossy(&.output.stdout),
+ stderr = String::from_utf8_lossy(&.output.stderr),
+ )]
+ UnsuccessfulExit { path: PathBuf, output: Output },
+ #[error(
+ "Node.js at {path:?} reported an invalid version: {output:?}. Configure a Node.js {minimum} or newer executable.",
+ minimum = SystemNode::MIN_VERSION,
+ )]
+ InvalidVersion {
+ path: PathBuf,
+ output: String,
+ #[source]
+ source: semver::Error,
+ },
+ #[error(
+ "Node.js at {path:?} is too old ({version}). Install Node.js {minimum} or newer, or configure a newer executable.",
+ minimum = SystemNode::MIN_VERSION,
+ )]
+ TooOld { path: PathBuf, version: Version },
+}
+
+impl SystemNode {
+ const MIN_VERSION: Version = Version::new(22, 0, 0);
+
+ /// Finds and validates Node.js using an explicit executable or search path.
+ ///
+ /// An explicit executable takes precedence and never falls back to another
+ /// candidate on failure. Otherwise the first executable named `node` in
+ /// `search_path` is checked, preserving PATH order even if it is too old.
+ /// `None` disables PATH lookup; it does not read the process's PATH.
+ ///
+ /// A configured basename is also looked up in `search_path`; use `./name`
+ /// to select one in the current directory. Relative paths containing
+ /// separators are resolved against that directory. On Windows, lookup
+ /// honors PATHEXT, including batch-file wrappers.
+ ///
+ /// The caller must finish loading its login-shell environment before calling
+ /// this method. The version probe inherits that environment, with PATH
+ /// replaced by `search_path` when supplied. Discovery does not launch a login
+ /// shell to obtain the environment.
+ ///
+ /// # Errors
+ ///
+ /// Returns a typed failure if lookup or execution fails, the version cannot
+ /// be parsed, or the executable reports a version older than 22.0.0.
+ pub async fn discover(
+ configured_path: Option<PathBuf>,
+ search_path: Option<OsString>,
+ ) -> std::result::Result<Self, NodeDiscoveryError> {
+ let path = smol::unblock({
+ let search_path = search_path.clone();
+ move || {
+ find_node_path(
+ configured_path.as_deref(),
+ search_path.as_deref(),
+ Path::new("."),
+ )
+ }
+ })
+ .await?;
+ let mut command = util::command::new_command(&path);
+ command.arg("--version").kill_on_drop(true);
+ if let Some(search_path) = search_path {
+ command.env("PATH", search_path);
+ }
+ let output = command
+ .output()
+ .await
+ .map_err(|source| NodeDiscoveryError::Probe {
+ path: path.clone(),
+ source,
+ })?;
+ let version = check_node_version(&path, output)?;
+ Ok(Self { path, version })
+ }
+
+ /// Returns the absolute executable path without resolving symlinks.
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ /// Returns the version reported by the executable.
+ pub fn version(&self) -> &Version {
+ &self.version
+ }
+}
+
+fn find_node_path(
+ configured_path: Option<&Path>,
+ search_path: Option<&OsStr>,
+ directory: &Path,
+) -> std::result::Result<PathBuf, NodeDiscoveryError> {
+ let path = configured_path.unwrap_or_else(|| Path::new("node"));
+ let path = which::which_in(path, search_path, directory).map_err(|source| {
+ NodeDiscoveryError::NotFound {
+ path: path.to_path_buf(),
+ source,
+ }
+ })?;
+ // The cwd may have been deleted even when Node's absolute path still works.
+ // Only relative results need it, but those must be anchored before launch
+ // so the command cannot search PATH a second time.
+ std::path::absolute(directory.join(path)).map_err(NodeDiscoveryError::CurrentDirectory)
+}
+
+fn check_node_version(
+ path: &Path,
+ output: Output,
+) -> std::result::Result<Version, NodeDiscoveryError> {
+ if !output.status.success() {
+ return Err(NodeDiscoveryError::UnsuccessfulExit {
+ path: path.to_path_buf(),
+ output,
+ });
+ }
+ let version_string = String::from_utf8_lossy(&output.stdout);
+ let version =
+ Version::parse(version_string.trim().trim_start_matches('v')).map_err(|source| {
+ NodeDiscoveryError::InvalidVersion {
+ path: path.to_path_buf(),
+ output: version_string.into_owned(),
+ source,
+ }
+ })?;
+ if version < SystemNode::MIN_VERSION {
+ return Err(NodeDiscoveryError::TooOld {
+ path: path.to_path_buf(),
+ version,
+ });
+ }
+ Ok(version)
+}
+
#[derive(Debug, Clone)]
pub struct SystemNodeRuntime {
node: PathBuf,
@@ -857,31 +1024,10 @@ pub struct SystemNodeRuntime {
}
impl SystemNodeRuntime {
- const MIN_VERSION: semver::Version = Version::new(22, 0, 0);
async fn new(node: PathBuf, npm: PathBuf) -> Result<Self> {
- let output = util::command::new_command(&node)
- .arg("--version")
- .output()
- .await
- .with_context(|| format!("running node from {:?}", node))?;
- if !output.status.success() {
- anyhow::bail!(
- "failed to run node --version. stdout: {}, stderr: {}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr),
- );
- }
- let version_str = String::from_utf8_lossy(&output.stdout);
- let version = semver::Version::parse(version_str.trim().trim_start_matches('v'))?;
- if version < Self::MIN_VERSION {
- anyhow::bail!(
- "node at {} is too old. want: {}, got: {}",
- node.to_string_lossy(),
- Self::MIN_VERSION,
- version
- )
- }
-
+ let node = SystemNode::discover(Some(node), env::var_os("PATH"))
+ .await?
+ .path;
let scratch_dir = paths::data_dir().join("node");
fs::create_dir(&scratch_dir).await.ok();
_ = fs::remove_dir_all(scratch_dir.join("cache")).await;
@@ -1190,17 +1336,78 @@ pub fn npm_command_env(node_binary: &Path) -> HashMap<String, String> {
#[cfg(test)]
mod tests {
- use std::path::Path;
+ use std::{
+ env, fs,
+ path::{Path, PathBuf},
+ process::{ExitStatus, Output},
+ };
use anyhow::{Result, bail};
use http_client::Url;
use semver::{Version, VersionReq};
use super::{
- NpmInfo, VersionStrategy, build_npm_command_args, deserialize_npm_info_from_response,
- proxy_argument, select_npm_package_version, should_install_npm_package_version,
+ NodeDiscoveryError, NpmInfo, VersionStrategy, build_npm_command_args, check_node_version,
+ deserialize_npm_info_from_response, find_node_path, proxy_argument,
+ select_npm_package_version, should_install_npm_package_version,
};
+ #[test]
+ fn test_node_lookup_distinguishes_basenames_and_relative_paths() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let binary_directory = directory.path().join("bin");
+ fs::create_dir(&binary_directory)?;
+ let filename = format!("node{}", env::consts::EXE_SUFFIX);
+ let node = binary_directory.join(&filename);
+ fs::write(&node, b"not executed by lookup tests")?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&node, fs::Permissions::from_mode(0o755))?;
+ }
+ for (configured_path, search_path) in [
+ (PathBuf::from(&filename), Some(binary_directory.as_os_str())),
+ (Path::new("bin").join(&filename), None),
+ ] {
+ assert_eq!(
+ find_node_path(Some(&configured_path), search_path, directory.path())?,
+ node
+ );
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn test_node_version_validation() -> Result<()> {
+ let path = Path::new("node");
+ for (stdout, expected) in [
+ ("v22.0.0\n", Version::new(22, 0, 0)),
+ (" \t22.1.0\r\n", Version::new(22, 1, 0)),
+ ] {
+ assert_eq!(check_node_version(path, node_output(stdout))?, expected);
+ }
+ for version in ["21.7.3", "22.0.0-rc.1"] {
+ let error = check_node_version(path, node_output(&format!("v{version}\n")))
+ .expect_err("unsupported version");
+ assert!(
+ matches!(&error, NodeDiscoveryError::TooOld { path: actual_path, version: actual_version }
+ if actual_path == path && actual_version == &Version::parse(version)?)
+ );
+ assert!(
+ error
+ .to_string()
+ .contains("Install Node.js 22.0.0 or newer")
+ );
+ }
+ let stdout = "not node\n";
+ assert!(matches!(
+ check_node_version(path, node_output(stdout)),
+ Err(NodeDiscoveryError::InvalidVersion { path: actual_path, output, .. })
+ if actual_path == path && output == stdout
+ ));
+ Ok(())
+ }
+
// Map localhost to 127.0.0.1
// NodeRuntime without environment information can not parse `localhost` correctly.
#[test]
@@ -1658,4 +1865,16 @@ mod tests {
);
Ok(())
}
+
+ fn node_output(stdout: &str) -> Output {
+ #[cfg(unix)]
+ use std::os::unix::process::ExitStatusExt;
+ #[cfg(windows)]
+ use std::os::windows::process::ExitStatusExt;
+ Output {
+ status: ExitStatus::from_raw(0),
+ stdout: stdout.as_bytes().to_vec(),
+ stderr: Vec::new(),
+ }
+ }
}
diff --git a/crates/node_runtime/tests/system_node.rs b/crates/node_runtime/tests/system_node.rs
new file mode 100644
index 00000000000..000609af29f
--- /dev/null
+++ b/crates/node_runtime/tests/system_node.rs
@@ -0,0 +1,196 @@
+//! Real-process checks for standalone system Node discovery.
+//!
+//! These intentionally non-deterministic tests run fake executables using the
+//! real command implementation, not GPUI's deterministic scheduler or an installed
+//! Node. Pure lookup and version parsing are covered by the crate's unit tests.
+
+#![cfg(unix)]
+
+use anyhow::Result;
+use node_runtime::{NodeDiscoveryError, SystemNode};
+use semver::Version;
+use std::{
+ env, fs,
+ os::unix::fs::{PermissionsExt, symlink},
+ path::{Path, PathBuf},
+};
+
+#[test]
+fn discovers_node_without_npm_and_passes_the_search_path_to_the_probe() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let target = fake_node(
+ &directory.path().join("target"),
+ r#"
+test "$1" = "--version" || exit 1
+test "$PATH/node" = "$0" || exit 2
+printf 'v22.0.0\n'
+"#,
+ )?;
+ let node = directory.path().join("node");
+ symlink(target, &node)?;
+ let discovered = smol::block_on(SystemNode::discover(
+ None,
+ Some(directory.path().as_os_str().to_owned()),
+ ))?;
+ assert_eq!(discovered.path(), node);
+ assert_eq!(discovered.version(), &Version::new(22, 0, 0));
+ Ok(())
+}
+
+#[test]
+fn empty_path_entry_runs_the_node_in_the_working_directory() -> Result<()> {
+ if env::var_os(CHILD).is_some() {
+ let discovered = smol::block_on(SystemNode::discover(None, Some("".into())))?;
+ assert_eq!(discovered.version(), &Version::new(22, 0, 0));
+ assert_eq!(discovered.path(), env::current_dir()?.join("node"));
+ for search_path in [
+ None,
+ Some(env::current_dir()?.join("missing").into_os_string()),
+ ] {
+ assert!(matches!(
+ smol::block_on(SystemNode::discover(None, search_path)),
+ Err(NodeDiscoveryError::NotFound { .. })
+ ));
+ }
+ return Ok(());
+ }
+
+ let directory = tempfile::tempdir()?;
+ fake_node(directory.path(), "printf 'v22.0.0\\n'")?;
+ let inherited_path = directory.path().join("other node");
+ fake_node(&inherited_path, "printf 'v24.0.0\\n'")?;
+ run_child_test(
+ "empty_path_entry_runs_the_node_in_the_working_directory",
+ directory.path(),
+ &inherited_path,
+ )
+}
+
+#[test]
+fn absolute_node_paths_work_after_working_directory_is_removed() -> Result<()> {
+ if env::var_os(CHILD).is_some() {
+ let directory = env::current_dir()?;
+ let node = directory.join("node");
+ let removed_directory = directory.join("removed");
+ fs::create_dir(&removed_directory)?;
+ env::set_current_dir(&removed_directory)?;
+ fs::remove_dir(&removed_directory)?;
+ for (configured_path, search_path) in [
+ (Some(node.clone()), None),
+ (None, Some(directory.into_os_string())),
+ ] {
+ let discovered = smol::block_on(SystemNode::discover(configured_path, search_path))?;
+ assert_eq!(discovered.path(), node);
+ assert_eq!(discovered.version(), &Version::new(22, 0, 0));
+ }
+ return Ok(());
+ }
+
+ let directory = tempfile::tempdir()?;
+ fake_node(directory.path(), "printf 'v22.0.0\\n'")?;
+ run_child_test(
+ "absolute_node_paths_work_after_working_directory_is_removed",
+ directory.path(),
+ directory.path(),
+ )
+}
+
+#[test]
+fn configured_node_takes_precedence_and_failed_overrides_do_not_fall_back() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let node = fake_node(&directory.path().join("path node"), "printf 'v22.0.0\\n'")?;
+ let configured = fake_node(
+ &directory.path().join("configured node"),
+ "printf 'v24.1.0\\n'",
+ )?;
+ let search_path = node
+ .parent()
+ .expect("node directory")
+ .as_os_str()
+ .to_owned();
+ let discovered = smol::block_on(SystemNode::discover(
+ Some(configured.clone()),
+ Some(search_path.clone()),
+ ))?;
+ assert_eq!(discovered.path(), configured);
+ assert_eq!(discovered.version(), &Version::new(24, 1, 0));
+
+ fake_node(
+ configured.parent().expect("configured directory"),
+ "printf 'v20.0.0\\n'",
+ )?;
+ assert!(matches!(
+ smol::block_on(SystemNode::discover(
+ Some(configured.clone()),
+ Some(search_path.clone())
+ )),
+ Err(NodeDiscoveryError::TooOld { path, .. }) if path == configured
+ ));
+ fs::remove_file(&configured)?;
+ assert!(matches!(
+ smol::block_on(SystemNode::discover(Some(configured), Some(search_path))),
+ Err(NodeDiscoveryError::NotFound { .. })
+ ));
+ Ok(())
+}
+
+#[test]
+fn path_order_is_preserved_when_the_first_node_is_too_old() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let first = directory.path().join("first");
+ let second = directory.path().join("second");
+ let old = fake_node(&first, "printf 'v21.7.3\\n'")?;
+ fake_node(&second, "printf 'v24.0.0\\n'")?;
+ assert!(matches!(
+ smol::block_on(SystemNode::discover(None, Some(env::join_paths([first, second])?))),
+ Err(NodeDiscoveryError::TooOld { path, .. }) if path == old
+ ));
+ Ok(())
+}
+
+#[test]
+fn reports_execution_failures_with_the_executable_path() -> Result<()> {
+ let directory = tempfile::tempdir()?;
+ let node = fake_node(
+ directory.path(),
+ "printf 'v22.0.0\\n'; printf 'broken installation' >&2; exit 7",
+ )?;
+ let error =
+ smol::block_on(SystemNode::discover(Some(node.clone()), None)).expect_err("nonzero exit");
+ assert!(
+ matches!(&error, NodeDiscoveryError::UnsuccessfulExit { path, output }
+ if path == &node && output.status.code() == Some(7))
+ );
+ assert!(error.to_string().contains("broken installation"));
+
+ fs::write(&node, b"#!/nonexistent-node-interpreter\n")?;
+ assert!(matches!(
+ smol::block_on(SystemNode::discover(Some(node.clone()), None)),
+ Err(NodeDiscoveryError::Probe { path, .. }) if path == node
+ ));
+ Ok(())
+}
+
+const CHILD: &str = "ZED_TEST_NODE_DISCOVERY_CHILD";
+
+/// Isolates cwd and inherited PATH changes from the other tests.
+fn run_child_test(test: &str, directory: &Path, inherited_path: &Path) -> Result<()> {
+ let output = smol::block_on(
+ util::command::new_command(env::current_exe()?)
+ .args(["--exact", test, "--nocapture"])
+ .current_dir(directory)
+ .env(CHILD, "1")
+ .env("PATH", inherited_path)
+ .output(),
+ )?;
+ assert!(output.status.success(), "{output:?}");
+ Ok(())
+}
+
+fn fake_node(directory: &Path, body: &str) -> Result<PathBuf> {
+ fs::create_dir_all(directory)?;
+ let path = directory.join("node");
+ fs::write(&path, format!("#!/bin/sh\n{body}\n"))?;
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o755))?;
+ Ok(path)
+}