Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions lib/utils/remaining-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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', ''),
);
Expand All @@ -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);
});
}
}
14 changes: 11 additions & 3 deletions test/lib/utils/remaining-flags.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down