cleanup(core): use the use generator instead of schematic

This commit is contained in:
Victor Savkin 2020-11-19 13:43:07 -05:00 committed by Victor Savkin
parent ea17900378
commit 06e13dae2f
40 changed files with 325 additions and 325 deletions

View File

@ -14630,7 +14630,7 @@ export const mediumGraph = {
}, },
{ {
file: file:
'apps/nx-docs-site/src/assets/content/shared/tools-workspace-schematics.md', 'apps/nx-docs-site/src/assets/content/shared/tools-workspace-generators.md',
hash: '36a8e3fdd9166bebbc14220e92feb4e32f0d2f96', hash: '36a8e3fdd9166bebbc14220e92feb4e32f0d2f96',
ext: '.md', ext: '.md',
}, },

View File

@ -1,25 +1,29 @@
# workspace-schematic # workspace-generator
Generates a workspace schematic Generates a workspace generator
## Usage ## Usage
```bash ```bash
nx generate workspace-schematic ... nx generate workspace-generator ...
``` ```
By default, Nx will search for `workspace-schematic` in the default collection provisioned in `angular.json`. ```bash
nx g workspace-schematic ... # same
```
By default, Nx will search for `workspace-generator` in the default collection provisioned in `angular.json`.
You can specify the collection explicitly as follows: You can specify the collection explicitly as follows:
```bash ```bash
nx g @nrwl/workspace:workspace-schematic ... nx g @nrwl/workspace:workspace-generator ...
``` ```
Show what will be generated without writing to disk: Show what will be generated without writing to disk:
```bash ```bash
nx g workspace-schematic ... --dry-run nx g workspace-generator ... --dry-run
``` ```
## Options ## Options

View File

@ -1,11 +1,11 @@
# workspace-schematic # workspace-generator
Runs a workspace schematic from the tools/schematics directory Runs a workspace generator from the tools/generators directory
## Usage ## Usage
```bash ```bash
nx workspace-schematic nx workspace-generator
``` ```
Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`. Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`.
@ -16,13 +16,13 @@ Install `nx` globally to invoke the command directly using `nx`, or use `npm run
Show help Show help
### list-schematics ### list-generators
List the available workspace-schematics List the available workspace-generators
### name ### name
The name of your schematic` The name of your generator`
### version ### version

View File

@ -236,9 +236,9 @@
"file": "angular/cli/workspace-lint" "file": "angular/cli/workspace-lint"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "angular/cli/workspace-schematic" "file": "angular/cli/workspace-generator"
} }
] ]
}, },
@ -287,9 +287,9 @@
"file": "angular/api-workspace/schematics/run-commands" "file": "angular/api-workspace/schematics/run-commands"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "angular/api-workspace/schematics/workspace-schematic" "file": "angular/api-workspace/schematics/workspace-generator"
} }
] ]
}, },
@ -941,8 +941,8 @@
}, },
{ {
"name": "Workspace Schematics", "name": "Workspace Schematics",
"id": "workspace-schematics", "id": "workspace-generators",
"file": "shared/tools-workspace-schematics" "file": "shared/tools-workspace-generators"
} }
] ]
}, },
@ -1329,9 +1329,9 @@
"file": "react/cli/workspace-lint" "file": "react/cli/workspace-lint"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "react/cli/workspace-schematic" "file": "react/cli/workspace-generator"
} }
] ]
}, },
@ -1380,9 +1380,9 @@
"file": "react/api-workspace/schematics/run-commands" "file": "react/api-workspace/schematics/run-commands"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "react/api-workspace/schematics/workspace-schematic" "file": "react/api-workspace/schematics/workspace-generator"
} }
] ]
}, },
@ -2034,8 +2034,8 @@
}, },
{ {
"name": "Workspace Schematics", "name": "Workspace Schematics",
"id": "workspace-schematics", "id": "workspace-generators",
"file": "shared/tools-workspace-schematics" "file": "shared/tools-workspace-generators"
} }
] ]
}, },
@ -2375,9 +2375,9 @@
"file": "node/cli/workspace-lint" "file": "node/cli/workspace-lint"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "node/cli/workspace-schematic" "file": "node/cli/workspace-generator"
} }
] ]
}, },
@ -2426,9 +2426,9 @@
"file": "node/api-workspace/schematics/run-commands" "file": "node/api-workspace/schematics/run-commands"
}, },
{ {
"name": "workspace-schematic", "name": "workspace-generator",
"id": "workspace-schematic", "id": "workspace-generator",
"file": "node/api-workspace/schematics/workspace-schematic" "file": "node/api-workspace/schematics/workspace-generator"
} }
] ]
}, },
@ -3074,8 +3074,8 @@
}, },
{ {
"name": "Workspace Schematics", "name": "Workspace Schematics",
"id": "workspace-schematics", "id": "workspace-generators",
"file": "shared/tools-workspace-schematics" "file": "shared/tools-workspace-generators"
} }
] ]
}, },

View File

@ -1,25 +1,29 @@
# workspace-schematic # workspace-generator
Generates a workspace schematic Generates a workspace generator
## Usage ## Usage
```bash ```bash
nx generate workspace-schematic ... nx generate workspace-generator ...
``` ```
By default, Nx will search for `workspace-schematic` in the default collection provisioned in `workspace.json`. ```bash
nx g workspace-schematic ... # same
```
By default, Nx will search for `workspace-generator` in the default collection provisioned in `workspace.json`.
You can specify the collection explicitly as follows: You can specify the collection explicitly as follows:
```bash ```bash
nx g @nrwl/workspace:workspace-schematic ... nx g @nrwl/workspace:workspace-generator ...
``` ```
Show what will be generated without writing to disk: Show what will be generated without writing to disk:
```bash ```bash
nx g workspace-schematic ... --dry-run nx g workspace-generator ... --dry-run
``` ```
## Options ## Options

View File

@ -1,11 +1,11 @@
# workspace-schematic # workspace-generator
Runs a workspace schematic from the tools/schematics directory Runs a workspace generator from the tools/generators directory
## Usage ## Usage
```bash ```bash
nx workspace-schematic nx workspace-generator
``` ```
Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`. Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`.
@ -16,13 +16,13 @@ Install `nx` globally to invoke the command directly using `nx`, or use `npm run
Show help Show help
### list-schematics ### list-generators
List the available workspace-schematics List the available workspace-generators
### name ### name
The name of your schematic` The name of your generator`
### version ### version

View File

@ -1,25 +1,29 @@
# workspace-schematic # workspace-generator
Generates a workspace schematic Generates a workspace generator
## Usage ## Usage
```bash ```bash
nx generate workspace-schematic ... nx generate workspace-generator ...
``` ```
By default, Nx will search for `workspace-schematic` in the default collection provisioned in `workspace.json`. ```bash
nx g workspace-schematic ... # same
```
By default, Nx will search for `workspace-generator` in the default collection provisioned in `workspace.json`.
You can specify the collection explicitly as follows: You can specify the collection explicitly as follows:
```bash ```bash
nx g @nrwl/workspace:workspace-schematic ... nx g @nrwl/workspace:workspace-generator ...
``` ```
Show what will be generated without writing to disk: Show what will be generated without writing to disk:
```bash ```bash
nx g workspace-schematic ... --dry-run nx g workspace-generator ... --dry-run
``` ```
## Options ## Options

View File

@ -1,11 +1,11 @@
# workspace-schematic # workspace-generator
Runs a workspace schematic from the tools/schematics directory Runs a workspace generator from the tools/generators directory
## Usage ## Usage
```bash ```bash
nx workspace-schematic nx workspace-generator
``` ```
Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`. Install `nx` globally to invoke the command directly using `nx`, or use `npm run nx` or `yarn nx`.
@ -16,13 +16,13 @@ Install `nx` globally to invoke the command directly using `nx`, or use `npm run
Show help Show help
### list-schematics ### list-generators
List the available workspace-schematics List the available workspace-generators
### name ### name
The name of your schematic` The name of your generator`
### version ### version

View File

@ -88,7 +88,7 @@ forEachCli('angular', () => {
'update:check': 'ng update', 'update:check': 'ng update',
postinstall: 'node ./decorate-angular-cli.js', postinstall: 'node ./decorate-angular-cli.js',
'dep-graph': 'nx dep-graph', 'dep-graph': 'nx dep-graph',
'workspace-schematic': 'nx workspace-schematic', 'workspace-generator': 'nx workspace-generator',
help: 'nx help', help: 'nx help',
}); });
expect( expect(

View File

@ -16,6 +16,7 @@ forEachCli('nx', () => {
describe('Help', () => { describe('Help', () => {
it('should show help', async () => { it('should show help', async () => {
newProject(); newProject();
// sss
const myapp = uniq('myapp'); const myapp = uniq('myapp');
runCLI(`generate @nrwl/web:app ${myapp}`); runCLI(`generate @nrwl/web:app ${myapp}`);

View File

@ -215,27 +215,27 @@ forEachCli((cli) => {
}); });
}); });
describe('workspace-schematic', () => { describe('workspace-generator', () => {
let custom: string; let custom: string;
let failing: string; let failing: string;
beforeEach(() => { beforeEach(() => {
custom = uniq('custom'); custom = uniq('custom');
failing = uniq('custom-failing'); failing = uniq('custom-failing');
runCLI(`g workspace-schematic ${custom} --no-interactive`); runCLI(`g workspace-generator ${custom} --no-interactive`);
runCLI(`g workspace-schematic ${failing} --no-interactive`); runCLI(`g workspace-generator ${failing} --no-interactive`);
checkFilesExist( checkFilesExist(
`tools/schematics/${custom}/index.ts`, `tools/generators/${custom}/index.ts`,
`tools/schematics/${custom}/schema.json` `tools/generators/${custom}/schema.json`
); );
checkFilesExist( checkFilesExist(
`tools/schematics/${failing}/index.ts`, `tools/generators/${failing}/index.ts`,
`tools/schematics/${failing}/schema.json` `tools/generators/${failing}/schema.json`
); );
}); });
it('should compile only schematic files with dependencies', () => { it('should compile only generator files with dependencies', () => {
const workspace = uniq('workspace'); const workspace = uniq('workspace');
updateFile( updateFile(
@ -251,12 +251,12 @@ forEachCli((cli) => {
` `
); );
updateFile( updateFile(
`tools/schematics/utils.ts`, `tools/generators/utils.ts`,
` `
export const noop = ()=>{} export const noop = ()=>{}
` `
); );
updateFile(`tools/schematics/${custom}/index.ts`, (content) => { updateFile(`tools/generators/${custom}/index.ts`, (content) => {
return ` return `
import { log } from '../../utils/logger'; \n import { log } from '../../utils/logger'; \n
${content} ${content}
@ -264,13 +264,13 @@ forEachCli((cli) => {
}); });
runCommand( runCommand(
`nx workspace-schematic ${custom} ${workspace} --no-interactive -d` `nx workspace-generator ${custom} ${workspace} --no-interactive -d`
); );
expect(() => expect(() =>
checkFilesExist( checkFilesExist(
`dist/out-tsc/tools/schematics/${custom}/index.js`, `dist/out-tsc/tools/generators/${custom}/index.js`,
`dist/out-tsc/tools/schematics/utils.js`, `dist/out-tsc/tools/generators/utils.js`,
`dist/out-tsc/tools/utils/logger.js` `dist/out-tsc/tools/utils/logger.js`
) )
).not.toThrow(); ).not.toThrow();
@ -279,8 +279,8 @@ forEachCli((cli) => {
).toThrow(); ).toThrow();
}); });
it('should support workspace-specific schematics', async () => { it('should support workspace-specific generators', async () => {
const json = readJson(`tools/schematics/${custom}/schema.json`); const json = readJson(`tools/generators/${custom}/schema.json`);
json.properties['directory'] = { json.properties['directory'] = {
type: 'string', type: 'string',
description: 'lib directory', description: 'lib directory',
@ -290,13 +290,13 @@ forEachCli((cli) => {
description: 'skip changes to tsconfig', description: 'skip changes to tsconfig',
}; };
updateFile( updateFile(
`tools/schematics/${custom}/schema.json`, `tools/generators/${custom}/schema.json`,
JSON.stringify(json) JSON.stringify(json)
); );
const indexFile = readFile(`tools/schematics/${custom}/index.ts`); const indexFile = readFile(`tools/generators/${custom}/index.ts`);
updateFile( updateFile(
`tools/schematics/${custom}/index.ts`, `tools/generators/${custom}/index.ts`,
indexFile.replace( indexFile.replace(
'name: schema.name', 'name: schema.name',
'name: schema.name, directory: schema.directory, skipTsConfig: schema.skipTsConfig' 'name: schema.name, directory: schema.directory, skipTsConfig: schema.skipTsConfig'
@ -305,29 +305,29 @@ forEachCli((cli) => {
const workspace = uniq('workspace'); const workspace = uniq('workspace');
const dryRunOutput = runCLI( const dryRunOutput = runCLI(
`workspace-schematic ${custom} ${workspace} --no-interactive --directory=dir --skipTsConfig=true -d` `workspace-generator ${custom} ${workspace} --no-interactive --directory=dir --skipTsConfig=true -d`
); );
expect(exists(`libs/dir/${workspace}/src/index.ts`)).toEqual(false); expect(exists(`libs/dir/${workspace}/src/index.ts`)).toEqual(false);
expect(dryRunOutput).toContain(`UPDATE ${workspaceConfigName()}`); expect(dryRunOutput).toContain(`UPDATE ${workspaceConfigName()}`);
expect(dryRunOutput).toContain('UPDATE nx.json'); expect(dryRunOutput).toContain('UPDATE nx.json');
const output = runCLI( const output = runCLI(
`workspace-schematic ${custom} ${workspace} --no-interactive --directory=dir` `workspace-generator ${custom} ${workspace} --no-interactive --directory=dir`
); );
checkFilesExist(`libs/dir/${workspace}/src/index.ts`); checkFilesExist(`libs/dir/${workspace}/src/index.ts`);
expect(output).toContain(`UPDATE ${workspaceConfigName()}`); expect(output).toContain(`UPDATE ${workspaceConfigName()}`);
expect(output).toContain('UPDATE nx.json'); expect(output).toContain('UPDATE nx.json');
const jsonFailing = readJson(`tools/schematics/${failing}/schema.json`); const jsonFailing = readJson(`tools/generators/${failing}/schema.json`);
jsonFailing.properties = {}; jsonFailing.properties = {};
jsonFailing.required = []; jsonFailing.required = [];
updateFile( updateFile(
`tools/schematics/${failing}/schema.json`, `tools/generators/${failing}/schema.json`,
JSON.stringify(jsonFailing) JSON.stringify(jsonFailing)
); );
updateFile( updateFile(
`tools/schematics/${failing}/index.ts`, `tools/generators/${failing}/index.ts`,
` `
export default function() { export default function() {
throw new Error(); throw new Error();
@ -336,15 +336,13 @@ forEachCli((cli) => {
); );
try { try {
await runCLI(`workspace-schematic ${failing} --no-interactive`); await runCLI(`workspace-generator ${failing} --no-interactive`);
fail(`Should exit 1 for a workspace-schematic that throws an error`); fail(`Should exit 1 for a workspace-generator that throws an error`);
} catch (e) {} } catch (e) {}
const listSchematicsOutput = runCLI( const listOutput = runCLI('workspace-generator --list-generators');
'workspace-schematic --list-schematics' expect(listOutput).toContain(custom);
); expect(listOutput).toContain(failing);
expect(listSchematicsOutput).toContain(custom);
expect(listSchematicsOutput).toContain(failing);
}, 1000000); }, 1000000);
}); });

View File

@ -1,6 +1,6 @@
{ {
"name": "@nrwl/nx-source", "name": "@nrwl/nx-source",
"version": "11.0.0-beta.2", "version": "11.0.0-beta.4",
"description": "Extensible Dev Tools for Monorepos", "description": "Extensible Dev Tools for Monorepos",
"homepage": "https://nx.dev", "homepage": "https://nx.dev",
"main": "index.js", "main": "index.js",

View File

@ -2,7 +2,7 @@ import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import { Workspace } from './workspace'; import { Workspace } from './workspace';
import { parseRunOneOptions } from './parse-run-one-options'; import { parseRunOneOptions } from './parse-run-one-options';
import { useNxToRunNxBuilderOrSchematic } from './use-nx-to-run-nx-builder-or-schematic'; import { useNxToRunNxBuilderOrGenerator } from './use-nx-to-run-nx-builder-or-generator';
/** /**
* Nx is being run inside a workspace. * Nx is being run inside a workspace.
@ -27,7 +27,7 @@ export function initLocal(workspace: Workspace) {
} else { } else {
// not using the tasks runner // not using the tasks runner
if (runOpts === false || process.env.NX_SKIP_TASKS_RUNNER) { if (runOpts === false || process.env.NX_SKIP_TASKS_RUNNER) {
loadCli(workspace, useNxToRunNxBuilderOrSchematic()); loadCli(workspace, useNxToRunNxBuilderOrGenerator());
} else { } else {
require('@nrwl/workspace' + '/src/command-line/run-one').runOne(runOpts); require('@nrwl/workspace' + '/src/command-line/run-one').runOne(runOpts);
} }

View File

@ -8,12 +8,12 @@ import {
} from '@nrwl/tao/src/shared/workspace'; } from '@nrwl/tao/src/shared/workspace';
const ws = new Workspaces(); const ws = new Workspaces();
export function useNxToRunNxBuilderOrSchematic() { export function useNxToRunNxBuilderOrGenerator() {
try { try {
const dir = findWorkspaceRoot(__dirname).dir; const dir = findWorkspaceRoot(__dirname).dir;
const args = process.argv.slice(2); const args = process.argv.slice(2);
const wd = ws.readWorkspaceConfiguration(dir); const wd = ws.readWorkspaceConfiguration(dir);
return isNxBuilder(dir, args, wd) || isNxSchematic(dir, args, wd); return isNxBuilder(dir, args, wd) || isNxGenerator(dir, args, wd);
} catch (e) { } catch (e) {
return false; return false;
} }
@ -33,17 +33,17 @@ function isNxBuilder(dir: string, args: string[], wd: WorkspaceDefinition) {
} }
} }
function isNxSchematic(dir: string, args: string[], wd: WorkspaceDefinition) { function isNxGenerator(dir: string, args: string[], wd: WorkspaceDefinition) {
try { try {
if (args[0] != 'g' && args[0] != 'generate') return false; if (args[0] != 'g' && args[0] != 'generate') return false;
const defaultCollection = wd.cli ? wd.cli.defaultCollection : null; const defaultCollection = wd.cli ? wd.cli.defaultCollection : null;
let [collectionName, schematicName] = args[1].split(':'); let [collectionName, generatorName] = args[1].split(':');
if (!schematicName) { if (!generatorName) {
schematicName = collectionName; generatorName = collectionName;
collectionName = defaultCollection; collectionName = defaultCollection;
} }
return ws.isNxSchematic(collectionName, schematicName); return ws.isNxGenerator(collectionName, generatorName);
} catch (e) { } catch (e) {
return false; return false;
} }

View File

@ -1,13 +1,13 @@
import * as minimist from 'minimist'; import * as minimist from 'minimist';
import { getLogger } from '../shared/logger'; import { getLogger } from '../shared/logger';
import { import {
combineOptionsForSchematic, combineOptionsForGenerator,
convertToCamelCase, convertToCamelCase,
handleErrors, handleErrors,
Options, Options,
Schema, Schema,
} from '../shared/params'; } from '../shared/params';
import { commandName, printHelp } from '../shared/print-help'; import { printHelp } from '../shared/print-help';
import { WorkspaceDefinition, Workspaces } from '../shared/workspace'; import { WorkspaceDefinition, Workspaces } from '../shared/workspace';
import { statSync, unlinkSync, writeFileSync } from 'fs'; import { statSync, unlinkSync, writeFileSync } from 'fs';
import { mkdirpSync, rmdirSync } from 'fs-extra'; import { mkdirpSync, rmdirSync } from 'fs-extra';
@ -18,8 +18,8 @@ const chalk = require('chalk');
export interface GenerateOptions { export interface GenerateOptions {
collectionName: string; collectionName: string;
schematicName: string; generatorName: string;
schematicOptions: Options; generatorOptions: Options;
help: boolean; help: boolean;
debug: boolean; debug: boolean;
dryRun: boolean; dryRun: boolean;
@ -30,7 +30,7 @@ export interface GenerateOptions {
function throwInvalidInvocation() { function throwInvalidInvocation() {
throw new Error( throw new Error(
`Specify the schematic name (e.g., ${commandName} generate collection-name:schematic-name)` `Specify the generator name (e.g., nx generate @nrwl/workspace:library)`
); );
} }
@ -39,7 +39,7 @@ function parseGenerateOpts(
mode: 'generate' | 'new', mode: 'generate' | 'new',
defaultCollection: string | null defaultCollection: string | null
): GenerateOptions { ): GenerateOptions {
const schematicOptions = convertToCamelCase( const generatorOptions = convertToCamelCase(
minimist(args, { minimist(args, {
boolean: ['help', 'dryRun', 'debug', 'force', 'interactive'], boolean: ['help', 'dryRun', 'debug', 'force', 'interactive'],
alias: { alias: {
@ -55,24 +55,24 @@ function parseGenerateOpts(
); );
let collectionName: string | null = null; let collectionName: string | null = null;
let schematicName: string | null = null; let generatorName: string | null = null;
if (mode === 'generate') { if (mode === 'generate') {
if ( if (
!schematicOptions['_'] || !generatorOptions['_'] ||
(schematicOptions['_'] as string[]).length === 0 (generatorOptions['_'] as string[]).length === 0
) { ) {
throwInvalidInvocation(); throwInvalidInvocation();
} }
[collectionName, schematicName] = (schematicOptions['_'] as string[]) [collectionName, generatorName] = (generatorOptions['_'] as string[])
.shift() .shift()
.split(':'); .split(':');
if (!schematicName) { if (!generatorName) {
schematicName = collectionName; generatorName = collectionName;
collectionName = defaultCollection; collectionName = defaultCollection;
} }
} else { } else {
collectionName = schematicOptions.collection as string; collectionName = generatorOptions.collection as string;
schematicName = ''; generatorName = '';
} }
if (!collectionName) { if (!collectionName) {
@ -81,24 +81,24 @@ function parseGenerateOpts(
const res = { const res = {
collectionName, collectionName,
schematicName, generatorName,
schematicOptions, generatorOptions,
help: schematicOptions.help as boolean, help: generatorOptions.help as boolean,
debug: schematicOptions.debug as boolean, debug: generatorOptions.debug as boolean,
dryRun: schematicOptions.dryRun as boolean, dryRun: generatorOptions.dryRun as boolean,
force: schematicOptions.force as boolean, force: generatorOptions.force as boolean,
interactive: schematicOptions.interactive as boolean, interactive: generatorOptions.interactive as boolean,
defaults: schematicOptions.defaults as boolean, defaults: generatorOptions.defaults as boolean,
}; };
delete schematicOptions.debug; delete generatorOptions.debug;
delete schematicOptions.d; delete generatorOptions.d;
delete schematicOptions.dryRun; delete generatorOptions.dryRun;
delete schematicOptions.force; delete generatorOptions.force;
delete schematicOptions.interactive; delete generatorOptions.interactive;
delete schematicOptions.defaults; delete generatorOptions.defaults;
delete schematicOptions.help; delete generatorOptions.help;
delete schematicOptions['--']; delete generatorOptions['--'];
return res; return res;
} }
@ -109,7 +109,7 @@ export function printGenHelp(
logger: Console logger: Console
) { ) {
printHelp( printHelp(
`${commandName} generate ${opts.collectionName}:${opts.schematicName}`, `nx generate ${opts.collectionName}:${opts.generatorName}`,
{ {
...schema, ...schema,
properties: { properties: {
@ -186,10 +186,10 @@ export async function generate(
readDefaultCollection(workspaceDefinition) readDefaultCollection(workspaceDefinition)
); );
if (ws.isNxSchematic(opts.collectionName, opts.schematicName)) { if (ws.isNxGenerator(opts.collectionName, opts.generatorName)) {
const { schema, implementation } = ws.readSchematic( const { schema, implementation } = ws.readGenerator(
opts.collectionName, opts.collectionName,
opts.schematicName opts.generatorName
); );
if (opts.help) { if (opts.help) {
@ -197,10 +197,10 @@ export async function generate(
return 0; return 0;
} }
const combinedOpts = await combineOptionsForSchematic( const combinedOpts = await combineOptionsForGenerator(
opts.schematicOptions, opts.generatorOptions,
opts.collectionName, opts.collectionName,
opts.schematicName, opts.generatorName,
workspaceDefinition, workspaceDefinition,
schema, schema,
opts.interactive opts.interactive

View File

@ -1,42 +1,35 @@
import { tags, terminal } from '@angular-devkit/core'; import { tags, terminal } from '@angular-devkit/core';
import { getLogger } from '../shared/logger'; import { getLogger } from '../shared/logger';
import { commandName, toolDescription } from '../shared/print-help';
export function help() { export function help() {
const logger = getLogger(true); const logger = getLogger(true);
logger.info(tags.stripIndent` logger.info(tags.stripIndent`
${terminal.bold(toolDescription)} ${terminal.bold('Nx - Extensible Dev Tools for Monorepos.')}
${terminal.bold('Create a new project.')} ${terminal.bold('Create a new project.')}
${commandName} new ${terminal.grey( nx new ${terminal.grey(
'[project-name] [--collection=schematic-collection] [options, ...]' '[project-name] [--collection=collection] [options, ...]'
)} )}
${terminal.bold('Generate code.')} ${terminal.bold('Generate code.')}
${commandName} generate ${terminal.grey( nx generate ${terminal.grey('[collection:][generator] [options, ...]')}
'[schematic-collection:][schematic] [options, ...]' nx g ${terminal.grey('[collection:][generator] [options, ...]')}
)}
${commandName} g ${terminal.grey(
'[schematic-collection:][schematic] [options, ...]'
)}
${terminal.bold('Run target.')} ${terminal.bold('Run target.')}
${commandName} run ${terminal.grey( nx run ${terminal.grey(
'[project][:target][:configuration] [options, ...]' '[project][:target][:configuration] [options, ...]'
)} )}
${commandName} r ${terminal.grey( nx r ${terminal.grey('[project][:target][:configuration] [options, ...]')}
'[project][:target][:configuration] [options, ...]'
)}
You can also use the infix notation to run a target: You can also use the infix notation to run a target:
${commandName} [target] [project] [options, ...] nx [target] [project] [options, ...]
${terminal.bold('Migrate packages and create migrations.json.')} ${terminal.bold('Migrate packages and create migrations.json.')}
${commandName} migrate ${terminal.grey('[package-name]')} nx migrate ${terminal.grey('[package-name]')}
${terminal.bold('Run migrations.')} ${terminal.bold('Run migrations.')}
${commandName} migrate ${terminal.grey('--run-migrations=[filename]')} nx migrate ${terminal.grey('--run-migrations=[filename]')}
`); `);
return 0; return 0;

View File

@ -96,8 +96,8 @@ async function createWorkflow(
registry: new schema.CoreSchemaRegistry(formats.standardFormats), registry: new schema.CoreSchemaRegistry(formats.standardFormats),
resolvePaths: [process.cwd(), root], resolvePaths: [process.cwd(), root],
}); });
const _params = opts.schematicOptions._; const _params = opts.generatorOptions._;
delete opts.schematicOptions._; delete opts.generatorOptions._;
workflow.registry.addSmartDefaultProvider('argv', (schema: JsonObject) => { workflow.registry.addSmartDefaultProvider('argv', (schema: JsonObject) => {
if ('index' in schema) { if ('index' in schema) {
return _params[Number(schema['index'])]; return _params[Number(schema['index'])];
@ -272,25 +272,25 @@ async function runSchematic(
} }
const defaults = const defaults =
opts.schematicName === 'tao-new' || opts.schematicName === 'ng-new' opts.generatorName === 'tao-new' || opts.generatorName === 'ng-new'
? {} ? {}
: await getSchematicDefaults( : await getSchematicDefaults(
root, root,
opts.collectionName, opts.collectionName,
opts.schematicName opts.generatorName
); );
const record = { loggingQueue: [] as string[], error: false }; const record = { loggingQueue: [] as string[], error: false };
workflow.reporter.subscribe(recorder || createRecorder(record, logger)); workflow.reporter.subscribe(recorder || createRecorder(record, logger));
const schematicOptions = normalizeOptions( const schematicOptions = normalizeOptions(
opts.schematicOptions, opts.generatorOptions,
flattenedSchema flattenedSchema
); );
if (schematicOptions['--'] && !allowAdditionalArgs) { if (schematicOptions['--'] && !allowAdditionalArgs) {
schematicOptions['--'].forEach((unmatched) => { schematicOptions['--'].forEach((unmatched) => {
const message = const message =
`Could not match option '${unmatched.name}' to the ${opts.collectionName}:${opts.schematicName} schema.` + `Could not match option '${unmatched.name}' to the ${opts.collectionName}:${opts.generatorName} schema.` +
(unmatched.possible.length > 0 (unmatched.possible.length > 0
? ` Possible matches : ${unmatched.possible.join()}` ? ` Possible matches : ${unmatched.possible.join()}`
: ''); : '');
@ -303,7 +303,7 @@ async function runSchematic(
await workflow await workflow
.execute({ .execute({
collection: opts.collectionName, collection: opts.collectionName,
schematic: opts.schematicName, schematic: opts.generatorName,
options: { ...defaults, ...schematicOptions }, options: { ...defaults, ...schematicOptions },
debug: opts.debug, debug: opts.debug,
logger, logger,
@ -335,13 +335,13 @@ export async function generate(
); );
const workflow = await createWorkflow(fsHost, root, opts); const workflow = await createWorkflow(fsHost, root, opts);
const collection = getCollection(workflow, opts.collectionName); const collection = getCollection(workflow, opts.collectionName);
const schematic = collection.createSchematic(opts.schematicName, true); const schematic = collection.createSchematic(opts.generatorName, true);
return ( return (
await runSchematic( await runSchematic(
root, root,
workflow, workflow,
logger, logger,
{ ...opts, schematicName: schematic.description.name }, { ...opts, generatorName: schematic.description.name },
schematic schematic
) )
).status; ).status;
@ -349,9 +349,9 @@ export async function generate(
export function wrapAngularDevkitSchematic( export function wrapAngularDevkitSchematic(
collectionName: string, collectionName: string,
schematicName: string generatorName: string
) { ) {
return (schematicOptions: { [k: string]: any }) => { return (generatorOptions: { [k: string]: any }) => {
return async (host: taoTree.Tree) => { return async (host: taoTree.Tree) => {
const emptyLogger = { const emptyLogger = {
log: (e) => {}, log: (e) => {},
@ -394,19 +394,19 @@ export function wrapAngularDevkitSchematic(
); );
const options = { const options = {
schematicOptions: { ...schematicOptions, _: [] }, generatorOptions: { ...generatorOptions, _: [] },
dryRun: true, dryRun: true,
interactive: false, interactive: false,
help: false, help: false,
debug: false, debug: false,
collectionName, collectionName,
schematicName, generatorName,
force: false, force: false,
defaults: false, defaults: false,
}; };
const workflow = await createWorkflow(fsHost, host.root, options); const workflow = await createWorkflow(fsHost, host.root, options);
const collection = getCollection(workflow, collectionName); const collection = getCollection(workflow, collectionName);
const schematic = collection.createSchematic(schematicName, true); const schematic = collection.createSchematic(generatorName, true);
const res = await runSchematic( const res = await runSchematic(
host.root, host.root,
workflow, workflow,
@ -437,7 +437,7 @@ export async function invokeNew(
const workflow = await createWorkflow(fsHost, root, opts); const workflow = await createWorkflow(fsHost, root, opts);
const collection = getCollection(workflow, opts.collectionName); const collection = getCollection(workflow, opts.collectionName);
const schematic = collection.createSchematic( const schematic = collection.createSchematic(
opts.schematicOptions.cli === 'ng' ? 'ng-new' : 'tao-new', opts.generatorOptions.cli === 'ng' ? 'ng-new' : 'tao-new',
true true
); );
const allowAdditionalArgs = true; // we can't yet know the schema to validate against const allowAdditionalArgs = true; // we can't yet know the schema to validate against
@ -446,7 +446,7 @@ export async function invokeNew(
root, root,
workflow, workflow,
logger, logger,
{ ...opts, schematicName: schematic.description.name }, { ...opts, generatorName: schematic.description.name },
schematic, schematic,
allowAdditionalArgs allowAdditionalArgs
) )

View File

@ -7,7 +7,7 @@ import {
Options, Options,
Schema, Schema,
} from '../shared/params'; } from '../shared/params';
import { commandName, printHelp } from '../shared/print-help'; import { printHelp } from '../shared/print-help';
import { import {
TargetDefinition, TargetDefinition,
WorkspaceDefinition, WorkspaceDefinition,
@ -26,7 +26,7 @@ export interface RunOptions {
function throwInvalidInvocation() { function throwInvalidInvocation() {
throw new Error( throw new Error(
`Specify the project name and the target (e.g., ${commandName} run proj:build)` `Specify the project name and the target (e.g., nx run proj:build)`
); );
} }
@ -86,11 +86,7 @@ export function printRunHelp(
schema: Schema, schema: Schema,
logger: Console logger: Console
) { ) {
printHelp( printHelp(`nx run ${opts.project}:${opts.target}`, schema, logger as any);
`${commandName} run ${opts.project}:${opts.target}`,
schema,
logger as any
);
} }
export function validateTargetAndConfiguration( export function validateTargetAndConfiguration(

View File

@ -41,7 +41,7 @@ export async function handleErrors(
return await fn(); return await fn();
} catch (err) { } catch (err) {
if (err.constructor.name === 'UnsuccessfulWorkflowExecution') { if (err.constructor.name === 'UnsuccessfulWorkflowExecution') {
logger.error('The Schematic workflow failed. See above.'); logger.error('The generator workflow failed. See above.');
} else { } else {
logger.error(err.message); logger.error(err.message);
} }
@ -287,10 +287,10 @@ export function combineOptionsForBuilder(
return combined; return combined;
} }
export async function combineOptionsForSchematic( export async function combineOptionsForGenerator(
commandLineOpts: Options, commandLineOpts: Options,
collectionName: string, collectionName: string,
schematicName: string, generatorName: string,
ws: WorkspaceDefinition, ws: WorkspaceDefinition,
schema: Schema, schema: Schema,
isInteractive: boolean isInteractive: boolean
@ -298,11 +298,20 @@ export async function combineOptionsForSchematic(
const schematicDefaults = const schematicDefaults =
ws.schematics && ws.schematics &&
ws.schematics[collectionName] && ws.schematics[collectionName] &&
ws.schematics[collectionName][schematicName] ws.schematics[collectionName][generatorName]
? ws.schematics[collectionName][schematicName] ? ws.schematics[collectionName][generatorName]
: {};
const generatorDefaults =
ws.generators &&
ws.generators[collectionName] &&
ws.generators[collectionName][generatorName]
? ws.generators[collectionName][generatorName]
: {}; : {};
let combined = convertAliases( let combined = convertAliases(
coerceTypesInOptions({ ...schematicDefaults, ...commandLineOpts }, schema), coerceTypesInOptions(
{ ...schematicDefaults, ...generatorDefaults, ...commandLineOpts },
schema
),
schema, schema,
false false
); );

View File

@ -33,14 +33,3 @@ ${args}
${formatOption('help', 'Show available options for project target.')} ${formatOption('help', 'Show available options for project target.')}
`); `);
} }
export let commandName = 'nx';
export let toolDescription = 'Nx - Extensible Dev Tools for Monorepos.';
export function setCommandNameAndDescription(
name: string,
description: string
) {
commandName = name;
toolDescription = description;
}

View File

@ -6,6 +6,7 @@ export interface WorkspaceDefinition {
projects: { [projectName: string]: ProjectDefinition }; projects: { [projectName: string]: ProjectDefinition };
defaultProject: string | undefined; defaultProject: string | undefined;
schematics: { [collectionName: string]: { [schematicName: string]: any } }; schematics: { [collectionName: string]: { [schematicName: string]: any } };
generators: { [collectionName: string]: { [generatorName: string]: any } };
cli: { defaultCollection: string }; cli: { defaultCollection: string };
} }
@ -43,8 +44,8 @@ export class Workspaces {
return schema['cli'] === 'nx'; return schema['cli'] === 'nx';
} }
isNxSchematic(collectionName: string, schematicName: string) { isNxGenerator(collectionName: string, generatorName: string) {
const schema = this.readSchematic(collectionName, schematicName).schema; const schema = this.readGenerator(collectionName, generatorName).schema;
return schema['cli'] === 'nx'; return schema['cli'] === 'nx';
} }
@ -65,29 +66,29 @@ export class Workspaces {
} }
} }
readSchematic(collectionName: string, schematicName: string) { readGenerator(collectionName: string, generatorName: string) {
try { try {
const { const {
schematicsFilePath, generatorsFilePath,
schematicsJson, generatorsJson,
normalizedSchematicName, normalizedGeneratorName,
} = this.readSchematicsJson(collectionName, schematicName); } = this.readGeneratorsJson(collectionName, generatorName);
const schematicsDir = path.dirname(schematicsFilePath); const generatorsDir = path.dirname(generatorsFilePath);
const schematicConfig = const generatorConfig = (generatorsJson.generators ||
schematicsJson.schematics[normalizedSchematicName]; generatorsJson.schematics)[normalizedGeneratorName];
const schemaPath = path.join(schematicsDir, schematicConfig.schema || ''); const schemaPath = path.join(generatorsDir, generatorConfig.schema || '');
const schema = JSON.parse(fs.readFileSync(schemaPath).toString()); const schema = JSON.parse(fs.readFileSync(schemaPath).toString());
const module = require(path.join( const module = require(path.join(
schematicsDir, generatorsDir,
schematicConfig.implementation generatorConfig.implementation
? schematicConfig.implementation ? generatorConfig.implementation
: schematicConfig.factory : generatorConfig.factory
)); ));
const implementation = module.default; const implementation = module.default;
return { schema, implementation }; return { schema, implementation };
} catch (e) { } catch (e) {
throw new Error( throw new Error(
`Unable to resolve ${collectionName}:${schematicName}.\n${e.message}` `Unable to resolve ${collectionName}:${generatorName}.\n${e.message}`
); );
} }
} }
@ -111,50 +112,50 @@ export class Workspaces {
return { builder, buildersFilePath, buildersJson }; return { builder, buildersFilePath, buildersJson };
} }
private readSchematicsJson(collectionName: string, schematic: string) { private readGeneratorsJson(collectionName: string, generator: string) {
let schematicsFilePath; let generatorsFilePath;
if (collectionName.endsWith('.json')) { if (collectionName.endsWith('.json')) {
schematicsFilePath = require.resolve(collectionName); generatorsFilePath = require.resolve(collectionName);
} else { } else {
const packageJsonPath = require.resolve(`${collectionName}/package.json`); const packageJsonPath = require.resolve(`${collectionName}/package.json`);
const packageJson = JSON.parse( const packageJson = JSON.parse(
fs.readFileSync(packageJsonPath).toString() fs.readFileSync(packageJsonPath).toString()
); );
const schematicsFile = packageJson.schematics; const generatorsFile = packageJson.generators
schematicsFilePath = require.resolve( ? packageJson.generators
path.join(path.dirname(packageJsonPath), schematicsFile) : packageJson.schematics;
generatorsFilePath = require.resolve(
path.join(path.dirname(packageJsonPath), generatorsFile)
); );
} }
const schematicsJson = JSON.parse( const generatorsJson = JSON.parse(
fs.readFileSync(schematicsFilePath).toString() fs.readFileSync(generatorsFilePath).toString()
); );
let normalizedSchematicName; let normalizedGeneratorName;
for (let k of Object.keys(schematicsJson.schematics)) { const gens = generatorsJson.generators || generatorsJson.schematics;
if (k === schematic) { for (let k of Object.keys(gens)) {
normalizedSchematicName = k; if (k === generator) {
normalizedGeneratorName = k;
break; break;
} }
if ( if (gens[k].aliases && gens[k].aliases.indexOf(generator) > -1) {
schematicsJson.schematics[k].aliases && normalizedGeneratorName = k;
schematicsJson.schematics[k].aliases.indexOf(schematic) > -1
) {
normalizedSchematicName = k;
break; break;
} }
} }
if (!normalizedSchematicName) { if (!normalizedGeneratorName) {
for (let parent of schematicsJson.extends || []) { for (let parent of generatorsJson.extends || []) {
try { try {
return this.readSchematicsJson(parent, schematic); return this.readGeneratorsJson(parent, generator);
} catch (e) {} } catch (e) {}
} }
throw new Error( throw new Error(
`Cannot find schematic '${schematic}' in ${schematicsFilePath}.` `Cannot find generator '${generator}' in ${generatorsFilePath}.`
); );
} }
return { schematicsFilePath, schematicsJson, normalizedSchematicName }; return { generatorsFilePath, generatorsJson, normalizedGeneratorName };
} }
} }

View File

@ -58,10 +58,11 @@
"description": "Create a library" "description": "Create a library"
}, },
"workspace-schematic": { "workspace-generator": {
"factory": "./src/schematics/workspace-schematic/workspace-schematic", "factory": "./src/schematics/workspace-generator/workspace-generator",
"schema": "./src/schematics/workspace-schematic/schema.json", "schema": "./src/schematics/workspace-generator/schema.json",
"description": "Generates a workspace schematic" "aliases": ["workspace-schematic"],
"description": "Generates a workspace generator"
}, },
"run-commands": { "run-commands": {

View File

@ -87,6 +87,6 @@ import * as strings from './src/utils/strings';
export { checkAndCleanWithSemver } from './src/utils/version-utils'; export { checkAndCleanWithSemver } from './src/utils/version-utils';
export { updatePackagesInPackageJson } from './src/utils/update-packages-in-package-json'; export { updatePackagesInPackageJson } from './src/utils/update-packages-in-package-json';
export { librarySchematic } from './src/schematics/library/library'; export { libraryGenerator } from './src/schematics/library/library';
export const stringUtils = strings; export const stringUtils = strings;

View File

@ -8,7 +8,7 @@ import { format } from './format';
import { workspaceLint } from './lint'; import { workspaceLint } from './lint';
import { list } from './list'; import { list } from './list';
import { report } from './report'; import { report } from './report';
import { workspaceSchematic } from './workspace-schematic'; import { workspaceGenerators } from './workspace-generators';
import { affected } from './affected'; import { affected } from './affected';
import { runMany } from './run-many'; import { runMany } from './run-many';
@ -34,7 +34,7 @@ export const commandsObject = yargs
` `
) )
.command( .command(
'generate [schematic-collection:][schematic] [options, ...]', 'generate [collection:][generator] [options, ...]',
` `
Generate code Generate code
(e.g., nx generate @nrwl/web:app myapp). (e.g., nx generate @nrwl/web:app myapp).
@ -150,26 +150,26 @@ export const commandsObject = yargs
(_) => workspaceLint() (_) => workspaceLint()
) )
.command( .command(
'workspace-schematic [name]', ['workspace-generator [name]', 'workspace-schematic [name]'],
'Runs a workspace schematic from the tools/schematics directory', 'Runs a workspace generator from the tools/generators directory',
(yargs) => { (yargs) => {
yargs.option('list-schematics', { yargs.option('list-generators', {
describe: 'List the available workspace-schematics', describe: 'List the available workspace-generators',
type: 'boolean', type: 'boolean',
}); });
/** /**
* Don't require `name` if only listing available * Don't require `name` if only listing available
* schematics * schematics
*/ */
if (yargs.argv.listSchematics !== true) { if (yargs.argv.listGenerators !== true) {
yargs.demandOption(['name']).positional('name', { yargs.demandOption(['name']).positional('name', {
type: 'string', type: 'string',
describe: 'The name of your schematic`', describe: 'The name of your generator`',
}); });
} }
return yargs; return yargs;
}, },
() => workspaceSchematic(process.argv.slice(3)) () => workspaceGenerators(process.argv.slice(3))
) )
.command( .command(
'migrate', 'migrate',

View File

@ -13,6 +13,7 @@ export const supportedNxCommands = [
'format:check', 'format:check',
'format:write', 'format:write',
'workspace-schematic', 'workspace-schematic',
'workspace-generator',
'workspace-lint', 'workspace-lint',
'migrate', 'migrate',
'report', 'report',

View File

@ -46,7 +46,7 @@ type TsConfig = {
references?: Array<{ path: string }>; references?: Array<{ path: string }>;
}; };
export async function workspaceSchematic(args: string[]) { export async function workspaceGenerators(args: string[]) {
const outDir = compileTools(); const outDir = compileTools();
const parsedArgs = parseOptions(args, outDir); const parsedArgs = parseOptions(args, outDir);
const logger = createConsoleLogger( const logger = createConsoleLogger(
@ -54,16 +54,16 @@ export async function workspaceSchematic(args: string[]) {
process.stdout, process.stdout,
process.stderr process.stderr
); );
const collectionFile = path.join(outDir, 'workspace-schematics.json'); const collectionFile = path.join(outDir, 'workspace-generators.json');
if (parsedArgs.listSchematics) { if (parsedArgs.listGenerators) {
return listSchematics(collectionFile, logger); return listGenerators(collectionFile, logger);
} }
const schematicName = args[0]; const generatorName = args[0];
const ws = new Workspaces(); const ws = new Workspaces();
if (ws.isNxSchematic(collectionFile, schematicName)) { if (ws.isNxGenerator(collectionFile, generatorName)) {
try { try {
execSync( execSync(
`npx tao g "${collectionFile}":${schematicName} ${args `npx tao g "${collectionFile}":${generatorName} ${args
.slice(1) .slice(1)
.join(' ')}`, .join(' ')}`,
{ stdio: ['inherit', 'inherit', 'inherit'] } { stdio: ['inherit', 'inherit', 'inherit'] }
@ -74,8 +74,8 @@ export async function workspaceSchematic(args: string[]) {
} else { } else {
try { try {
const workflow = createWorkflow(parsedArgs.dryRun); const workflow = createWorkflow(parsedArgs.dryRun);
await executeSchematic( await executeAngularDevkitSchematic(
schematicName, generatorName,
parsedArgs, parsedArgs,
workflow, workflow,
outDir, outDir,
@ -93,10 +93,10 @@ function compileTools() {
removeSync(toolsOutDir); removeSync(toolsOutDir);
compileToolsDir(toolsOutDir); compileToolsDir(toolsOutDir);
const schematicsOutDir = path.join(toolsOutDir, 'schematics'); const generatorsOutDir = path.join(toolsOutDir, 'generators');
const collectionData = constructCollection(); const collectionData = constructCollection();
saveCollection(schematicsOutDir, collectionData); saveCollection(generatorsOutDir, collectionData);
return schematicsOutDir; return generatorsOutDir;
} }
function getToolsOutDir() { function getToolsOutDir() {
@ -104,10 +104,10 @@ function getToolsOutDir() {
} }
function compileToolsDir(outDir: string) { function compileToolsDir(outDir: string) {
copySync(schematicsDir(), path.join(outDir, 'schematics')); copySync(generatorsDir(), path.join(outDir, 'generators'));
const tmpTsConfigPath = createTmpTsConfig(toolsTsConfigPath(), { const tmpTsConfigPath = createTmpTsConfig(toolsTsConfigPath(), {
include: [path.join(schematicsDir(), '**/*.ts')], include: [path.join(generatorsDir(), '**/*.ts')],
}); });
const packageExec = getPackageManagerExecuteCommand(); const packageExec = getPackageManagerExecuteCommand();
@ -123,11 +123,11 @@ function compileToolsDir(outDir: string) {
} }
function constructCollection() { function constructCollection() {
const schematics = {}; const generators = {};
fs.readdirSync(schematicsDir()).forEach((c) => { fs.readdirSync(generatorsDir()).forEach((c) => {
const childDir = path.join(schematicsDir(), c); const childDir = path.join(generatorsDir(), c);
if (exists(path.join(childDir, 'schema.json'))) { if (exists(path.join(childDir, 'schema.json'))) {
schematics[c] = { generators[c] = {
factory: `./${c}`, factory: `./${c}`,
schema: `./${path.join(c, 'schema.json')}`, schema: `./${path.join(c, 'schema.json')}`,
description: `Schematic ${c}`, description: `Schematic ${c}`,
@ -135,21 +135,21 @@ function constructCollection() {
} }
}); });
return { return {
name: 'workspace-schematics', name: 'workspace-generators',
version: '1.0', version: '1.0',
schematics, schematics: generators, // TODO vsavkin: remove this
}; };
} }
function saveCollection(dir: string, collection: any) { function saveCollection(dir: string, collection: any) {
writeFileSync( writeFileSync(
path.join(dir, 'workspace-schematics.json'), path.join(dir, 'workspace-generators.json'),
JSON.stringify(collection) JSON.stringify(collection)
); );
} }
function schematicsDir() { function generatorsDir() {
return path.join(rootDirectory, 'tools', 'schematics'); return path.join(rootDirectory, 'tools', 'generators');
} }
function toolsDir() { function toolsDir() {
@ -176,7 +176,7 @@ function createWorkflow(dryRun: boolean) {
}); });
} }
function listSchematics(collectionName: string, logger: logging.Logger) { function listGenerators(collectionName: string, logger: logging.Logger) {
try { try {
const engineHost = new NodeModulesEngineHost(); const engineHost = new NodeModulesEngineHost();
const engine = new SchematicEngine(engineHost); const engine = new SchematicEngine(engineHost);
@ -234,7 +234,7 @@ function createPromptProvider(): schema.PromptProvider {
} }
// execute schematic // execute schematic
async function executeSchematic( async function executeAngularDevkitSchematic(
schematicName: string, schematicName: string,
options: { [p: string]: any }, options: { [p: string]: any },
workflow: NodeWorkflow, workflow: NodeWorkflow,
@ -374,7 +374,7 @@ function parseOptions(args: string[], outDir: string): { [k: string]: any } {
} }
} }
return yargsParser(args, { return yargsParser(args, {
boolean: ['dryRun', 'listSchematics', 'interactive', ...booleanProps], boolean: ['dryRun', 'listGenerators', 'interactive', ...booleanProps],
alias: { alias: {
dryRun: ['d'], dryRun: ['d'],
listSchematics: ['l'], listSchematics: ['l'],

View File

@ -143,7 +143,7 @@ export default function (schema: Schema): Rule {
}; };
} }
export const librarySchematic = wrapAngularDevkitSchematic( export const libraryGenerator = wrapAngularDevkitSchematic(
'@nrwl/workspace', '@nrwl/workspace',
'library' 'library'
); );

View File

@ -1,8 +1,8 @@
import { Tree, formatFiles, installPackagesTask } from '@nrwl/devkit'; import { Tree, formatFiles, installPackagesTask } from '@nrwl/devkit';
import { librarySchematic } from '@nrwl/workspace'; import { libraryGenerator } from '@nrwl/workspace';
export default async function(host: Tree, schema: any) { export default async function(host: Tree, schema: any) {
await librarySchematic({name: schema.name})(host); await libraryGenerator({name: schema.name})(host);
await formatFiles(host); await formatFiles(host);
return () => { return () => {
installPackagesTask(host) installPackagesTask(host)

View File

@ -1,7 +1,7 @@
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import workspaceSchematic from './workspace-schematic'; import workspaceGenerator from './workspace-generator';
describe('workspace-schematic', () => { describe('workspace-generator', () => {
it('should generate a target', async () => { it('should generate a target', async () => {
const tree = createTreeWithEmptyWorkspace(); const tree = createTreeWithEmptyWorkspace();
const opts = { const opts = {
@ -9,9 +9,9 @@ describe('workspace-schematic', () => {
skipFormat: true, skipFormat: true,
}; };
await workspaceSchematic(tree, opts); await workspaceGenerator(tree, opts);
expect(tree.exists('tools/schematics/custom/index.ts')).toBeTruthy(); expect(tree.exists('tools/generators/custom/index.ts')).toBeTruthy();
expect(tree.exists('tools/schematics/custom/schema.json')).toBeTruthy(); expect(tree.exists('tools/generators/custom/schema.json')).toBeTruthy();
}); });
}); });

View File

@ -8,7 +8,7 @@ export default async function (host: Tree, schema: Schema) {
generateFiles( generateFiles(
host, host,
path.join(__dirname, 'files'), path.join(__dirname, 'files'),
path.join('tools/schematics', schema.name), path.join('tools/generators', schema.name),
options options
); );
if (!schema.skipFormat) { if (!schema.skipFormat) {

View File

@ -24,16 +24,8 @@
"format": "nx format:write", "format": "nx format:write",
"format:write": "nx format:write", "format:write": "nx format:write",
"format:check": "nx format:check", "format:check": "nx format:check",
<% if(cli === 'angular') { %>
"update": "ng update @nrwl/workspace",
<% } %>
<% if(cli === 'nx') { %>
"update": "nx migrate latest", "update": "nx migrate latest",
<% } %> "workspace-generator": "nx workspace-generator",
"workspace-schematic": "nx workspace-schematic",
"dep-graph": "nx dep-graph", "dep-graph": "nx dep-graph",
"help": "nx help" "help": "nx help"
}, },

View File

@ -6,19 +6,19 @@ export function fetchCorePlugins() {
const corePlugins: CorePlugin[] = [ const corePlugins: CorePlugin[] = [
{ {
name: '@nrwl/angular', name: '@nrwl/angular',
capabilities: 'schematics', capabilities: 'generators',
}, },
{ {
name: '@nrwl/cypress', name: '@nrwl/cypress',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/express', name: '@nrwl/express',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/jest', name: '@nrwl/jest',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/linter', name: '@nrwl/linter',
@ -26,35 +26,35 @@ export function fetchCorePlugins() {
}, },
{ {
name: '@nrwl/nest', name: '@nrwl/nest',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/next', name: '@nrwl/next',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/node', name: '@nrwl/node',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/nx-plugin', name: '@nrwl/nx-plugin',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/react', name: '@nrwl/react',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/storybook', name: '@nrwl/storybook',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/web', name: '@nrwl/web',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
{ {
name: '@nrwl/workspace', name: '@nrwl/workspace',
capabilities: 'builders,schematics', capabilities: 'builders,generators',
}, },
]; ];
return corePlugins; return corePlugins;

View File

@ -32,7 +32,7 @@ export function getInstalledPluginsFromPackageJson(
}) })
.sort() .sort()
.map((name) => getPluginCapabilities(workspaceRoot, name)) .map((name) => getPluginCapabilities(workspaceRoot, name))
.filter((x) => x && !!(x.schematics || x.builders)); .filter((x) => x && !!(x.generators || x.builders));
} }
export function listInstalledPlugins(installedPlugins: PluginCapabilities[]) { export function listInstalledPlugins(installedPlugins: PluginCapabilities[]) {
@ -43,8 +43,8 @@ export function listInstalledPlugins(installedPlugins: PluginCapabilities[]) {
if (hasElements(p.builders)) { if (hasElements(p.builders)) {
capabilities.push('builders'); capabilities.push('builders');
} }
if (hasElements(p.schematics)) { if (hasElements(p.generators)) {
capabilities.push('schematics'); capabilities.push('generators');
} }
return `${terminal.bold(p.name)} (${capabilities.join()})`; return `${terminal.bold(p.name)} (${capabilities.join()})`;
}), }),

View File

@ -1,4 +1,4 @@
export interface PluginSchematic { export interface PluginGenerator {
factory: string; factory: string;
schema: string; schema: string;
description: string; description: string;
@ -15,12 +15,12 @@ export interface PluginBuilder {
export interface PluginCapabilities { export interface PluginCapabilities {
name: string; name: string;
builders: { [name: string]: PluginBuilder }; builders: { [name: string]: PluginBuilder };
schematics: { [name: string]: PluginSchematic }; generators: { [name: string]: PluginGenerator };
} }
export interface CorePlugin { export interface CorePlugin {
name: string; name: string;
capabilities: 'builders' | 'schematics' | 'builders,schematics'; capabilities: 'builders' | 'generators' | 'builders,generators';
link?: string; link?: string;
} }

View File

@ -40,12 +40,19 @@ export function getPluginCapabilities(
const packageJson = readJsonFile(packageJsonPath); const packageJson = readJsonFile(packageJsonPath);
return { return {
name: pluginName, name: pluginName,
schematics: tryGetCollection( generators:
workspaceRoot, tryGetCollection(
pluginName, workspaceRoot,
packageJson.schematics, pluginName,
'schematics' packageJson.generators,
), 'generators'
) ||
tryGetCollection(
workspaceRoot,
pluginName,
packageJson.schematics,
'schematics'
),
builders: tryGetCollection( builders: tryGetCollection(
workspaceRoot, workspaceRoot,
pluginName, pluginName,
@ -77,22 +84,22 @@ export function listPluginCapabilities(pluginName: string) {
} }
const hasBuilders = hasElements(plugin.builders); const hasBuilders = hasElements(plugin.builders);
const hasSchematics = hasElements(plugin.schematics); const hasGenerators = hasElements(plugin.generators);
if (!hasBuilders && !hasSchematics) { if (!hasBuilders && !hasGenerators) {
output.warn({ title: `No capabilities found in ${pluginName}` }); output.warn({ title: `No capabilities found in ${pluginName}` });
return; return;
} }
const bodyLines = []; const bodyLines = [];
if (hasSchematics) { if (hasGenerators) {
bodyLines.push(terminal.bold(terminal.green('SCHEMATICS'))); bodyLines.push(terminal.bold(terminal.green('GENERATORS')));
bodyLines.push(''); bodyLines.push('');
bodyLines.push( bodyLines.push(
...Object.keys(plugin.schematics).map( ...Object.keys(plugin.generators).map(
(name) => (name) =>
`${terminal.bold(name)} : ${plugin.schematics[name].description}` `${terminal.bold(name)} : ${plugin.generators[name].description}`
) )
); );
if (hasBuilders) { if (hasBuilders) {