Skip to content

Commit

Permalink
feat(misc): update pr with comments
Browse files Browse the repository at this point in the history
  • Loading branch information
xiongemi committed Apr 19, 2023
1 parent 40732b4 commit ac95251
Show file tree
Hide file tree
Showing 28 changed files with 220 additions and 120 deletions.
2 changes: 1 addition & 1 deletion docs/generated/manifests/packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1833,7 +1833,7 @@
"type": "generator"
},
"/packages/nx-plugin/generators/create-package": {
"description": "Create a framework package that uses Nx CLI",
"description": "Create a package which can be used by npx to create a new workspace",
"file": "generated/packages/nx-plugin/generators/create-package.json",
"hidden": false,
"name": "create-package",
Expand Down
2 changes: 1 addition & 1 deletion docs/generated/packages-metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -1811,7 +1811,7 @@
"type": "generator"
},
{
"description": "Create a framework package that uses Nx CLI",
"description": "Create a package which can be used by npx to create a new workspace",
"file": "generated/packages/nx-plugin/generators/create-package.json",
"hidden": false,
"name": "create-package",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,18 @@
"importPath": {
"type": "string",
"description": "How the plugin will be published, like `create-framework-app`. Note this must be a valid NPM name. Will use name if not provided."
},
"e2eTestRunner": {
"type": "string",
"enum": ["jest", "none"],
"description": "Test runner to use for end to end (E2E) tests.",
"default": "jest"
}
},
"required": ["name", "project"],
"presets": []
},
"description": "Create a framework package that uses Nx CLI",
"description": "Create a package which can be used by npx to create a new workspace",
"implementation": "/packages/nx-plugin/src/generators/create-package/create-package.ts",
"aliases": [],
"hidden": false,
Expand Down
5 changes: 2 additions & 3 deletions docs/generated/packages/nx-plugin/generators/preset.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@
"description": "Plugin name",
"aliases": ["name"]
},
"cliName": {
"createPackageName": {
"type": "string",
"description": "Name of cli command to create workspace with plugin",
"aliases": ["name"]
"description": "Name of package which creates a workspace"
}
},
"required": ["pluginName"],
Expand Down
2 changes: 2 additions & 0 deletions e2e/workspace-create/src/create-nx-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ describe('create-nx-plugin', () => {

runCreatePlugin(pluginName, {
packageManager,
extraArgs: `--createPackageName=create-${wsName}-package`,
});

checkFilesExist(
Expand Down Expand Up @@ -53,5 +54,6 @@ describe('create-nx-plugin', () => {
checkFilesExist(`dist/create-${pluginName}-package/bin/index.js`);

expect(() => runCLI(`e2e e2e`)).not.toThrow();
expect(() => runCLI(`e2e create-${wsName}-package-e2e`)).not.toThrow();
});
});
23 changes: 21 additions & 2 deletions packages/create-nx-plugin/bin/create-nx-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,26 @@ async function determinePluginName(
return results.pluginName;
}

async function determineCreatePackageName(
parsedArgs: CreateNxPluginArguments
): Promise<string> {
if (parsedArgs.createPackageName) {
return Promise.resolve(parsedArgs.createPackageName);
}

const results = await enquirer.prompt<{ createPackageName: string }>([
{
name: 'createPackageName',
message: `Create package name (optional) `,
type: 'input',
},
]);
return results.createPackageName;
}

interface CreateNxPluginArguments {
pluginName: string;
cliName?: string;
createPackageName?: string;
packageManager: PackageManager;
ci: CI;
allPrompts: boolean;
Expand All @@ -95,7 +112,7 @@ export const commandsObject: yargs.Argv<CreateNxPluginArguments> = yargs
type: 'string',
alias: ['name'],
})
.option('cliName', {
.option('createPackageName', {
describe: 'Name of the CLI package to create workspace with plugin',
type: 'string',
}),
Expand Down Expand Up @@ -170,13 +187,15 @@ async function normalizeArgsMiddleware(
): Promise<void> {
try {
const pluginName = await determinePluginName(argv);
const createPackageName = await determineCreatePackageName(argv);
const packageManager = await determinePackageManager(argv);
const defaultBase = await determineDefaultBase(argv);
const nxCloud = await determineNxCloud(argv);
const ci = await determineCI(argv, nxCloud);

Object.assign(argv, {
pluginName,
createPackageName,
nxCloud,
packageManager,
defaultBase,
Expand Down
4 changes: 3 additions & 1 deletion packages/create-nx-workspace/src/create-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ export async function createPreset<T extends CreateWorkspaceOptions>(
}
}

if (process.env.NX_VERBOSE_LOGGING !== 'true') {
if (
!(process.env.NX_VERBOSE_LOGGING === 'true' || args.includes('--verbose'))
) {
args = '--quiet ' + args;
}
const command = `g ${preset}:preset ${args}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export interface CreateWorkspaceOptions {
name: string; // Workspace name (e.g. org name)
packageManager: PackageManager; // Package manager to use
nxCloud: boolean; // Enable Nx Cloud
presetVersion?: string; // Version of the preset to use
/**
* @description Enable interactive mode with presets
* @default true
Expand Down
4 changes: 2 additions & 2 deletions packages/nx-plugin/generators.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"create-package": {
"factory": "./src/generators/create-package/create-package",
"schema": "./src/generators/create-package/schema.json",
"description": "Create a framework package that uses Nx CLI"
"description": "Create a package which can be used by npx to create a new workspace"
},
"e2e-project": {
"factory": "./src/generators/e2e-project/e2e",
Expand Down Expand Up @@ -55,7 +55,7 @@
"create-package": {
"factory": "./src/generators/create-package/create-package#createPackageSchematic",
"schema": "./src/generators/create-package/schema.json",
"description": "Create a framework package that uses Nx CLI"
"description": "Create a package which can be used by npx to create a new workspace"
},
"e2e-project": {
"factory": "./src/generators/e2e-project/e2e#e2eProjectSchematic",
Expand Down
2 changes: 1 addition & 1 deletion packages/nx-plugin/src/executors/e2e/e2e.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async function runTests(
context: ExecutorContext
): Promise<boolean> {
const { success } = await jestExecutor(
{ ...jestOptions, watch: false, runInBand: true },
{ runInBand: true, ...jestOptions, watch: false },
context
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ describe('NxPlugin Create Package Generator', () => {
assets: [],
buildableProjectDepsInPackageJsonType: 'dependencies',
},
dependsOn: ['^build'],
});
});

Expand Down
93 changes: 60 additions & 33 deletions packages/nx-plugin/src/generators/create-package/create-package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,24 @@ import {
convertNxGenerator,
formatFiles,
updateProjectConfiguration,
updateJson,
GeneratorCallback,
runTasksInSerial,
} from '@nrwl/devkit';
import { libraryGenerator as jsLibraryGenerator } from '@nrwl/js';
import { join } from 'path';
import { nxVersion } from '../../utils/versions';
import generatorGenerator from '../generator/generator';
import { CreatePackageSchema } from './schema';
import { NormalizedSchema, normalizeSchema } from './utils/normalize-schema';
import e2eProjectGenerator from '../e2e-project/e2e';

export async function createPackageGenerator(
host: Tree,
schema: CreatePackageSchema
) {
const tasks: GeneratorCallback[] = [];

const options = normalizeSchema(host, schema);
const pluginPackageName = await addPresetGenerator(host, {
...options,
Expand All @@ -27,20 +33,23 @@ export async function createPackageGenerator(

const installTask = addDependenciesToPackageJson(
host,
{},
{
'create-nx-workspace': nxVersion,
}
},
{}
);
tasks.push(installTask);

await createCliPackage(host, options, pluginPackageName);
addTestsToE2eProject(host, options, pluginPackageName);
if (options.e2eTestRunner !== 'none') {
tasks.push(await addE2eProject(host, options, pluginPackageName));
}

if (!options.skipFormat) {
await formatFiles(host);
}

return installTask;
return runTasksInSerial(...tasks);
}

/**
Expand Down Expand Up @@ -74,24 +83,24 @@ async function createCliPackage(
...options,
rootProject: false,
config: 'project',
buildable: true,
publishable: true,
bundler: options.bundler,
importPath: options.importPath,
skipTsConfig: true,
});

host.delete(join(options.projectRoot, 'src'));

// Add the bin entry to the package.json
const packageJsonPath = join(options.projectRoot, 'package.json');
const packageJson = readJson(host, packageJsonPath);
packageJson.bin = {
[options.name]: './bin/index.js',
};
packageJson.dependencies = {
'create-nx-workspace': nxVersion,
};
host.write(packageJsonPath, JSON.stringify(packageJson));
updateJson(host, join(options.projectRoot, 'package.json'), (packageJson) => {
packageJson.bin = {
[options.name]: './bin/index.js',
};
packageJson.dependencies = {
'create-nx-workspace': nxVersion,
};
return packageJson;
});

// update project build target to use the bin entry
const projectConfiguration = readProjectConfiguration(
Expand All @@ -105,13 +114,19 @@ async function createCliPackage(
);
projectConfiguration.targets.build.options.buildableProjectDepsInPackageJsonType =
'dependencies';
projectConfiguration.targets.build.dependsOn = ['^build'];
projectConfiguration.implicitDependencies = [options.project];
updateProjectConfiguration(host, options.projectName, projectConfiguration);

// Add bin files to tsconfg.lib.json
const tsConfigPath = join(options.projectRoot, 'tsconfig.lib.json');
const tsConfig = readJson(host, tsConfigPath);
tsConfig.include.push('bin/**/*.ts');
host.write(tsConfigPath, JSON.stringify(tsConfig));
updateJson(
host,
join(options.projectRoot, 'tsconfig.lib.json'),
(tsConfig) => {
tsConfig.include.push('bin/**/*.ts');
return tsConfig;
}
);

generateFiles(
host,
Expand All @@ -125,21 +140,13 @@ async function createCliPackage(
);
}

function getE2eProjectConfiguration(host: Tree, e2eProjectName: string) {
try {
return readProjectConfiguration(host, e2eProjectName);
} catch (e) {
return;
}
}

/**
* Add a test file to plugin e2e project
* @param host
* @param options
* @returns
*/
function addTestsToE2eProject(
async function addE2eProject(
host: Tree,
options: NormalizedSchema,
pluginPackageName: string
Expand All @@ -158,12 +165,30 @@ function addTestsToE2eProject(
const cliOutputPath =
cliProjectConfiguration.targets.build.options.outputPath;

const e2eProjectConfiguration =
getE2eProjectConfiguration(host, 'e2e') ??
getE2eProjectConfiguration(host, `${options.project}-e2e`);
if (!e2eProjectConfiguration) {
return; // e2e project does not exist, do not add tests
}
const e2eTask = await e2eProjectGenerator(host, {
pluginName: options.projectName,
projectDirectory: options.projectDirectory,
pluginOutputPath,
npmPackageName: options.name,
minimal: false,
skipFormat: true,
rootProject: false,
});

const e2eProjectConfiguration = readProjectConfiguration(
host,
`${options.projectName}-e2e`
);
e2eProjectConfiguration.targets.e2e.dependsOn = ['^build'];
updateProjectConfiguration(
host,
e2eProjectConfiguration.name,
e2eProjectConfiguration
);

// delete the default e2e test file
host.delete(e2eProjectConfiguration.sourceRoot);

generateFiles(
host,
join(__dirname, './files/e2e'),
Expand All @@ -176,6 +201,8 @@ function addTestsToE2eProject(
tmpl: '',
}
);

return e2eTask;
}

export default createPackageGenerator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@ import { createWorkspace } from 'create-nx-workspace';

async function main() {
const name = process.argv[2]; // TODO: use libraries like yargs or enquirer to set your workspace name
if (!name) {
throw new Error('Please provide a name for the workspace');
}

// TODO: update below to customize the workspace
await createWorkspace('<%= preset %>', {
name,
nxCloud: false,
packageManager: 'npm',
// This assumes "<%= preset %>" and "<%= projectName %>" are at the same version
// eslint-disable-next-line @typescript-eslint/no-var-requires
presetVersion: require('../package.json').version,
});

console.log(`Successfully created the workspace: ${name}.`);
Expand Down
Loading

0 comments on commit ac95251

Please sign in to comment.