forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharchitect.ts
More file actions
372 lines (310 loc) · 11.8 KB
/
Copy patharchitect.ts
File metadata and controls
372 lines (310 loc) · 11.8 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {
BaseException,
JsonObject,
JsonParseMode,
Path,
dirname,
experimental,
getSystemPath,
join,
logging,
normalize,
parseJson,
virtualFs,
} from '@angular-devkit/core';
import { resolve as nodeResolve } from '@angular-devkit/core/node';
import { Observable, forkJoin, of, throwError } from 'rxjs';
import { concatMap, map, tap } from 'rxjs/operators';
export class ProjectNotFoundException extends BaseException {
constructor(projectName: string) {
super(`Project '${projectName}' could not be found in Workspace.`);
}
}
export class TargetNotFoundException extends BaseException {
constructor(projectName: string, targetName: string) {
super(`Target '${targetName}' could not be found in project '${projectName}'.`);
}
}
export class ConfigurationNotFoundException extends BaseException {
constructor(projectName: string, configurationName: string) {
super(`Configuration '${configurationName}' could not be found in project '${projectName}'.`);
}
}
// TODO: break this exception apart into more granular ones.
export class BuilderCannotBeResolvedException extends BaseException {
constructor(builder: string) {
super(`Builder '${builder}' cannot be resolved.`);
}
}
export class ArchitectNotYetLoadedException extends BaseException {
constructor() { super(`Architect needs to be loaded before Architect is used.`); }
}
export class BuilderNotFoundException extends BaseException {
constructor(builder: string) {
super(`Builder ${builder} could not be found.`);
}
}
export interface BuilderContext {
logger: logging.Logger;
host: virtualFs.Host<{}>;
workspace: experimental.workspace.Workspace;
architect: Architect;
}
// TODO: use Build Event Protocol
// https://docs.bazel.build/versions/master/build-event-protocol.html
// https://github.com/googleapis/googleapis/tree/master/google/devtools/build/v1
export interface BuildEvent {
success: boolean;
}
export interface Builder<OptionsT> {
run(builderConfig: BuilderConfiguration<Partial<OptionsT>>): Observable<BuildEvent>;
}
export interface BuilderPathsMap {
builders: { [k: string]: BuilderPaths };
}
export interface BuilderPaths {
class: Path;
schema: Path;
description: string;
}
export interface BuilderDescription {
name: string;
schema: JsonObject;
description: string;
}
export interface BuilderConstructor<OptionsT> {
new(context: BuilderContext): Builder<OptionsT>;
}
export interface BuilderConfiguration<OptionsT = {}> {
root: Path;
sourceRoot?: Path;
projectType: string;
builder: string;
options: OptionsT;
}
export interface TargetSpecifier<OptionsT = {}> {
project: string;
target: string;
configuration?: string;
overrides?: Partial<OptionsT>;
}
export interface TargetMap {
[k: string]: Target;
}
export declare type TargetOptions<T = JsonObject> = T;
export declare type TargetConfiguration<T = JsonObject> = Partial<T>;
export interface Target<T = JsonObject> {
builder: string;
options: TargetOptions<T>;
configurations?: { [k: string]: TargetConfiguration<T> };
}
export class Architect {
private readonly _targetsSchemaPath = join(normalize(__dirname), 'targets-schema.json');
private readonly _buildersSchemaPath = join(normalize(__dirname), 'builders-schema.json');
private _targetsSchema: JsonObject;
private _buildersSchema: JsonObject;
private _architectSchemasLoaded = false;
private _targetMapMap = new Map<string, TargetMap>();
private _builderPathsMap = new Map<string, BuilderPaths>();
private _builderDescriptionMap = new Map<string, BuilderDescription>();
private _builderConstructorMap = new Map<string, BuilderConstructor<{}>>();
constructor(private _workspace: experimental.workspace.Workspace) { }
loadArchitect() {
if (this._architectSchemasLoaded) {
return of(this);
} else {
return forkJoin(
this._loadJsonFile(this._targetsSchemaPath),
this._loadJsonFile(this._buildersSchemaPath),
).pipe(
concatMap(([targetsSchema, buildersSchema]) => {
this._targetsSchema = targetsSchema;
this._buildersSchema = buildersSchema;
this._architectSchemasLoaded = true;
// Validate and cache all project target maps.
return forkJoin(
...this._workspace.listProjectNames().map(projectName => {
const unvalidatedTargetMap = this._workspace.getProjectArchitect(projectName);
return this._workspace.validateAgainstSchema<TargetMap>(
unvalidatedTargetMap, this._targetsSchema).pipe(
tap(targetMap => this._targetMapMap.set(projectName, targetMap)),
);
}),
);
}),
map(() => this),
);
}
}
listProjectTargets(projectName: string): string[] {
return Object.keys(this._getProjectTargetMap(projectName));
}
private _getProjectTargetMap(projectName: string): TargetMap {
if (!this._targetMapMap.has(projectName)) {
throw new ProjectNotFoundException(projectName);
}
return this._targetMapMap.get(projectName) as TargetMap;
}
private _getProjectTarget<T = {}>(projectName: string, targetName: string): Target<T> {
const targetMap = this._getProjectTargetMap(projectName);
const target = targetMap[targetName] as {} as Target<T>;
if (!target) {
throw new TargetNotFoundException(projectName, targetName);
}
return target;
}
getBuilderConfiguration<OptionsT>(targetSpec: TargetSpecifier): BuilderConfiguration<OptionsT> {
const {
project: projectName,
target: targetName,
configuration: configurationName,
overrides,
} = targetSpec;
const project = this._workspace.getProject(projectName);
const target = this._getProjectTarget(projectName, targetName);
const options = target.options;
let configuration: TargetConfiguration = {};
if (configurationName) {
if (!target.configurations) {
throw new ConfigurationNotFoundException(projectName, configurationName);
}
configuration = target.configurations[configurationName];
if (!configuration) {
throw new ConfigurationNotFoundException(projectName, configurationName);
}
}
const builderConfiguration: BuilderConfiguration<OptionsT> = {
root: project.root as Path,
sourceRoot: project.sourceRoot as Path | undefined,
projectType: project.projectType,
builder: target.builder,
options: {
...options,
...configuration,
...overrides as {},
} as OptionsT,
};
return builderConfiguration;
}
run<OptionsT>(
builderConfig: BuilderConfiguration<OptionsT>,
partialContext: Partial<BuilderContext> = {},
): Observable<BuildEvent> {
const context: BuilderContext = {
logger: new logging.NullLogger(),
architect: this,
host: this._workspace.host,
workspace: this._workspace,
...partialContext,
};
let builderDescription: BuilderDescription;
return this.getBuilderDescription(builderConfig).pipe(
tap(description => builderDescription = description),
concatMap(() => this.validateBuilderOptions(builderConfig, builderDescription)),
tap(validatedBuilderConfig => builderConfig = validatedBuilderConfig),
map(() => this.getBuilder(builderDescription, context)),
concatMap(builder => builder.run(builderConfig)),
);
}
getBuilderDescription<OptionsT>(
builderConfig: BuilderConfiguration<OptionsT>,
): Observable<BuilderDescription> {
// Check cache for this builder description.
if (this._builderDescriptionMap.has(builderConfig.builder)) {
return of(this._builderDescriptionMap.get(builderConfig.builder) as BuilderDescription);
}
return new Observable((obs) => {
// TODO: this probably needs to be more like NodeModulesEngineHost.
const basedir = getSystemPath(this._workspace.root);
const [pkg, builderName] = builderConfig.builder.split(':');
const pkgJsonPath = nodeResolve(pkg, { basedir, resolvePackageJson: true, checkLocal: true });
let buildersJsonPath: Path;
let builderPaths: BuilderPaths;
// Read the `builders` entry of package.json.
return this._loadJsonFile(normalize(pkgJsonPath)).pipe(
concatMap((pkgJson: JsonObject) => {
const pkgJsonBuildersentry = pkgJson['builders'] as string;
if (!pkgJsonBuildersentry) {
return throwError(new BuilderCannotBeResolvedException(builderConfig.builder));
}
buildersJsonPath = join(dirname(normalize(pkgJsonPath)), pkgJsonBuildersentry);
return this._loadJsonFile(buildersJsonPath);
}),
// Validate builders json.
concatMap((builderPathsMap) => this._workspace.validateAgainstSchema<BuilderPathsMap>(
builderPathsMap, this._buildersSchema)),
concatMap((builderPathsMap) => {
builderPaths = builderPathsMap.builders[builderName];
if (!builderPaths) {
return throwError(new BuilderCannotBeResolvedException(builderConfig.builder));
}
// Resolve paths in the builder paths.
const builderJsonDir = dirname(buildersJsonPath);
builderPaths.schema = join(builderJsonDir, builderPaths.schema);
builderPaths.class = join(builderJsonDir, builderPaths.class);
// Save the builder paths so that we can lazily load the builder.
this._builderPathsMap.set(builderConfig.builder, builderPaths);
// Load the schema.
return this._loadJsonFile(builderPaths.schema);
}),
map(builderSchema => {
const builderDescription = {
name: builderConfig.builder,
schema: builderSchema,
description: builderPaths.description,
};
// Save to cache before returning.
this._builderDescriptionMap.set(builderDescription.name, builderDescription);
return builderDescription;
}),
).subscribe(obs);
});
}
validateBuilderOptions<OptionsT>(
builderConfig: BuilderConfiguration<OptionsT>, builderDescription: BuilderDescription,
): Observable<BuilderConfiguration<OptionsT>> {
return this._workspace.validateAgainstSchema<OptionsT>(
builderConfig.options, builderDescription.schema,
).pipe(
map(validatedOptions => {
builderConfig.options = validatedOptions;
return builderConfig;
}),
);
}
getBuilder<OptionsT>(
builderDescription: BuilderDescription, context: BuilderContext,
): Builder<OptionsT> {
const name = builderDescription.name;
let builderConstructor: BuilderConstructor<OptionsT>;
// Check cache for this builder.
if (this._builderConstructorMap.has(name)) {
builderConstructor = this._builderConstructorMap.get(name) as BuilderConstructor<OptionsT>;
} else {
if (!this._builderPathsMap.has(name)) {
throw new BuilderNotFoundException(name);
}
const builderPaths = this._builderPathsMap.get(name) as BuilderPaths;
// TODO: support more than the default export, maybe via builder#import-name.
const builderModule = require(getSystemPath(builderPaths.class));
builderConstructor = builderModule['default'] as BuilderConstructor<OptionsT>;
// Save builder to cache before returning.
this._builderConstructorMap.set(builderDescription.name, builderConstructor);
}
const builder = new builderConstructor(context);
return builder;
}
private _loadJsonFile(path: Path): Observable<JsonObject> {
return this._workspace.host.read(normalize(path)).pipe(
map(buffer => virtualFs.fileBufferToString(buffer)),
map(str => parseJson(str, JsonParseMode.Loose) as {} as JsonObject),
);
}
}