Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/cac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,8 @@ export class CAC extends EventTarget {

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 @@ -307,6 +307,22 @@ export class Command {
}
}
}

/**
* Check if the number of args is more than expected
*/
checkUnusedArgs(): void {
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}`)
}
}
}

export class GlobalCommand extends Command {
Expand Down
10 changes: 10 additions & 0 deletions tests/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.ts', ['lint', '--help'])
Expand Down
Loading