Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: throw error on unused args #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/CAC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,11 @@ class CAC extends EventEmitter {
this.unsetMatchedCommand()
}

if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
if (
this.options.version &&
this.showVersionOnExit &&
this.matchedCommandName == null
) {
this.outputVersion()
run = false
this.unsetMatchedCommand()
Expand Down Expand Up @@ -328,6 +332,8 @@ class CAC extends EventEmitter {

command.checkRequiredArgs()

command.checkUnusedArgs()

const actionArgs: any[] = []
command.args.forEach((arg, index) => {
if (arg.variadic) {
Expand Down
16 changes: 16 additions & 0 deletions src/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,22 @@ class Command {
}
}
}

/**
* Check if the number of args is more than expected
*/
checkUnusedArgs() {
const hasVariadicArg = this.args.some((arg) => arg.variadic)
const maximumArgsCount = hasVariadicArg ? Infinity : this.args.length

if (maximumArgsCount < this.cli.args.length) {
const argsString = this.cli.args
.slice(maximumArgsCount)
.map((arg) => `\`${arg}\``)
.join(', ')
throw new CACError(`Unused args: ${argsString}`)
}
}
}

class GlobalCommand extends Command {
Expand Down
10 changes: 10 additions & 0 deletions src/__test__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,16 @@ test('throw on unknown options', () => {
}).toThrowError('Unknown option `--xx`')
})

test('throw on unused args', () => {
const cli = cac()

cli.command('build [entry]', 'Build your app').action(() => {})

expect(() => {
cli.parse(`node bin build app.js foo bar`.split(' '))
}).toThrowError('Unused args: `foo`, `bar`')
})

describe('--version in help message', () => {
test('sub command', async () => {
const output = await getOutput('help.js', ['lint', '--help'])
Expand Down