Skip to content

fix: subcommand resolution incorrectly consumes flag values#231

Merged
pi0 merged 3 commits intounjs:mainfrom
wyattjoh:fix/subcommand-flag-values
Mar 15, 2026
Merged

fix: subcommand resolution incorrectly consumes flag values#231
pi0 merged 3 commits intounjs:mainfrom
wyattjoh:fix/subcommand-flag-values

Conversation

@wyattjoh
Copy link
Copy Markdown
Contributor

@wyattjoh wyattjoh commented Mar 10, 2026

Summary

  • Fix subcommand resolution when parent commands define string/enum args alongside subCommands
  • Replace naive "first non-dash token" heuristic with findSubCommandIndex() that uses arg definitions to skip flag values
  • Previously, --name Citty build would treat "Citty" as the subcommand name instead of "build"

Problem

When a parent command defines args with type: "string" or type: "enum" alongside subCommands, the subcommand resolver uses rawArgs.findIndex(arg => !arg.startsWith("-")) to find the subcommand token. This picks up the flag's value (e.g. "Citty" from --name Citty) instead of the actual subcommand name.

Closes #133

Solution

Added findSubCommandIndex() helper in src/command.ts that:

  1. Builds a set of flags that consume a value (string/enum types + aliases in all case variants)
  2. Walks rawArgs, skipping value tokens consumed by those flags
  3. Returns the index of the first non-flag, non-consumed token (the subcommand)

Updated both runCommand() and resolveSubCommand() to use this helper.

Test plan

  • Parent string arg + subcommand: --name Citty build
  • String arg with = syntax: --name=Citty build
  • String arg with alias: -n Citty build
  • Parent enum arg: --env prod build
  • Boolean arg doesn't consume next token: --verbose build
  • resolveSubCommand with parent string args
  • All 63 existing + new tests pass
  • No type errors

Summary by CodeRabbit

  • Bug Fixes

    • Improved subcommand resolution to correctly handle parent command arguments in various formats (flags, aliases, enums, booleans, and value forms), ensuring accurate subcommand selection and preventing incorrect consumption of following tokens.
  • Tests

    • Added comprehensive tests covering subcommand scenarios with parent command arguments and resolution behavior to prevent regressions and validate edge cases.

When a parent command defines both subCommands and string/enum args,
the subcommand resolver treats flag values as subcommand names. For
example, `--name Citty build` fails because "Citty" is the first
non-dash token and gets interpreted as a subcommand name.

Replace the naive `findIndex(arg => !arg.startsWith("-"))` heuristic
with a helper that uses the parent command's arg definitions to skip
over value tokens consumed by string/enum flags.

Closes unjs#133
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 10, 2026

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 97c65677-1d06-45ac-8861-3ac68cf33daa

📥 Commits

Reviewing files that changed from the base of the PR and between fb978e3 and 931bee1.

📒 Files selected for processing (1)
  • src/command.ts

📝 Walkthrough

Walkthrough

Replaces the previous non-flag heuristic with a new internal helper findSubCommandIndex() that scans raw args while skipping values of value-bearing flags (using resolved arg definitions); updates runCommand() and resolveSubCommand() to use it and imports camelCase from "scule". No public API changes.

Changes

Cohort / File(s) Summary
Subcommand parsing & helpers
src/command.ts
Adds findSubCommandIndex(rawArgs, argsDef) and _isValueFlag(flag, argsDef) to locate subcommand tokens while ignoring values of value-bearing flags; replaces prior non-flag token heuristic in runCommand() and resolveSubCommand(); imports camelCase from scule.
Tests: subcommand resolution
test/main.test.ts
Adds tests under "sub command with parent args" and resolveSubCommand to verify subcommand detection when parent defines string/enum/alias/boolean args and ensure subcommand tokens aren't consumed as flag values.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 I hopped through flags and tokens bright,

skipped the values, found the command by light.
No more mistook a sub for a flag,
I twitched my nose and gave a glad wag.
— a rabbit, parsing in the night

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly identifies the main issue being fixed: subcommand resolution incorrectly consuming flag values as subcommand tokens.
Linked Issues check ✅ Passed The changes directly address issue #133 by implementing a findSubCommandIndex helper that properly skips flag values when detecting subcommands, supporting string/enum/alias arguments with correct value consumption logic.
Out of Scope Changes check ✅ Passed All code changes are focused on the subcommand resolution bug fix, with comprehensive test coverage for the specific scenarios outlined in issue #133; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/command.ts`:
- Around line 21-30: The loop that scans rawArgs (used by runCommand() /
resolveSubCommand()) currently returns the first bare token unconditionally,
causing ambiguity when a parent command defines positional args; update the
logic so that when encountering a bare token it first checks the current
command's subCommands map for that token and only treat it as a subcommand if
present; if the current command declares positional parameters (e.g.,
command.positional or command.positionals length > 0) and the token is not a
known subcommand, treat it as a positional (do not return its index as a
subcommand) or else throw a clear validation error when a command defines both
positionals and subCommands and a token could match both, ensuring valuedFlags
and the existing skip-i logic remain unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 707119f8-a441-44c9-aed5-adaab6ea9d8d

📥 Commits

Reviewing files that changed from the base of the PR and between 29dfd29 and 8d0feae.

📒 Files selected for processing (2)
  • src/command.ts
  • test/main.test.ts

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 15, 2026

Codecov Report

❌ Patch coverage is 95.45455% with 1 line in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@29dfd29). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/command.ts 95.45% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #231   +/-   ##
=======================================
  Coverage        ?   96.95%           
=======================================
  Files           ?        7           
  Lines           ?      328           
  Branches        ?      123           
=======================================
  Hits            ?      318           
  Misses          ?        9           
  Partials        ?        1           

☔ View full report in Codecov by Sentry.
📢 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.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/command.ts (1)

92-118: Add explicit regression tests for -- end-of-options semantics.

findSubCommandIndex intentionally stops scanning at --; adding tests for this behavior will lock expected dispatch semantics and prevent future regressions.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/command.ts` around lines 92 - 118, Add explicit regression tests for the
end-of-options semantics in findSubCommandIndex: write unit tests that call
findSubCommandIndex with rawArgs arrays that include "--" (e.g. ["--",
"subcmd"], flags before then "--", and flags with values before "--") and assert
it returns -1 and does not treat tokens after "--" as flags; also add tests
showing that valuedFlags handling (the valuedFlags Set built from ArgsDef) still
skips flag values before "--" but stops scanning once "--" is encountered.
Reference the function name findSubCommandIndex, the rawArgs parameter, and the
valuedFlags behavior when creating the tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/command.ts`:
- Around line 92-118: Add explicit regression tests for the end-of-options
semantics in findSubCommandIndex: write unit tests that call findSubCommandIndex
with rawArgs arrays that include "--" (e.g. ["--", "subcmd"], flags before then
"--", and flags with values before "--") and assert it returns -1 and does not
treat tokens after "--" as flags; also add tests showing that valuedFlags
handling (the valuedFlags Set built from ArgsDef) still skips flag values before
"--" but stops scanning once "--" is encountered. Reference the function name
findSubCommandIndex, the rawArgs parameter, and the valuedFlags behavior when
creating the tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9a914a6d-de5f-4114-802f-904ff62eaf0c

📥 Commits

Reviewing files that changed from the base of the PR and between 8d0feae and fb978e3.

📒 Files selected for processing (1)
  • src/command.ts

Replace Set-based precomputation with direct iteration and camelCase normalization.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link
Copy Markdown
Member

@pi0 pi0 left a comment

Choose a reason for hiding this comment

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

Thnx! I have done a refactor to reduce cost (931bee1). Tests still pass but please LMK if you found an issue with it!

@pi0 pi0 merged commit 69252d4 into unjs:main Mar 15, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Non positional arguments of main command usage does not allow to use any other commands

2 participants