Skip to content

Commit b347fbd

Browse files
clydinalan-agius4
authored andcommitted
fix(@angular/cli): preserve all arguments following --
Previously, `createNormalizeOptionsMiddleware` treated `--` (populated by yargs when `'populate--': true` is enabled) like any non-array option, collapsing its array to the last element and logging a spurious warning. In addition, `CommandModule.handler` only stripped `_` and `$0` from parsed arguments, allowing `--` to leak into `camelCasedOptions` and be forwarded to commands as an unexpected option. Exclude `--` from option normalization, extract `--` in `CommandModule.handler` into `passthroughArgs`, and reject non-empty `--` arguments with a `CommandModuleError` for commands that do not opt into `acceptsPassthroughArgs`.
1 parent 600c5d3 commit b347fbd

4 files changed

Lines changed: 195 additions & 2 deletions

File tree

‎packages/angular/cli/src/command-builder/command-module.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ export abstract class CommandModule<T extends {} = {}> implements CommandModuleI
5454
readonly longDescription?: string;
5555
readonly longDescriptionRelativePath?: string;
5656
protected readonly shouldReportAnalytics: boolean = true;
57+
protected readonly acceptsPassthroughArgs: boolean = false;
58+
protected passthroughArgs: readonly string[] | undefined;
5759
readonly scope: CommandScope = CommandScope.Both;
5860

5961
private readonly optionsWithAnalytics = new Map<
@@ -96,9 +98,21 @@ export abstract class CommandModule<T extends {} = {}> implements CommandModuleI
9698
abstract run(options: Options<T> & OtherOptions): Promise<number | void> | number | void;
9799

98100
async handler(args: ArgumentsCamelCase<T> & OtherOptions): Promise<void> {
99-
const { _, $0, ...options } = args;
101+
const { _, $0, '--': passthroughArgs, ...options } = args;
100102
const { logger } = this.context;
101103

104+
if (Array.isArray(passthroughArgs) && passthroughArgs.length > 0) {
105+
if (!this.acceptsPassthroughArgs) {
106+
throw new CommandModuleError(
107+
`Arguments following "--" are not supported by the "${this.commandName}" command.`,
108+
);
109+
}
110+
111+
this.passthroughArgs = passthroughArgs.map(String);
112+
} else {
113+
this.passthroughArgs = undefined;
114+
}
115+
102116
// Camelize options as yargs will return the object in kebab-case when camel casing is disabled.
103117
const camelCasedOptions: Record<string, unknown> = {};
104118
for (const [key, value] of Object.entries(options)) {
@@ -139,6 +153,7 @@ export abstract class CommandModule<T extends {} = {}> implements CommandModuleI
139153
throw e;
140154
}
141155
} finally {
156+
this.passthroughArgs = undefined;
142157
await stopPeriodicFlushes?.();
143158

144159
if (typeof exitCode === 'number' && exitCode > 0) {
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { logging } from '@angular-devkit/core';
10+
import type { ArgumentsCamelCase, Argv } from 'yargs';
11+
import { CommandModule, CommandModuleError, Options, OtherOptions } from './command-module';
12+
import { CommandContext } from './definitions';
13+
14+
class UnsupportedPassthroughCommand extends CommandModule {
15+
override readonly command = 'test-cmd';
16+
override readonly describe = 'Test command';
17+
override readonly shouldReportAnalytics = false;
18+
receivedOptions: (Options<{}> & OtherOptions) | undefined;
19+
20+
override builder(argv: Argv): Argv {
21+
return argv;
22+
}
23+
24+
override run(options: Options<{}> & OtherOptions): number {
25+
this.receivedOptions = options;
26+
27+
return 0;
28+
}
29+
}
30+
31+
class SupportedPassthroughCommand extends CommandModule {
32+
override readonly command = 'pass-cmd';
33+
override readonly describe = 'Command supporting passthrough';
34+
override readonly shouldReportAnalytics = false;
35+
protected override readonly acceptsPassthroughArgs = true;
36+
receivedOptions: (Options<{}> & OtherOptions) | undefined;
37+
receivedPassthroughArgs: readonly string[] | undefined;
38+
39+
override builder(argv: Argv): Argv {
40+
return argv;
41+
}
42+
43+
override run(options: Options<{}> & OtherOptions): number {
44+
this.receivedOptions = options;
45+
this.receivedPassthroughArgs = this.passthroughArgs;
46+
47+
return 0;
48+
}
49+
}
50+
51+
function createCommandContext(): CommandContext {
52+
return {
53+
currentDirectory: '/workspace',
54+
root: '/workspace',
55+
logger: new logging.NullLogger(),
56+
args: {
57+
positional: [],
58+
options: {
59+
help: false,
60+
jsonHelp: false,
61+
getYargsCompletions: false,
62+
},
63+
},
64+
} as unknown as CommandContext;
65+
}
66+
67+
describe('CommandModule passthrough arguments', () => {
68+
it('rejects arguments after "--" when command does not support passthrough', async () => {
69+
const command = new UnsupportedPassthroughCommand(createCommandContext());
70+
const args = {
71+
_: ['test-cmd'],
72+
$0: 'ng',
73+
'--': ['--update'],
74+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
75+
76+
await expectAsync(command.handler(args)).toBeRejectedWithError(
77+
CommandModuleError,
78+
'Arguments following "--" are not supported by the "test-cmd" command.',
79+
);
80+
expect(command.receivedOptions).toBeUndefined();
81+
});
82+
83+
it('allows empty "--" array on commands that do not support passthrough', async () => {
84+
const command = new UnsupportedPassthroughCommand(createCommandContext());
85+
const args = {
86+
_: ['test-cmd'],
87+
$0: 'ng',
88+
'--': [],
89+
watch: false,
90+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
91+
92+
await command.handler(args);
93+
94+
expect(command.receivedOptions).toEqual({ watch: false });
95+
expect('--' in (command.receivedOptions ?? {})).toBeFalse();
96+
});
97+
98+
it('forwards "--" arguments via passthroughArgs and omits "--" from options when supported', async () => {
99+
const command = new SupportedPassthroughCommand(createCommandContext());
100+
const args = {
101+
_: ['pass-cmd'],
102+
$0: 'ng',
103+
'--': ['--update', '--reporter=verbose'],
104+
watch: false,
105+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
106+
107+
await command.handler(args);
108+
109+
expect(command.receivedPassthroughArgs).toEqual(['--update', '--reporter=verbose']);
110+
expect(command.receivedOptions).toEqual({ watch: false });
111+
expect('--' in (command.receivedOptions ?? {})).toBeFalse();
112+
});
113+
});

‎packages/angular/cli/src/command-builder/utilities/normalize-options-middleware.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export function createNormalizeOptionsMiddleware(localeYargs: Argv): (args: Argu
2626
const arrayOptions = new Set(array);
2727

2828
for (const [key, value] of Object.entries(args)) {
29-
if (key !== '_' && Array.isArray(value) && !arrayOptions.has(key)) {
29+
if (key !== '_' && key !== '--' && Array.isArray(value) && !arrayOptions.has(key)) {
3030
const newValue = value.pop();
3131
// eslint-disable-next-line no-console
3232
console.warn(
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import type { Arguments, Argv } from 'yargs';
10+
import { createNormalizeOptionsMiddleware } from './normalize-options-middleware';
11+
12+
describe('createNormalizeOptionsMiddleware', () => {
13+
function createMockYargs(arrayOptions: string[] = []): Argv {
14+
return {
15+
getOptions: () => ({ array: arrayOptions }),
16+
} as unknown as Argv;
17+
}
18+
19+
it('preserves "--" as an array without warning', () => {
20+
const warnSpy = spyOn(console, 'warn');
21+
const middleware = createNormalizeOptionsMiddleware(createMockYargs());
22+
const args: Arguments = {
23+
_: ['test'],
24+
$0: 'ng',
25+
'--': ['--update', '--reporter=verbose'],
26+
};
27+
28+
middleware(args);
29+
30+
expect(args['--']).toEqual(['--update', '--reporter=verbose']);
31+
expect(warnSpy).not.toHaveBeenCalled();
32+
});
33+
34+
it('collapses non-array duplicate options and warns', () => {
35+
const warnSpy = spyOn(console, 'warn');
36+
const middleware = createNormalizeOptionsMiddleware(createMockYargs());
37+
const args: Arguments = {
38+
_: [],
39+
$0: 'ng',
40+
configuration: ['development', 'production'],
41+
};
42+
43+
middleware(args);
44+
45+
expect(args['configuration']).toBe('production');
46+
expect(warnSpy).toHaveBeenCalledWith(
47+
"Option 'configuration' has been specified multiple times. The value 'production' will be used.",
48+
);
49+
});
50+
51+
it('preserves declared array options without warning', () => {
52+
const warnSpy = spyOn(console, 'warn');
53+
const middleware = createNormalizeOptionsMiddleware(createMockYargs(['include']));
54+
const args: Arguments = {
55+
_: [],
56+
$0: 'ng',
57+
include: ['a.spec.ts', 'b.spec.ts'],
58+
};
59+
60+
middleware(args);
61+
62+
expect(args['include']).toEqual(['a.spec.ts', 'b.spec.ts']);
63+
expect(warnSpy).not.toHaveBeenCalled();
64+
});
65+
});

0 commit comments

Comments
 (0)