File tree Expand file tree Collapse file tree 3 files changed +28
-0
lines changed
Expand file tree Collapse file tree 3 files changed +28
-0
lines changed Original file line number Diff line number Diff 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 ) {
Original file line number Diff line number Diff 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
312328export class GlobalCommand extends Command {
Original file line number Diff line number Diff 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+
168178describe ( '--version in help message' , ( ) => {
169179 test ( 'sub command' , async ( ) => {
170180 const output = await getOutput ( 'help.ts' , [ 'lint' , '--help' ] )
You can’t perform that action at this time.
0 commit comments