Skip to content

Commit d0636d9

Browse files
authored
feat: throw error on unused args (#135)
* feat: throw error on unused args * chore: fix build
1 parent 665242c commit d0636d9

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

src/cac.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,8 @@ export class CAC extends EventTarget {
349349

350350
command.checkRequiredArgs()
351351

352+
command.checkUnusedArgs()
353+
352354
const actionArgs: any[] = []
353355
command.args.forEach((arg, index) => {
354356
if (arg.variadic) {

src/command.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,22 @@ export class Command {
307307
}
308308
}
309309
}
310+
311+
/**
312+
* Check if the number of args is more than expected
313+
*/
314+
checkUnusedArgs(): void {
315+
const hasVariadicArg = this.args.some((arg) => arg.variadic)
316+
const maximumArgsCount = hasVariadicArg ? Infinity : this.args.length
317+
318+
if (maximumArgsCount < this.cli.args.length) {
319+
const argsString = this.cli.args
320+
.slice(maximumArgsCount)
321+
.map((arg) => `\`${arg}\``)
322+
.join(', ')
323+
throw new CACError(`Unused args: ${argsString}`)
324+
}
325+
}
310326
}
311327

312328
export class GlobalCommand extends Command {

tests/index.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,16 @@ test('throw on unknown options', () => {
165165
}).toThrowError('Unknown option `--xx`')
166166
})
167167

168+
test('throw on unused args', () => {
169+
const cli = cac()
170+
171+
cli.command('build [entry]', 'Build your app').action(() => {})
172+
173+
expect(() => {
174+
cli.parse(`node bin build app.js foo bar`.split(' '))
175+
}).toThrowError('Unused args: `foo`, `bar`')
176+
})
177+
168178
describe('--version in help message', () => {
169179
test('sub command', async () => {
170180
const output = await getOutput('help.ts', ['lint', '--help'])

0 commit comments

Comments
 (0)