diff --git a/packages/angular/cli/src/package-managers/factory.ts b/packages/angular/cli/src/package-managers/factory.ts index ed15fcb8a05c..082a51ae42e5 100644 --- a/packages/angular/cli/src/package-managers/factory.ts +++ b/packages/angular/cli/src/package-managers/factory.ts @@ -136,8 +136,7 @@ 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) { @@ -145,22 +144,19 @@ export async function createPackageManager(options: { } // 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.`, + ); } } @@ -169,7 +165,7 @@ export async function createPackageManager(options: { logger, tempDirectory, version, - initializationError, + missingBinaryError, }); logger?.debug(`Successfully created PackageManager for '${name}'.`); diff --git a/packages/angular/cli/src/package-managers/factory_spec.ts b/packages/angular/cli/src/package-managers/factory_spec.ts new file mode 100644 index 000000000000..9a2d9b6b05fe --- /dev/null +++ b/packages/angular/cli/src/package-managers/factory_spec.ts @@ -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); + }); +}); diff --git a/packages/angular/cli/src/package-managers/package-manager.ts b/packages/angular/cli/src/package-managers/package-manager.ts index cc9a6d700b55..1187618ae9c6 100644 --- a/packages/angular/cli/src/package-managers/package-manager.ts +++ b/packages/angular/cli/src/package-managers/package-manager.ts @@ -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; } /** @@ -94,6 +100,7 @@ export class PackageManager { readonly #initializationError?: Error; #dependencyCache: Map | null = null; #version: string | undefined; + #binaryCheck: Promise | undefined; #minimumReleaseAge: Promise | undefined; #activeTasks = 0; readonly #pendingTasks: (() => void)[] = []; @@ -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 { + 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. @@ -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]; @@ -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}"`); diff --git a/packages/angular/cli/src/package-managers/package-manager_spec.ts b/packages/angular/cli/src/package-managers/package-manager_spec.ts index 6f1bf9b7b7ec..495507963599 100644 --- a/packages/angular/cli/src/package-managers/package-manager_spec.ts +++ b/packages/angular/cli/src/package-managers/package-manager_spec.ts @@ -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']);