Skip to content

Commit

Permalink
feat(misc): expose nx init command flags
Browse files Browse the repository at this point in the history
  • Loading branch information
leosvelperez committed Apr 13, 2023
1 parent 1fb9edc commit 9258259
Show file tree
Hide file tree
Showing 13 changed files with 152 additions and 121 deletions.
6 changes: 4 additions & 2 deletions e2e/nx-init/src/nx-init-angular.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ describe('nx init (Angular CLI)', () => {

it('should successfully convert an Angular CLI workspace to an Nx standalone workspace', () => {
const output = runCommand(
`${pmc.runUninstalledPackage} nx@${getPublishedVersion()} init -y`
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init --no-interactive`
);

expect(output).toContain('Nx is now enabled in your workspace!');
Expand Down Expand Up @@ -64,7 +66,7 @@ describe('nx init (Angular CLI)', () => {
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init -y --integrated`
} nx@${getPublishedVersion()} init --integrated --no-interactive`
);

expect(output).toContain('Nx is now enabled in your workspace!');
Expand Down
2 changes: 1 addition & 1 deletion e2e/nx-init/src/nx-init-monorepo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('nx init (Monorepo)', () => {
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init -y --cacheable=build`
} nx@${getPublishedVersion()} init --cacheable=build --no-interactive`
);

expect(output).toContain('🎉 Done!');
Expand Down
2 changes: 1 addition & 1 deletion e2e/nx-init/src/nx-init-nest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('nx init (for NestCLI)', () => {
const output = execSync(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init -y --cacheable=format`,
} nx@${getPublishedVersion()} init --cacheable=format --no-interactive`,
{
cwd: projectRoot,
encoding: 'utf-8',
Expand Down
4 changes: 2 additions & 2 deletions e2e/nx-init/src/nx-init-npm-repo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('nx init (NPM repo)', () => {
const output = runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init -y --cacheable=echo`
} nx@${getPublishedVersion()} init --cacheable=echo --no-interactive`
);
console.log(output);
expect(output).toContain('Enabled computation caching');
Expand Down Expand Up @@ -61,7 +61,7 @@ describe('nx init (NPM repo)', () => {
runCommand(
`${
pmc.runUninstalledPackage
} nx@${getPublishedVersion()} init -y --cacheable=compound`
} nx@${getPublishedVersion()} init --cacheable=compound --no-interactive`
);

const output = runCommand('npm run compound TEST');
Expand Down
15 changes: 10 additions & 5 deletions packages/nx/src/command-line/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import { directoryExists, readJsonFile } from '../utils/fileutils';
import { PackageJson } from '../utils/package-json';

export interface InitArgs {
addE2e: boolean;
force: boolean;
integrated: boolean;
interactive: boolean;
vite: boolean;
nxCloud?: boolean;
}

export async function initHandler(options: InitArgs) {
Expand All @@ -40,15 +45,15 @@ export async function initHandler(options: InitArgs) {
} else if (existsSync('package.json')) {
const packageJson: PackageJson = readJsonFile('package.json');
if (existsSync('angular.json')) {
await addNxToAngularCliRepo(options.integrated);
await addNxToAngularCliRepo(options);
} else if (isCRA(packageJson)) {
await addNxToCraRepo(options.integrated);
await addNxToCraRepo(options);
} else if (isNestCLI(packageJson)) {
await addNxToNest(packageJson);
await addNxToNest(options, packageJson);
} else if (isMonorepo(packageJson)) {
await addNxToMonorepo();
await addNxToMonorepo(options);
} else {
await addNxToNpmRepo();
await addNxToNpmRepo(options);
}
} else {
const useDotNxFolder = await prompt<{ useDotNxFolder: string }>([
Expand Down
61 changes: 46 additions & 15 deletions packages/nx/src/command-line/nx-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import * as chalk from 'chalk';
import { execSync } from 'child_process';
import * as path from 'path';
import * as yargs from 'yargs';
import { nxVersion } from '../utils/versions';
import { examples } from './examples';
import { workspaceRoot } from '../utils/workspace-root';
import { getPackageManagerCommand } from '../utils/package-manager';
import { runNxSync } from '../utils/child-process';
import { writeJsonFile } from '../utils/fileutils';
import { getPackageManagerCommand } from '../utils/package-manager';
import { workspaceRoot } from '../utils/workspace-root';
import { examples } from './examples';
import { WatchArguments } from './watch';
import { runNxSync } from '../utils/child-process';
import { stripIndents } from '../utils/strip-indents';

// Ensure that the output takes up the available width of the terminal.
yargs.wrap(yargs.terminalWidth());
Expand Down Expand Up @@ -305,7 +303,7 @@ export const commandsObject = yargs
command: 'init',
describe:
'Adds Nx to any type of workspace. It installs nx, creates an nx.json configuration file and optionally sets up distributed caching. For more info, check https://nx.dev/recipes/adopting-nx.',
builder: (yargs) => withIntegratedOption(yargs),
builder: (yargs) => withInitOptions(yargs),
handler: async (args: any) => {
await (await import('./init')).initHandler(args);
process.exit(0);
Expand Down Expand Up @@ -1119,14 +1117,47 @@ function withListOptions(yargs) {
});
}

function withIntegratedOption(yargs) {
return yargs.option('integrated', {
type: 'boolean',
description:
'Migrate to an Nx integrated layout workspace. Only for CRA and Angular projects.',
// TODO(leo): keep it hidden until feature is released
hidden: true,
});
function withInitOptions(yargs: yargs.Argv) {
// TODO(leo): make them visible in docs/help once the feature is released in Nx 16
return yargs
.options('nxCloud', {
type: 'boolean',
description: 'Set up distributed caching with Nx Cloud.',
hidden: true,
})
.option('interactive', {
describe: 'When false disables interactive input prompts for options.',
type: 'boolean',
default: true,
hidden: true,
})
.option('integrated', {
type: 'boolean',
description:
'Migrate to an Nx integrated layout workspace. Only for Angular CLI workspaces and CRA projects.',
default: false,
hidden: true,
})
.option('addE2e', {
describe:
'Set up Cypress E2E tests in integrated workspaces. Only for CRA projects.',
type: 'boolean',
default: false,
hidden: true,
})
.option('force', {
describe:
'Force the migration to continue and ignore custom webpack setup or uncommitted changes. Only for CRA projects.',
type: 'boolean',
default: false,
hidden: true,
})
.options('vite', {
type: 'boolean',
description: 'Use Vite as the bundler. Only for CRA projects.',
default: true,
hidden: true,
});
}

function runMigration() {
Expand Down
21 changes: 12 additions & 9 deletions packages/nx/src/nx-init/add-nx-to-monorepo.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { prompt } from 'enquirer';
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
import ignore from 'ignore';
import { join, relative } from 'path';
import * as yargsParser from 'yargs-parser';
import { InitArgs } from '../command-line/init';
import { readJsonFile } from '../utils/fileutils';
import { output } from '../utils/output';
import { getPackageManagerCommand } from '../utils/package-manager';
Expand All @@ -15,15 +16,13 @@ import {
runInstall,
} from './utils';

type Options = Pick<InitArgs, 'nxCloud' | 'interactive'>;

const parsedArgs = yargsParser(process.argv, {
boolean: ['yes'],
string: ['cacheable'], // only used for testing
alias: {
yes: ['y'],
},
});

export async function addNxToMonorepo() {
export async function addNxToMonorepo(options: Options) {
const repoRoot = process.cwd();

if (!existsSync(joinPathFragments(repoRoot, 'package.json'))) {
Expand All @@ -43,7 +42,7 @@ export async function addNxToMonorepo() {
let scriptOutputs = {} as { [script: string]: string };
let useCloud: boolean;

if (parsedArgs.yes !== true && scripts.length > 0) {
if (options.interactive && scripts.length > 0) {
output.log({
title: `🧑‍🔧 Please answer the following questions about the scripts found in your workspace in order to generate task runner configuration`,
});
Expand Down Expand Up @@ -83,13 +82,17 @@ export async function addNxToMonorepo() {
)[scriptName];
}

useCloud = await askAboutNxCloud();
useCloud =
options.nxCloud === undefined ? await askAboutNxCloud() : options.nxCloud;
} else {
targetDefaults = [];
cacheableOperations = parsedArgs.cacheable
? parsedArgs.cacheable.split(',')
: [];
useCloud = false;
useCloud =
options.interactive && options.nxCloud === undefined
? await askAboutNxCloud()
: options.nxCloud ?? false;
}

createNxJsonFile(
Expand Down
30 changes: 15 additions & 15 deletions packages/nx/src/nx-init/add-nx-to-nest.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import { unlinkSync, writeFileSync } from 'fs-extra';
import * as yargsParser from 'yargs-parser';
import * as enquirer from 'enquirer';
import { unlinkSync, writeFileSync } from 'fs-extra';
import { join } from 'path';
import * as yargsParser from 'yargs-parser';
import { InitArgs } from '../command-line/init';
import { NrwlJsPluginConfig, NxJsonConfiguration } from '../config/nx-json';
import { ProjectConfiguration } from '../config/workspace-json-project-json';
import { fileExists, readJsonFile, writeJsonFile } from '../utils/fileutils';
import { output } from '../utils/output';
import { PackageJson } from '../utils/package-json';
import { fileExists, readJsonFile, writeJsonFile } from '../utils/fileutils';
import { getPackageManagerCommand } from '../utils/package-manager';
import { markRootPackageJsonAsNxProject } from './add-nx-to-npm-repo';
import {
addDepsToPackageJson,
askAboutNxCloud,
createNxJsonFile,
initCloud,
runInstall,
} from './utils';
import { getPackageManagerCommand } from '../utils/package-manager';
import { markRootPackageJsonAsNxProject } from './add-nx-to-npm-repo';
import { ProjectConfiguration } from '../config/workspace-json-project-json';
import { NrwlJsPluginConfig, NxJsonConfiguration } from '../config/nx-json';

type Options = Pick<InitArgs, 'nxCloud' | 'interactive'>;
type NestCLIConfiguration = any;

const parsedArgs = yargsParser(process.argv, {
boolean: ['yes'],
string: ['cacheable'], // only used for testing
alias: {
yes: ['y'],
},
});

export async function addNxToNest(packageJson: PackageJson) {
export async function addNxToNest(options: Options, packageJson: PackageJson) {
const repoRoot = process.cwd();

output.log({ title: `🐳 Nx initialization` });
Expand Down Expand Up @@ -68,7 +67,7 @@ export async function addNxToNest(packageJson: PackageJson) {
let scriptOutputs = {};
let useCloud: boolean;

if (parsedArgs.yes !== true) {
if (options.interactive) {
output.log({
title: `🧑‍🔧 Please answer the following questions about the scripts found in your package.json in order to generate task runner configuration`,
});
Expand Down Expand Up @@ -96,12 +95,13 @@ export async function addNxToNest(packageJson: PackageJson) {
)[scriptName];
}

useCloud = await askAboutNxCloud();
useCloud =
options.nxCloud === undefined ? await askAboutNxCloud() : options.nxCloud;
} else {
cacheableOperations = parsedArgs.cacheable
? parsedArgs.cacheable.split(',')
: [];
useCloud = false;
useCloud = options.nxCloud ?? false;
}

createNxJsonFile(
Expand Down
32 changes: 16 additions & 16 deletions packages/nx/src/nx-init/add-nx-to-npm-repo.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import { output } from '../utils/output';
import * as yargsParser from 'yargs-parser';
import * as enquirer from 'enquirer';
import * as yargsParser from 'yargs-parser';
import { InitArgs } from '../command-line/init';
import { readJsonFile, writeJsonFile } from '../utils/fileutils';
import { output } from '../utils/output';
import { PackageJson } from '../utils/package-json';
import {
getPackageManagerCommand,
PackageManagerCommands,
} from '../utils/package-manager';
import { joinPathFragments } from '../utils/path';
import {
addDepsToPackageJson,
askAboutNxCloud,
createNxJsonFile,
initCloud,
runInstall,
} from './utils';
import { joinPathFragments } from '../utils/path';
import { PackageJson } from '../utils/package-json';
import {
getPackageManagerCommand,
PackageManagerCommands,
} from '../utils/package-manager';

type Options = Pick<InitArgs, 'nxCloud' | 'interactive'>;

const parsedArgs = yargsParser(process.argv, {
boolean: ['yes'],
string: ['cacheable'], // only used for testing
alias: {
yes: ['y'],
},
});

export async function addNxToNpmRepo() {
export async function addNxToNpmRepo(options: Options) {
const repoRoot = process.cwd();

output.log({ title: `🐳 Nx initialization` });
Expand All @@ -38,7 +37,7 @@ export async function addNxToNpmRepo() {
(s) => !s.startsWith('pre') && !s.startsWith('post')
);

if (parsedArgs.yes !== true) {
if (options.interactive) {
output.log({
title: `🧑‍🔧 Please answer the following questions about the scripts found in your package.json in order to generate task runner configuration`,
});
Expand Down Expand Up @@ -68,12 +67,13 @@ export async function addNxToNpmRepo() {
)[scriptName];
}

useCloud = await askAboutNxCloud();
useCloud =
options.nxCloud === undefined ? await askAboutNxCloud() : options.nxCloud;
} else {
cacheableOperations = parsedArgs.cacheable
? parsedArgs.cacheable.split(',')
: [];
useCloud = false;
useCloud = options.nxCloud ?? false;
}

createNxJsonFile(repoRoot, [], cacheableOperations, {});
Expand Down
Loading

0 comments on commit 9258259

Please sign in to comment.