Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
62 changes: 60 additions & 2 deletions src/install/PackageManager/patchPackage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use crate::package_manager_real::package_manager_directories::{
compute_cache_dir_and_subpath, get_temporary_directory,
};
use crate::{
BuntagHashBuf, DependencyID, Features, PackageID, Resolution, buntaghashbuf_make,
initialize_store, invalid_package_id,
BuntagHashBuf, DependencyID, Features, PackageID, Resolution, ResolutionTag,
buntaghashbuf_make, initialize_store, invalid_package_id,
};

#[inline]
Expand Down Expand Up @@ -270,6 +270,7 @@ pub fn do_patch_commit(
// `compute_cache_dir_and_subpath` resolves `pkg.resolution`'s strings against `manager.lockfile`.
manager.lockfile = lockfile;
let name = manager.lockfile.str(&pkg.name).to_vec();
crash_if_folder_target(&manager.lockfile, pkg.meta.id, &name);
let cache_result =
compute_cache_dir_and_subpath(manager, &name, &pkg.resolution, &mut folder_path_buf, None);
let cache_dir: Fd = cache_result.cache_dir;
Expand Down Expand Up @@ -834,6 +835,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> {
};

let name = lockfile.str(&package.name).to_vec();
crash_if_folder_target(lockfile, actual_package.meta.id, &name);
Comment thread
robobun marked this conversation as resolved.
Resolved
let existing_patchfile_hash: Option<u64> = 'existing_patchfile_hash: {
let mut name_and_version = Vec::new();
write!(
Expand Down Expand Up @@ -890,6 +892,7 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> {
let strbuf = manager.lockfile.buffers.string_bytes.as_slice();
let pkg = *manager.lockfile.packages.get(pkg_id as usize);
let pkg_name = pkg.name.slice(strbuf).to_vec();
crash_if_folder_target(&manager.lockfile, pkg_id, &pkg_name);

let existing_patchfile_hash: Option<u64> = 'existing_patchfile_hash: {
let mut name_and_version = Vec::new();
Expand Down Expand Up @@ -1249,6 +1252,61 @@ fn node_modules_folder_for_dependency_id(
}
}

/// Exits when `pkg_id` resolves to a folder on disk (a `file:` directory or a
/// workspace member). `bun install` links such a folder in place and never
/// applies a patch to it: `patched_package_missing_from_cache` finds the folder
/// itself. `compute_cache_dir_and_subpath` also resolves every folder against
/// the project root, which is the wrong base for a `file:` path a registry
/// package declares.
fn crash_if_folder_target(lockfile: &Lockfile, pkg_id: PackageID, name: &[u8]) {
let strbuf = lockfile.buffers.string_bytes.as_slice();
let resolution = &lockfile.packages.items_resolution()[pkg_id as usize];
let folder = match resolution.tag {
ResolutionTag::Folder => resolution.folder().slice(strbuf),
ResolutionTag::Workspace => {
bun_core::pretty_errorln!(
"<r><red>error<r>: cannot patch <b>{}<r>: it is a workspace package, and bun install never applies a patch to one",
bstr::BStr::new(name),
);
bun_core::note!(
"edit <b>{}<r> directly",
bstr::BStr::new(resolution.workspace().slice(strbuf)),
);
Global::crash();
}
_ => return,
Comment thread
robobun marked this conversation as resolved.
Resolved
};

// A `file:` path a registry package declares is relative to that package,
// which ships the folder. Every other declarer (the root, a workspace, a
// local `file:` package, a root override) wrote a path in the project.
Comment thread
robobun marked this conversation as resolved.
Resolved
let dependency_id = lockfile
.buffers
.resolutions
.iter()
.position(|&resolved| resolved == pkg_id)
.map(|id| DependencyID::try_from(id).expect("int cast"));
let dependent = dependency_id
.filter(|&id| !lockfile.is_trusted_folder_dependency(id))
.and_then(|id| lockfile.get_parent_pkg_of_dependency(id))
.map(|id| lockfile.str(&lockfile.packages.items_name()[id as usize]));

bun_core::pretty_errorln!(
"<r><red>error<r>: cannot patch <b>{}<r>: it is a <b>file:{}<r> dependency, and bun install never applies a patch to a file: folder",
bstr::BStr::new(name),
bstr::BStr::new(folder),
);
match dependent {
Some(dependent) => bun_core::note!(
"to change it, run <cyan>bun patch {}<r> and edit <b>{}<r> inside that package, which ships the folder",
bstr::BStr::new(dependent),
bstr::BStr::new(folder),
),
None => bun_core::note!("edit <b>{}<r> directly", bstr::BStr::new(folder)),
}
Global::crash();
}

type IdPair = (DependencyID, PackageID);

fn pkg_info_for_name_and_version(
Expand Down
176 changes: 176 additions & 0 deletions test/cli/install/bun-patch.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { $, ShellOutput } from "bun";
import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test";
import { lstatSync, readFileSync } from "fs";
import { rm } from "fs/promises";
import { bunEnv, bunExe, isASAN, tempDir, VerdaccioRegistry } from "harness";
import { isAbsolute, join, sep } from "path";

Expand Down Expand Up @@ -1234,3 +1235,178 @@ describe.concurrent("bun patch --commit for non-registry dependencies", () => {
expect(patchKey).toBe("pkg-to-patch@./dep.tgz");
});
});

// `bun install` links a folder dependency (a `file:` directory or a workspace member) in place and
// never applies a patch to it, and `bun patch --commit` on one failed with "failed to read from
// cache (readlink)". `bun patch` still prepared it, and read every folder from the project root.
// bundled-file@2.0.0 declares "bundled-file-dep": "file:vendor/bundled-file-dep" and ships that
// folder in its tarball, relative to the installed package: ENOENT when the project has no such
// folder, and the project's unrelated folder copied over the installed package when it has one.
describe("a folder dependency as the target", () => {
const registry = new VerdaccioRegistry();

beforeAll(async () => {
await registry.start();
});

afterAll(() => {
registry.stop();
});

const shippedFolderRefusal =
"error: cannot patch bundled-file-dep: it is a file:vendor/bundled-file-dep dependency, and bun install never applies a patch to a file: folder\n" +
"note: to change it, run bun patch bundled-file and edit vendor/bundled-file-dep inside that package, which ships the folder\n";
const installedDep = join("node_modules", "bundled-file", "node_modules", "bundled-file-dep");

// CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`.
async function runBun(cwd: string, ...args: string[]) {
await using proc = Bun.spawn({
cmd: [bunExe(), ...args],
cwd,
env: { ...bunEnv, BUN_INSTALL_CACHE_DIR: join(cwd, ".bun-cache") },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout, stderr, exitCode };
}

async function createProject(packageJson: Record<string, unknown>, files: Record<string, string> = {}) {
const { packageDir } = await registry.createTestDir({
bunfigOpts: { linker: "hoisted" },
files: { "package.json": JSON.stringify({ name: "proj", ...packageJson }), ...files },
});
const { stderr, exitCode } = await runBun(packageDir, "install");
expect(stderr).not.toContain("error:");
expect(exitCode).toBe(0);
return packageDir;
}

async function createProjectWithShippedFolder(files: Record<string, string> = {}) {
const packageDir = await createProject({ dependencies: { "bundled-file": "2.0.0" } }, files);
expect(await Bun.file(join(packageDir, installedDep, "index.js")).text()).toBe(
'module.exports = "bundled-file-dep";\n',
);
return packageDir;
}

async function expectRefused(packageDir: string, refusal: string, ...args: string[]) {
const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", ...args);
expect(stderr).toEndWith(refusal);
expect(stdout).not.toContain("To patch");
expect(exitCode).toBe(1);
}

async function expectShippedFolderRefused(packageDir: string, ...args: string[]) {
await expectRefused(packageDir, shippedFolderRefusal, ...args);
expect(await Bun.file(join(packageDir, installedDep, "index.js")).text()).toBe(
'module.exports = "bundled-file-dep";\n',
);
}

test.concurrent("bun patch <name> refuses a folder an installed package ships", async () => {
const packageDir = await createProjectWithShippedFolder();
await expectShippedFolderRefused(packageDir, "bundled-file-dep");
expect(await Bun.file(join(packageDir, "vendor", "bundled-file-dep", "package.json")).exists()).toBe(false);
});

test.concurrent("bun patch <path> refuses a folder an installed package ships", async () => {
const packageDir = await createProjectWithShippedFolder();
await expectShippedFolderRefused(packageDir, installedDep);
});

test.concurrent("bun patch <name> refuses when the project has an unrelated folder at that path", async () => {
const packageDir = await createProjectWithShippedFolder({
"vendor/bundled-file-dep/package.json": JSON.stringify({ name: "unrelated", version: "9.9.9" }),
"vendor/bundled-file-dep/index.js": 'module.exports = "unrelated";\n',
});
await expectShippedFolderRefused(packageDir, "bundled-file-dep");
});

test.concurrent("bun patch --commit <path> refuses a folder an installed package ships", async () => {
const packageDir = await createProjectWithShippedFolder();
await expectShippedFolderRefused(packageDir, "--commit", installedDep);
expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toBeUndefined();
});

// A root override writes the path in the root package.json, so the folder is the project's own.
test.concurrent("bun patch <name> refuses a file: override of a registry package's dependency", async () => {
const packageDir = await createProject(
{
dependencies: { "bundled-file": "2.0.0" },
overrides: { "bundled-file-dep": "file:./vendor/override-dep" },
},
{
"vendor/override-dep/package.json": JSON.stringify({ name: "bundled-file-dep", version: "3.0.0" }),
"vendor/override-dep/index.js": 'module.exports = "override-dep";\n',
},
);
await expectRefused(
packageDir,
"error: cannot patch bundled-file-dep: it is a file:./vendor/override-dep dependency, and bun install never applies a patch to a file: folder\n" +
"note: edit ./vendor/override-dep directly\n",
"bundled-file-dep",
);
});

test.concurrent("bun patch <name> refuses a file: dependency of the project", async () => {
const packageDir = await createProject(
{ dependencies: { "local-dep": "file:./local-dep" } },
{
"local-dep/package.json": JSON.stringify({ name: "local-dep", version: "1.0.0" }),
"local-dep/index.js": 'module.exports = "local-dep";\n',
},
);
const refusal =
"error: cannot patch local-dep: it is a file:local-dep dependency, and bun install never applies a patch to a file: folder\n" +
"note: edit local-dep directly\n";
await expectRefused(packageDir, refusal, "local-dep");
await expectRefused(packageDir, refusal, "--commit", "node_modules/local-dep");
expect(await Bun.file(join(packageDir, "node_modules", "local-dep", "index.js")).text()).toBe(
'module.exports = "local-dep";\n',
);
});

test.concurrent("bun patch <name> refuses a workspace member", async () => {
const packageDir = await createProject(
{ workspaces: ["packages/*"], dependencies: { member: "workspace:*" } },
{
"packages/member/package.json": JSON.stringify({ name: "member", version: "1.0.0" }),
"packages/member/index.js": 'module.exports = "member";\n',
},
);
const refusal =
"error: cannot patch member: it is a workspace package, and bun install never applies a patch to one\n" +
"note: edit packages/member directly\n";
await expectRefused(packageDir, refusal, "member");
await expectRefused(packageDir, refusal, "--commit", "node_modules/member");
expect(lstatSync(join(packageDir, "node_modules", "member")).isSymbolicLink()).toBe(true);
});

// The remedy the note names: patch the package that ships the folder.
test.concurrent("bun patch bundled-file carries an edit to the shipped folder", async () => {
const packageDir = await createProjectWithShippedFolder();

const prepare = await runBun(packageDir, "patch", "bundled-file");
expect(prepare.stderr).not.toContain("error:");
expect(prepare.exitCode).toBe(0);

await Bun.write(
join(packageDir, "node_modules", "bundled-file", "vendor", "bundled-file-dep", "index.js"),
'module.exports = "patched";\n',
);

const commit = await runBun(packageDir, "patch", "--commit", "node_modules/bundled-file");
expect(commit.stderr).not.toContain("error:");
expect(commit.exitCode).toBe(0);
expect((await Bun.file(join(packageDir, "package.json")).json()).patchedDependencies).toEqual({
"bundled-file@2.0.0": "patches/bundled-file@2.0.0.patch",
});

await rm(join(packageDir, "node_modules"), { recursive: true, force: true });
const install = await runBun(packageDir, "install");
expect(install.stderr).not.toContain("error:");
expect(install.exitCode).toBe(0);
expect(await Bun.file(join(packageDir, installedDep, "index.js")).text()).toBe('module.exports = "patched";\n');
});
});
Loading