Skip to content

Commit

Permalink
fix(core): not exit when one plugin installation failed
Browse files Browse the repository at this point in the history
  • Loading branch information
xiongemi committed Dec 10, 2024
1 parent a267063 commit fd0bf2b
Show file tree
Hide file tree
Showing 7 changed files with 339 additions and 184 deletions.
4 changes: 3 additions & 1 deletion packages/js/src/utils/typescript/ts-solution-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ export function assertNotUsingTsSolutionSetup(
],
});

process.exit(1);
throw new Error(
`The ${artifactString} doesn't yet support the existing TypeScript setup. See the error above.`
);
}

export function findRuntimeTsConfigName(
Expand Down
89 changes: 31 additions & 58 deletions packages/nx/src/command-line/add/add.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { exec } from 'child_process';
import { existsSync } from 'fs';
import * as ora from 'ora';
import { isAngularPluginInstalled } from '../../adapter/angular-json';
import type { GeneratorsJsonEntry } from '../../config/misc-interfaces';
import * as yargsParser from 'yargs-parser';
import { readNxJson, type NxJsonConfiguration } from '../../config/nx-json';
import { runNxAsync, runNxSync } from '../../utils/child-process';
import { runNxAsync } from '../../utils/child-process';
import { writeJsonFile } from '../../utils/fileutils';
import { logger } from '../../utils/logger';
import { output } from '../../utils/output';
Expand All @@ -14,12 +13,12 @@ import {
getPackageManagerVersion,
} from '../../utils/package-manager';
import { handleErrors } from '../../utils/handle-errors';
import { getPluginCapabilities } from '../../utils/plugins';
import { nxVersion } from '../../utils/versions';
import { workspaceRoot } from '../../utils/workspace-root';
import type { AddOptions } from './command-object';
import { normalizeVersionForNxJson } from '../init/implementation/dot-nx/add-nx-scripts';
import { gte } from 'semver';
import { installPlugin } from '../init/configure-plugins';

export function addHandler(options: AddOptions): Promise<number> {
return handleErrors(options.verbose, async () => {
Expand Down Expand Up @@ -109,48 +108,41 @@ async function initializePlugin(
options: AddOptions,
nxJson: NxJsonConfiguration
): Promise<void> {
const capabilities = await getPluginCapabilities(workspaceRoot, pkgName, {});
const generators = capabilities?.generators;
if (!generators) {
output.log({
title: `No generators found in ${pkgName}. Skipping initialization.`,
});
return;
}
const unparsedCommandArgs: { [key: string]: any } = yargsParser(
options.__overrides_unparsed__,
{
configuration: {
'parse-numbers': false,
'parse-positional-numbers': false,
'dot-notation': false,
'camel-case-expansion': false,
},
}
);

const initGenerator = findInitGenerator(generators);
if (!initGenerator) {
output.log({
title: `No "init" generator found in ${pkgName}. Skipping initialization.`,
});
return;
if (coreNxPluginVersions.has(pkgName)) {
unparsedCommandArgs.keepExistingVersions = true;

if (
options.updatePackageScripts ||
(options.updatePackageScripts === undefined &&
nxJson.useInferencePlugins !== false &&
process.env.NX_ADD_PLUGINS !== 'false')
) {
unparsedCommandArgs.updatePackageScripts = true;
}
}

const spinner = ora(`Initializing ${pkgName}...`);
spinner.start();

try {
const args = [];
if (coreNxPluginVersions.has(pkgName)) {
args.push(`--keepExistingVersions`);

if (
options.updatePackageScripts ||
(options.updatePackageScripts === undefined &&
nxJson.useInferencePlugins !== false &&
process.env.NX_ADD_PLUGINS !== 'false')
) {
args.push(`--updatePackageScripts`);
}
}

if (options.__overrides_unparsed__.length) {
args.push(...options.__overrides_unparsed__);
}

runNxSync(`g ${pkgName}:${initGenerator} ${args.join(' ')}`, {
stdio: [0, 1, 2],
});
await installPlugin(
pkgName,
workspaceRoot,
options.verbose,
unparsedCommandArgs
);
} catch (e) {
spinner.fail();
output.addNewline();
Expand All @@ -164,25 +156,6 @@ async function initializePlugin(
spinner.succeed();
}

function findInitGenerator(
generators: Record<string, GeneratorsJsonEntry>
): string | undefined {
if (generators['init']) {
return 'init';
}

const angularPluginInstalled = isAngularPluginInstalled();
if (angularPluginInstalled && generators['ng-add']) {
return 'ng-add';
}

return Object.keys(generators).find(
(name) =>
generators[name].aliases?.includes('init') ||
(angularPluginInstalled && generators[name].aliases?.includes('ng-add'))
);
}

function parsePackageSpecifier(
packageSpecifier: string
): [pkgName: string, version: string] {
Expand Down
121 changes: 79 additions & 42 deletions packages/nx/src/command-line/import/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { tmpdir } from 'tmp';
import { prompt } from 'enquirer';
import { output } from '../../utils/output';
import * as createSpinner from 'ora';
import { detectPlugins, installPlugins } from '../init/init-v2';
import { detectPlugins } from '../init/init-v2';
import { readNxJson } from '../../config/nx-json';
import { workspaceRoot } from '../../utils/workspace-root';
import {
Expand All @@ -24,11 +24,11 @@ import { runInstall } from '../init/implementation/utils';
import { getBaseRef } from '../../utils/command-line-utils';
import { prepareSourceRepo } from './utils/prepare-source-repo';
import { mergeRemoteSource } from './utils/merge-remote-source';
import {
getPackagesInPackageManagerWorkspace,
needsInstall,
} from './utils/needs-install';
import { minimatch } from 'minimatch';
import {
configurePlugins,
runPackageManagerInstallPlugins,
} from '../init/configure-plugins';

const importRemoteName = '__tmp_nx_import__';

Expand Down Expand Up @@ -60,7 +60,7 @@ export interface ImportOptions {

export async function importHandler(options: ImportOptions) {
process.env.NX_RUNNING_NX_IMPORT = 'true';
let { sourceRepository, ref, source, destination } = options;
let { sourceRepository, ref, source, destination, verbose } = options;
const destinationGitClient = new GitRepository(process.cwd());

if (await destinationGitClient.hasUncommittedChanges()) {
Expand Down Expand Up @@ -219,11 +219,6 @@ export async function importHandler(options: ImportOptions) {
}

const packageManager = detectPackageManager(workspaceRoot);

const originalPackageWorkspaces = await getPackagesInPackageManagerWorkspace(
packageManager
);

const sourceIsNxWorkspace = existsSync(join(sourceGitClient.root, 'nx.json'));

const relativeDestination = relative(
Expand Down Expand Up @@ -287,42 +282,28 @@ export async function importHandler(options: ImportOptions) {
destinationGitClient
);

// If install fails, we should continue since the errors could be resolved later.
let installFailed = false;
if (plugins.length > 0) {
try {
output.log({ title: 'Installing Plugins' });
installPlugins(workspaceRoot, plugins, pmc, updatePackageScripts);

await destinationGitClient.amendCommit();
} catch (e) {
installFailed = true;
output.error({
title: `Install failed: ${e.message || 'Unknown error'}`,
bodyLines: [e.stack],
});
}
} else if (await needsInstall(packageManager, originalPackageWorkspaces)) {
try {
output.log({
title: 'Installing dependencies for imported code',
});

runInstall(workspaceRoot, getPackageManagerCommand(packageManager));

await destinationGitClient.amendCommit();
} catch (e) {
installFailed = true;
output.error({
title: `Install failed: ${e.message || 'Unknown error'}`,
bodyLines: [e.stack],
});
let installed = await runInstallDestinationRepo(
packageManager,
destinationGitClient
);

if (installed && plugins.length > 0) {
installed = await runPluginsInstall(plugins, pmc, destinationGitClient);
if (installed) {
await configurePlugins(
plugins,
updatePackageScripts,
pmc,
workspaceRoot,
verbose,
destinationGitClient
);
}
}

console.log(await destinationGitClient.showStat());

if (installFailed) {
if (installed === false) {
const pmc = getPackageManagerCommand(packageManager);
output.warn({
title: `The import was successful, but the install failed`,
Expand Down Expand Up @@ -397,6 +378,62 @@ async function createTemporaryRemote(
}

/**
* Run install for the imported code and plugins
* @returns true if the install failed
*/
async function runInstallDestinationRepo(
packageManager: PackageManager,
destinationGitClient: GitRepository
): Promise<boolean> {
let installed = true;
try {
output.log({
title: 'Installing dependencies for imported code',
});
runInstall(workspaceRoot, getPackageManagerCommand(packageManager));
await destinationGitClient.amendCommit();
} catch (e) {
installed = false;
output.error({
title: `Install failed: ${e.message || 'Unknown error'}`,
bodyLines: [e.stack],
});
}
return installed;
}

async function runPluginsInstall(
plugins: string[],
pmc: PackageManagerCommands,
destinationGitClient: GitRepository
) {
let installed = true;
output.log({ title: 'Installing Plugins' });
try {
runPackageManagerInstallPlugins(workspaceRoot, pmc, plugins);
await destinationGitClient.amendCommit();
} catch (e) {
installed = false;
output.error({
title: `Install failed: ${e.message || 'Unknown error'}`,
bodyLines: [
'The following plugins were not installed:',
...plugins.map((p) => `- ${chalk.bold(p)}`),
e.stack,
],
});
output.error({
title: `To install the plugins manually`,
bodyLines: [
'You may need to run commands to install the plugins:',
...plugins.map((p) => `- ${chalk.bold(pmc.exec + ' nx add ' + p)}`),
],
});
}
return installed;
}

/*
* If the user imports a project that isn't in the workspaces entry, we should add that path to the workspaces entry.
*/
async function handleMissingWorkspacesEntry(
Expand Down
44 changes: 0 additions & 44 deletions packages/nx/src/command-line/import/utils/needs-install.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as createSpinner from 'ora';
import { dirname, join, relative } from 'path';
import { mkdir, rm } from 'node:fs/promises';
import { join, relative } from 'path';
import { GitRepository } from '../../../utils/git-utils';

export async function prepareSourceRepo(
Expand Down
Loading

0 comments on commit fd0bf2b

Please sign in to comment.