diff --git a/lib/utils/remaining-flags.ts b/lib/utils/remaining-flags.ts index 533a5ca82..7ba021856 100644 --- a/lib/utils/remaining-flags.ts +++ b/lib/utils/remaining-flags.ts @@ -2,13 +2,16 @@ import { CommanderStatic } from 'commander'; export function getRemainingFlags(cli: CommanderStatic) { const rawArgs = [...cli.rawArgs]; + + const spliceIndex = rawArgs.findIndex((item: string) => + item.startsWith('--'), + ); + if (spliceIndex === -1) { + return []; + } + return rawArgs - .splice( - Math.max( - rawArgs.findIndex((item: string) => item.startsWith('--')), - 0, - ), - ) + .splice(spliceIndex) .filter((item: string, index: number, array: string[]) => { // If the option is consumed by commander.js, then we skip it if (cli.options.find((o: any) => o.short === item || o.long === item)) { @@ -18,7 +21,7 @@ export function getRemainingFlags(cli: CommanderStatic) { // If it's an argument of an option consumed by commander.js, then we // skip it too const prevKeyRaw = array[index - 1]; - if (prevKeyRaw) { + if (prevKeyRaw?.startsWith('-')) { const previousKey = camelCase( prevKeyRaw.replace(/--/g, '').replace('no', ''), ); @@ -40,7 +43,13 @@ export function getRemainingFlags(cli: CommanderStatic) { */ function camelCase(flag: string) { - return flag.split('-').reduce((str, word) => { + const words = flag.split('-').filter((word) => word.length > 0); + + if (words.length === 0) { + return ''; + } + + return words.reduce((str, word) => { return str + word[0].toUpperCase() + word.slice(1); }); -} +} \ No newline at end of file diff --git a/test/lib/utils/remaining-flags.spec.ts b/test/lib/utils/remaining-flags.spec.ts index e5f581f90..21f1ac3e5 100644 --- a/test/lib/utils/remaining-flags.spec.ts +++ b/test/lib/utils/remaining-flags.spec.ts @@ -21,13 +21,21 @@ describe('getRemainingFlags', () => { expect(remaining).toContain('--extra'); }); - it('should return all args when no flags start with dashes', () => { + it('should return an empty array when no flags start with dashes', () => { const program = new Command(); program.parse(['node', 'nest', 'build']); const remaining = getRemainingFlags(program as any); - // When no --flag is found, splice(0) returns all raw args - expect(remaining).toEqual(['node', 'nest', 'build']); + // When no --flag is found, should terminate early and return [] + expect(remaining).toEqual([]); + }); + + it('should not crash when a flag contains -no-', () => { + const program = new Command(); + program.parse(['node', 'nest', 'build', '--custom-no-custom', '--custom']); + + const remaining = getRemainingFlags(program as any); + expect(remaining).toEqual(['--custom-no-custom', '--custom']); }); it('should handle multiple unknown flags', () => {