Repository navigation
Expand file tree
/
Copy patharchitect-command-module.ts
More file actions
251 lines (211 loc) · 8.46 KB
/
Copy patharchitect-command-module.ts
File metadata and controls
251 lines (211 loc) · 8.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* @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 { workspaces } from '@angular-devkit/core';
import { Argv } from 'yargs';
import { getProjectByCwd } from '../utilities/config';
import { memoize } from '../utilities/memoize';
import { ArchitectBaseCommandModule } from './architect-base-command-module';
import {
CommandModuleError,
CommandModuleImplementation,
Options,
OtherOptions,
} from './command-module';
import {
JsonHelpBuilder,
schemaOptionsToJsonHelpOptions,
setJsonHelpBuilders,
} from './utilities/json-help';
export interface ArchitectCommandArgs {
configuration?: string;
project?: string;
}
export abstract class ArchitectCommandModule
extends ArchitectBaseCommandModule<ArchitectCommandArgs>
implements CommandModuleImplementation<ArchitectCommandArgs>
{
abstract readonly multiTarget: boolean;
/**
* A mapping of human-readable builder names to their corresponding Architect builder
* identifiers (for example, `{ Application: '@angular/build:application' }`).
*
* When defined, `--json-help` resolves the schema options for each builder and includes
* them under the `builders` property of the JSON help output instead of flattening
* a single project target's builder options into the command's top-level options.
*/
readonly builders?: Readonly<Record<string, string>>;
findDefaultBuilderName?(
project: workspaces.ProjectDefinition,
target: Target,
): Promise<string | undefined>;
async builder(argv: Argv): Promise<Argv<ArchitectCommandArgs>> {
const target = this.getArchitectTarget();
// Add default builder if target is not in project and a command default is provided
if (this.findDefaultBuilderName && this.context.workspace) {
for (const [project, projectDefinition] of this.context.workspace.projects) {
const targetDefinition = projectDefinition.targets.get(target);
if (targetDefinition?.builder) {
continue;
}
const defaultBuilder = await this.findDefaultBuilderName(projectDefinition, {
project,
target,
});
if (!defaultBuilder) {
continue;
}
if (targetDefinition) {
targetDefinition.builder = defaultBuilder;
} else {
projectDefinition.targets.set(target, {
builder: defaultBuilder,
});
}
}
}
const project = this.getArchitectProject();
const { jsonHelp, getYargsCompletions, help } = this.context.args.options;
const localYargs: Argv<ArchitectCommandArgs> = argv
.positional('project', {
describe:
'The name of the project to run the command for. Can be an application or a library.',
type: 'string',
// Hide choices from JSON help so that we don't display them in AIO.
choices: jsonHelp ? undefined : this.getProjectChoices(),
})
.option('configuration', {
describe:
`One or more named builder configurations as a comma-separated ` +
`list as specified in the "configurations" section in angular.json.\n` +
`The builder uses the named configurations to run the given target.\n` +
`For more information, see https://angular.dev/reference/configs/workspace-config#alternate-build-configurations.`,
alias: 'c',
type: 'string',
// Show only in when using --help and auto completion because otherwise comma seperated configuration values will be invalid.
// Also, hide choices from JSON help so that we don't display them in AIO.
choices:
(getYargsCompletions || help) && !jsonHelp && project
? this.getConfigurationChoices(project)
: undefined,
})
.strict();
if (jsonHelp && this.builders) {
const buildersHelp: JsonHelpBuilder[] = await Promise.all(
Object.entries(this.builders).map(async ([name, builderName]) => ({
name,
options: schemaOptionsToJsonHelpOptions(await this.getOptionsForBuilder(builderName)),
})),
);
setJsonHelpBuilders(this.context.yargsInstance, buildersHelp);
return localYargs;
}
if (!project) {
return localYargs;
}
const schemaOptions = await this.getArchitectTargetOptions({
project,
target,
});
return this.addSchemaOptionsToCommand(localYargs, schemaOptions);
}
async run(options: Options<ArchitectCommandArgs> & OtherOptions): Promise<number | void> {
const originalProcessTitle = process.title;
try {
const target = this.getArchitectTarget();
const { configuration = '', project, ...architectOptions } = options;
if (project) {
process.title = `${originalProcessTitle} (${project})`;
return await this.runSingleTarget({ configuration, target, project }, architectOptions);
}
// This runs each target sequentially.
// Running them in parallel would jumble the log messages.
let result = 0;
const projectNames = this.getProjectNamesByTarget(target);
if (!projectNames) {
return this.onMissingTarget('Cannot determine project or target for command.');
}
for (const project of projectNames) {
process.title = `${originalProcessTitle} (${project})`;
result |= await this.runSingleTarget({ configuration, target, project }, architectOptions);
}
return result;
} finally {
process.title = originalProcessTitle;
}
}
private getArchitectProject(): string | undefined {
const { options, positional } = this.context.args;
const [, projectName] = positional;
if (projectName) {
return projectName;
}
// Yargs allows positional args to be used as flags.
if (typeof options['project'] === 'string') {
return options['project'];
}
const target = this.getArchitectTarget();
const projectFromTarget = this.getProjectNamesByTarget(target);
return projectFromTarget?.length ? projectFromTarget[0] : undefined;
}
@memoize
private getProjectNamesByTarget(target: string): string[] | undefined {
const workspace = this.getWorkspaceOrThrow();
const allProjectsForTargetName: string[] = [];
for (const [name, project] of workspace.projects) {
if (project.targets.has(target)) {
allProjectsForTargetName.push(name);
}
}
if (allProjectsForTargetName.length === 0) {
return undefined;
}
if (this.multiTarget) {
// For multi target commands, we always list all projects that have the target.
return allProjectsForTargetName;
} else {
if (allProjectsForTargetName.length === 1) {
return allProjectsForTargetName;
}
const maybeProject = getProjectByCwd(workspace);
if (maybeProject) {
return allProjectsForTargetName.includes(maybeProject) ? [maybeProject] : undefined;
}
const { getYargsCompletions, help } = this.context.args.options;
if (!getYargsCompletions && !help) {
// Only issue the below error when not in help / completion mode.
throw new CommandModuleError(
'Cannot determine project for command.\n' +
'This is a multi-project workspace and more than one project supports this command. ' +
`Run "ng ${this.command}" to execute the command for a specific project or change the current ` +
'working directory to a project directory.\n\n' +
`Available projects are:\n${allProjectsForTargetName
.sort()
.map((p) => `- ${p}`)
.join('\n')}`,
);
}
}
return undefined;
}
/** @returns a sorted list of project names to be used for auto completion. */
private getProjectChoices(): string[] | undefined {
const { workspace } = this.context;
return workspace ? [...workspace.projects.keys()].sort() : undefined;
}
/** @returns a sorted list of configuration names to be used for auto completion. */
private getConfigurationChoices(project: string): string[] | undefined {
const projectDefinition = this.context.workspace?.projects.get(project);
if (!projectDefinition) {
return undefined;
}
const target = this.getArchitectTarget();
const configurations = projectDefinition.targets.get(target)?.configurations;
return configurations ? Object.keys(configurations).sort() : undefined;
}
}