Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[[case]]
name = "system_pm_preserves_node_and_path"
vp = "global"
skip-platforms = ["windows"]
prewarm-package-managers = false
steps = [["node", "verify.mjs", "system-pm"]]

[[case]]
name = "managed_shim_preserves_system_node_path"
vp = "global"
skip-platforms = ["windows"]
prewarm-package-managers = false
steps = [["node", "verify.mjs", "shim"]]

[[case]]
name = "explicit_pm_preserves_system_node_path"
vp = "global"
skip-platforms = ["windows"]
prewarm-package-managers = false
steps = [["node", "verify.mjs", "explicit-pm"]]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# explicit_pm_preserves_system_node_path

## `node verify.mjs explicit-pm`

```
explicit-pm: selected Node and original PATH precedence preserved
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# managed_shim_preserves_system_node_path

## `node verify.mjs shim`

```
shim: selected Node and original PATH precedence preserved
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# system_pm_preserves_node_and_path

## `node verify.mjs system-pm`

```
system-pm: selected Node and original PATH precedence preserved
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { chmodSync, mkdirSync, writeFileSync, symlinkSync } from 'node:fs';
import { delimiter, join } from 'node:path';

const scenario = process.argv[2];
const root = process.cwd();
const first = join(root, 'first-bin');
const nodeBin = join(root, 'node-bin');
const pmBin = join(root, 'pm-bin');
for (const dir of [first, nodeBin, pmBin]) {
mkdirSync(dir, { recursive: true });
}
function executable(path, content) {
writeFileSync(path, content);
chmodSync(path, 0o755);
}
// Each later directory supplies a competing tool to expose accidental PATH promotion.
symlinkSync(process.execPath, join(nodeBin, 'node'));
executable(join(first, 'path-probe'), '#!/bin/sh\necho preferred\n');
executable(join(nodeBin, 'path-probe'), '#!/bin/sh\necho shadowed-by-node\n');
executable(join(pmBin, 'npm'), '#!/bin/sh\necho system-npm\n');
executable(join(pmBin, 'path-probe'), '#!/bin/sh\necho shadowed-by-pm\n');
executable(join(pmBin, 'node'), '#!/bin/sh\necho shadowed-by-pm\nexit 1\n');
const manager = '#!/bin/sh\nif [ "${1-}" = "--version" ]; then echo 10.18.0; else node probe.mjs; fi\n';
executable(join(pmBin, 'pnpm'), manager);
writeFileSync(
'package.json',
JSON.stringify({ name: 'system-first-path', private: true, packageManager: 'pnpm@10.18.0' }),
);
writeFileSync(
'probe.mjs',
`
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
assert.equal(execFileSync('path-probe', { encoding: 'utf8' }).trim(), 'preferred');
assert.match(execFileSync('node', ['--version'], { encoding: 'utf8' }), /^v/);
console.log('selected Node and original PATH precedence preserved');
`,
);
const env = {
...process.env,
PATH: [first, nodeBin, pmBin, process.env.PATH].join(delimiter),
// Start a fresh shell selection instead of inheriting the runner's Node selection.
VP_PATH_INJECTED_TOOLS: '',
};
function run(args) {
const result = spawnSync('vp', args, { env, encoding: 'utf8' });
assert.equal(result.status, 0, `${args.join(' ')}\n${result.stdout}\n${result.stderr}`);
return result.stdout;
}
run(['env', 'off', 'node']);
run(['env', 'off', 'pm']);
if (scenario === 'system-pm') {
assert.match(run(['install']), /selected Node and original PATH precedence preserved/);
run(['env', 'on', 'node']);
assert.match(run(['install']), /selected Node and original PATH precedence preserved/);
assert.match(
run(['env', 'exec', '--node', process.versions.node, 'pnpm', 'install']),
/selected Node and original PATH precedence preserved/,
);
} else {
const managed = join(process.env.VP_HOME, 'package_manager/pnpm/10.18.0/pnpm/bin');
mkdirSync(managed, { recursive: true });
for (const tool of ['pnpm', 'pnpx']) {
executable(join(managed, tool), manager);
}
run(['env', 'on', 'pnpm']);
if (scenario === 'shim') {
const result = spawnSync(join(process.env.VP_HOME, 'bin/pnpm'), ['install'], {
env,
encoding: 'utf8',
});
assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);
assert.match(result.stdout, /selected Node and original PATH precedence preserved/);
} else {
assert.match(
run(['env', 'exec', '--package-manager', 'pnpm@10.18.0', 'pnpm', 'install']),
/selected Node and original PATH precedence preserved/,
);
}
}
console.log(`${scenario}: selected Node and original PATH precedence preserved`);
30 changes: 22 additions & 8 deletions crates/vp_global_cli/src/commands/env/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,16 @@ async fn execute_with_version(
(config::resolve_version(cwd).await?.version, None)
};
if let Some(bin_dir) = system_node_bin {
path_prefixes.push((bin_dir.into_path_buf(), vec!["node"]));
path_prefixes.push((bin_dir.into_path_buf(), vec!["node"], true));
} else {
let runtime =
vp_js_runtime::download_runtime(vp_js_runtime::JsRuntimeType::Node, &resolved_node)
.await?;
path_prefixes
.push((runtime.get_bin_prefix().as_path().to_path_buf(), vec!["node", "npm", "npx"]));
path_prefixes.push((
runtime.get_bin_prefix().as_path().to_path_buf(),
vec!["node", "npm", "npx"],
false,
));
}
let explicit_package_manager = package_manager.is_some();
let mut system_package_manager = None;
Expand Down Expand Up @@ -195,6 +198,7 @@ async fn execute_with_version(
.package_manager_type
.bin_name_for_tool(&selected.package_manager_type.to_string()),
],
true,
),
);
system_package_manager =
Expand All @@ -221,23 +225,33 @@ async fn execute_with_version(
let system_version = read_tool_version(&path).await.unwrap_or(version);
path_prefixes.insert(
0,
(bin_dir.as_path().to_path_buf(), vec![kind.bin_name_for_tool(&kind.to_string())]),
(
bin_dir.as_path().to_path_buf(),
vec![kind.bin_name_for_tool(&kind.to_string())],
true,
),
);
Some(format!("{kind}@{system_version}"))
} else {
let (install_dir, _, _) =
download_package_manager_for_cwd(cwd, kind, &version, hash.as_deref()).await?;
path_prefixes
.insert(0, (install_dir.join("bin").into_path_buf(), kind.bin_names().to_vec()));
path_prefixes.insert(
0,
(install_dir.join("bin").into_path_buf(), kind.bin_names().to_vec(), false),
);
Some(format!("{kind}@{version}"))
}
} else {
None
};

let mut child_env = ToolPathEnv::from_env();
for (dir, tools) in path_prefixes.into_iter().rev() {
child_env.prepend(dir, &tools, PrependOptions::default())?;
for (dir, tools, system) in path_prefixes.into_iter().rev() {
// Preserve system PATH order unless another selected component shadows this tool.
let already_selected = system
&& vp_command::resolve_bin(tools[0], Some(child_env.path()), cwd)
.is_ok_and(|path| path.parent().is_some_and(|parent| parent.as_path() == dir));
child_env.prepend(dir, &tools, PrependOptions { dedupe_anywhere: already_selected })?;
}

// 5. Execute command
Expand Down
15 changes: 10 additions & 5 deletions crates/vp_global_cli/src/shim/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,12 +720,15 @@ async fn resolve_package_manager_tool(
async fn prepare_js_child_path(
cwd: &AbsolutePath,
node_bin_dir: &AbsolutePath,
system_node: bool,
mut env: ToolPathEnv,
) -> Result<ToolPathEnv, Error> {
if vp_shared::EnvConfig::get().env_forbidden {
return Ok(env);
}
env.prepend(node_bin_dir, &["node"], PrependOptions::default())?;
// System Node is already reachable; promoting its directory also promotes unrelated tools.
let node_options = PrependOptions { dedupe_anywhere: system_node };
env.prepend(node_bin_dir, &["node"], node_options)?;
if let Some(npm_path) = resolve_package_manager_tool(cwd, "npm").await? {
if let Some(bin_dir) = npm_path.parent() {
env.prepend(bin_dir, PackageManagerType::Npm.bin_names(), PrependOptions::default())?;
Expand All @@ -741,7 +744,7 @@ async fn prepare_js_child_path(
node_bin_dir.join(name).as_path().is_file()
})
.collect();
env.prepend(node_bin_dir, &tools, PrependOptions::default())?;
env.prepend(node_bin_dir, &tools, node_options)?;
}
Ok(env)
}
Expand Down Expand Up @@ -837,7 +840,7 @@ async fn select_core_tool(
// Adding a missing tool must retain the parent's Node and npm precedence.
env
} else {
prepare_js_child_path(cwd, node_bin_dir, env)
prepare_js_child_path(cwd, node_bin_dir, resolution.is_none(), env)
.await
.map_err(|error| vec![format!("Failed to prepare child process PATH: {error}")])?
};
Expand Down Expand Up @@ -1077,7 +1080,9 @@ pub(crate) async fn package_binary_invocation(
let node_bin_dir =
node_path.parent().ok_or_else(|| "Node has no parent directory".to_string())?;
let child_env = if let Ok(cwd) = current_dir() {
prepare_js_child_path(&cwd, node_bin_dir, env).await.map_err(|error| error.to_string())?
prepare_js_child_path(&cwd, node_bin_dir, false, env)
.await
.map_err(|error| error.to_string())?
} else {
// As in `prepare_js_child_path`, VP_ENV_FORBIDDEN adds no directories.
if !vp_shared::EnvConfig::get().env_forbidden {
Expand Down Expand Up @@ -3051,7 +3056,7 @@ mod tests {
let vars = forbidden_vars(&layout, &path, forbidden, &[]);
let (cwd, node_dir) = (layout.cwd.clone(), node_dir.clone());
EnvConfig::with_vars_async(vars, move |_| async move {
prepare_js_child_path(&cwd, &node_dir, ToolPathEnv::from_env())
prepare_js_child_path(&cwd, &node_dir, true, ToolPathEnv::from_env())
.await
.unwrap()
.into_envs()
Expand Down
15 changes: 12 additions & 3 deletions crates/vp_pm_cli/src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ use vt_path::AbsolutePath;

use crate::{
EnvironmentPackageManagerResolution, PackageManager, PackageManagerType,
cli::PackageManagerCommand, download_package_manager_for_cwd, error::Error,
package_manager_override, resolution::run_resolution,
cli::PackageManagerCommand,
download_package_manager_for_cwd,
error::Error,
package_manager_override,
resolution::{CommandResolution, run_resolution},
};

#[derive(Debug)]
Expand Down Expand Up @@ -96,7 +99,13 @@ async fn dispatch_with_manager(
};
let package_manager = manager.client;
let why_hint_packages = command.why_hint_packages(package_manager).map(<[String]>::to_vec);
let resolution = command.resolve_for_manager(&manager)?;
let mut resolution = command.resolve_for_manager(&manager)?;
if let CommandResolution::Run(command) = &mut resolution.outcome
&& PackageManagerType::from_name(&command.program) == Some(package_manager)
{
// Run the manager used for version checks without changing its children's PATH.
command.program = manager.bin_prefix.join(&command.program).to_string();
}
let status = run_resolution(cwd, resolution, render_diagnostics).await?;
Ok(DispatchResult { status, why_hint_packages })
}
Expand Down
7 changes: 6 additions & 1 deletion crates/vp_pm_cli/src/resolution/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ where

if let CommandResolution::Run(command) = &mut resolution.outcome {
let mut env = ToolPathEnv::from_env();
env.prepend(manager.get_bin_prefix(), &manager.bin_names(), PrependOptions::default())?;
// Promoting a system manager's directory can also shadow the selected Node.js.
env.prepend(
manager.get_bin_prefix(),
&manager.bin_names(),
PrependOptions { dedupe_anywhere: !manager.is_managed() },
Comment thread
liangmiQwQ marked this conversation as resolved.
Resolved
)?;
for (key, value) in env.into_envs() {
command.env.insert(key.to_string(), value.to_string_lossy().into_owned());
}
Expand Down
Loading