Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add corepack project install command #551

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,18 @@ version range, as it will always select the latest available version from 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
Expand Down
8 changes: 7 additions & 1 deletion sources/commands/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,19 @@ export abstract class BaseCommand extends Command<Context> {
previousPackageManager,
} = await specUtils.setLocalPackageManager(this.context.cwd, info);

await this.installLocalPackageManager(info, previousPackageManager);
}

async installLocalPackageManager(info: PreparedPackageManagerInfo, previousPackageManager?: string) {
mmkal marked this conversation as resolved.
Show resolved Hide resolved
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;
Expand Down
46 changes: 46 additions & 0 deletions sources/commands/Project.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
2 changes: 2 additions & 0 deletions sources/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,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';
Expand Down Expand Up @@ -62,6 +63,7 @@ export async function runMain(argv: Array<string>) {
cli.register(PackCommand);
cli.register(UpCommand);
cli.register(UseCommand);
cli.register(ProjectInstallCommand);

// Deprecated commands
cli.register(HydrateCommand);
Expand Down
81 changes: 81 additions & 0 deletions tests/Project.test.ts
Original file line number Diff line number Diff line change
@@ -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: `[email protected]`,
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)

Check failure on line 33 in tests/Project.test.ts

View workflow job for this annotation

GitHub Actions / Testing chores

Missing semicolon
mmkal marked this conversation as resolved.
Show resolved Hide resolved
});
});

it(`should install with pnpm`, async () => {
await xfs.mktempPromise(async cwd => {
await xfs.writeJsonPromise(ppath.join(cwd, `package.json`), {
packageManager: `[email protected]`,
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)

Check failure on line 55 in tests/Project.test.ts

View workflow job for this annotation

GitHub Actions / Testing chores

Missing semicolon
mmkal marked this conversation as resolved.
Show resolved Hide resolved
});
});

it(`should install with yarn`, async () => {
await xfs.mktempPromise(async cwd => {
await xfs.writeJsonPromise(ppath.join(cwd, `package.json`), {
packageManager: `[email protected]`,
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)

Check failure on line 77 in tests/Project.test.ts

View workflow job for this annotation

GitHub Actions / Testing chores

Missing semicolon
mmkal marked this conversation as resolved.
Show resolved Hide resolved
});
});
});
});
Loading