-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathexec.rs
More file actions
319 lines (280 loc) · 12 KB
/
exec.rs
File metadata and controls
319 lines (280 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//! Exec command for executing commands with a specific Node.js version.
//!
//! Handles two modes:
//! 1. Explicit version: `vp env exec --node <version> [--npm <version>] <command>`
//! 2. Shim mode: `vp env exec <tool> [args...]` where tool is node/npm/npx or a global package binary
//!
//! The shim mode uses the same dispatch logic as Unix symlinks, ensuring identical behavior
//! across platforms (used by Windows .cmd wrappers and Git Bash shell scripts).
use std::process::ExitStatus;
use vite_js_runtime::NodeProvider;
use vite_shared::{env_vars, format_path_prepended};
use crate::{
error::Error,
shim::{dispatch as shim_dispatch, is_shim_tool},
};
/// Execute the exec command.
///
/// When `--node` is provided, runs a command with the specified Node.js version.
/// When `--node` is not provided and the command is a shim tool (node/npm/npx or global package),
/// uses the same shim dispatch logic as Unix symlinks.
pub async fn execute(
node_version: Option<&str>,
npm_version: Option<&str>,
command: &[String],
) -> Result<ExitStatus, Error> {
let command = normalize_wrapper_command(command);
if command.is_empty() {
eprintln!("vp env exec: missing command to execute");
eprintln!("Usage: vp env exec [--node <version>] <command> [args...]");
return Ok(exit_status(1));
}
// If --node is provided, use explicit version mode (existing behavior)
if let Some(version) = node_version {
return execute_with_version(version, npm_version, &command).await;
}
// No --node provided - check if first command is a shim tool
// This includes:
// - Core tools (node, npm, npx)
// - Globally installed package binaries (tsc, eslint, etc.)
let tool = &command[0];
if is_shim_tool(tool) {
// Clear recursion env var to force fresh version resolution.
// This is needed because `vp env exec` may be invoked from within a context
// where VP_TOOL_RECURSION is already set (e.g., when pnpm runs through
// the vite-plus shim). Without clearing it, shim_dispatch would passthrough
// to the system node instead of resolving the version.
// SAFETY: This is safe because we're about to spawn a child process and we want
// fresh version resolution, not passthrough behavior.
unsafe {
std::env::remove_var(env_vars::VP_TOOL_RECURSION);
}
// Use the SAME shim dispatch as Unix symlinks - this ensures:
// - Core tools: Version resolved from .node-version/package.json/default
// - Package binaries: Uses Node.js version from package metadata
// - Automatic Node.js download if needed
// - Recursion prevention via VP_TOOL_RECURSION
// - Shim mode checking (managed vs system-first)
let args: Vec<String> = command[1..].to_vec();
let exit_code = shim_dispatch(tool, &args).await;
return Ok(exit_status(exit_code));
}
// Not a shim tool and no --node - error
eprintln!("vp env exec: --node is required when running non-shim commands");
eprintln!("Usage: vp env exec --node <version> <command> [args...]");
eprintln!();
eprintln!("For shim tools, --node is optional (version resolved automatically):");
eprintln!(" vp env exec node script.js # Core tool");
eprintln!(" vp env exec npm install # Core tool");
eprintln!(" vp env exec tsc --version # Global package");
Ok(exit_status(1))
}
/// Normalize arguments when invoked via Windows shim wrappers.
///
/// Wrappers insert `--` after the tool name so flags like `--help` aren't
/// consumed by clap while parsing `vp env exec`. Remove only that inserted
/// separator before forwarding args to the target tool.
fn normalize_wrapper_command(command: &[String]) -> Vec<String> {
let from_wrapper = std::env::var_os(env_vars::VP_SHIM_WRAPPER).is_some();
let normalized = normalize_wrapper_command_inner(command, from_wrapper);
if from_wrapper {
// SAFETY: We're in a short-lived CLI process and clearing a wrapper-only
// marker before tool execution avoids leaking it to child processes.
unsafe {
std::env::remove_var(env_vars::VP_SHIM_WRAPPER);
}
}
normalized
}
fn normalize_wrapper_command_inner(command: &[String], from_wrapper: bool) -> Vec<String> {
let mut normalized = command.to_vec();
if from_wrapper && normalized.len() >= 2 && normalized[1] == "--" {
normalized.remove(1);
}
normalized
}
/// Execute a command with an explicitly specified Node.js version.
async fn execute_with_version(
node_version: &str,
npm_version: Option<&str>,
command: &[String],
) -> Result<ExitStatus, Error> {
// Warn about unsupported --npm flag
if npm_version.is_some() {
eprintln!("Warning: --npm flag is not yet implemented, using bundled npm");
}
// 1. Resolve version
let provider = NodeProvider::new();
let resolved_version = resolve_version(node_version, &provider).await?;
// 2. Ensure installed (download if needed)
let runtime =
vite_js_runtime::download_runtime(vite_js_runtime::JsRuntimeType::Node, &resolved_version)
.await?;
// 3. Clear recursion env var to force re-evaluation in child processes
// SAFETY: This is safe because we're about to spawn a child process and we want
// to ensure the env var is not inherited. We're not reading this env var in other
// threads at this point.
unsafe {
std::env::remove_var(env_vars::VP_TOOL_RECURSION);
}
// 4. Build PATH with node bin dir first (uses platform-specific separator)
// Always prepend to ensure the requested Node version is first in PATH
let node_bin_dir = runtime.get_bin_prefix();
let new_path = format_path_prepended(node_bin_dir.as_path());
// 5. Execute command
let (cmd, args) = command.split_first().unwrap();
let status =
tokio::process::Command::new(cmd).args(args).env("PATH", new_path).status().await?;
Ok(status)
}
/// Resolve version to an exact version.
///
/// Handles aliases (lts, latest) and version ranges.
async fn resolve_version(version: &str, provider: &NodeProvider) -> Result<String, Error> {
match version.to_lowercase().as_str() {
"lts" => {
let resolved = provider.resolve_latest_version().await?;
Ok(resolved.to_string())
}
"latest" => {
let resolved = provider.resolve_absolute_latest_version().await?;
Ok(resolved.to_string())
}
_ => {
// For exact versions, use directly
if NodeProvider::is_exact_version(version) {
// Strip v prefix if present
let normalized = version.strip_prefix('v').unwrap_or(version);
Ok(normalized.to_string())
} else {
// For ranges/partial versions, resolve to exact
let resolved = provider.resolve_version(version).await?;
Ok(resolved.to_string())
}
}
}
}
/// Create an exit status with the given code.
fn exit_status(code: i32) -> ExitStatus {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
ExitStatus::from_raw(code << 8)
}
#[cfg(windows)]
{
use std::os::windows::process::ExitStatusExt;
ExitStatus::from_raw(code as u32)
}
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use serial_test::serial;
use tempfile::TempDir;
use super::*;
struct VpHomeGuard {
original_vp_home: Option<OsString>,
_temp_dir: TempDir,
}
impl VpHomeGuard {
fn new() -> Self {
let temp_dir = TempDir::new().unwrap();
let original_vp_home = std::env::var_os(env_vars::VP_HOME);
// SAFETY: This test helper is only used from serial tests and restores the
// process-global environment before dropping.
unsafe {
std::env::set_var(env_vars::VP_HOME, temp_dir.path());
}
Self { original_vp_home, _temp_dir: temp_dir }
}
}
impl Drop for VpHomeGuard {
fn drop(&mut self) {
// SAFETY: We restore the original process-global environment captured in new().
unsafe {
match &self.original_vp_home {
Some(value) => std::env::set_var(env_vars::VP_HOME, value),
None => std::env::remove_var(env_vars::VP_HOME),
}
}
}
}
#[tokio::test]
async fn test_execute_missing_command() {
let result = execute(Some("20.18.0"), None, &[]).await;
assert!(result.is_ok());
let status = result.unwrap();
assert!(!status.success());
}
#[tokio::test]
#[serial]
async fn test_execute_node_version() {
let _guard = VpHomeGuard::new();
// Run 'node --version' with a specific Node.js version
let command = vec!["node".to_string(), "--version".to_string()];
let result = execute(Some("20.18.0"), None, &command).await;
assert!(result.is_ok(), "{result:?}");
let status = result.unwrap();
assert!(status.success());
}
#[tokio::test]
async fn test_resolve_version_exact() {
let provider = NodeProvider::new();
let version = resolve_version("20.18.0", &provider).await.unwrap();
assert_eq!(version, "20.18.0");
}
#[tokio::test]
async fn test_resolve_version_with_v_prefix() {
let provider = NodeProvider::new();
let version = resolve_version("v20.18.0", &provider).await.unwrap();
assert_eq!(version, "20.18.0");
}
#[tokio::test]
async fn test_resolve_version_partial() {
let provider = NodeProvider::new();
let version = resolve_version("20", &provider).await.unwrap();
// Should resolve to a 20.x.x version - check starts with "20."
assert!(version.starts_with("20."), "Expected version starting with '20.', got: {version}");
}
#[tokio::test]
async fn test_resolve_version_range() {
let provider = NodeProvider::new();
let version = resolve_version("^20.0.0", &provider).await.unwrap();
// Should resolve to a 20.x.x version - check starts with "20."
assert!(version.starts_with("20."), "Expected version starting with '20.', got: {version}");
}
#[tokio::test]
async fn test_resolve_version_lts() {
let provider = NodeProvider::new();
let version = resolve_version("lts", &provider).await.unwrap();
// Should resolve to a valid version (format: x.y.z)
let parts: Vec<&str> = version.split('.').collect();
assert_eq!(parts.len(), 3, "Expected version format x.y.z, got: {version}");
// Major version should be >= 20 (current LTS line)
let major: u32 = parts[0].parse().expect("Major version should be a number");
assert!(major >= 20, "Expected major version >= 20, got: {major}");
}
#[tokio::test]
async fn test_shim_mode_error_for_non_shim_command() {
// Running a non-shim command without --node should error
let command = vec!["python".to_string(), "--version".to_string()];
let result = execute(None, None, &command).await;
assert!(result.is_ok());
let status = result.unwrap();
// Should fail because python is not a shim tool and --node was not provided
assert!(!status.success(), "Non-shim command without --node should fail");
}
#[test]
fn test_normalize_wrapper_command_strips_only_wrapper_separator() {
let command = vec!["node".to_string(), "--".to_string(), "--version".to_string()];
let normalized = normalize_wrapper_command_inner(&command, true);
assert_eq!(normalized, vec!["node", "--version"]);
}
#[test]
fn test_normalize_wrapper_command_no_wrapper_keeps_separator() {
let command = vec!["node".to_string(), "--".to_string(), "--version".to_string()];
let normalized = normalize_wrapper_command_inner(&command, false);
assert_eq!(normalized, command);
}
}