Skip to content
Draft
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
Expand Up @@ -3,7 +3,7 @@ name = "command_add_npm11_with_workspace"
vp = "global"
skip-platforms = ["windows"]
steps = [
{ argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], comment = "should add package to workspace root" },
{ argv = ["vp", "add", "testnpm2", "-D", "-w", "--", "--no-audit"], cwd = "packages/app", comment = "add to the root from a workspace member" },
{ argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true },
{ argv = ["vp", "add", "@vite-plus-test/utils", "--workspace", "--", "--no-audit"], comment = "reject unsupported --workspace without adding packages to the root", continue-on-failure = true },
{ argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true },
Expand All @@ -17,4 +17,7 @@ steps = [
{ argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true },
{ argv = ["vp", "install", "[email protected]", "--filter", "*", "--workspace-root", "--", "--no-audit"], comment = "should install packages alias for add command" },
{ argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"], continue-on-failure = true },
{ argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove the root devDependency and preserve the member dependencies" },
{ argv = ["vpt", "print-file", "package.json", "packages/app/package.json", "packages/utils/package.json"] },
{ argv = ["node", "-e", "const { packages } = require('./package-lock.json'); console.log(packages[''].devDependencies?.testnpm2, packages['packages/app'].dependencies.testnpm2)"], comment = "the lockfile records the same removal at the root and keeps the app dependency" },
]
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# command_add_npm11_with_workspace

## `vp add testnpm2 -D -w -- --no-audit`
## `cd packages/app && vp add testnpm2 -D -w -- --no-audit`

should add package to workspace root
add to the root from a workspace member

```

Expand Down Expand Up @@ -274,3 +274,55 @@ added 1 package in <duration>
}
}
```

## `cd packages/app && vp remove -w testnpm2 -- --no-audit`

remove the root devDependency and preserve the member dependencies

```

up to date in <duration>
```

## `vpt print-file package.json packages/app/package.json packages/utils/package.json`

```
{
"name": "command-add-npm11-with-workspace",
"version": "1.0.0",
"workspaces": [
"packages/*"
],
"packageManager": "[email protected]",
"dependencies": {
"test-vite-plus-install": "1.0.0",
"test-vite-plus-package": "^1.0.0"
}
}
{
"name": "app",
"dependencies": {
"test-vite-plus-install": "1.0.0",
"test-vite-plus-package": "^1.0.0",
"testnpm2": "1.0.1"
}
}
{
"name": "@vite-plus-test/utils",
"version": "1.0.0",
"private": true,
"dependencies": {
"test-vite-plus-install": "1.0.0",
"test-vite-plus-package": "^1.0.0",
"testnpm2": "1.0.1"
}
}
```

## `node -e 'const { packages } = require('\''./package-lock.json'\''); console.log(packages['\'''\''].devDependencies?.testnpm2, packages['\''packages/app'\''].dependencies.testnpm2)'`

the lockfile records the same removal at the root and keeps the app dependency

```
undefined 1.0.1
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "root",
"private": true,
"packageManager": "[email protected]",
"workspaces": [
"packages/*"
],
"devDependencies": {
"testnpm2": "1.0.1",
"test-vite-plus-install": "1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "app",
"version": "1.0.0",
"packageManager": "[email protected]",
"workspaces": [
"plugins/*"
],
"dependencies": {
"testnpm2": "1.0.1",
"test-vite-plus-install": "1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "docs",
"version": "1.0.0",
"dependencies": {
"test-vite-plus-install": "1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "docs",
"version": "1.0.0",
"dependencies": {
"testnpm2": "1.0.1",
"test-vite-plus-install": "1.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[[case]]
name = "command_remove_npm8_nested_workspace"
vp = "global"
steps = [
{ argv = ["vp", "remove", "-w", "testnpm2", "--", "--no-audit"], cwd = "packages/app", comment = "remove only the outer root declaration when the current member owns a workspace" },
{ argv = ["vp", "remove", "-w", "--filter", "docs", "test-vite-plus-install", "--", "--no-audit"], cwd = "packages/app", comment = "select the outer docs package when the inner workspace also has a member named docs" },
{ argv = ["vp", "remove", "-w", "testnpm2", "--", "--workspace=../docs", "--no-audit"], cwd = "packages/app", comment = "resolve an attached workspace path from the calling member" },
["vpt", "print-file", "package.json", "packages/app/package.json", "packages/docs/package.json", "packages/app/plugins/docs/package.json"],
["node", "-p", "require('./package-lock.json').packages['packages/app'].dependencies"],
["vpt", "stat-file", "packages/app/package-lock.json", "--assert", "missing"],
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# command_remove_npm8_nested_workspace

## `cd packages/app && vp remove -w testnpm2 -- --no-audit`

remove only the outer root declaration when the current member owns a workspace

```

added 4 packages in <duration>
```

## `cd packages/app && vp remove -w --filter docs test-vite-plus-install -- --no-audit`

select the outer docs package when the inner workspace also has a member named docs

```

up to date in <duration>
```

## `cd packages/app && vp remove -w testnpm2 -- --workspace=../docs --no-audit`

resolve an attached workspace path from the calling member

```

up to date in <duration>
```

## `vpt print-file package.json packages/app/package.json packages/docs/package.json packages/app/plugins/docs/package.json`

```
{
"name": "root",
"private": true,
"packageManager": "[email protected]",
"workspaces": [
"packages/*"
]
}
{
"name": "app",
"version": "1.0.0",
"packageManager": "[email protected]",
"workspaces": [
"plugins/*"
],
"dependencies": {
"testnpm2": "1.0.1",
"test-vite-plus-install": "1.0.0"
}
}
{
"name": "docs",
"version": "1.0.0"
}
{
"name": "docs",
"version": "1.0.0",
"dependencies": {
"test-vite-plus-install": "1.0.0"
}
}
```

## `node -p require('./package-lock.json').packages['packages/app'].dependencies`

```
{ 'test-vite-plus-install': '1.0.0', testnpm2: '1.0.1' }
```

## `vpt stat-file packages/app/package-lock.json --assert missing`

```
packages/app/package-lock.json: missing
```
93 changes: 84 additions & 9 deletions crates/vp_pm_cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,8 @@ impl NpmConfig {
project_root: Option<PathBuf>,
cwd: Option<&AbsolutePath>,
) -> Self {
let mut project_values = HashMap::new();
if let Some(root) = project_root {
load_npmrc(root.join(".npmrc"), &mut project_values);
}
let user_config = npm_user_config_path(cwd)
.or_else(|| project_values.get("userconfig").map(|path| config_path(path, cwd)))
.unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf());
let mut user_values = HashMap::new();
load_npmrc(user_config, &mut user_values);
let (project_values, user_values) =
project_and_user_npmrc(project_root, cwd, npm_user_config_path(cwd));

// Higher-priority layers select config files; merge their values from low to high.
// Default global paths require npm, so only explicitly selected files are loaded.
Expand Down Expand Up @@ -341,6 +334,23 @@ fn load_npmrc(path: PathBuf, values: &mut HashMap<String, String>) {
}
}

fn project_and_user_npmrc(
project_root: Option<PathBuf>,
cwd: Option<&AbsolutePath>,
userconfig: Option<PathBuf>,
) -> (HashMap<String, String>, HashMap<String, String>) {
let mut project = HashMap::new();
if let Some(root) = project_root {
load_npmrc(root.join(".npmrc"), &mut project);
}
let userconfig = userconfig
.or_else(|| project.get("userconfig").map(|path| config_path(path, cwd)))
.unwrap_or_else(|| EnvConfig::get().user_home.join(".npmrc").into_path_buf());
let mut user = HashMap::new();
load_npmrc(userconfig, &mut user);
(project, user)
}

fn parse_npmrc_value(value: &str) -> String {
let value = value.trim();
if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
Expand Down Expand Up @@ -390,6 +400,35 @@ pub fn npm_user_config_path(cwd: Option<&AbsolutePath>) -> Option<PathBuf> {
env_value("userconfig").map(|path| config_path(&expand_value(&path), cwd))
}

/// Find the global npmrc selected before a workspace edit overrides npm's prefix.
pub(crate) fn workspace_globalconfig(
root: &AbsolutePath,
cwd: &AbsolutePath,
cli_userconfig: Option<&str>,
env: &HashMap<String, String>,
) -> Option<PathBuf> {
let from_env = |name: &str| {
let key = vt_str::format!("npm_config_{name}");
env.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(&key))
.and_then(|(_, value)| (!value.is_empty()).then(|| expand_value(value)))
.or_else(|| env_value(name).map(|value| expand_value(&value)))
};
let userconfig = cli_userconfig
.map(expand_value)
.or_else(|| from_env("userconfig"))
.map(|value| config_path(&value, Some(cwd)));
let (project, user) =
project_and_user_npmrc(Some(root.as_path().to_path_buf()), Some(cwd), userconfig);
let configured = |key: &str| {
from_env(key)
.or_else(|| project.get(key).cloned())
.or_else(|| user.get(key).cloned())
.map(|value| config_path(&value, Some(cwd)))
};
configured("globalconfig").or_else(|| configured("prefix").map(|p| p.join("etc/npmrc")))
}

/// Resolve the `Authorization` header value npm would send to `url` from the npm config at `cwd`.
#[must_use]
pub fn npm_authorization_for_url(cwd: &AbsolutePath, url: &str) -> Option<String> {
Expand Down Expand Up @@ -572,6 +611,42 @@ mod tests {
});
}

#[test]
fn workspace_globalconfig_resolves_project_and_user_paths_from_the_caller() {
let root = project_with_npmrc("userconfig=./user.npmrc\nprefix=./project-prefix\n");
let caller = root.path().join("child");
fs::create_dir(&caller).unwrap();
fs::write(caller.join("user.npmrc"), "globalconfig=./user-global.npmrc\n").unwrap();
let root = AbsolutePath::new(root.path()).unwrap();
let cwd = AbsolutePath::new(&caller).unwrap();
EnvConfig::with_vars(
[
("npm_config_userconfig", None::<&std::ffi::OsStr>),
("NPM_CONFIG_USERCONFIG", None),
("npm_config_globalconfig", None),
("NPM_CONFIG_GLOBALCONFIG", None),
("npm_config_prefix", None),
("NPM_CONFIG_PREFIX", None),
],
|_| {
let mut env = HashMap::new();
assert_eq!(
workspace_globalconfig(root, cwd, None, &env),
Some(caller.join("user-global.npmrc")),
);
env.insert("NPM_CONFIG_USERCONFIG".into(), "missing".into());
assert_eq!(
workspace_globalconfig(root, cwd, None, &env),
Some(caller.join("project-prefix/etc/npmrc")),
);
assert_eq!(
workspace_globalconfig(root, cwd, Some("user.npmrc"), &env),
Some(caller.join("user-global.npmrc")),
);
},
);
}

#[test]
fn relative_config_paths_use_caller_cwd_without_changing_workspace_root() {
with_isolated_npm_config(|| {
Expand Down
14 changes: 13 additions & 1 deletion crates/vp_pm_cli/src/resolution/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub(crate) struct ResolvedCommand {
pub(crate) args: Vec<String>,
pub(crate) env: BTreeMap<String, String>,
pub(crate) pre_run: Vec<PreRunAction>,
pub(crate) npm_workspace_edit: Option<NpmWorkspaceEdit>,
}

impl ResolvedCommand {
Expand All @@ -23,7 +24,7 @@ impl ResolvedCommand {
// Include npm/npx fallbacks: Vite+ manages their versions too.
env.insert("npm_config_update_notifier".to_string(), "false".to_string());
}
Self { program, args: Vec::new(), env, pre_run: Vec::new() }
Self { program, args: Vec::new(), env, pre_run: Vec::new(), npm_workspace_edit: None }
}
}

Expand All @@ -33,6 +34,12 @@ impl From<CommandBuilder> for CommandResolution {
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NpmWorkspaceEdit {
AutomaticRoot,
LegacyRoot { local_dependency: bool },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PreRunAction {
CreateDir { path: String },
Expand Down Expand Up @@ -94,6 +101,11 @@ impl CommandBuilder {
self
}

pub(crate) fn npm_workspace_edit(&mut self, edit: Option<NpmWorkspaceEdit>) -> &mut Self {
self.command.npm_workspace_edit = edit;
self
}

pub(crate) fn create_dir(&mut self, path: impl ToString) -> &mut Self {
self.command.pre_run.push(PreRunAction::CreateDir { path: path.to_string() });
self
Expand Down
11 changes: 8 additions & 3 deletions crates/vp_pm_cli/src/resolution/commands/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,14 @@ impl Npm {
return cmd.into();
}

cmd.arg("install")
.repeated("--workspace", args.filter.iter())
.arg_if("--include-workspace-root", args.workspace_root);
cmd.npm_workspace_edit(self.workspace_edit(
args.workspace_root && !args.packages.is_empty(),
!args.filter.is_empty(),
&args.packages,
))
.arg("install")
.repeated("--workspace", args.filter.iter())
.arg_if("--include-workspace-root", args.workspace_root);
match args.save_dependency.target() {
Some(SaveDependencyTarget::Production) => {
// `--save` overrides npm's `save=false` setting when the user explicitly selects production.
Expand Down
Loading
Loading