Skip to content

fix: keep args after boolean options as strings - #180

Open
ybai08 wants to merge 1 commit into
cacjs:mainfrom
ybai08:fix/boolean-option-positional-args
Open

ybai08 wants to merge 1 commit into
cacjs:mainfrom
ybai08:fix/boolean-option-positional-args

Conversation

@ybai08

@ybai08 ybai08 commented Oct 17, 2026

Copy link
Copy Markdown

Fixes #162

Problem

Positional args normally come back as strings, but one that follows a boolean option is turned into a number:

const cli = cac()
cli.option('--run', 'Run once')
cli.parse(['node', 'bin', '03', '04']).args          // ['03', '04']
cli.parse(['node', 'bin', '--run', '03', '04']).args // [3, '04']

This happens because mri treats the arg after a boolean flag as a possible value. When the arg is not true or false, mri pushes it back to _, but it runs it through +val first. So 03 turns into 3, 1e3 into 1000 and 0x10 into 16. With vitest, vitest --run 03 passes 3 as the filter, and that breaks string handling further down (see #162). The [123, "123", "123"] output reported in #23 has the same cause.

Fix

Before calling mri, inlineBooleanValues rewrites a boolean option that would take the next arg as its value (e.g. --run or -rw) to the inline form (--run=true). mri then reads the next arg as an ordinary positional arg and keeps it as a string. The check follows mri's own rules: a short group's last letter takes the value, --no-*, =, and empty or dashed next args are skipped, and a true/false next arg is left alone so --run false still sets false. Option values do not change.

Not changed: --run=7 still adds 7 to the args, the same as before. That comes from the same mri branch, but it only happens when someone writes an inline value for a boolean flag.

Testing

  • Added keep args after boolean options as strings to tests/index.test.ts. It fails on main (expected [ 3, '04', 1000 ] to deeply equal [ '03', '04', '1e3' ]) and passes with this change.
  • vitest run (22 passed), eslint ., tsgo --noEmit and prettier --check src tests all pass.
  • Compared parse() on main and on this branch over 200k random argv lists, built from boolean, string and negated options, short groups, --x=v, -, true/false, empty and numeric args. Options and thrown errors matched exactly. The args differed only where main returned a number and this branch returns the original string.

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.

no-command [...args] - first arg munged to number type

1 participant