Skip to content

fix(cli): forward every argument of test, start, and stop to the script - #13344

Merged
zkochan merged 1 commit into
mainfrom
fix-script-command-args
Jul 25, 2026
Merged

zkochan merged 1 commit into
mainfrom
fix-script-command-args

Conversation

@zkochan

@zkochan zkochan commented Jul 25, 2026 •

Copy link
Copy Markdown
Member

Summary

pnpm test --watch fails with a usage error, and pnpm stop --if-present runs pnpm's flag instead of the script's. pnpm has no commands by these names at all — test, start, and stop reach run through the pnpm <script> fallback (run.ts's opts.fallbackCommandUsed branch), so parsing stops at the command name and every later token is the script's.

pacquet registered them as commands, so clap parsed their arguments: test and start declared none and rejected everything, while stop claimed the tokens it recognized.

invocation pnpm pacquet before after
test --watch forwarded usage error ✅
test -- --flag ["--","--flag"] usage error ✅
start --port 3000 forwarded usage error ✅
stop --if-present forwarded taken as pnpm's flag ✅
stop -s forwarded taken as pnpm's flag ✅
stop -- --other=1 ["--","--other=1"] ["--other=1"] ✅

All three now take the single trailing_var_arg positional run got in #13300, through a shared ScriptShortcutArgs, and parse_boundary knows their arguments begin right after the command name. restart is a real command upstream, with its own --if-present, and is left alone.

The leading separator

One case needs more than the shape change. clap consumes the first -- as its own escape until the positional has taken a value — and a shortcut's arguments can open on the separator, because no script name precedes them. leading_separator writes a second -- there for clap to eat.

It keys off the boundary scan reporting that the command is a shortcut, not off the boundary index alone: for run the boundary points past the script name, where clap already keeps the separator, so an index-only rule double-writes pnpm run build -- --flag. The unit tests caught that on the first attempt.

Behavior changes worth calling out

Both follow from these being script shortcuts rather than commands, and both match pnpm — but neither is strictly "the bug", so they should not land unnoticed:

  • pnpm test -s no longer silences pnpm's reporter. -s is now the script's argument. Verified against pnpm, which passes -s through. pnpm -s test still silences.
  • pnpm stop --if-present no longer skips a missing script. pnpm reports Command "stop" not found for exactly that invocation; pnpm --if-present stop is the spelling that skips, and still does.

Each has a test pinning both spellings.

Verification

Every form checked by running both binaries against a script that prints its own argv — 22 invocations across test / start / stop / restart / run / the pnpm <script> fallback, including -- -- x. All match.

Two existing tests encoded the old behavior (shorthands::short_s_expands_for_commands_that_do_not_own_it, restart::stop_without_script_succeeds_with_if_present); both now assert the upstream rule, the latter alongside a new mirror test for the post-command spelling. I confirmed script_shortcuts_forward_every_argument_to_the_script fails when the shortcut list is emptied.

Full gate green: 7071 tests, clippy, dylint, taplo.

Closes #13301

Squash Commit Body

pnpm has no commands by these names: they reach `run` through the
`pnpm <script>` fallback, so parsing stops at the command name and every
later token is the script's. pacquet registered them as commands, so clap
parsed their arguments — `test` and `start` declared none at all and
rejected everything, and `stop` claimed the tokens it recognized:

    pnpm test --watch          usage error        -> forwarded
    pnpm test -- --flag        usage error        -> ["--", "--flag"]
    pnpm stop --if-present     taken as the flag  -> forwarded
    pnpm stop -s               taken as the flag  -> forwarded
    pnpm stop -- --other=1     ["--other=1"]      -> ["--", "--other=1"]

Give all three the single trailing_var_arg shape `run` got in
pnpm/pnpm#13300, through a shared ScriptShortcutArgs, and teach the
parse boundary that their arguments start right after the command name.
`restart` is a real command upstream, with its own --if-present, and is
left as it is.

A leading `--` needs one extra step: clap consumes it as its own escape
until the positional has taken a value, and a shortcut's arguments can
open on it because no script name precedes them. `leading_separator`
writes a second one there, keyed off the boundary scan reporting that the
command is a shortcut — the boundary alone is not enough, since for `run`
it points past the script name, where clap already keeps the separator.

Two consequences worth naming, both of them the parity behavior:
`pnpm test -s` no longer silences pnpm's own reporter, and
`pnpm stop --if-present` no longer skips a missing script — for either,
the flag must precede the command name, as it must under pnpm.

Closes pnpm/pnpm#13301

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.
  • Updated the documentation if needed.

Written by an agent (Claude Code, claude-opus-5).


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Script shortcuts such as test, start, and stop now forward all trailing arguments to the requested script.
    • Arguments resembling flags, including --if-present and -s, are passed through correctly.
    • Explicit -- separators are preserved when invoking shortcut scripts.
  • Tests
    • Added coverage for argument forwarding, separator handling, and script lifecycle behavior.

pnpm has no commands by these names: they reach `run` through the
`pnpm <script>` fallback, so parsing stops at the command name and every
later token is the script's. pacquet registered them as commands, so clap
parsed their arguments — `test` and `start` declared none at all and
rejected everything, and `stop` claimed the tokens it recognized:

    pnpm test --watch          usage error        -> forwarded
    pnpm test -- --flag        usage error        -> ["--", "--flag"]
    pnpm stop --if-present     taken as the flag  -> forwarded
    pnpm stop -s               taken as the flag  -> forwarded
    pnpm stop -- --other=1     ["--other=1"]      -> ["--", "--other=1"]

Give all three the single trailing_var_arg shape `run` got in
#13300, through a shared ScriptShortcutArgs, and teach the
parse boundary that their arguments start right after the command name.
`restart` is a real command upstream, with its own --if-present, and is
left as it is.

A leading `--` needs one extra step: clap consumes it as its own escape
until the positional has taken a value, and a shortcut's arguments can
open on it because no script name precedes them. `leading_separator`
writes a second one there, keyed off the boundary scan reporting that the
command is a shortcut — the boundary alone is not enough, since for `run`
it points past the script name, where clap already keeps the separator.

Two consequences worth naming, both of them the parity behavior:
`pnpm test -s` no longer silences pnpm's own reporter, and
`pnpm stop --if-present` no longer skips a missing script — for either,
the flag must precede the command name, as it must under pnpm.

Closes #13301

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings July 25, 2026 12:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Script shortcut argument forwarding

Layer / File(s) Summary
Preserve shortcut argument boundaries
pnpm/crates/cli/src/parse_boundary.rs, pnpm/crates/cli/src/leading_separator.rs, pnpm/crates/cli/src/lib.rs, pnpm/crates/cli/src/*/tests.rs
Shortcut boundaries are classified and leading -- separators are preserved before clap parsing.
Define shortcut argument parsing
pnpm/crates/cli/src/cli_args.rs, pnpm/crates/cli/src/cli_args/cli_command.rs, pnpm/crates/cli/src/cli_args/script_shortcut.rs, pnpm/crates/cli/src/cli_args/pre_command.rs
ScriptShortcutArgs captures trailing tokens for test, start, and stop, and command variants carry those arguments.
Route arguments to script execution
pnpm/crates/cli/src/cli_args/dispatch.rs, pnpm/crates/cli/src/cli_args/dispatch_script.rs, pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs
Shortcut arguments are converted to RunArgs and passed through test, start, and stop execution paths.
Validate forwarding behavior
pnpm/crates/cli/src/shorthands/tests.rs, pnpm/crates/cli/tests/restart.rs, pnpm/crates/cli/tests/run.rs, .changeset/pacquet-script-shortcut-args.md
Tests cover flag-shaped arguments, separators, shortcut variants, and --if-present ordering; the changeset documents the behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI as pacquet CLI
  participant Parser as clap parser
  participant Dispatch as dispatch_script
  participant Script as package script
  CLI->>CLI: Preserve leading separator
  CLI->>Parser: Parse test/start/stop arguments
  Parser->>Dispatch: Pass ScriptShortcutArgs
  Dispatch->>Script: Forward all trailing tokens
Loading

Assessment against linked issues

Objective Addressed Explanation
Forward trailing arguments for pnpm test and pnpm start, including -- [#13301] ✅
Ensure shortcut argument handling covers flag-shaped tokens without wrapper parsing errors [#13301] ✅

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#13300 — Changes the same Rust script execution plumbing for preserving and forwarding script arguments.
  • pnpm/pnpm#13303 — Modifies argv transformation to preserve user-provided -- separators.
  • pnpm/pnpm#13309 — Provides related parse-boundary work used to determine forwarded argv.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-script-command-args

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix script shortcuts (test/start/stop) to forward argv verbatim

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Treat test, start, and stop as script shortcuts that accept trailing argv.
• Preserve a leading -- so forwarded script args keep their separator.
• Add regression tests and a changeset to match upstream pnpm behavior.
Diagram

graph TD
A["argv (OsString[])"] --> G["parse_boundary scan"] --> B["flag_relocation"] --> C["leading_separator"] --> D["clap parse (CliArgs)"] --> H["ScriptShortcutArgs"] --> E["dispatch_script"] --> F["run (RunArgs)"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Remove `test/start/stop` as clap subcommands entirely
  • ➕ Perfectly mirrors pnpm’s “unknown command -> script fallback” behavior
  • ➕ Avoids any chance of clap consuming shortcut arguments
  • ➖ May reduce discoverability/help/completions if the project relies on explicit subcommands
  • ➖ More invasive CLI surface-area change (breaking docs/tooling expectations)
2. Parse `test/start/stop` with a raw-argv capture hook instead of `trailing_var_arg`
  • ➕ Could avoid the special-case leading_separator pass by handling -- manually
  • ➕ Keeps subcommands explicit while bypassing clap option parsing for them
  • ➖ More custom parsing logic and edge cases to maintain
  • ➖ Harder to keep consistent with other pre-clap passes like boundary detection/flag relocation
3. Treat `--if-present` as global-only and error if it appears after shortcuts
  • ➕ Prevents the behavioral footgun where stop --if-present no longer skips missing scripts
  • ➕ Clearer user feedback
  • ➖ Diverges from pnpm semantics, which forward everything after shortcut name
  • ➖ Introduces a nonstandard exception that users must learn

Recommendation: Current approach is the best fit: model test/start/stop as script shortcuts with a single trailing_var_arg positional and teach boundary/argv pre-processing about that shape. It matches pnpm’s semantics, fixes the reported parsing failures, and is well-covered by targeted regression tests (including the subtle leading -- case).

Files changed (15) +283 / -48

Bug fix (7) +145 / -35
cli_command.rsMake test/start/stop carry ScriptShortcutArgs instead of owning options +6/-6

Make test/start/stop carry ScriptShortcutArgs instead of owning options

• Changes 'CliCommand::{Test,Start,Stop}' variants to take 'ScriptShortcutArgs' so all tokens after the command name are captured as script argv. Updates internal command classification logic accordingly and removes 'StopArgs' usage.

pnpm/crates/cli/src/cli_args/cli_command.rs

dispatch.rsRoute test/start/stop through dispatch with shortcut args +2/-2

Route test/start/stop through dispatch with shortcut args

• Updates dispatch routing so 'test' and 'start' pass the parsed 'ScriptShortcutArgs' into 'dispatch_script'. This ensures runtime uses the same forwarded argv that clap captured.

pnpm/crates/cli/src/cli_args/dispatch.rs

dispatch_script.rsUnify test/start/stop execution by converting shortcut args into RunArgs +23/-21

Unify test/start/stop execution by converting shortcut args into RunArgs

• Refactors 'test'/'start'/'stop' helpers to accept 'ScriptShortcutArgs' and build 'RunArgs' via 'into_run_args(script_name, if_present)'. Removes the local helper that constructed 'RunArgs' and adjusts non-recursive 'stop' execution to use the new 'ScriptShortcutArgs::run' API.

pnpm/crates/cli/src/cli_args/dispatch_script.rs

script_shortcut.rsAdd ScriptShortcutArgs to capture trailing script argv for shortcuts +47/-0

Add ScriptShortcutArgs to capture trailing script argv for shortcuts

• Introduces a shared 'ScriptShortcutArgs' struct using clap 'trailing_var_arg' + 'allow_hyphen_values' to capture forwarded script tokens verbatim. Provides helpers to convert into 'RunArgs' or execute directly, and documents why shortcuts must not declare their own options.

pnpm/crates/cli/src/cli_args/script_shortcut.rs

leading_separator.rsPreserve a leading '--' for forwarded shortcut argv +36/-0

Preserve a leading '--' for forwarded shortcut argv

• Adds an argv pre-processing pass that detects script shortcuts and duplicates a '--' at the exact boundary index so clap consumes one escape token while preserving the user’s separator for the script. Uses 'parse_boundary::command_boundary' metadata to avoid interfering with 'run'/other commands.

pnpm/crates/cli/src/leading_separator.rs

lib.rsWire leading_separator pass into CLI argv preprocessing +4/-0

Wire leading_separator pass into CLI argv preprocessing

• Invokes 'preserve_leading_separator' after flag relocation and before clap parsing. This ensures the '--' handling fix applies consistently to all entrypoints into clap parsing.

pnpm/crates/cli/src/lib.rs

parse_boundary.rsTeach boundary scanning about script shortcuts and return richer metadata +27/-6

Teach boundary scanning about script shortcuts and return richer metadata

• Adds 'SCRIPT_SHORTCUTS' and extends boundary detection to return 'CommandBoundary { index, is_script_shortcut }'. Updates 'passthrough_from' and boundary logic so shortcuts start forwarding immediately after the command name (unlike 'run', which skips the script name), enabling correct separator preservation and argument forwarding.

pnpm/crates/cli/src/parse_boundary.rs

Refactor (2) +3 / -3
cli_args.rsRegister new script_shortcut args module and drop stop module +1/-1

Register new script_shortcut args module and drop stop module

• Adds 'script_shortcut' module to the CLI args tree and removes the dedicated 'stop' args module from exports. This aligns the args layout with the new shared shortcut argument type.

pnpm/crates/cli/src/cli_args.rs

pre_command.rsUpdate command_name mapping for new CliCommand variant shapes +2/-2

Update command_name mapping for new CliCommand variant shapes

• Adjusts 'command_name' pattern matches to account for 'Test(_)' and 'Start(_)' now carrying args. Behavior remains the same, but the mapping compiles with the new enum variants.

pnpm/crates/cli/src/cli_args/pre_command.rs

Tests (5) +130 / -10
tests.rsMigrate stop in-process tests to ScriptShortcutArgs +7/-7

Migrate stop in-process tests to ScriptShortcutArgs

• Updates existing 'stop' script execution unit tests to construct and run 'ScriptShortcutArgs' rather than the deleted 'StopArgs'. Keeps coverage for missing-script behavior with and without 'if_present'.

pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs

tests.rsAdd unit tests for leading '--' preservation behavior +56/-0

Add unit tests for leading '--' preservation behavior

• Covers shortcut commands opening on '--', separators after an initial arg, 'run' with a script name, global options preceding the command, and commands that should leave separators to clap. Ensures argv rewriting is precise and does not double-write 'run build -- --flag'.

pnpm/crates/cli/src/leading_separator/tests.rs

tests.rsAdjust '-s' shorthand tests: shortcuts now forward '-s' to scripts +5/-1

Adjust '-s' shorthand tests: shortcuts now forward '-s' to scripts

• Removes the expectation that 'pnpm test -s' expands to '--reporter=silent' and adds coverage ensuring 'test/start/stop' leave '-s' untouched as a script argument. Retains behavior for pre-command 'pnpm -s test' and for the generic script fallback.

pnpm/crates/cli/src/shorthands/tests.rs

restart.rsUpdate integration tests for '--if-present' placement with stop shortcut +23/-2

Update integration tests for '--if-present' placement with stop shortcut

• Changes the success case to require '--if-present' before 'stop', and adds a new test asserting 'stop --if-present' fails when the script is missing. This pins the intentional behavior change that post-command flags are script-owned for shortcuts.

pnpm/crates/cli/tests/restart.rs

run.rsAdd integration test ensuring shortcuts forward all argv including '--' +39/-0

Add integration test ensuring shortcuts forward all argv including '--'

• Adds a Unix-only test that creates scripts which record argv and verifies 'test/start/stop' forward tokens verbatim (including '--' and pnpm-looking flags like '--if-present'/'-s'). Validates end-to-end behavior through clap parsing and dispatch.

pnpm/crates/cli/tests/run.rs

Documentation (1) +5 / -0
pacquet-script-shortcut-args.mdAdd changeset documenting script-shortcut argv forwarding +5/-0

Add changeset documenting script-shortcut argv forwarding

• Introduces a patch changeset explaining that 'test'/'start'/'stop' now forward all post-command tokens to the script, including '--', matching pnpm behavior. Calls out prior failures ('--watch', '--port') and flag collisions ('--if-present', '-s').

.changeset/pacquet-script-shortcut-args.md

@greptile-apps

greptile-apps Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge with no actionable correctness or security issues identified.

The shortcut boundary, separator preservation, clap argument shape, and direct and recursive dispatch paths consistently preserve script arguments while retaining the intended missing-script semantics.

Reviews (1): Last reviewed commit: "fix(cli): forward every argument of test..." | Re-trigger Greptile

@github-actions

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     10.4±0.17ms    35.9 MB/sec    1.01     10.5±0.15ms    35.5 MB/sec
packument/parse                1.01     37.3±0.46µs  1780.5 MB/sec    1.00     36.8±0.41µs  1802.8 MB/sec
tarball/download_dependency    1.00      2.7±0.07ms  1589.5 KB/sec    1.00      2.7±0.07ms  1596.6 KB/sec

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs (1)

61-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use regular comments for private-test rationale. These /// blocks attach documentation to private test functions/helpers while narrating test behavior rather than documenting a public API contract.

  • pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs#L61-L61: change the test-driver rationale to //.
  • pnpm/crates/cli/tests/restart.rs#L182-L184: retain only the ordering invariant as a regular comment.
  • pnpm/crates/cli/tests/restart.rs#L201-L203: retain only the trailing-argument invariant as a regular comment.
  • pnpm/crates/cli/tests/run.rs#L741-L744: retain the fallback-parity rationale as a regular comment.

As per coding guidelines, “Use rustdoc comments for public API contracts and regular comments for implementation rationale.”

🤖 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/script_shortcut/tests.rs` at line 61, The test
rationale comments in
pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs:61-61,
pnpm/crates/cli/tests/restart.rs:182-184,
pnpm/crates/cli/tests/restart.rs:201-203, and
pnpm/crates/cli/tests/run.rs:741-744 should use regular comments instead of
rustdoc comments. Replace the `///` markers at each site with `//`, retaining
only the ordering invariant, trailing-argument invariant, fallback-parity
rationale, and ScriptShortcutArgs::run test-driver rationale respectively.

Sources: Coding guidelines, Path instructions

pnpm/crates/cli/tests/run.rs (1)

745-774: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Make the forwarding assertion lossless and cross-platform.

#[cfg(unix)] leaves this CLI behavior untested on Windows, while "$*" joins arguments and cannot prove token boundaries were preserved. Use a platform-neutral recorder and compare an encoded argument sequence, including empty and whitespace-containing arguments.

Per REVIEW_GUIDE.md, CLI wiring regressions need e2e coverage and must be cross-platform where relevant.

🤖 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/tests/run.rs` around lines 745 - 774, Update
script_shortcuts_forward_every_argument_to_the_script to remove the Unix-only
restriction and use a cross-platform argument recorder. Encode each received
argument with an unambiguous delimiter or structured format so empty and
whitespace-containing values retain their boundaries, then extend the cases and
assertions to compare the complete encoded argument sequence, including the
existing flag and “--” scenarios.

Source: Path instructions

🤖 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.

Nitpick comments:
In `@pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs`:
- Line 61: The test rationale comments in
pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs:61-61,
pnpm/crates/cli/tests/restart.rs:182-184,
pnpm/crates/cli/tests/restart.rs:201-203, and
pnpm/crates/cli/tests/run.rs:741-744 should use regular comments instead of
rustdoc comments. Replace the `///` markers at each site with `//`, retaining
only the ordering invariant, trailing-argument invariant, fallback-parity
rationale, and ScriptShortcutArgs::run test-driver rationale respectively.

In `@pnpm/crates/cli/tests/run.rs`:
- Around line 745-774: Update
script_shortcuts_forward_every_argument_to_the_script to remove the Unix-only
restriction and use a cross-platform argument recorder. Encode each received
argument with an unambiguous delimiter or structured format so empty and
whitespace-containing values retain their boundaries, then extend the cases and
assertions to compare the complete encoded argument sequence, including the
existing flag and “--” scenarios.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 463b9f98-ce06-4e98-8151-9b864b31ebc0

📥 Commits

Reviewing files that changed from the base of the PR and between f7e1fee and 2987282.

📒 Files selected for processing (16)
  • .changeset/pacquet-script-shortcut-args.md
  • pnpm/crates/cli/src/cli_args.rs
  • pnpm/crates/cli/src/cli_args/cli_command.rs
  • pnpm/crates/cli/src/cli_args/dispatch.rs
  • pnpm/crates/cli/src/cli_args/dispatch_script.rs
  • pnpm/crates/cli/src/cli_args/pre_command.rs
  • pnpm/crates/cli/src/cli_args/script_shortcut.rs
  • pnpm/crates/cli/src/cli_args/script_shortcut/tests.rs
  • pnpm/crates/cli/src/cli_args/stop.rs
  • pnpm/crates/cli/src/leading_separator.rs
  • pnpm/crates/cli/src/leading_separator/tests.rs
  • pnpm/crates/cli/src/lib.rs
  • pnpm/crates/cli/src/parse_boundary.rs
  • pnpm/crates/cli/src/shorthands/tests.rs
  • pnpm/crates/cli/tests/restart.rs
  • pnpm/crates/cli/tests/run.rs
💤 Files with no reviewable changes (1)
  • pnpm/crates/cli/src/cli_args/stop.rs

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 25, 2026
@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (2) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 24 rules

Grey Divider


Remediation recommended

1. leading_separator comment uses past tense 📘 Rule violation ⚙ Maintainability
Description
A new module-level comment uses historical phrasing (was already right) rather than describing
current behavior. This conflicts with the rule requiring comments to document current behavior, not
historical implementations.
Code

pnpm/crates/cli/src/leading_separator.rs[R14-18]

+//! Only the script shortcuts can hit this: every other command that
+//! forwards a command line puts a script or command name ahead of the
+//! separator, which lands a value in the positional first, and from there
+//! clap keeps every `--` verbatim — the reason `pnpm run build -- --flag`
+//! was already right.
Relevance

⭐⭐⭐ High

Team has accepted rewording comments to present-tense/current-behavior wording in this Rust CLI
code.

PR-#12919
PR-#13207

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance ID 772199 forbids comments that describe historical implementations using past-tense
phrasing. The added comment explicitly says pnpm run build -- --flag was already right, which is
historical wording rather than a statement of current behavior.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/cli/src/leading_separator.rs[14-18]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The doc comment in `leading_separator.rs` references past behavior using `was already right`, which is discouraged by the comment policy.

## Issue Context
Comments should describe what the code does now; historical notes should live in PR description/commit history.

## Fix Focus Areas
- pnpm/crates/cli/src/leading_separator.rs[14-18]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Unnecessary clap rebuild 🐞 Bug ➹ Performance
Description
preserve_leading_separator() always calls parse_boundary::command_boundary(), which constructs a
fresh clap Command via CliArgs::command() even when argv doesn’t contain a separator and no
mutation occurs. This adds avoidable per-invocation startup overhead on the CLI hot path.
Code

pnpm/crates/cli/src/leading_separator.rs[R23-31]

+pub(crate) fn preserve_leading_separator(mut argv: Vec<OsString>) -> Vec<OsString> {
+    let Some(boundary) = command_boundary(&argv).filter(|boundary| boundary.is_script_shortcut)
+    else {
+        return argv;
+    };
+    if argv.get(boundary.index).is_none_or(|token| token != "--") {
+        return argv;
+    }
+    argv.insert(boundary.index, OsString::from("--"));
Relevance

⭐⭐⭐ High

They’ve accepted optimizing away repeated CliArgs::command()/clap rebuilds on boundary/argv
parsing hot paths.

PR-#13309

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new pass is called for every invocation in run_cli(), and it calls command_boundary().
command_boundary() constructs a fresh clap Command (CliArgs::command()), so this introduces an
extra full clap-tree build even in cases where the function returns argv unchanged.

pnpm/crates/cli/src/lib.rs[60-72]
pnpm/crates/cli/src/leading_separator.rs[23-33]
pnpm/crates/cli/src/parse_boundary.rs[66-73]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`preserve_leading_separator()` currently computes the command boundary by calling `parse_boundary::command_boundary(&argv)`, and `command_boundary()` builds a new clap command tree (`CliArgs::command()`). This happens on every CLI invocation because `run_cli()` unconditionally calls `preserve_leading_separator()`, even when argv has no `--` and no rewrite is necessary.

### Issue Context
The CLI already constructs a clap `Command` (`with_boolean_negations(CliArgs::command())`) earlier in startup and uses it for other pre-clap passes (shorthands and flag relocation). Adding another full clap-tree build in the new pass is an avoidable cost.

### Fix Focus Areas
- pnpm/crates/cli/src/leading_separator.rs[23-31]
- pnpm/crates/cli/src/parse_boundary.rs[66-83]
- pnpm/crates/cli/src/lib.rs[65-72]

### Suggested fix approaches (pick one)
1) **Fast-path early return**: In `preserve_leading_separator`, first check for the presence of any `"--"` token in `argv`; if none, return immediately *before* calling `command_boundary()`.
2) **Reuse existing clap command**: Refactor boundary detection so it can operate on the already-built `Command` from `run_cli()` (e.g., add a `command_boundary_with_command(cmd: &Command, argv: &[OsString])` helper and call it from `preserve_leading_separator`).

Either approach removes the unconditional extra clap-tree construction and reduces startup work for the common case where no leading separator exists.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset declares only pacquet and does not include a pnpm entry. This violates the
requirement that changesets explicitly declare pnpm with a valid bump type.
Code

.changeset/pacquet-script-shortcut-args.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

⭐ Low

Exact precedents show team rejects adding required pnpm entry to pacquet-only changesets.

PR-#12991
PR-#13304
PR-#13297

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Compliance ID 713436 requires changeset front-matter to include a pnpm entry with a valid bump
type. The added changeset front-matter contains only "pacquet": patch and no pnpm entry.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/pacquet-script-shortcut-args.md[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The changeset `.changeset/pacquet-script-shortcut-args.md` is missing a required `pnpm` entry in its front-matter.

## Issue Context
Repo policy requires changesets to explicitly include the `pnpm` package with an appropriate bump type (`patch`/`minor`/`major`).

## Fix Focus Areas
- .changeset/pacquet-script-shortcut-args.md[1-3]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.04%. Comparing base (cf8fdc4) to head (2987282).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13344   +/-   ##
=======================================
  Coverage   87.04%   87.04%           
=======================================
  Files         534      535    +1     
  Lines       91806    91824   +18     
=======================================
+ Hits        79911    79932   +21     
+ Misses      11895    11892    -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zkochan
zkochan merged commit c3754b1 into main Jul 25, 2026
34 checks passed
@zkochan
zkochan deleted the fix-script-command-args branch July 25, 2026 13:05
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…pt (pnpm#13344)

pnpm has no commands by these names: they reach `run` through the
`pnpm <script>` fallback, so parsing stops at the command name and every
later token is the script's. pacquet registered them as commands, so clap
parsed their arguments — `test` and `start` declared none at all and
rejected everything, and `stop` claimed the tokens it recognized:

    pnpm test --watch          usage error        -> forwarded
    pnpm test -- --flag        usage error        -> ["--", "--flag"]
    pnpm stop --if-present     taken as the flag  -> forwarded
    pnpm stop -s               taken as the flag  -> forwarded
    pnpm stop -- --other=1     ["--other=1"]      -> ["--", "--other=1"]

Give all three the single trailing_var_arg shape `run` got in
pnpm#13300, through a shared ScriptShortcutArgs, and teach the
parse boundary that their arguments start right after the command name.
`restart` is a real command upstream, with its own --if-present, and is
left as it is.

A leading `--` needs one extra step: clap consumes it as its own escape
until the positional has taken a value, and a shortcut's arguments can
open on it because no script name precedes them. `leading_separator`
writes a second one there, keyed off the boundary scan reporting that the
command is a shortcut — the boundary alone is not enough, since for `run`
it points past the script name, where clap already keeps the separator.

Two consequences worth naming, both of them the parity behavior:
`pnpm test -s` no longer silences pnpm's own reporter, and
`pnpm stop --if-present` no longer skips a missing script — for either,
the flag must precede the command name, as it must under pnpm.

Closes pnpm#13301

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Jul 27, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pacquet: pnpm test and pnpm start reject trailing arguments (pnpm test --watch fails)

3 participants