Skip to content

Commit 64aff7a

Browse files
committed
feat(@angular/cli): forward arguments after -- to supporting builders
Allow architect-backed commands (`ng test`, `ng run`, etc.) to forward arguments after `--` to builders that explicitly opt in via the `"x-passthrough": true` schema keyword on an array option. This adds a `passthrough` flag to `Option` parsed from `"x-passthrough"` in `parseJsonSchemaToOptions`, enables `acceptsPassthroughArgs` on `ArchitectBaseCommandModule`, and updates `runSingleTarget` to route `passthroughArgs` to the target builder's `x-passthrough` option (appending after any explicit option values) or throw a `CommandModuleError` when the builder does not declare one. The `@angular/build` `unit-test` builder marks `runnerArgs` with `"x-passthrough": true` so `ng test -- <args>` forwards arguments to Vitest. The `ng test` help description and Vitest snapshot e2e test are updated accordingly.
1 parent 305ae03 commit 64aff7a

7 files changed

Lines changed: 325 additions & 2 deletions

File tree

‎packages/angular/build/src/builders/unit-test/schema.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,8 @@
2929
"description": "Additional command line arguments to provide to the test runner. Each argument must be a separate value, for example `--runner-args=--update --runner-args=--bail=1`. This option is only available for the Vitest runner and only a subset of the Vitest command line options is supported. Options that have an equivalent builder option, such as `--reporter` or `--coverage`, must be configured with the builder option.",
3030
"items": {
3131
"type": "string"
32-
}
32+
},
33+
"x-passthrough": true
3334
},
3435
"browsers": {
3536
"description": "Specifies the browsers to use for test execution. When not specified, the Vitest runner runs tests in a Node.js environment using `happy-dom` if it is installed, otherwise `jsdom`, and the Karma runner uses the browsers of its configuration. Browser names ending with `Headless` enable headless mode (e.g., `ChromiumHeadless` for Vitest with the Playwright provider, or `ChromeHeadless` for Karma).",

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

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export abstract class ArchitectBaseCommandModule<T extends object>
3737
implements CommandModuleImplementation<T>
3838
{
3939
override scope = CommandScope.In;
40+
protected override readonly acceptsPassthroughArgs = true;
4041
protected readonly missingTargetChoices: MissingTargetChoice[] | undefined;
4142

4243
protected async runSingleTarget(target: Target, options: OtherOptions): Promise<number> {
@@ -51,12 +52,47 @@ export abstract class ArchitectBaseCommandModule<T extends object>
5152
return this.onMissingTarget(e.message);
5253
}
5354

55+
let targetOptions = options;
56+
if (this.passthroughArgs?.length) {
57+
const builderOptions = await this.getOptionsForBuilder(builderName);
58+
const passthroughOptions = builderOptions.filter((option) => option.passthrough);
59+
if (passthroughOptions.length > 1) {
60+
throw new CommandModuleError(
61+
`The '${builderName}' builder schema defines multiple options with 'x-passthrough'.`,
62+
);
63+
}
64+
65+
const [passthroughOption] = passthroughOptions;
66+
if (!passthroughOption) {
67+
throw new CommandModuleError(
68+
`The '${builderName}' builder does not accept arguments after '--'.`,
69+
);
70+
}
71+
72+
if (passthroughOption.type !== 'array') {
73+
throw new CommandModuleError(
74+
`The '${builderName}' builder option '${passthroughOption.name}' has 'x-passthrough' enabled but is not an array.`,
75+
);
76+
}
77+
78+
const existing = options[passthroughOption.name];
79+
const existingArgs = Array.isArray(existing)
80+
? existing
81+
: existing !== undefined && existing !== null
82+
? [existing]
83+
: [];
84+
targetOptions = {
85+
...options,
86+
[passthroughOption.name]: [...existingArgs, ...this.passthroughArgs],
87+
};
88+
}
89+
5490
const isAngularBuild = builderName.startsWith('@angular/build:');
5591

5692
const { logger } = this.context;
5793
const run = await this.getArchitect(isAngularBuild).scheduleTarget(
5894
target,
59-
options as json.JsonObject,
95+
targetOptions as json.JsonObject,
6096
{
6197
logger,
6298
},
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
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 { Target } from '@angular-devkit/architect';
10+
import { logging } from '@angular-devkit/core';
11+
import type { ArgumentsCamelCase, Argv } from 'yargs';
12+
import { ArchitectBaseCommandModule } from './architect-base-command-module';
13+
import { CommandModuleError, Options, OtherOptions } from './command-module';
14+
import { CommandContext } from './definitions';
15+
import { Option } from './utilities/json-schema';
16+
17+
class TestArchitectCommand extends ArchitectBaseCommandModule<{}> {
18+
override readonly command = 'test';
19+
override readonly describe = 'Test architect command';
20+
override readonly shouldReportAnalytics = false;
21+
22+
builderOptions: Option[] = [];
23+
builderName = '@angular/build:unit-test';
24+
scheduledOptions: Record<string, unknown> | undefined;
25+
26+
override builder(argv: Argv): Argv {
27+
return argv;
28+
}
29+
30+
override async run(options: Options<{}> & OtherOptions): Promise<number> {
31+
return this.runSingleTarget({ project: 'app', target: 'test' }, options);
32+
}
33+
34+
protected override getArchitectHost() {
35+
return {
36+
getBuilderNameForTarget: async (_target: Target) => this.builderName,
37+
} as never;
38+
}
39+
40+
protected override async getOptionsForBuilder(_builderConf: string): Promise<Option[]> {
41+
return this.builderOptions;
42+
}
43+
44+
protected override getArchitect() {
45+
return {
46+
scheduleTarget: async (_target: Target, options: Record<string, unknown>) => {
47+
this.scheduledOptions = options;
48+
49+
return {
50+
lastOutput: Promise.resolve({ success: true }),
51+
stop: async () => {},
52+
};
53+
},
54+
} as never;
55+
}
56+
}
57+
58+
function createCommandContext(): CommandContext {
59+
return {
60+
currentDirectory: '/workspace',
61+
root: '/workspace',
62+
logger: new logging.NullLogger(),
63+
args: {
64+
positional: [],
65+
options: {
66+
help: false,
67+
jsonHelp: false,
68+
getYargsCompletions: false,
69+
},
70+
},
71+
} as unknown as CommandContext;
72+
}
73+
74+
describe('ArchitectBaseCommandModule passthrough arguments', () => {
75+
it('forwards arguments after "--" to the x-passthrough option', async () => {
76+
const command = new TestArchitectCommand(createCommandContext());
77+
command.builderOptions = [
78+
{
79+
name: 'runnerArgs',
80+
description: 'Runner args',
81+
type: 'array',
82+
passthrough: true,
83+
},
84+
];
85+
86+
const args = {
87+
_: ['test'],
88+
$0: 'ng',
89+
'--': ['--update', '--bail=1'],
90+
watch: false,
91+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
92+
93+
await command.handler(args);
94+
95+
expect(command.scheduledOptions).toEqual({
96+
watch: false,
97+
runnerArgs: ['--update', '--bail=1'],
98+
});
99+
});
100+
101+
it('concatenates explicit option values before "--" passthrough arguments', async () => {
102+
const command = new TestArchitectCommand(createCommandContext());
103+
command.builderOptions = [
104+
{
105+
name: 'runnerArgs',
106+
description: 'Runner args',
107+
type: 'array',
108+
passthrough: true,
109+
},
110+
];
111+
112+
const args = {
113+
_: ['test'],
114+
$0: 'ng',
115+
'runner-args': ['--shard=1/2'],
116+
'--': ['--update'],
117+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
118+
119+
await command.handler(args);
120+
121+
expect(command.scheduledOptions).toEqual({
122+
runnerArgs: ['--shard=1/2', '--update'],
123+
});
124+
});
125+
126+
it('rejects "--" arguments when the target builder has no x-passthrough option', async () => {
127+
const command = new TestArchitectCommand(createCommandContext());
128+
command.builderName = '@angular/build:application';
129+
command.builderOptions = [
130+
{
131+
name: 'watch',
132+
description: 'Watch',
133+
type: 'boolean',
134+
},
135+
];
136+
137+
const args = {
138+
_: ['build'],
139+
$0: 'ng',
140+
'--': ['--update'],
141+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
142+
143+
await expectAsync(command.handler(args)).toBeRejectedWithError(
144+
CommandModuleError,
145+
"The '@angular/build:application' builder does not accept arguments after '--'.",
146+
);
147+
expect(command.scheduledOptions).toBeUndefined();
148+
});
149+
150+
it('rejects "--" arguments when the target builder defines multiple x-passthrough options', async () => {
151+
const command = new TestArchitectCommand(createCommandContext());
152+
command.builderOptions = [
153+
{
154+
name: 'runnerArgs',
155+
description: 'Runner args',
156+
type: 'array',
157+
passthrough: true,
158+
},
159+
{
160+
name: 'extraArgs',
161+
description: 'Extra args',
162+
type: 'array',
163+
passthrough: true,
164+
},
165+
];
166+
167+
const args = {
168+
_: ['test'],
169+
$0: 'ng',
170+
'--': ['--update'],
171+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
172+
173+
await expectAsync(command.handler(args)).toBeRejectedWithError(
174+
CommandModuleError,
175+
"The '@angular/build:unit-test' builder schema defines multiple options with 'x-passthrough'.",
176+
);
177+
expect(command.scheduledOptions).toBeUndefined();
178+
});
179+
180+
it('rejects "--" arguments when the x-passthrough option is not an array', async () => {
181+
const command = new TestArchitectCommand(createCommandContext());
182+
command.builderOptions = [
183+
{
184+
name: 'runnerArg',
185+
description: 'Runner arg',
186+
type: 'string',
187+
passthrough: true,
188+
},
189+
];
190+
191+
const args = {
192+
_: ['test'],
193+
$0: 'ng',
194+
'--': ['--update'],
195+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
196+
197+
await expectAsync(command.handler(args)).toBeRejectedWithError(
198+
CommandModuleError,
199+
"The '@angular/build:unit-test' builder option 'runnerArg' has 'x-passthrough' enabled but is not an array.",
200+
);
201+
expect(command.scheduledOptions).toBeUndefined();
202+
});
203+
204+
it('wraps a scalar existing option value before "--" passthrough arguments', async () => {
205+
const command = new TestArchitectCommand(createCommandContext());
206+
command.builderOptions = [
207+
{
208+
name: 'runnerArgs',
209+
description: 'Runner args',
210+
type: 'array',
211+
passthrough: true,
212+
},
213+
];
214+
215+
const args = {
216+
_: ['run'],
217+
$0: 'ng',
218+
'runner-args': '--shard=1/2',
219+
'--': ['--update'],
220+
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;
221+
222+
await command.handler(args);
223+
224+
expect(command.scheduledOptions).toEqual({
225+
runnerArgs: ['--shard=1/2', '--update'],
226+
});
227+
});
228+
});

‎packages/angular/cli/src/command-builder/utilities/json-schema.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ export interface Option extends YargsOptions {
6060
* Allowed boolean values when `boolean` is one of the supported types.
6161
*/
6262
booleanValues?: ReadonlySet<boolean>;
63+
64+
/**
65+
* Whether arguments after `--` should be forwarded to this option.
66+
*/
67+
passthrough?: boolean;
6368
}
6469

6570
/**
@@ -530,6 +535,7 @@ export async function parseJsonSchemaToOptions(
530535
positional,
531536
types,
532537
booleanValues: types.includes('boolean') ? getAllowedBooleanValues(current) : undefined,
538+
passthrough: current['x-passthrough'] === true || undefined,
533539
...(type === 'object'
534540
? {
535541
type: 'array',

‎packages/angular/cli/src/command-builder/utilities/json-schema_spec.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,4 +580,31 @@ describe('parseJsonSchemaToOptions', () => {
580580
]);
581581
});
582582
});
583+
584+
describe('with x-passthrough', () => {
585+
it('sets passthrough to true when x-passthrough is true and undefined otherwise', async () => {
586+
const jsonSchema = {
587+
'$id': 'FakeSchema',
588+
'title': 'Fake Schema',
589+
'type': 'object',
590+
'properties': {
591+
'runnerArgs': {
592+
'type': 'array',
593+
'items': { 'type': 'string' },
594+
'x-passthrough': true,
595+
},
596+
'other': {
597+
'type': 'string',
598+
},
599+
},
600+
};
601+
const registry = new schema.CoreSchemaRegistry();
602+
const options = await parseJsonSchemaToOptions(registry, jsonSchema);
603+
604+
expect(options.find((opt) => opt.name === 'runnerArgs')).toEqual(
605+
jasmine.objectContaining({ name: 'runnerArgs', passthrough: true }),
606+
);
607+
expect(options.find((opt) => opt.name === 'other')?.passthrough).toBeUndefined();
608+
});
609+
});
583610
});
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
Takes the name of the project, as specified in the `projects` section of the `angular.json` workspace configuration file.
22
When a project name is not supplied, it will execute for all projects.
3+
4+
Arguments following `--` are forwarded directly to the test runner when supported by the configured builder (for example, `ng test -- --update`).

‎tests/e2e/tests/vitest/snapshot.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,27 @@ describe('App', () => {
124124
/Snapshots\s+\d+ (written|updated|failed|obsolete)/,
125125
'Snapshots were unexpectedly modified after being updated.',
126126
);
127+
128+
// Sixth run: update snapshots via `-- --update` passthrough
129+
await replaceInFile('src/app/app.ts', 'test-project (updated)', 'test-project (passthrough)');
130+
const { stdout: passthroughUpdateStdout } = await ng('test', '--', '--update');
131+
assert.match(
132+
stripVTControlCharacters(passthroughUpdateStdout),
133+
/Snapshots\s+2 updated/,
134+
'Snapshots were not updated when `-- --update` was passed.',
135+
);
136+
137+
const passthroughSpecContent = await readFile('src/app/app.spec.ts');
138+
assert.match(
139+
passthroughSpecContent,
140+
/toMatchInlineSnapshot\(`"test-project \(passthrough\)"`\)/,
141+
'Inline snapshot was not updated via `-- --update`.',
142+
);
143+
144+
const passthroughSnapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap');
145+
assert.match(
146+
passthroughSnapshotContent,
147+
/exports\[`App > should match file snapshot 1`\] = `"test-project \(passthrough\)"`;/,
148+
'File snapshot was not updated via `-- --update`.',
149+
);
127150
}

0 commit comments

Comments
 (0)