|
23 | 23 | //! Category C - Local CLI Delegation: |
24 | 24 | //! - `delegate`: Local CLI delegation |
25 | 25 |
|
| 26 | +use vite_path::AbsolutePath; |
| 27 | + |
| 28 | +use crate::{error::Error, js_executor::JsExecutor}; |
| 29 | + |
| 30 | +/// Ensure the JS runtime is downloaded and prepend its bin directory to PATH. |
| 31 | +/// This should be called before executing any package manager command. |
| 32 | +/// |
| 33 | +/// If `project_path` contains a package.json, uses the project's runtime |
| 34 | +/// (based on devEngines.runtime). Otherwise, falls back to the CLI's runtime. |
| 35 | +pub async fn prepend_js_runtime_to_path_env(project_path: &AbsolutePath) -> Result<(), Error> { |
| 36 | + let mut executor = JsExecutor::new(None); |
| 37 | + |
| 38 | + // Use project runtime if package.json exists, otherwise use CLI runtime |
| 39 | + let package_json_path = project_path.join("package.json"); |
| 40 | + let runtime = if package_json_path.as_path().exists() { |
| 41 | + executor.ensure_project_runtime(project_path).await? |
| 42 | + } else { |
| 43 | + executor.ensure_cli_runtime().await? |
| 44 | + }; |
| 45 | + |
| 46 | + let node_bin_path = runtime.get_bin_prefix().as_path().to_path_buf(); |
| 47 | + |
| 48 | + // Check if node bin path already exists in PATH to avoid duplicates |
| 49 | + let current_path = std::env::var_os("PATH").unwrap_or_default(); |
| 50 | + let paths: Vec<_> = std::env::split_paths(¤t_path).collect(); |
| 51 | + |
| 52 | + if paths.iter().any(|p| p == &node_bin_path) { |
| 53 | + return Ok(()); |
| 54 | + } |
| 55 | + |
| 56 | + // Prepend node bin to PATH |
| 57 | + let mut new_paths = vec![node_bin_path]; |
| 58 | + new_paths.extend(paths); |
| 59 | + let new_path = std::env::join_paths(new_paths).expect("Failed to join paths"); |
| 60 | + // SAFETY: We're modifying PATH at the start of command execution before any |
| 61 | + // parallel operations. This is safe because package manager commands run |
| 62 | + // sequentially and child processes inherit the modified environment. |
| 63 | + unsafe { std::env::set_var("PATH", new_path) }; |
| 64 | + |
| 65 | + Ok(()) |
| 66 | +} |
| 67 | + |
26 | 68 | // Category A: Package manager commands |
27 | 69 | pub mod add; |
28 | 70 | pub mod dedupe; |
|
0 commit comments