Repository navigation
Conversation
Edge-aware `engineStrict` landed in ea1d6ef: `compute_skipped_snapshots` dispatches on inbound edges from the lockfile walk, so an incompatible package reached through a regular dependency edge fails the install even when it is also optionally reachable. The real port (`fail_on_unsupported_dependency_of_optional_dependency`, asserting `ERR_PNPM_UNSUPPORTED_PLATFORM`) was written in the same change and passes, and TEST_PORTING.md records the item as ported. The `known_failures` stub for the same upstream test survived that landing, so `just known-failures` still advertised the gap and a same-named stub sat alongside the real test claiming pacquet skips this shape. Remove the module — it held nothing else — along with a leftover `eprintln!` of the captured stderr in the real test. Leaves two live stubs, both pinned cross-stack divergences awaiting a product decision rather than an implementation. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pnpm's `-w` runs a command on the root workspace project from anywhere inside the workspace; pacquet had no such flag, so the reported `pnpm add -D oxlint@latest oxfmt@latest oxlint-tsgolint@latest -w` failed with "unexpected argument '-w' found". Multi-package `add` was fixed earlier, leaving the flag as the remaining half of that report. Implemented where pnpm implements it — as a universal option resolved before dispatch, by rewriting `--dir` to the workspace root. Every command already resolves its project from `dir`, so none of them need to know the flag exists. The upward walk runs on a canonicalized path: `--dir` still holds whatever was typed at this point, and its default `.` has no parent to climb, so searching from it would report "not in a workspace" from every directory. Both of pnpm's guards come along: `--global` has no workspace root to act on (`ERR_PNPM_OPTIONS_CONFLICT`), and outside a workspace there is nothing to re-anchor to (`ERR_PNPM_NOT_IN_WORKSPACE`). `--global` is per-command in pacquet rather than universal, so `CliCommand::is_global` asks the ten commands that expose it; `config` keeps its copy on each subcommand's `ConfigFlags`, hence the accessor there. Verified against the TypeScript CLI: `prefix -w`, plain `prefix`, `-g -w`, and `-w` outside a workspace all produce identical results in both stacks. Fixes #13031. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAdds ChangesWorkspace root execution
Estimated code review effort: 3 (Moderate) | ~20 minutes Assessment against linked issues
Out-of-scope changes
Sequence Diagram(s)sequenceDiagram
participant User
participant run_cli
participant CliArgs
participant WorkspaceFinder
participant RootProject
User->>run_cli: Invoke command with -w
run_cli->>CliArgs: apply_workspace_root()
CliArgs->>WorkspaceFinder: find_workspace_dir(dir)
WorkspaceFinder-->>CliArgs: workspace root
CliArgs->>RootProject: Rewrite command directory
RootProject-->>User: Execute command at workspace root
Possibly related PRs
Suggested labels: Suggested reviewers: ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
PR Summary by Qodofeat(pacquet): add -w/--workspace-root by re-anchoring --dir at workspace root
AI Description
Diagram
High-Level Assessment
Files changed (7)
|
Micro-Benchmark ResultsLinux |
Code Review by Qodo
Context used✅ Compliance rules (platform):
24 rules 1. Global conflict missed
|
PR Code Suggestions ✨Warning
No code suggestions found for the PR. |
Confidence Score: 3/5The PR should not merge until workspace-root participates correctly in recursive project selection and every command exposing global mode is covered by the conflict guard. Rewriting Files Needing Attention: pnpm/crates/cli/src/cli_args/cli_command.rs, pnpm/crates/cli/tests/workspace_root.rs Reviews (1): Last reviewed commit: "feat(pacquet): add the -w / --workspace-..." | Re-trigger Greptile |
| .ok_or(WorkspaceRootError::NotInWorkspace)?; | ||
| self.dir = workspace_dir; |
There was a problem hiding this comment.
Workspace root omitted recursively
When -w is combined with -r or --filter, this code only changes dir and does not add the root project to project selection, causing recursive or filtered operations to omit the workspace root while the TypeScript CLI includes it.
Context Used: pnpm/CLAUDE.md (source)
Knowledge Base Used: Rust CLI core: argument parsing, dispatch, config, and reporting
| fn is_global(&self) -> bool { | ||
| match self { | ||
| CliCommand::Add(args) => args.global, | ||
| CliCommand::Bin(args) => args.global, | ||
| CliCommand::Config(args) => args.is_global(), | ||
| CliCommand::List(args) | CliCommand::Ll(args) => args.global, | ||
| CliCommand::Outdated(args) => args.global, | ||
| CliCommand::Prefix(args) => args.global, | ||
| CliCommand::Remove(args) => args.global, | ||
| CliCommand::Root(args) => args.global, | ||
| CliCommand::Runtime(args) => args.global, | ||
| CliCommand::Update(args) => args.global, | ||
| _ => false, | ||
| } | ||
| } |
There was a problem hiding this comment.
Approve-builds bypasses conflict guard
When approve-builds --global is combined with --workspace-root, this match returns false because it omits ApproveBuilds, so the universal conflict check is bypassed and the command reports ERR_PNPM_APPROVE_BUILDS_NOT_SUPPORTED_WITH_GLOBAL instead of the required ERR_PNPM_OPTIONS_CONFLICT.
Context Used: pnpm/CLAUDE.md (source)
Knowledge Base Used: Rust CLI core: argument parsing, dispatch, config, and reporting
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pnpm/crates/cli/src/cli_args/cli_command.rs`:
- Around line 264-285: Update apply_workspace_root to propagate
dunce::canonicalize failures instead of falling back to the raw self.dir; pass
only the canonical path to find_workspace_dir, map a successful None result to
WorkspaceRootError::NotInWorkspace, and add a regression test covering a
traversal path that resolves outside the workspace with a missing target.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 6e9e1ff9-da43-4531-b1ae-030039cfd665
📒 Files selected for processing (7)
.changeset/pacquet-workspace-root-flag.mdpnpm/crates/cli/src/cli_args/cli_command.rspnpm/crates/cli/src/cli_args/config.rspnpm/crates/cli/src/cli_args/dispatch.rspnpm/crates/cli/src/lib.rspnpm/crates/cli/tests/optional_dependencies.rspnpm/crates/cli/tests/workspace_root.rs
💤 Files with no reviewable changes (1)
- pnpm/crates/cli/tests/optional_dependencies.rs
| /// Re-anchor `--dir` at the workspace root for `-w` / | ||
| /// `--workspace-root`, so the command runs on the root project from | ||
| /// anywhere inside the workspace. | ||
| /// | ||
| /// Rewriting `dir` is the whole implementation, matching pnpm: every | ||
| /// command already resolves its project from `dir`, so none of them | ||
| /// need to know the flag exists. | ||
| pub fn apply_workspace_root(&mut self) -> Result<(), WorkspaceRootError> { | ||
| if !self.workspace_root { | ||
| return Ok(()); | ||
| } | ||
| if self.command.is_global() { | ||
| return Err(WorkspaceRootError::ConflictsWithGlobal); | ||
| } | ||
| // The upward walk needs a real path to climb: `--dir` still holds | ||
| // whatever was typed, and its default `.` has no parent to walk to. | ||
| // Dispatch canonicalizes `dir` again later, which is idempotent. | ||
| let from = dunce::canonicalize(&self.dir).unwrap_or_else(|_| self.dir.clone()); | ||
| let workspace_dir = pacquet_workspace::find_workspace_dir(&from) | ||
| .map_err(|_| WorkspaceRootError::NotInWorkspace)? | ||
| .ok_or(WorkspaceRootError::NotInWorkspace)?; | ||
| self.dir = workspace_dir; |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 6 --type rust 'fn\s+find_workspace_dir\b' pnpm
rg -n -C 4 --type rust 'apply_workspace_root|workspace_root_outside_a_workspace' pnpmRepository: pnpm/pnpm
Length of output: 4761
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '--- cli_command.rs relevant section ---\n'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs
printf '\n--- root_finder.rs relevant section ---\n'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs
printf '\n--- workspace_root.rs relevant tests ---\n'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs
printf '\n--- TypeScript pnpm implementation search for --workspace-root/dir handling ---\n'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || trueRepository: pnpm/pnpm
Length of output: 238
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Behavioral probe: model path walking semantics relevant to `../../outside-missing` and existing workspace
python3 - <<'PY'
from pathlib import Path
import os, tempfile
import shutil
def walk_to_root(cwd: str):
"""Minimal model of the existing Rust walk: start from given entry point, keep climbing parent for missing cwd only,
then return first entry point that passes manifest predicate if any, or None."""
p = Path(cwd)
visited_entries = {str(p)}
attempts = 0
while True:
attempts += 1
if p.name == ".pnpm-workspace.yaml":
return p.parent
if p.name == "pnpm-workspace.yaml":
return p.parent
if p == Path.cwd():
return None
q = p.parent
if not (q / "package.json").exists():
if p not in visited_entries:
return None
p = q
continue
if len(attempts) > 20:
raise RuntimeError("infinite")
p = q
with tempfile.TemporaryDirectory() as td:
td = Path(td)
root = td / "root"
root.mkdir()
dir1 = root / "dir1"
dir1.mkdir()
(root / "package.json").write_text("{}")
(root / ".pnpm-workspace.yaml").write_text("packages:\n - 'dir1'\n")
candidate = dir1 / ".." / ".." / "outside-missing"
# Real existing-candidate lookup is not in this scenario; Rust path.walk behavior for candidate that is not symlink here:
print(f"exists before: {candidate.exists()}")
print(f"root_finder equivalent root (from effective dir1): {walk_to_root(str(dir1))}")
# The issue is only if `from` is syntactically canonicalized when current_dir is workspace/root.
old = os.getcwd()
try:
os.chdir(str(root))
print(f"root_finder equivalent root from syntactic sibling via symlink-less traversal when cwd=root:", end=" ")
print(walk_to_root(str(candidate)))
finally:
os.chdir(old)
PYRepository: pnpm/pnpm
Length of output: 330
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- cli_command.rs relevant section ---'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs
echo
echo '--- root_finder.rs relevant section ---'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs
echo
echo '--- workspace_root.rs relevant tests ---'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs
echo
echo '--- TypeScript pnpm implementation search for --workspace-root/dir handling ---'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || true
echo
echo '--- deterministic path-walk probe ---'
python3 - <<'PY'
from pathlib import Path
import tempfile
def root_finder_like_walk(cwd: str):
p = Path(cwd)
attempts = 0
while True:
attempts += 1
name = p.name if p.name else None
if name == ".pnpm-workspace.yaml":
return p.parent
if name == "pnpm-workspace.yaml":
return p.parent
if p == Path.cwd():
return None
q = p.parent
if not (q / "package.json").exists():
if not q.exists():
return None
p = q
continue
if attempts > 20:
raise RuntimeError("infinite")
p = q
with tempfile.TemporaryDirectory() as td:
td = Path(td)
root = td / "root"
root.mkdir()
dir1 = root / "dir1"
dir1.mkdir()
(root / "package.json").write_text("{}")
(root / ".pnpm-workspace.yaml").write_text("packages:\n - 'dir1'\n")
candidate = dir1 / ".." / ".." / "outside-missing"
print(f"current dir: {Path.cwd()}")
print(f"candidate: {candidate}")
print(f"candidate exists: {candidate.exists()}")
print(f"root_finder_like_walk from candidate: {root_finder_like_walk(str(candidate))}")
PYRepository: pnpm/pnpm
Length of output: 139
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- cli_command.rs relevant section ---'
sed -n '130,180p;250,295p' pnpm/crates/cli/src/cli_args/cli_command.rs
echo
echo '--- root_finder.rs relevant section ---'
sed -n '1,140p' pnpm/crates/workspace/src/root_finder.rs
echo
echo '--- workspace_root.rs relevant tests ---'
sed -n '1,140p' pnpm/crates/cli/tests/workspace_root.rs
echo
echo '--- TypeScript pnpm implementation search for --workspace-root/dir handling ---'
rg -n -C 6 'workspace-root|workspaceRoot|apply.*workspace|workspaceRoot|cwd:.*workspace|ERR_PNPM_NOT_IN_WORKSPACE|findWorkspaceDir' pnpm/packages pnpm/cli 2>/dev/null || true
echo
echo '--- deterministic path-walk probe ---'
python3 - <<'PY'
from pathlib import Path
import tempfile
def root_finder_like_walk(cwd: str):
p = Path(cwd)
attempts = 0
while True:
attempts += 1
name = p.name if p.name else None
if name == ".pnpm-workspace.yaml":
return p.parent
if name == "pnpm-workspace.yaml":
return p.parent
if p == Path.cwd():
return None
q = p.parent
if not (q / "package.json").exists():
if not q.exists():
return None
p = q
continue
if attempts > 20:
raise RuntimeError("infinite")
p = q
with tempfile.TemporaryDirectory() as td:
td = Path(td)
root = td / "root"
root.mkdir()
dir1 = root / "dir1"
dir1.mkdir()
(root / "package.json").write_text("{}")
(root / ".pnpm-workspace.yaml").write_text("packages:\n - 'dir1'\n")
candidate = dir1 / ".." / ".." / "outside-missing"
print(f"current dir: {Path.cwd()}")
print(f"candidate: {candidate}")
print(f"candidate exists: {candidate.exists()}")
print(f"root_finder_like_walk from candidate: {root_finder_like_walk(str(candidate))}")
PYRepository: pnpm/pnpm
Length of output: 139
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re, sys
for path in [
Path('pnpm/crates/cli/src/cli_args/cli_command.rs'),
Path('pnpm/crates/workspace/src/root_finder.rs'),
Path('pnpm/crates/cli/tests/workspace_root.rs'),
]:
print(f'\n### {path} exists={path.exists()} size={path.stat().st_size if path.exists() else "n/a"}')
txt = path.read_text(errors='replace')
for needle in ['apply_workspace_root', 'find_workspace_dir', 'workspace_root_outside_a_workspace', 'not_in_workspace']:
matches = [m.start() for m in re.finditer(re.escape(needle), txt, re.I)]
print(f'{needle}: matches={len(matches)}')
path = Path('pnpm/crates/workspace/src/root_finder.rs')
txt = path.read_text(errors='replace')
print('\n--- root_finder walk implementation ---')
for i,line in enumerate(txt.splitlines(),1):
if 'find_workspace_dir_by_walk' in line or 'canonicalize' in line or 'fs::read_dir' in line or 'package.json' in line or '.pnpm-workspace.yaml' in line:
print(f'{i}: {line}')
PYRepository: pnpm/pnpm
Length of output: 975
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
def view(path, lines):
print(f'\n### {path}')
txt = path.read_text(errors='replace')
all_lines = txt.splitlines()
for start,end in [(max(1,line-5), line+5) for line in lines]:
print(f'-- lines {start}-{end} --')
for i in range(start, min(end, len(all_lines))+1):
print(f'{i:4}: {all_lines[i-1]}')
view(Path('pnpm/crates/workspace/src/root_finder.rs'), [1, 60, 105, 140])
view(Path('pnpm/crates/cli/src/cli_args/cli_command.rs'), [140, 260, 281])
view(Path('pnpm/crates/cli/tests/workspace_root.rs'), [80, 105, 130, 160])
for p in [Path('pnpm/crates/workspace/src/root_finder.rs'), Path('pnpm/crates/cli/tests/workspace_root.rs')]:
txt = p.read_text(errors='replace')
print(f'\n--- package.json occurrences in {p} ---')
for i,l in enumerate(txt.splitlines(),1):
if 'package.json' in l:
print(f'{i}: {l}')
PYRepository: pnpm/pnpm
Length of output: 5162
🌐 Web query:
pnpm workspace-root flag package manager official docs
💡 Result:
The --workspace-root (or -w) flag is a global CLI flag in pnpm that allows you to execute commands as if they were started from the root of the workspace, regardless of your current working directory [1][2]. When you use this flag, pnpm redirects the command to the workspace root, which is useful in several scenarios: 1. Adding Dependencies to the Root: By default, pnpm prevents you from adding dependencies to the root workspace package to avoid accidental dependencies being declared at the root level [3]. Using the -w flag bypasses this safety check, allowing you to add, remove, or update packages in the root package.json [3]. 2. Recursive Command Execution: When used with recursive commands (such as pnpm -r or pnpm -w), it alters how the filter works [4]. While recursive commands typically exclude the root project by default [5], adding the --workspace-root flag includes the root project in the execution scope [4]. The workspace root itself is defined by the existence of a pnpm-workspace.yaml file in a directory [6][7].
Citations:
- 1: https://pnpm.io/pnpm-cli
- 2: https://pnpm.io/10.x/pnpm-cli
- 3: https://pnpm.io/cli/add
- 4: feat(cli): support the --workspace-root (-w) flag #13281
- 5: https://pnpm.io/cli/recursive
- 6: https://pnpm.io/pnpm-workspace_yaml
- 7: https://pnpm.io/workspaces
🌐 Web query:
pnpm workspace root flag outside workspace ERR_PNPM_NOT_IN_WORKSPACE behavior
💡 Result:
The ERR_PNPM_NOT_IN_WORKSPACE error is triggered when a pnpm command that requires a workspace environment is executed outside of a valid pnpm workspace [1]. A pnpm workspace is identified by the presence of a pnpm-workspace.yaml file in the root directory [2][3][4]. The workspace-root flag, available as -w or --workspace-root, is designed to allow commands to execute as if they were started from the root of the workspace rather than the current working directory [5][6][7]. When you use -w, you are explicitly instructing pnpm to locate and operate within the context of the workspace root [5][6]. However, the -w flag does not override the requirement that a workspace must exist [1]. If you run a command with the -w flag in a directory that is not part of a pnpm workspace, or in a directory where a pnpm workspace cannot be discovered, pnpm will still raise an ERR_PNPM_NOT_IN_WORKSPACE error because the fundamental prerequisite for a workspace-level operation is missing [1]. In summary: 1. ERR_PNPM_NOT_IN_WORKSPACE: Indicates that the command requires a workspace, but none was found [1]. 2. Workspace-root flag (-w): Tells pnpm to execute at the root of the workspace [5][7]. 3. Interaction: The -w flag is a tool for navigating within an existing workspace; it cannot create a workspace context where one does not exist [1]. If you are outside a workspace, the flag cannot bypass the need for a pnpm-workspace.yaml file [2][1].
Citations:
- 1: feat(cli): support the --workspace-root (-w) flag #13281
- 2: https://pnpm.io/es/workspaces
- 3: https://pnpm.io/ru/10.x/workspaces
- 4: https://pnpm.io/tr/next/workspaces
- 5: https://pnpm.io/es/pnpm-cli
- 6: https://pnpm.io/es/10.x/pnpm-cli
- 7: https://pnpm.io/pnpm-cli
🌐 Web query:
pnpm workspace-root flag outside workspace directory symlink traversal
💡 Result:
There is no direct "workspace-root flag outside workspace directory symlink traversal" vulnerability described as a singular, unified issue in pnpm. However, path traversal and unauthorized symlink creation issues—often involving symlinks and workspace-related operations—have been identified and addressed in recent pnpm versions [1][2][3][4]. The core concern regarding the --workspace-root (-w) flag involves how pnpm determines the workspace root. In some versions, the flag resolves the directory using canonicalization (which follows symlinks) [5]. If a directory is a symlink pointing outside the expected project structure, pnpm may incorrectly identify the workspace root, potentially leading to operations being performed in an unintended directory [5]. Developers have noted this as a security risk, recommending the use of absolute, lexically-normalized paths that do not resolve symlinks for workspace discovery [5]. Separately, pnpm has faced significant path traversal vulnerabilities related to how it handles dependency and configuration paths, which can be exploited even with --ignore-scripts: 1. CVE-2026-50016: This vulnerability involves transitive dependency aliases (e.g., from registry metadata) containing path traversal segments [4][6]. During installation, pnpm used these aliases to construct filesystem paths for symlinking without proper validation, allowing malicious packages to overwrite project files or directories with symlinks [4]. 2. CVE-2026-59195 (GHSA-qrv3-253h-g69c): This involves path traversal in the configDependencies block of pnpm-lock.yaml [1][2][7][3]. Malicious repositories could use crafted package names or versions containing traversal characters to escape the node_modules/.pnpm-config directory, enabling arbitrary symlink creation on the host filesystem [1][2][7]. These vulnerabilities have been patched in recent pnpm releases (e.g., versions 10.34.4, 11.8.0, and others depending on the specific advisory) by implementing strict path validation and rejecting traversal components in configuration and dependency names [2][3][6]. Users are advised to upgrade to the latest versions to mitigate these risks [3].
Citations:
- 1: https://cvereports.com/reports/GHSA-QRV3-253H-G69C
- 2: fix: reject path-traversal config dependency names from the env lockfile #12470
- 3: https://security.snyk.io/vuln/SNYK-JS-PNPM-17660535
- 4: GHSA-hwx4-2j3j-g496
- 5: feat(cli): support the --workspace-root (-w) flag #13281
- 6: https://nvd.nist.gov/vuln/detail/cve-2026-50016
- 7: https://osv.dev/vulnerability/GHSA-qrv3-253h-g69c
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
import re
# Read only the deterministic Rust walk-body shape from the repository source.
src = Path('pnpm/crates/workspace/src/root_finder.rs').read_text()
body = re.search(r'fn find_workspace_dir_by_walk\(cwd: &Path\)(.*?)\n\}', src, re.S).group(1)
print('find_workspace_dir_by_walk body:')
for i, line in enumerate(body.splitlines(), 1):
print(f'{i:3}: {line}')
print('\nContains package.json check:', 'package.json' in body)
print('Uses Path::ancestors:', 'cwd.ancestors()' in body or 'ancestors()' in body)
print('Uses package.json manifest check:', 'package.json' in body)
# Compare against the reviewed fallback behavior: non-canonical path can contain ".."
# ancestors that syntactically climb outside the current-process cwd first.
example = Path('/tmp/root').joinpath('dir1').joinpath('..').joinpath('..').joinpath('outside-missing')
print('\nLexical ancestors of problematic --dir from cwd /tmp/root:')
for i, part in enumerate(example.parents):
print(f'{i+1}: {part}')
PYRepository: pnpm/pnpm
Length of output: 1727
🌐 Web query:
pnpm PR 13281 workspace-root outside workspace pnpm-workspace.yaml workspaceRoot
💡 Result:
The pnpm Pull Request #13281 introduces the --workspace-root (or -w) CLI flag to provide explicit control when executing pnpm commands in a workspace environment [1]. Key features and behaviors of this PR include: - Target Workspace Root: It allows running pnpm commands (such as add) specifically against the root of the workspace, even when executed from a subdirectory [1]. - Command Redirection: When -w is used, it redirects the --dir option to the workspace root, ensuring the command interacts with the root package.json rather than the nearest project manifest [1]. - Error Handling: The PR adds logic to explicitly reject invalid usages of this flag, specifically when running with --global or when outside of a workspace context [1]. It uses standard pnpm error codes like ERR_PNPM_OPTIONS_CONFLICT and ERR_PNPM_NOT_IN_WORKSPACE [1]. - Recursive Commands: It adjusts recursive command selectors to allow targeting only the root project or including it alongside other filtered projects [1]. In the context of pnpm workspaces, the pnpm-workspace.yaml file is the authoritative marker that defines the workspace root [2][3]. Commands are typically executed relative to the nearest detected pnpm-workspace.yaml [4]. The --workspace-root flag provides a mechanism to override default behaviors (such as adding dependencies to a sub-package) by forcing the operation to the defined workspace root [1].
Citations:
- 1: feat(cli): support the --workspace-root (-w) flag #13281
- 2: https://pnpm.io/pnpm-workspace_yaml
- 3: https://pnpm.io/workspaces
- 4: Ignore (nearest) pnpm-workspace.yaml file if it does not include the active package #11656
Reject non-canonical --dir values before locating the workspace.
When canonicalization fails, apply_workspace_root passes the raw --dir to find_workspace_dir(), whose cwd.ancestors() walk remains lexical. A value like <workspace>/../../outside-missing climbs through <workspace>/.. before resolving to the intended outside directory, so -w can select the workspace root even though the requested location is outside it. Propagate canonicalization failures, and map only a successful lookup returning None to ERR_PNPM_NOT_IN_WORKSPACE; add a regression test for this traversal case.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pnpm/crates/cli/src/cli_args/cli_command.rs` around lines 264 - 285, Update
apply_workspace_root to propagate dunce::canonicalize failures instead of
falling back to the raw self.dir; pass only the canonical path to
find_workspace_dir, map a successful None result to
WorkspaceRootError::NotInWorkspace, and add a regression test covering a
traversal path that resolves outside the workspace with a missing target.
Source: Path instructions
|
Closing as a duplicate — We converged on the same design independently: declare The two bot findings on this PR both point at that difference and are already correct on
Nothing here is worth salvaging: the merged PR's tests in Written by an agent (Claude Code, claude-opus-5). |
…kspace (#13297) `pnpm --dir ../../elsewhere add -w foo` from inside a workspace added to that workspace's root instead of failing, when `../../elsewhere` did not exist. pnpm reports ERR_PNPM_NOT_IN_WORKSPACE. `apply_workspace_root` falls back to `std::path::absolute` when the `--dir` cannot be canonicalized, which is what keeps a nonexistent `--dir` inside the workspace working. On Unix that leaves `..` components in place, and `find_workspace_dir` walks ancestors lexically — so the walk climbed back up through the very `..` components that had taken it out of the workspace and found the workspace it had just left. Resolve `..` in the fallback with `pacquet_fs::lexical_normalize` (the existing filesystem-free normalizer) before the walk. A nonexistent `--dir` that stays inside the workspace still resolves to the root, and an existing directory outside it still errors — both already covered by tests. Found by CodeRabbit on #13294, a duplicate of #13281 closed in favor of it; the finding applies to the merged implementation. Verified against the TypeScript CLI: all three `--dir` shapes now agree.
…kspace (pnpm#13297) `pnpm --dir ../../elsewhere add -w foo` from inside a workspace added to that workspace's root instead of failing, when `../../elsewhere` did not exist. pnpm reports ERR_PNPM_NOT_IN_WORKSPACE. `apply_workspace_root` falls back to `std::path::absolute` when the `--dir` cannot be canonicalized, which is what keeps a nonexistent `--dir` inside the workspace working. On Unix that leaves `..` components in place, and `find_workspace_dir` walks ancestors lexically — so the walk climbed back up through the very `..` components that had taken it out of the workspace and found the workspace it had just left. Resolve `..` in the fallback with `pacquet_fs::lexical_normalize` (the existing filesystem-free normalizer) before the walk. A nonexistent `--dir` that stays inside the workspace still resolves to the root, and an existing directory outside it still errors — both already covered by tests. Found by CodeRabbit on pnpm#13294, a duplicate of pnpm#13281 closed in favor of it; the finding applies to the merged implementation. Verified against the TypeScript CLI: all three `--dir` shapes now agree.
Summary
pnpm add -D oxlint@latest oxfmt@latest oxlint-tsgolint@latest -w(#13031) still fails on currentmain. The multi-package half was fixed earlier; what remains is the flag:pacquet had no
-w/--workspace-rootat all. This adds it, implemented where pnpm implements it — as a universal option resolved before dispatch that rewrites--dirto the workspace root. Every command already resolves its project fromdir, so no command needs to know the flag exists.Both of pnpm's guards come along:
-wwith--globalERR_PNPM_OPTIONS_CONFLICT-woutside a workspaceERR_PNPM_NOT_IN_WORKSPACE--globalis per-command in pacquet rather than universal, soCliCommand::is_globalasks the ten commands that expose it;configkeeps its copy on each subcommand'sConfigFlags, hence the small accessor there.One subtlety worth calling out for review: the upward walk runs on a canonicalized path. At this point
--dirstill holds whatever was typed, and its default.has no parent to climb — searching from it reports "not in a workspace" from every directory. Dispatch canonicalizesdiragain later, which is idempotent.Verification
Behavior checked against the built TypeScript bundle rather than inferred from its source — identical in all four cases:
packages/foo/src/utils)pnpm prefix…/wroot/packages/foopnpm prefix -w…/wrootpnpm prefix -g -w--workspace-root may not be used with --globalERR_PNPM_OPTIONS_CONFLICTpnpm prefix -woutside a workspace--workspace-root may only be used inside a workspaceERR_PNPM_NOT_IN_WORKSPACEFour tests in
crates/cli/tests/workspace_root.rs, including the reportedadd -D … -wshape asserting the deps land in the root manifest and not in the member the command ran from. I checked the tests fail against a deliberately neutered re-anchor before committing (2 of 4 fail, the two behavioral ones).just readygreen (6936 tests) andcargo dylintclean.Fixes #13031.
Squash Commit Body
Checklist
pnpm/port, or the description notes what still needs porting.(pacquet-only catch-up: the TypeScript CLI already has
-w.)pnpm changeset) if this PR changes any publishedpackage. Keep it short and written for pnpm users — it becomes a release note.
--help; pnpm.io already documents-w.)Follow-up, deliberately not in this PR
pnpm also refuses a bare
pnpm addat the workspace root when the workspace defines more than one package pattern, telling the user to pass-w(ERR_PNPM_ADDING_TO_ROOT, bypassed byignoreWorkspaceRootCheck). pacquet knows theignore-workspace-root-checkconfig key but has no such guard. That is a separate behavior change — it makes a currently-working command start failing — so it belongs in its own PR rather than riding along with the flag it references.Written by an agent (Claude Code, claude-opus-5).
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.Summary by CodeRabbit
-w/--workspace-rootto run commands against the workspace root from any workspace directory.--workspace-rootwith global mode or using it outside a workspace.