Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 14 additions & 18 deletions packages/angular/cli/src/package-managers/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,31 +136,27 @@ export async function createPackageManager(options: {
const host = NodeJS_HOST;

const result = await determinePackageManager(host, cwd, configuredPackageManager, logger, dryRun);
const { name, source } = result;
let { version } = result;
const { name, source, version } = result;

const descriptor = SUPPORTED_PACKAGE_MANAGERS[name];
if (!descriptor) {
throw new Error(`Unsupported package manager: "${name}"`);
}

// Do not verify if the package manager is installed during a dry run.
let initializationError: Error | undefined;
// Otherwise it is verified on first use, so commands that do not run it do not wait for it.
let missingBinaryError: Error | undefined;
if (!dryRun && !version) {
try {
version = await getPackageManagerVersion(host, cwd, name, logger);
} catch {
if (source === 'default') {
initializationError = new Error(
`'${DEFAULT_PACKAGE_MANAGER}' was selected as the default package manager, but it is not installed or` +
` cannot be found in the PATH. Please install '${DEFAULT_PACKAGE_MANAGER}' to continue.`,
);
} else {
initializationError = new Error(
`The project is configured to use '${name}', but it is not installed or cannot be` +
` found in the PATH. Please install '${name}' to continue.`,
);
}
if (source === 'default') {
missingBinaryError = new Error(
`'${DEFAULT_PACKAGE_MANAGER}' was selected as the default package manager, but it is not installed or` +
` cannot be found in the PATH. Please install '${DEFAULT_PACKAGE_MANAGER}' to continue.`,
);
} else {
missingBinaryError = new Error(
`The project is configured to use '${name}', but it is not installed or cannot be` +
` found in the PATH. Please install '${name}' to continue.`,
);
}
}

Expand All @@ -169,7 +165,7 @@ export async function createPackageManager(options: {
logger,
tempDirectory,
version,
initializationError,
missingBinaryError,
});

logger?.debug(`Successfully created PackageManager for '${name}'.`);
Expand Down
26 changes: 26 additions & 0 deletions packages/angular/cli/src/package-managers/factory_spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import { createPackageManager } from './factory';
import { NodeJS_HOST } from './host';

describe('createPackageManager', () => {
it('should not run the package manager binary', async () => {
const runCommandSpy = spyOn(NodeJS_HOST, 'runCommand').and.resolveTo({
stdout: '10.0.0',
stderr: '',
});

const pm = await createPackageManager({ cwd: '/tmp', configuredPackageManager: ['npm'] });

expect(pm.name).toBe('npm');
expect(runCommandSpy).not.toHaveBeenCalled();
expect(await pm.getVersion()).toBe('10.0.0');
expect(runCommandSpy).toHaveBeenCalledTimes(1);
});
});
38 changes: 36 additions & 2 deletions packages/angular/cli/src/package-managers/package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ export interface PackageManagerOptions {
* If provided, this error will be thrown when attempting to execute any command.
*/
initializationError?: Error;

/**
* If provided, the binary is verified the first time a command needs it,
* and this error is thrown when it is not installed.
*/
missingBinaryError?: Error;
}

/**
Expand All @@ -94,6 +100,7 @@ export class PackageManager {
readonly #initializationError?: Error;
#dependencyCache: Map<string, InstalledPackage> | null = null;
#version: string | undefined;
#binaryCheck: Promise<void> | undefined;
#minimumReleaseAge: Promise<number> | undefined;
#activeTasks = 0;
readonly #pendingTasks: (() => void)[] = [];
Expand Down Expand Up @@ -138,6 +145,28 @@ export class PackageManager {
}
}

/**
* Verifies once that the binary is installed, when `missingBinaryError` is set.
* The output of the version command is kept, so `getVersion` does not run it again.
*/
#checkBinary(): Promise<void> {
const error = this.options.missingBinaryError;
if (!error || this.#version) {
return Promise.resolve();
}

return (this.#binaryCheck ??= this.host
.runCommand(this.descriptor.binary, this.descriptor.versionCommand, { cwd: this.cwd })
.then(
({ stdout }) => {
this.#version = stdout.trim();
},
() => {
throw error;
},
));
}

/**
* A private method to lazily populate the dependency cache.
* This is a performance optimization to avoid running `npm list` multiple times.
Expand Down Expand Up @@ -206,6 +235,7 @@ export class PackageManager {
): Promise<{ stdout: string; stderr: string }> {
return this.#runWithThrottle(async () => {
this.ensureInstalled();
await this.#checkBinary();

const { registry, cwd, ...runOptions } = options;
const finalArgs = [...args];
Expand Down Expand Up @@ -454,8 +484,12 @@ export class PackageManager {
return this.#version;
}

const { stdout } = await this.#run(this.descriptor.versionCommand);
this.#version = stdout.trim();
this.ensureInstalled();
await this.#checkBinary();
if (!this.#version) {
const { stdout } = await this.#run(this.descriptor.versionCommand);
this.#version = stdout.trim();
}

if (!valid(this.#version)) {
throw new Error(`Invalid semver version for ${this.name}: "${this.#version}"`);
Expand Down
32 changes: 32 additions & 0 deletions packages/angular/cli/src/package-managers/package-manager_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,38 @@ describe('PackageManager', () => {
});
});

describe('missingBinaryError', () => {
it('should not run the binary until a command needs it', async () => {
const pm = new PackageManager(host, '/tmp', descriptor, {
missingBinaryError: new Error('Not installed'),
});
expect(runCommandSpy).not.toHaveBeenCalled();

expect(await pm.getVersion()).toBe('1.2.3');
expect(await pm.getVersion()).toBe('1.2.3');
expect(runCommandSpy).toHaveBeenCalledTimes(1);
});

it('should throw missingBinaryError when the binary is not installed', async () => {
const error = new Error('Not installed');
const pm = new PackageManager(host, '/tmp', descriptor, { missingBinaryError: error });
runCommandSpy.and.rejectWith(new Error('spawn npm ENOENT'));

await expectAsync(pm.getVersion()).toBeRejectedWith(error);
await expectAsync(pm.install()).toBeRejectedWith(error);
expect(runCommandSpy).toHaveBeenCalledTimes(1);
});

it('should validate the version read by the binary check', async () => {
const pm = new PackageManager(host, '/tmp', descriptor, {
missingBinaryError: new Error('Not installed'),
});
runCommandSpy.and.resolveTo({ stdout: 'not-a-version', stderr: '' });

await expectAsync(pm.getVersion()).toBeRejectedWithError(/Invalid semver version/);
});
});

describe('getMinimumReleaseAge', () => {
it('should return 0 when the package manager descriptor does not support getReleaseAgeConfigCommand', async () => {
const pm = new PackageManager(host, '/tmp', SUPPORTED_PACKAGE_MANAGERS['bun']);
Expand Down