Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/reference/error-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ A prompt with no declared default was reached where it cannot be shown — under

### CLI.SECOND_PACKAGE_COPY

An ORM or Composer command was refused because the project has its own copy of a Prisma package the command loads (`@prisma/orm-toolchain` or `@prisma/orm-framework`, and `@prisma/composer` for Composer commands), and the running `prisma` would load a different copy: another version, or the same version installed in another place, such as a global `prisma`. Values made by one copy are refused by the other, and what the command writes is read later by the project's own copy, so the run stops before the project's `prisma.config.ts` is evaluated. Refused are the commands that read the project's config, plus `orm init` (it loads the project's own ORM packages and writes files the project reads) and `lsp` (it loads the project's config itself); `emulator list` is not refused. The project's copies are looked for from one directory: the directory of the `--config` file (its real path, when it is a link) when one is given, otherwise the directory of the nearest `prisma.config.ts` at or above the current directory within the repository (the first directory with a `.git` entry), otherwise the current directory. From there, the nearest `node_modules/<package>` up to the repository root counts. Config files further up, and `parent` links, are not followed, so a copy beside a repository-wide config does not refuse a package's own command. Nor are files the config points to in another directory, most often the contract source: they load the packages from where they are, so a copy beside them is not compared. A package the project does not install, or whose copy cannot be read, is not checked. The summary names the first package that differs and both versions; `why` gives every differing package with both versions and both locations, and says so when the versions are equal. Next actions: when the project has its own `prisma`, it is not the one running, and it would not be refused, a run-command with the command path, and the `--config` the user gave, in a form that never downloads a package (`npx --no-install prisma`, `pnpm exec prisma`, `yarn run prisma`, `bun run prisma`); the user adds their other arguments, which are left out because they can hold a database URL; when that `prisma` is reachable only through `--config`, the same advice in words. When the `prisma` the user would run is refused too, the versions to change the project's packages to, or the project's versions a `prisma` release must use; for the same version installed twice, to reinstall the project's dependencies. When the project has no `prisma`, to install it in the project and run that one. Raised by the shell before the command runs; if the check itself fails, nothing is refused. `--help` is unaffected. Exits 2. Meta: `command` (the command path, such as `db migrate`), `packages` (a list of `{ name, project: { version, path }, cli: { version, path } }`).
An ORM or Composer command was refused because the project has its own copy of a Prisma package the command loads (`@prisma/orm-toolchain` or `@prisma/orm-framework`, and `@prisma/composer` for Composer commands), and the running `prisma` would load a different copy: another version, or the same version installed in another place, such as a global `prisma`. Values made by one copy are refused by the other, and what the command writes is read later by the project's own copy, so the run stops before the project's `prisma.config.ts` is evaluated. Refused are the commands that read the project's config, plus `orm init` (it loads the project's own ORM packages and writes files the project reads) and `lsp` (it loads the project's config itself); `emulator list` is not refused. The project's copies are looked for from one directory: the directory of the `--config` file (its real path, when it is a link) when one is given, otherwise the directory of the nearest `prisma.config.ts` at or above the current directory within the repository (the first directory with a `.git` entry), otherwise the current directory. From there, the nearest `node_modules/<package>` up to the repository root counts. Config files further up, and `parent` links, are not followed, so a copy beside a repository-wide config does not refuse a package's own command. Nor are files the config points to in another directory, most often the contract source: they load the packages from where they are, so a copy beside them is not compared. A package the project does not install, or whose copy cannot be read, is not checked. The summary names the first package that differs and both versions; `why` gives every differing package with both versions and both locations, and says so when the versions are equal. Next actions: when the project has its own `prisma`, it is not the one running, and it would not be refused, a run-command with the command path, and the `--config` the user gave, in a form that never downloads a package: the package manager's runner (`npx --no-install prisma`, `pnpm exec prisma`, `yarn exec prisma`, `bunx --no-install prisma`) when that `prisma` is installed in the current directory and the directory has a `package.json`, otherwise the path of its bin from the current directory, such as `../../node_modules/.bin/prisma` (`..\..\node_modules\.bin\prisma` on Windows), because the runners do not search parent folders the way Node does; the user adds their other arguments, which are left out because they can hold a database URL; when that `prisma` is reachable only through `--config`, the same advice in words. When the `prisma` the user would run is refused too, the versions to change the project's packages to, or the project's versions a `prisma` release must use; for the same version installed twice, to reinstall the project's dependencies. When the project has no `prisma`, to install it in the project and run that one. Raised by the shell before the command runs; if the check itself fails, nothing is refused. `--help` is unaffected. Exits 2. Meta: `command` (the command path, such as `db migrate`), `packages` (a list of `{ name, project: { version, path }, cli: { version, path } }`).

### CLI.SPAWN_FAILED

Expand Down
30 changes: 26 additions & 4 deletions packages/cli/src/lib/package-copies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,32 @@ export async function findProjectPackage(
dir: string,
name: string,
): Promise<Result<PackageCopy | null, PackageCopyUnreadableError>> {
const packageDir = searchDirs(path.resolve(dir))
.map((candidate) => path.join(candidate, "node_modules", name))
.find((candidate) => existsSync(path.join(candidate, "package.json")));
return packageDir === undefined ? Result.ok(null) : readCopy(packageDir);
const found = await findProjectInstall(dir, name);
return found.map((install) => install?.copy ?? null);
}

export interface ProjectInstall {
readonly copy: PackageCopy;
/** The `node_modules` folder the package was found in, as found,
* before links are followed. */
readonly nodeModules: string;
}

/** `findProjectPackage`, also saying where the package was found. */
export async function findProjectInstall(
dir: string,
name: string,
): Promise<Result<ProjectInstall | null, PackageCopyUnreadableError>> {
const nodeModules = searchDirs(path.resolve(dir))
.map((candidate) => path.join(candidate, "node_modules"))
.find((candidate) =>
existsSync(path.join(candidate, name, "package.json")),
);
if (nodeModules === undefined) {
return Result.ok(null);
}
const copy = await readCopy(path.join(nodeModules, name));
return copy.map((read) => ({ copy: read, nodeModules }));
}

async function findShellPackage(
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export async function main(
const refusedCommands = await refusedCommandsFor({
argv: proc.argv.slice(2),
cwd: proc.cwd(),
platform: proc.platform,
}).catch(() => []);
let cli: Cli;
try {
Expand Down
84 changes: 65 additions & 19 deletions packages/cli/src/second-copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* writes is read later by the project's own copy, so a second copy
* stops the command before the project's config is evaluated.
*/
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
Expand Down Expand Up @@ -34,10 +35,10 @@ import { configPathFromArgv, flagTokens } from "./lib/argv";
import {
type CheckedPackage,
COMPOSER_COMMAND_PACKAGES,
findProjectPackage,
findProjectInstall,
findSecondCopies,
ORM_COMMAND_PACKAGES,
type PackageCopy,
type ProjectInstall,
projectPackageDir,
type SecondCopy,
} from "./lib/package-copies";
Expand Down Expand Up @@ -120,6 +121,8 @@ export interface SecondCopyCheckRequest {
readonly cwd: string;
/** The file the shell resolves its own packages from. */
readonly shellModuleFile?: string;
/** The platform whose shells the advice is written for. */
readonly platform?: string;
}

/**
Expand Down Expand Up @@ -152,6 +155,7 @@ export async function refusedCommandsFor(
}
const recovery = await recoveryFor({
cwd: request.cwd,
platform: request.platform ?? process.platform,
configPath,
projectDir,
shellModuleFile,
Expand Down Expand Up @@ -201,7 +205,10 @@ export type SecondCopyRecovery =
* run the command. */
| {
readonly kind: "run-project-prisma";
readonly runner: string;
/** What runs it from the current directory, ready to paste: the
* package manager's runner when that finds this prisma, otherwise
* the path of its bin. */
readonly invocation: string;
/** The `--config` the user gave, kept so the command reads the
* same config. */
readonly configPath: string | undefined;
Expand All @@ -226,14 +233,16 @@ export type SecondCopyRecovery =

async function recoveryFor(request: {
readonly cwd: string;
readonly platform: string;
readonly configPath: string | undefined;
readonly projectDir: string;
readonly shellModuleFile: string;
readonly packages: readonly CheckedPackage[];
}): Promise<SecondCopyRecovery> {
const fromCwd = await projectPrismaAt(request.cwd);
const projectPrisma = fromCwd ?? (await projectPrismaAt(request.projectDir));
if (projectPrisma === null) {
const projectPrisma = (fromCwd ?? (await projectPrismaAt(request.projectDir)))
?.copy;
if (projectPrisma === undefined) {
return { kind: "install-project-prisma" };
}
if (isInside(realpathOr(request.shellModuleFile), projectPrisma.path)) {
Expand All @@ -257,19 +266,55 @@ async function recoveryFor(request: {
: path.resolve(request.cwd, request.configPath),
};
}
const manager = Result.try(() => detectPackageManagerSync(request.cwd));
return {
kind: "run-project-prisma",
runner: installedBinRunner(
(manager.isOk() ? manager.value : null) ?? "npm",
),
invocation: runnerFinds(request.cwd, fromCwd.nodeModules)
? `${runnerAt(request.cwd)} ${CLI_NAME}`
: binPathFrom(request.cwd, fromCwd.nodeModules, request.platform),
configPath: request.configPath,
};
}

/**
* Whether the package manager's runner, run from `cwd`, runs the prisma
* found in `nodeModules`. The runners do not search parent folders the
* way Node does. Tried with pnpm 10.27: from a folder with a
* `package.json` and no prisma, `pnpm exec` runs the workspace root's
* prisma, and from a folder with `node_modules` but no `package.json`
* it fails. So only a prisma installed in `cwd`, beside a
* `package.json`, is certain.
*/
function runnerFinds(cwd: string, nodeModules: string): boolean {
return (
existsSync(path.join(cwd, "package.json")) &&
nodeModules === path.join(path.resolve(cwd), "node_modules")
);
}

function runnerAt(cwd: string): string {
const manager = Result.try(() => detectPackageManagerSync(cwd));
return installedBinRunner((manager.isOk() ? manager.value : null) ?? "npm");
}

/** The prisma bin in `nodeModules`, by its path from `cwd`. Its words
* are only `.`, `..`, `node_modules`, `.bin` and `prisma`, so it needs
* no quoting; on Windows the backslash form runs in cmd.exe and
* PowerShell alike. */
function binPathFrom(
cwd: string,
nodeModules: string,
platform: string,
): string {
const segments = path
.relative(path.resolve(cwd), path.join(nodeModules, ".bin", CLI_NAME))
.split(path.sep);
const fromCwd = segments[0] === ".." ? segments : [".", ...segments];
return fromCwd.join(platform === "win32" ? "\\" : "/");
}

/** The project's own prisma; an unreadable one counts as none. */
async function projectPrismaAt(dir: string): Promise<PackageCopy | null> {
const found = await findProjectPackage(dir, CLI_NAME);
async function projectPrismaAt(dir: string): Promise<ProjectInstall | null> {
const found = await findProjectInstall(dir, CLI_NAME);
return found.isOk() ? found.value : null;
}

Expand Down Expand Up @@ -333,14 +378,15 @@ function nextActions(
{
kind: "run-command",
label: `Run the project's own ${CLI_NAME} instead, adding your other arguments after the command`,
command: formatShellCommand([
...recovery.runner.split(" "),
CLI_NAME,
...commandPath.split(" "),
...(recovery.configPath === undefined
? []
: ["--config", recovery.configPath]),
]),
command: [
recovery.invocation,
formatShellCommand([
...commandPath.split(" "),
...(recovery.configPath === undefined
? []
: ["--config", recovery.configPath]),
]),
].join(" "),
},
];
case "run-project-prisma-elsewhere":
Expand Down
151 changes: 140 additions & 11 deletions packages/cli/tests/second-copy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
* temporary folder.
*/
import { existsSync, readFileSync } from "node:fs";
import { mkdir, mkdtemp, realpath, symlink, writeFile } from "node:fs/promises";
import {
mkdir,
mkdtemp,
realpath,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
Expand Down Expand Up @@ -121,6 +128,16 @@ async function writePackage(
);
}

/** A package at `packageRoot` that installed its own prisma, with the
* bin a package manager links for it. */
async function writePackageWithPrisma(packageRoot: string): Promise<void> {
await writePackage(packageRoot, path.basename(packageRoot), "1.0.0");
const nodeModules = path.join(packageRoot, "node_modules");
await writePackage(path.join(nodeModules, "prisma"), "prisma", "8.0.0-rc.35");
await mkdir(path.join(nodeModules, ".bin"), { recursive: true });
await writeFile(path.join(nodeModules, ".bin", "prisma"), "", "utf8");
}

/** The project installed its own toolchain, at another release than
* the CLI carries. */
async function makeProjectWithSecondCopy(): Promise<{
Expand Down Expand Up @@ -635,11 +652,7 @@ describe("a product command in a project with a second copy", () => {
describe("what the error says", () => {
it("offers the project's own prisma, which would pass, as a command that never downloads", async () => {
const { dir } = await makeProjectWithSecondCopy();
await writePackage(
path.join(dir, "node_modules", "prisma"),
"prisma",
"8.0.0-rc.35",
);
await writePackageWithPrisma(dir);
await writeFile(path.join(dir, "pnpm-lock.yaml"), "", "utf8");
const proc = makeProcess({ argv: ["db", "migrate", "--json"], cwd: dir });

Expand All @@ -657,11 +670,7 @@ describe("what the error says", () => {

it("keeps the --config the user gave in the suggested command, and nothing else", async () => {
const { dir } = await makeProjectWithSecondCopy();
await writePackage(
path.join(dir, "node_modules", "prisma"),
"prisma",
"8.0.0-rc.35",
);
await writePackageWithPrisma(dir);
await writeFile(path.join(dir, "package-lock.json"), "{}", "utf8");
const configDir = path.join(dir, "config dir");
await mkdir(configDir, { recursive: true });
Expand Down Expand Up @@ -691,6 +700,126 @@ describe("what the error says", () => {
]);
});

describe("from a folder of a workspace package that has no package.json", () => {
/** A pnpm workspace whose root and whose package each installed
* prisma, and a folder inside the package holding a config. */
async function makeWorkspaceFolder(): Promise<string> {
const root = path.join(await makeRoot(), "monorepo");
await mkdir(path.join(root, ".git"), { recursive: true });
await writePackageWithPrisma(root);
await writeFile(
path.join(root, "pnpm-workspace.yaml"),
"packages:\n - services/*\n",
"utf8",
);
await writeFile(path.join(root, "pnpm-lock.yaml"), "", "utf8");
const service = path.join(root, "services", "control-plane");
await writePackageWithPrisma(service);
await writePackage(
path.join(service, "node_modules", TOOLCHAIN),
TOOLCHAIN,
"8.0.0-rc.24",
);
const folder = path.join(service, "scripts", "usage-testing");
await mkdir(folder, { recursive: true });
await writeFile(path.join(folder, "prisma.config.ts"), "", "utf8");
return folder;
}

it("gives the path of the package's prisma, which pnpm exec would not run", async () => {
const cwd = await makeWorkspaceFolder();

const error = await refusalOf(
await refusedCommandsFor({
argv: ["contract", "emit"],
cwd,
platform: "linux",
}),
"contract emit",
);

expect(error.nextActions).toEqual([
{
kind: "run-command",
label:
"Run the project's own prisma instead, adding your other arguments after the command",
command: "../../node_modules/.bin/prisma contract emit",
},
]);
});

it("keeps the --config the user gave after that path", async () => {
const cwd = await makeWorkspaceFolder();

const error = await refusalOf(
await refusedCommandsFor({
argv: ["contract", "emit", "--config", "prisma.config.ts"],
cwd,
platform: "linux",
}),
"contract emit",
);

expect(error.nextActions[0]?.command).toBe(
"../../node_modules/.bin/prisma contract emit --config prisma.config.ts",
);
});

it("gives the path when the folder has its own package.json but no prisma", async () => {
const cwd = await makeWorkspaceFolder();
await writePackage(cwd, "usage-testing", "1.0.0");

const error = await refusalOf(
await refusedCommandsFor({
argv: ["contract", "emit"],
cwd,
platform: "linux",
}),
"contract emit",
);

expect(error.nextActions[0]?.command).toBe(
"../../node_modules/.bin/prisma contract emit",
);
});

it("gives the path unquoted, with backslashes, on Windows", async () => {
const cwd = await makeWorkspaceFolder();

const error = await refusalOf(
await refusedCommandsFor({
argv: ["contract", "emit"],
cwd,
platform: "win32",
}),
"contract emit",
);

expect(error.nextActions[0]?.command).toBe(
"..\\..\\node_modules\\.bin\\prisma contract emit",
);
});
});

it("gives the path of a prisma installed beside no package.json", async () => {
const { dir } = await makeProjectWithSecondCopy();
await writePackageWithPrisma(dir);
await rm(path.join(dir, "package.json"));

const error = await refusalOf(
await refusedCommandsFor({
argv: ["db", "migrate"],
cwd: dir,
platform: "linux",
}),
"db migrate",
);

expect(error.nextActions[0]?.command).toBe(
"./node_modules/.bin/prisma db migrate",
);
});

it("names the versions to change when the project's own prisma would be refused too", async () => {
const { dir } = await makeProjectWithSecondCopy();
const projectPrisma = path.join(dir, "node_modules", "prisma");
Expand Down
Loading