Skip to content
Merged
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
3 changes: 2 additions & 1 deletion packages/angular/build/src/builders/unit-test/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
"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.",
"items": {
"type": "string"
}
},
"x-passthrough": true
},
"browsers": {
"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).",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export abstract class ArchitectBaseCommandModule<T extends object>
implements CommandModuleImplementation<T>
{
override scope = CommandScope.In;
protected override readonly acceptsPassthroughArgs = true;
protected readonly missingTargetChoices: MissingTargetChoice[] | undefined;

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

let targetOptions = options;
if (this.passthroughArgs?.length) {
const builderOptions = await this.getOptionsForBuilder(builderName);
const passthroughOptions = builderOptions.filter((option) => option.passthrough);
if (passthroughOptions.length > 1) {
throw new CommandModuleError(
`The '${builderName}' builder schema defines multiple options with 'x-passthrough'.`,
);
}

const [passthroughOption] = passthroughOptions;
if (!passthroughOption) {
throw new CommandModuleError(
`The '${builderName}' builder does not accept arguments after '--'.`,
);
}

if (passthroughOption.type !== 'array') {
throw new CommandModuleError(
`The '${builderName}' builder option '${passthroughOption.name}' has 'x-passthrough' enabled but is not an array.`,
);
}

const existing = options[passthroughOption.name];
const existingArgs = Array.isArray(existing)
? existing
: existing !== undefined && existing !== null
? [existing]
: [];
targetOptions = {
...options,
[passthroughOption.name]: [...existingArgs, ...this.passthroughArgs],
};
Comment thread
clydin marked this conversation as resolved.
Resolved
}

const isAngularBuild = builderName.startsWith('@angular/build:');

const { logger } = this.context;
const run = await this.getArchitect(isAngularBuild).scheduleTarget(
target,
options as json.JsonObject,
targetOptions as json.JsonObject,
{
logger,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { Target } from '@angular-devkit/architect';
import { logging } from '@angular-devkit/core';
import type { ArgumentsCamelCase, Argv } from 'yargs';
import { ArchitectBaseCommandModule } from './architect-base-command-module';
import { CommandModuleError, Options, OtherOptions } from './command-module';
import { CommandContext } from './definitions';
import { Option } from './utilities/json-schema';

class TestArchitectCommand extends ArchitectBaseCommandModule<{}> {
override readonly command = 'test';
override readonly describe = 'Test architect command';
override readonly shouldReportAnalytics = false;

builderOptions: Option[] = [];
builderName = '@angular/build:unit-test';
scheduledOptions: Record<string, unknown> | undefined;

override builder(argv: Argv): Argv {
return argv;
}

override async run(options: Options<{}> & OtherOptions): Promise<number> {
return this.runSingleTarget({ project: 'app', target: 'test' }, options);
}

protected override getArchitectHost() {
return {
getBuilderNameForTarget: async (_target: Target) => this.builderName,
} as never;
}

protected override async getOptionsForBuilder(_builderConf: string): Promise<Option[]> {
return this.builderOptions;
}

protected override getArchitect() {
return {
scheduleTarget: async (_target: Target, options: Record<string, unknown>) => {
this.scheduledOptions = options;

return {
lastOutput: Promise.resolve({ success: true }),
stop: async () => {},
};
},
} as never;
}
}

function createCommandContext(): CommandContext {
return {
currentDirectory: '/workspace',
root: '/workspace',
logger: new logging.NullLogger(),
args: {
positional: [],
options: {
help: false,
jsonHelp: false,
getYargsCompletions: false,
},
},
} as unknown as CommandContext;
}

describe('ArchitectBaseCommandModule passthrough arguments', () => {
it('forwards arguments after "--" to the x-passthrough option', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderOptions = [
{
name: 'runnerArgs',
description: 'Runner args',
type: 'array',
passthrough: true,
},
];

const args = {
_: ['test'],
$0: 'ng',
'--': ['--update', '--bail=1'],
watch: false,
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await command.handler(args);

expect(command.scheduledOptions).toEqual({
watch: false,
runnerArgs: ['--update', '--bail=1'],
});
});

it('concatenates explicit option values before "--" passthrough arguments', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderOptions = [
{
name: 'runnerArgs',
description: 'Runner args',
type: 'array',
passthrough: true,
},
];

const args = {
_: ['test'],
$0: 'ng',
'runner-args': ['--shard=1/2'],
'--': ['--update'],
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await command.handler(args);

expect(command.scheduledOptions).toEqual({
runnerArgs: ['--shard=1/2', '--update'],
});
});

it('rejects "--" arguments when the target builder has no x-passthrough option', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderName = '@angular/build:application';
command.builderOptions = [
{
name: 'watch',
description: 'Watch',
type: 'boolean',
},
];

const args = {
_: ['build'],
$0: 'ng',
'--': ['--update'],
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await expectAsync(command.handler(args)).toBeRejectedWithError(
CommandModuleError,
"The '@angular/build:application' builder does not accept arguments after '--'.",
);
expect(command.scheduledOptions).toBeUndefined();
});

it('rejects "--" arguments when the target builder defines multiple x-passthrough options', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderOptions = [
{
name: 'runnerArgs',
description: 'Runner args',
type: 'array',
passthrough: true,
},
{
name: 'extraArgs',
description: 'Extra args',
type: 'array',
passthrough: true,
},
];

const args = {
_: ['test'],
$0: 'ng',
'--': ['--update'],
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await expectAsync(command.handler(args)).toBeRejectedWithError(
CommandModuleError,
"The '@angular/build:unit-test' builder schema defines multiple options with 'x-passthrough'.",
);
expect(command.scheduledOptions).toBeUndefined();
});

it('rejects "--" arguments when the x-passthrough option is not an array', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderOptions = [
{
name: 'runnerArg',
description: 'Runner arg',
type: 'string',
passthrough: true,
},
];

const args = {
_: ['test'],
$0: 'ng',
'--': ['--update'],
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await expectAsync(command.handler(args)).toBeRejectedWithError(
CommandModuleError,
"The '@angular/build:unit-test' builder option 'runnerArg' has 'x-passthrough' enabled but is not an array.",
);
expect(command.scheduledOptions).toBeUndefined();
});

it('wraps a scalar existing option value before "--" passthrough arguments', async () => {
const command = new TestArchitectCommand(createCommandContext());
command.builderOptions = [
{
name: 'runnerArgs',
description: 'Runner args',
type: 'array',
passthrough: true,
},
];

const args = {
_: ['run'],
$0: 'ng',
'runner-args': '--shard=1/2',
'--': ['--update'],
} as unknown as ArgumentsCamelCase<{}> & OtherOptions;

await command.handler(args);

expect(command.scheduledOptions).toEqual({
runnerArgs: ['--shard=1/2', '--update'],
});
});
});
17 changes: 16 additions & 1 deletion packages/angular/cli/src/command-builder/command-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export abstract class CommandModule<T extends {} = {}> implements CommandModuleI
readonly longDescription?: string;
readonly longDescriptionRelativePath?: string;
protected readonly shouldReportAnalytics: boolean = true;
protected readonly acceptsPassthroughArgs: boolean = false;
protected passthroughArgs: readonly string[] | undefined;
readonly scope: CommandScope = CommandScope.Both;

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

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

if (Array.isArray(passthroughArgs) && passthroughArgs.length > 0) {
if (!this.acceptsPassthroughArgs) {
throw new CommandModuleError(
`Arguments following "--" are not supported by the "${this.commandName}" command.`,
);
}

this.passthroughArgs = passthroughArgs.map(String);
} else {
this.passthroughArgs = undefined;
}

// Camelize options as yargs will return the object in kebab-case when camel casing is disabled.
const camelCasedOptions: Record<string, unknown> = {};
for (const [key, value] of Object.entries(options)) {
Expand Down Expand Up @@ -139,6 +153,7 @@ export abstract class CommandModule<T extends {} = {}> implements CommandModuleI
throw e;
}
} finally {
this.passthroughArgs = undefined;
await stopPeriodicFlushes?.();

if (typeof exitCode === 'number' && exitCode > 0) {
Expand Down
Loading
Loading