diff --git a/README.md b/README.md index 67d396d5c..61398b213 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,18 @@ range specified in `devEngines.packageManager.version`, or fallback to the same major line. Should you need to upgrade to a new major, use an explicit `corepack use {name}@latest` call (or simply `corepack use {name}`). +### `corepack project install` + +Installs the package manager used in the local project, and then uses it to +install dependencies. + +This is roughly equivalent to running `corepack enable && npm install` for a +project using npm, or `corepack enable && pnpm install` for project using pnpm +and so on. + +It can be useful for writing scripts to run against arbitrary projects, when +the package manager is not known in advance. + ## Environment Variables - `COREPACK_DEFAULT_TO_LATEST` can be set to `0` in order to instruct Corepack diff --git a/sources/commands/Base.ts b/sources/commands/Base.ts index 950195427..928d8aea6 100644 --- a/sources/commands/Base.ts +++ b/sources/commands/Base.ts @@ -32,13 +32,19 @@ export abstract class BaseCommand extends Command { previousPackageManager, } = await specUtils.setLocalPackageManager(this.context.cwd, info); + await this.installLocalPackageManager(info, previousPackageManager); + } + + async installLocalPackageManager(info: PreparedPackageManagerInfo, previousPackageManager?: string) { const command = this.context.engine.getPackageManagerSpecFor(info.locator).commands?.use ?? null; if (command === null) return 0; // Adding it into the environment avoids breaking package managers that // don't expect those options. - process.env.COREPACK_MIGRATE_FROM = previousPackageManager; + if (previousPackageManager) + process.env.COREPACK_MIGRATE_FROM = previousPackageManager; + this.context.stdout.write(`\n`); const [binaryName, ...args] = command; diff --git a/sources/commands/Project.ts b/sources/commands/Project.ts new file mode 100644 index 000000000..eada1bd27 --- /dev/null +++ b/sources/commands/Project.ts @@ -0,0 +1,46 @@ +import {Command, UsageError} from 'clipanion'; +import semverValid from 'semver/functions/valid'; +import semverValidRange from 'semver/ranges/valid'; + +import {BaseCommand} from './Base'; + +// modified from ./Enable.ts +// https://github.com/nodejs/corepack/issues/505 +export class ProjectInstallCommand extends BaseCommand { + static paths = [ + [`project`, `install`], + ]; + + static usage = Command.Usage({ + description: `Add the Corepack shims to the install directories, and run the install command of the specified package manager`, + details: ` + When run, this command will check whether the shims for the specified package managers can be found with the correct values inside the install directory. If not, or if they don't exist, they will be created. + + Then, it will run the install command of the specified package manager. If no package manager is specified, it will default to npm. + + It will locate the install directory by running the equivalent of \`which corepack\`. + `, + examples: [[ + `Enable all shims and install, putting shims next to the \`corepack\` binary`, + `$0 project install`, + ]], + }); + + async execute() { + const [descriptor] = await this.resolvePatternsToDescriptors({ + patterns: [], + }); + + if (!semverValid(descriptor.range) && !semverValidRange(descriptor.range)) + throw new UsageError(`The 'corepack project install' command can only be used when your project's packageManager field is set to a semver version or semver range`); + + const resolved = await this.context.engine.resolveDescriptor(descriptor); + if (!resolved) + throw new UsageError(`Failed to successfully resolve '${descriptor.range}' to a valid ${descriptor.name} release`); + + this.context.stdout.write(`Installing ${resolved.name}@${resolved.reference} in the project...\n`); + + const packageManagerInfo = await this.context.engine.ensurePackageManager(resolved); + await this.installLocalPackageManager(packageManagerInfo); + } +} diff --git a/sources/main.ts b/sources/main.ts index faa7d6cd7..f64a83c08 100644 --- a/sources/main.ts +++ b/sources/main.ts @@ -10,6 +10,7 @@ import {EnableCommand} from './commands/Enable'; import {InstallGlobalCommand} from './commands/InstallGlobal'; import {InstallLocalCommand} from './commands/InstallLocal'; import {PackCommand} from './commands/Pack'; +import {ProjectInstallCommand} from './commands/Project'; import {UpCommand} from './commands/Up'; import {UseCommand} from './commands/Use'; import {HydrateCommand} from './commands/deprecated/Hydrate'; @@ -67,6 +68,7 @@ export async function runMain(argv: Array) { cli.register(PackCommand); cli.register(UpCommand); cli.register(UseCommand); + cli.register(ProjectInstallCommand); // Deprecated commands cli.register(HydrateCommand); diff --git a/tests/Project.test.ts b/tests/Project.test.ts new file mode 100644 index 000000000..5273866a8 --- /dev/null +++ b/tests/Project.test.ts @@ -0,0 +1,81 @@ +import {ppath, xfs, npath} from '@yarnpkg/fslib'; +import process from 'node:process'; +import {describe, beforeEach, it, expect} from 'vitest'; + +import {runCli} from './_runCli'; + +beforeEach(async () => { + // `process.env` is reset after each tests in setupTests.js. + process.env.COREPACK_HOME = npath.fromPortablePath(await xfs.mktempPromise()); + process.env.COREPACK_DEFAULT_TO_LATEST = `0`; +}); + +describe(`ProjectCommand`, () => { + describe(`InstallSubcommand`, () => { + it(`should install with npm`, async () => { + await xfs.mktempPromise(async cwd => { + await xfs.writeJsonPromise(ppath.join(cwd, `package.json`), { + packageManager: `npm@6.14.2`, + license: `MIT`, + dependencies: { + ms: `2.1.3`, + }, + }); + + await expect(runCli(cwd, [`project`, `install`])).resolves.toMatchObject({ + exitCode: 0, + stdout: expect.stringMatching(/^(?!.*Error).*$/s), + stderr: expect.stringContaining(`created a lockfile as package-lock.json`), + }); + + const dir = await xfs.readdirPromise(cwd); + expect(dir).toContain(`package-lock.json`); + expect(xfs.existsSync(ppath.join(cwd, `node_modules/ms/package.json`))).toBe(true); + }); + }); + + it(`should install with pnpm`, async () => { + await xfs.mktempPromise(async cwd => { + await xfs.writeJsonPromise(ppath.join(cwd, `package.json`), { + packageManager: `pnpm@5.8.0`, + license: `MIT`, + dependencies: { + ms: `2.1.3`, + }, + }); + + await expect(runCli(cwd, [`project`, `install`])).resolves.toMatchObject({ + exitCode: 0, + stdout: expect.stringMatching(/^(?!.*Error).*$/s), + stderr: ``, + }); + + const dir = await xfs.readdirPromise(cwd); + expect(dir).toContain(`pnpm-lock.yaml`); + expect(xfs.existsSync(ppath.join(cwd, `node_modules/ms/package.json`))).toBe(true); + }); + }); + + it(`should install with yarn`, async () => { + await xfs.mktempPromise(async cwd => { + await xfs.writeJsonPromise(ppath.join(cwd, `package.json`), { + packageManager: `yarn@1.22.4`, + license: `MIT`, + dependencies: { + ms: `2.1.3`, + }, + }); + + await expect(runCli(cwd, [`project`, `install`])).resolves.toMatchObject({ + exitCode: 0, + stdout: expect.stringMatching(/^(?!.*Error).*$/s), + stderr: ``, + }); + + const dir = await xfs.readdirPromise(cwd); + expect(dir).toContain(`yarn.lock`); + expect(xfs.existsSync(ppath.join(cwd, `node_modules/ms/package.json`))).toBe(true); + }); + }); + }); +});