Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Schematics CLI Refactoring #18945

Merged
merged 5 commits into from
Oct 2, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions etc/api/angular_devkit/schematics/tools/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,20 @@ export declare class NodePackageDoesNotSupportSchematics extends BaseException {
export declare class NodeWorkflow extends workflow.BaseWorkflow {
get engine(): FileSystemEngine;
get engineHost(): NodeModulesEngineHost;
constructor(host: virtualFs.Host, options: {
force?: boolean;
dryRun?: boolean;
constructor(host: virtualFs.Host, options: NodeWorkflowOptions & {
root?: Path;
packageManager?: string;
packageRegistry?: string;
registry?: schema.CoreSchemaRegistry;
resolvePaths?: string[];
});
constructor(root: string, options: NodeWorkflowOptions);
}

export interface NodeWorkflowOptions {
dryRun?: boolean;
force?: boolean;
packageManager?: string;
packageRegistry?: string;
registry?: schema.CoreSchemaRegistry;
resolvePaths?: string[];
schemaValidation?: boolean;
}

export declare type OptionTransform<T extends object, R extends object> = (schematic: FileSystemSchematicDescription, options: T, context?: FileSystemSchematicContext) => Observable<R> | PromiseLike<R> | R;
Expand Down
71 changes: 42 additions & 29 deletions packages/angular_devkit/schematics/tools/workflow/node-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,45 @@
* 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 { Path, getSystemPath, schema, virtualFs } from '@angular-devkit/core';
import { Path, getSystemPath, normalize, schema, virtualFs } from '@angular-devkit/core';
import { NodeJsSyncHost } from '@angular-devkit/core/node';
import {
workflow,
} from '@angular-devkit/schematics'; // tslint:disable-line:no-implicit-dependencies
import { BuiltinTaskExecutor } from '../../tasks/node';
import { FileSystemEngine } from '../description';
import { NodeModulesEngineHost } from '../node-module-engine-host';
import { validateOptionsWithSchema } from '../schema-option-transform';

export interface NodeWorkflowOptions {
force?: boolean;
dryRun?: boolean;
packageManager?: string;
packageRegistry?: string;
registry?: schema.CoreSchemaRegistry;
resolvePaths?: string[];
schemaValidation?: boolean;
}

/**
* A workflow specifically for Node tools.
*/
export class NodeWorkflow extends workflow.BaseWorkflow {
constructor(
host: virtualFs.Host,
options: {
force?: boolean;
dryRun?: boolean;
root?: Path;
packageManager?: string;
packageRegistry?: string;
registry?: schema.CoreSchemaRegistry;
resolvePaths?: string[],
},
) {
constructor(root: string, options: NodeWorkflowOptions);

constructor(host: virtualFs.Host, options: NodeWorkflowOptions & { root?: Path });

constructor(hostOrRoot: virtualFs.Host | string, options: NodeWorkflowOptions & { root?: Path }) {
let host;
let root;
if (typeof hostOrRoot === 'string') {
root = normalize(hostOrRoot);
host = new virtualFs.ScopedHost(new NodeJsSyncHost(), root);
} else {
host = hostOrRoot;
root = options.root;
}

const engineHost = new NodeModulesEngineHost(options.resolvePaths);
super({
host,
Expand All @@ -39,29 +54,27 @@ export class NodeWorkflow extends workflow.BaseWorkflow {
registry: options.registry,
});

engineHost.registerTaskExecutor(
BuiltinTaskExecutor.NodePackage,
{
allowPackageManagerOverride: true,
packageManager: options.packageManager,
rootDirectory: options.root && getSystemPath(options.root),
registry: options.packageRegistry,
},
);
engineHost.registerTaskExecutor(
BuiltinTaskExecutor.RepositoryInitializer,
{
rootDirectory: options.root && getSystemPath(options.root),
},
);
engineHost.registerTaskExecutor(BuiltinTaskExecutor.NodePackage, {
allowPackageManagerOverride: true,
packageManager: options.packageManager,
rootDirectory: root && getSystemPath(root),
registry: options.packageRegistry,
});
engineHost.registerTaskExecutor(BuiltinTaskExecutor.RepositoryInitializer, {
rootDirectory: root && getSystemPath(root),
});
engineHost.registerTaskExecutor(BuiltinTaskExecutor.RunSchematic);
engineHost.registerTaskExecutor(BuiltinTaskExecutor.TslintFix);

if (options.schemaValidation) {
engineHost.registerOptionsTransform(validateOptionsWithSchema(this.registry));
}

this._context = [];
}

get engine(): FileSystemEngine {
return this._engine as {} as FileSystemEngine;
return this._engine as FileSystemEngine;
}
get engineHost(): NodeModulesEngineHost {
return this._engineHost as NodeModulesEngineHost;
Expand Down
46 changes: 12 additions & 34 deletions packages/angular_devkit/schematics_cli/bin/schematics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,10 @@
// symbol polyfill must go first
import 'symbol-observable';
// tslint:disable-next-line:ordered-imports import-groups
import {
JsonObject,
logging,
normalize,
schema,
tags,
virtualFs,
} from '@angular-devkit/core';
import { NodeJsSyncHost, ProcessOutput, createConsoleLogger } from '@angular-devkit/core/node';
import {
DryRunEvent,
UnsuccessfulWorkflowExecution,
formats,
} from '@angular-devkit/schematics';
import { NodeWorkflow, validateOptionsWithSchema } from '@angular-devkit/schematics/tools';
import { logging, schema, tags } from '@angular-devkit/core';
import { ProcessOutput, createConsoleLogger } from '@angular-devkit/core/node';
import { UnsuccessfulWorkflowExecution } from '@angular-devkit/schematics';
import { NodeWorkflow } from '@angular-devkit/schematics/tools';
import * as ansiColors from 'ansi-colors';
import * as inquirer from 'inquirer';
import * as minimist from 'minimist';
Expand Down Expand Up @@ -77,7 +66,7 @@ function _listSchematics(workflow: NodeWorkflow, collectionName: string, logger:
}

function _createPromptProvider(): schema.PromptProvider {
return (definitions: Array<schema.PromptDefinition>) => {
return (definitions) => {
const questions: inquirer.QuestionCollection = definitions.map(definition => {
const question: inquirer.Question = {
name: definition.id,
Expand Down Expand Up @@ -158,16 +147,12 @@ export async function main({
const force = argv['force'];
const allowPrivate = argv['allow-private'];

/** Create a Virtual FS Host scoped to where the process is being run. **/
const fsHost = new virtualFs.ScopedHost(new NodeJsSyncHost(), normalize(process.cwd()));
const registry = new schema.CoreSchemaRegistry(formats.standardFormats);

/** Create the workflow that will be executed with this run. */
const workflow = new NodeWorkflow(fsHost, {
/** Create the workflow scoped to the working directory that will be executed with this run. */
const workflow = new NodeWorkflow(process.cwd(), {
force,
dryRun,
registry,
resolvePaths: [process.cwd(), __dirname],
schemaValidation: true,
});

/** If the user wants to list schematics, we simply show all the schematic names. */
Expand All @@ -181,9 +166,6 @@ export async function main({
return 1;
}

registry.addPostTransform(schema.transforms.addUndefinedDefaults);
workflow.engineHost.registerOptionsTransform(validateOptionsWithSchema(registry));

// Indicate to the user when nothing has been done. This is automatically set to off when there's
// a new DryRunEvent.
let nothingDone = true;
Expand All @@ -203,7 +185,7 @@ export async function main({
*
* This is a simple way to only show errors when an error occur.
*/
workflow.reporter.subscribe((event: DryRunEvent) => {
workflow.reporter.subscribe((event) => {
nothingDone = false;
// Strip leading slash to prevent confusion.
const eventPath = event.path.startsWith('/') ? event.path.substr(1) : event.path;
Expand All @@ -216,14 +198,10 @@ export async function main({
logger.error(`ERROR! ${eventPath} ${desc}.`);
break;
case 'update':
loggingQueue.push(tags.oneLine`
${colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)
`);
loggingQueue.push(`${colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)`);
break;
case 'create':
loggingQueue.push(tags.oneLine`
${colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)
`);
loggingQueue.push(`${colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)`);
break;
case 'delete':
loggingQueue.push(`${colors.yellow('DELETE')} ${eventPath}`);
Expand Down Expand Up @@ -273,7 +251,7 @@ export async function main({
workflow.registry.useXDeprecatedProvider(msg => logger.warn(msg));

// Pass the rest of the arguments as the smart default "argv". Then delete it.
workflow.registry.addSmartDefaultProvider('argv', (schema: JsonObject) => {
workflow.registry.addSmartDefaultProvider('argv', (schema) => {
if ('index' in schema) {
return argv._[Number(schema['index'])];
} else {
Expand Down