From 0ce6e0d999f79af4f09ebf920b687c059ff64ce0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 07:33:47 +0000 Subject: [PATCH 1/7] bun patch --commit: link node_modules/ into the isolated store again With the isolated linker, `bun patch ` swaps the link of a root or workspace dependency for a detached copy of the package. Since 1.3.14 the linker keeps a real directory that it finds where a link belongs, so the copy stayed after `--commit` and the package could not load its own dependencies. The root and workspace entries now put the link of the committed package back. They do it after their dependencies are installed, and only when the store entry carries the tag of the new patch. A patch that does not apply keeps the copy with the edits. `bun patch --commit` now refuses a folder that is a link. `git diff` records such a link as `new file mode 120000`, and no install can apply that patch. With the link back in place, a second `--commit` would otherwise replace a good patch file with a broken one. --- src/install/PackageManager.rs | 5 + src/install/PackageManager/patchPackage.rs | 13 ++ src/install/isolated_install/Installer.rs | 77 +++++++- src/install/isolated_install/Symlinker.rs | 12 +- test/cli/install/bun-patch.test.ts | 208 ++++++++++++++++++--- 5 files changed, 277 insertions(+), 38 deletions(-) diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index d1075ccba9a3..d334cbec37ff 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -461,6 +461,9 @@ pub struct PackageManager { pub(crate) patched_dependencies_to_remove: ArrayHashMap, + // bun patch --commit: the package whose patch was just written; the isolated linker puts its links back. + pub(crate) committed_patch: Option, + pub(crate) active_lifecycle_scripts: crate::lifecycle_script_runner::List<'static>, pub(crate) last_reported_slow_lifecycle_script_at: u64, pub(crate) cached_tick_for_slow_lifecycle_script_logging: u64, @@ -2147,6 +2150,7 @@ pub fn init( wr!(edited_package_jsons, Vec::new()); wr!(catalog_add, add_catalog::State::default()); wr!(patched_dependencies_to_remove, ArrayHashMap::default()); + wr!(committed_patch, None); wr!(last_reported_slow_lifecycle_script_at, 0); wr!(cached_tick_for_slow_lifecycle_script_logging, 0); } @@ -2615,6 +2619,7 @@ fn init_with_runtime_once( wr!(edited_package_jsons, Vec::new()); wr!(catalog_add, add_catalog::State::default()); wr!(patched_dependencies_to_remove, ArrayHashMap::default()); + wr!(committed_patch, None); wr!(last_reported_slow_lifecycle_script_at, 0); wr!(cached_tick_for_slow_lifecycle_script_logging, 0); } diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 22f89dfd3146..f4e881732aad 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -267,6 +267,17 @@ pub fn do_patch_commit( } }; + // A link into the isolated store is not a copy from `bun patch`. `git diff` would record the + // link itself (`new file mode 120000`), and no install can apply that patch. + if !is_real_dir_not_symlink(&changes_dir) { + bun_core::pretty_errorln!( + "error: {} is not a folder that bun patch prepared. Run `bun patch {}` first.", + bstr::BStr::new(&changes_dir), + bstr::BStr::new(manager.options.positionals[1]), + ); + Global::crash(); + } + // `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(); @@ -600,6 +611,8 @@ pub fn do_patch_commit( b".bun-patch-tag", ])); + manager.committed_patch = Some(string_hash(&patch_key)); + Ok(Some(PatchCommitResult { patch_key: patch_key.into_boxed_slice(), patchfile_path, diff --git a/src/install/isolated_install/Installer.rs b/src/install/isolated_install/Installer.rs index 1ee1715dbf53..b9696c224004 100644 --- a/src/install/isolated_install/Installer.rs +++ b/src/install/isolated_install/Installer.rs @@ -21,8 +21,9 @@ use crate::postinstall_optimizer; use crate::postinstall_optimizer::PostinstallOptimizer; use crate::resolution; use crate::{ - self as install, DependencyID, Lockfile, PackageID, PackageManager, PackageNameHash, - Resolution, TaskCallbackContext, TruncatedPackageNameHash, bin, invalid_dependency_id, + self as install, DependencyID, Lockfile, PackageID, PackageManager, PackageNameAndVersionHash, + PackageNameHash, Resolution, TaskCallbackContext, TruncatedPackageNameHash, bin, + invalid_dependency_id, }; // Bring `items_()` column accessors into scope for // `MultiArrayList` / `Slice`. @@ -1488,12 +1489,13 @@ impl Task { symlinker::Strategy::ExpectMissing }; - let changed = match installer.symlink_dependencies(self.entry_id, strategy) { - sys::Result::Ok(changed) => changed, - sys::Result::Err(err) => { - return Ok(Yield::failure(TaskError::SymlinkDependencies(err))); - } - }; + let changed = + match installer.symlink_dependencies(self.entry_id, strategy, None) { + sys::Result::Ok(changed) => changed, + sys::Result::Err(err) => { + return Ok(Yield::failure(TaskError::SymlinkDependencies(err))); + } + }; if relinking { if !changed { @@ -1536,6 +1538,13 @@ impl Task { Step::SymlinkDependencyBinaries => { let current_step = Step::SymlinkDependencyBinaries; + if matches!(pkg_res.tag, ResolutionTag::Root | ResolutionTag::Workspace) { + if let sys::Result::Err(err) = + installer.relink_committed_patch(self.entry_id) + { + return Ok(Yield::failure(TaskError::SymlinkDependencies(err))); + } + } if let Err(err) = installer.link_dependency_bins(self.entry_id) { return Ok(Yield::failure(TaskError::Binaries(err))); } @@ -2235,10 +2244,12 @@ impl<'a> Installer<'a> { } /// Ok(true) when at least one dependency link of the entry was written. + /// `only_patch` limits the links to that patched package, once the store holds it patched. fn symlink_dependencies( &self, entry_id: StoreEntryId, strategy: symlinker::Strategy, + only_patch: Option, ) -> sys::Result { let lockfile = self.lockfile(); let string_buf = lockfile.buffers.string_bytes.as_slice(); @@ -2279,6 +2290,12 @@ impl<'a> Installer<'a> { self.append_store_path(&mut dep_store_path, dep.entry_id); } + if let Some(patch) = only_patch { + if !self.store_holds_patch(dep.entry_id, patch, &mut dep_store_path) { + continue; + } + } + let dest_len = dest.len(); dest.undo(1); let target = dest.relative(&dep_store_path); @@ -2298,6 +2315,50 @@ impl<'a> Installer<'a> { Ok(changed) } + /// True when `entry_id` is the package that `patch` applies to, and `store_path` (the + /// package directory of the entry) has the tag file of that patch. + fn store_holds_patch( + &self, + entry_id: StoreEntryId, + patch: PackageNameAndVersionHash, + store_path: &mut AutoAbsPath, + ) -> bool { + let node_id = self.store.entries.items_node_id()[entry_id.get() as usize]; + let pkg_id = self.store.nodes.items_pkg_id()[node_id.get() as usize]; + let pkgs = self.lockfile().packages.slice(); + + let Ok(PatchInfo::Patch(info)) = self.package_patch_info( + pkgs.items_name()[pkg_id as usize], + pkgs.items_name_hash()[pkg_id as usize], + &pkgs.items_resolution()[pkg_id as usize], + ) else { + return false; + }; + if info.name_and_version_hash != patch { + return false; + } + + let mut tag_buf: install::BuntagHashBuf = Default::default(); + let tag = install::buntaghashbuf_make(&mut tag_buf, info.contents_hash); + let store_path_len = store_path.len(); + store_path.append(&*tag).assume_ok(); + let has_tag = sys::exists_z(store_path.slice_z()); + store_path.set_length(store_path_len); + has_tag + } + + /// `bun patch` swaps the link of a root or workspace dependency for a detached copy of the + /// package, and `Strategy::ExpectExisting` keeps a real directory. `bun patch --commit` puts + /// the link back here, after the dependencies of the entry are installed: a patch that did + /// not apply leaves no tag in the store, and then the copy with the edits stays. + fn relink_committed_patch(&self, entry_id: StoreEntryId) -> sys::Result<()> { + let Some(patch) = self.manager().committed_patch else { + return Ok(()); + }; + self.symlink_dependencies(entry_id, symlinker::Strategy::ReplaceDirectory, Some(patch))?; + Ok(()) + } + pub(crate) fn link_dependency_bins(&self, parent_entry_id: StoreEntryId) -> crate::Result<()> { let lockfile = self.lockfile(); let store = self.store; diff --git a/src/install/isolated_install/Symlinker.rs b/src/install/isolated_install/Symlinker.rs index 52c90735abba..f45f1a3c6847 100644 --- a/src/install/isolated_install/Symlinker.rs +++ b/src/install/isolated_install/Symlinker.rs @@ -54,7 +54,7 @@ impl Symlinker { }, }; } - Strategy::ExpectExisting => { + Strategy::ExpectExisting | Strategy::ReplaceDirectory => { let mut current_link_buf = bun_paths::path_buffer_pool::get(); let current_link_len = match bun_sys::readlink(self.dest.slice_z(), &mut current_link_buf) { @@ -80,7 +80,9 @@ impl Symlinker { // directory, leave it: this is the `bun patch ` // workspace (a detached copy the user is editing // before `--commit`), and `deleteTree` here would - // silently destroy their in-progress edits. If it's + // silently destroy their in-progress edits. After + // `--commit` those edits are in the store, and + // `ReplaceDirectory` puts the link back. If it's // a regular file, replace it. _ => { #[cfg(windows)] @@ -99,10 +101,10 @@ impl Symlinker { } else { false }; - if is_dir { + if is_dir && !matches!(strategy, Strategy::ReplaceDirectory) { return Ok(false); } - let _ = bun_sys::unlink(self.dest.slice_z()); + let _ = Fd::cwd().delete_tree(self.dest.slice_z()); return self.symlink().map(|()| true); } }; @@ -153,4 +155,6 @@ impl Symlinker { pub enum Strategy { ExpectExisting, ExpectMissing, + /// `ExpectExisting`, except that a real directory at `dest` is deleted and replaced by the link. + ReplaceDirectory, } diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 0e61d4526398..60c41696d9a4 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1,7 +1,7 @@ import { $, ShellOutput } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { lstatSync, readFileSync } from "fs"; -import { bunEnv, bunExe, isASAN, tempDir, VerdaccioRegistry } from "harness"; +import { existsSync, lstatSync, readFileSync, symlinkSync } from "fs"; +import { bunEnv, bunExe, isASAN, isWindows, tempDir, VerdaccioRegistry } from "harness"; import { isAbsolute, join, sep } from "path"; const expectNoError = (o: ShellOutput) => expect(o.stderr.toString()).not.toContain("error"); @@ -66,21 +66,35 @@ describe("error messages", () => { }); }); +// CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Concurrent tests that +// install the same tarball spec into one shared cache replace each other's `@T@` folder on Windows. +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 }; +} + +const registry = new VerdaccioRegistry(); + +beforeAll(async () => { + await registry.start(); +}); + +afterAll(() => { + registry.stop(); +}); + // `bun patch` identifies packages by `name@label`, where a tarball package's label is // the spec it was installed from. These labels used to be formatted into 1024 byte // stack buffers (512 bytes in the installer itself), so a long enough spec crashed // every command that formatted it. describe("packages whose label is longer than 1024 bytes", () => { - const registry = new VerdaccioRegistry(); - - beforeAll(async () => { - await registry.start(); - }); - - afterAll(() => { - registry.stop(); - }); - // `x/../` normalizes away, so the tarball still lives at a short path that is valid // on every platform while the recorded spec stays long. const longSpec = (tarball: string) => `./${Buffer.alloc(1050, "x/../").toString()}${tarball}`; @@ -96,20 +110,6 @@ describe("packages whose label is longer than 1024 bytes", () => { return packageDir; } - // CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`. Two of these concurrent - // tests install the same tarball spec; sharing one cache, they replace each other's `@T@` folder on Windows. - 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 install(cwd: string) { const { stderr, exitCode } = await runBun(cwd, "install"); expect(stderr).not.toContain("error:"); @@ -177,6 +177,162 @@ describe("packages whose label is longer than 1024 bytes", () => { }); }); +// With the isolated linker `node_modules/` is a link into `node_modules/.bun`, and the +// dependencies of are siblings of its store entry. `bun patch ` swaps the link for a +// detached copy of the package, and a copy in a real directory cannot reach those siblings. +describe("bun patch --commit with the isolated linker", () => { + const isLink = (path: string) => lstatSync(path).isSymbolicLink(); + const NOT_PREPARED = "is not a folder that bun patch prepared."; + + async function install(globalStore: boolean, files: Record) { + const { packageDir } = await registry.createTestDir({ + bunfigOpts: { linker: "isolated", globalStore }, + files: files as any, + }); + const { stderr, exitCode } = await runBun(packageDir, "install"); + expect(stderr).not.toContain("error:"); + expect(exitCode).toBe(0); + return packageDir; + } + + // Returns the detached copy that `bun patch ` puts in place of the link at `folder`. + async function patch(packageDir: string, arg: string, folder: string) { + const copy = join(packageDir, folder); + expect(isLink(copy)).toBe(true); + const { stdout, stderr, exitCode } = await runBun(packageDir, "patch", arg); + expect(stderr).not.toContain("error:"); + expect(stdout).toContain(`edit the following folder:\n\n ${folder}\n`); + expect(exitCode).toBe(0); + expect(isLink(copy)).toBe(false); + return copy; + } + + // index.js of has-bin-entries requires each dependency of the package, and "no-deps" is one. + const addPatchedExport = async (copy: string) => + Bun.write( + join(copy, "index.js"), + (await Bun.file(join(copy, "index.js")).text()) + "\nmodule.exports.patched = true;\n", + ); + const load = (cwd: string) => + runBun( + cwd, + "-e", + `const pkg = require("has-bin-entries"); console.log(pkg.version, pkg.patched, pkg.dependencies["no-deps"].version);`, + ); + + const rootOnly = { + "package.json": JSON.stringify({ + name: "foo", + dependencies: { "has-bin-entries": "1.0.0", "a-dep": "1.0.1" }, + }), + }; + + test.concurrent.each([ + { globalStore: false, commitArg: "has-bin-entries" }, + { globalStore: true, commitArg: "node_modules/has-bin-entries" }, + ])( + "links node_modules/ into node_modules/.bun again (globalStore: $globalStore, --commit $commitArg)", + async ({ globalStore, commitArg }) => { + const packageDir = await install(globalStore, rootOnly); + const committed = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + const uncommitted = await patch(packageDir, "a-dep", "node_modules/a-dep"); + await addPatchedExport(committed); + await Bun.write(join(uncommitted, "edit.js"), "module.exports = 'in progress';\n"); + + const commit = await runBun(packageDir, "patch", "--commit", commitArg); + expect(commit.stderr).not.toContain("error:"); + expect(commit.exitCode).toBe(0); + + // The edits to a-dep are not committed, so its copy stays. + expect({ + committed: isLink(committed), + uncommitted: isLink(uncommitted), + edit: await Bun.file(join(uncommitted, "edit.js")).text(), + }).toEqual({ + committed: true, + uncommitted: false, + edit: "module.exports = 'in progress';\n", + }); + + const loaded = await load(packageDir); + expect(loaded.stderr).toBe(""); + expect(loaded.stdout).toBe("1.0.0 true 1.0.0\n"); + expect(loaded.exitCode).toBe(0); + + // bin-with-require.js requires "no-deps" as well. + const bin = await runBun(packageDir, "run", "has-bin-entries-with-require"); + expect(bin.stdout).toBe("no-deps\n1.0.0\n"); + expect(bin.exitCode).toBe(0); + + // The copy is gone. A second --commit must not write a patch of the link. + const patchFile = join(packageDir, "patches", "has-bin-entries@1.0.0.patch"); + const patchText = await Bun.file(patchFile).text(); + const again = await runBun(packageDir, "patch", "--commit", commitArg); + expect(again.stderr).toContain(NOT_PREPARED); + expect(again.exitCode).toBe(1); + expect(await Bun.file(patchFile).text()).toBe(patchText); + }, + ); + + test.concurrent("refuses to commit a link that bun patch did not replace", async () => { + const packageDir = await install(false, rootOnly); + const packageJson = await Bun.file(join(packageDir, "package.json")).text(); + + for (const arg of ["has-bin-entries", "node_modules/has-bin-entries"]) { + const commit = await runBun(packageDir, "patch", "--commit", arg); + expect(commit.stderr).toContain(`${NOT_PREPARED} Run \`bun patch ${arg}\` first.`); + expect(commit.exitCode).toBe(1); + } + + expect({ + patches: existsSync(join(packageDir, "patches")), + packageJson: await Bun.file(join(packageDir, "package.json")).text(), + }).toEqual({ patches: false, packageJson }); + }); + + test.concurrent("links the dependency of a workspace package again", async () => { + const packageDir = await install(false, { + "package.json": JSON.stringify({ + name: "foo", + workspaces: ["packages/*"], + dependencies: { "has-bin-entries": "2.0.0", w: "workspace:*" }, + }), + packages: { + w: { + "package.json": JSON.stringify({ name: "w", version: "1.0.0", dependencies: { "has-bin-entries": "1.0.0" } }), + }, + }, + }); + // `node_modules/w` is a link to packages/w, so this is packages/w/node_modules/has-bin-entries. + const folder = "node_modules/w/node_modules/has-bin-entries"; + await addPatchedExport(await patch(packageDir, "has-bin-entries@1.0.0", folder)); + + const commit = await runBun(packageDir, "patch", "--commit", folder); + expect(commit.stderr).not.toContain("error:"); + expect(commit.exitCode).toBe(0); + + expect(isLink(join(packageDir, "packages", "w", "node_modules", "has-bin-entries"))).toBe(true); + const loaded = await load(join(packageDir, "packages", "w")); + expect(loaded.stderr).toBe(""); + expect(loaded.stdout).toBe("1.0.0 true 1.0.0\n"); + expect(loaded.exitCode).toBe(0); + }); + + // A patch that adds a symlink does not apply (`bad_file_mode`). Windows is skipped: git records + // a symlink as mode 120000 only with `core.symlinks`, which is off there by default. + test.skipIf(isWindows).concurrent("keeps the edited copy when the patch does not apply", async () => { + const packageDir = await install(false, rootOnly); + const copy = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + symlinkSync("index.js", join(copy, "link.js")); + + const commit = await runBun(packageDir, "patch", "--commit", "has-bin-entries"); + expect(commit.stderr).toContain("failed to patch package: has-bin-entries@1.0.0"); + expect(commit.exitCode).toBe(1); + + expect({ copy: isLink(copy), edit: isLink(join(copy, "link.js")) }).toEqual({ copy: false, edit: true }); + }); +}); + describe("bun patch ", async () => { describe("workspace interactions", async () => { /** From 4a9c092298af1fb61a25bb2110acb6e12993f292 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:53:49 +0000 Subject: [PATCH 2/7] bun patch --commit: relink only the folder that was diffed, after the install The link goes back for the folder that `--commit` diffed, found by its real path, and not for every copy of the same name@version. A second copy at another link keeps its edits. The relink moves from the task of the root or workspace entry to the main thread, after every task is done. An entry in a dependency cycle does not wait for its dependencies, so the tag of the new patch could be missing when the task looked for it. The copy moves aside before the link is written and is deleted after. A delete that stops part-way no longer leaves a partial copy where the next `--commit` would diff it. `--commit` that finds no changes also puts the link back: the copy equals the package. The recovery hint of the new refusal moves to a `note:` line. --- src/install/PackageManager.rs | 4 +- src/install/PackageManager/patchPackage.rs | 45 ++++++++++++- src/install/isolated_install.rs | 2 + src/install/isolated_install/Installer.rs | 73 +++++++++++++--------- src/install/isolated_install/Symlinker.rs | 33 +++++++++- test/cli/install/bun-patch.test.ts | 64 ++++++++++++++++++- 6 files changed, 179 insertions(+), 42 deletions(-) diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index d334cbec37ff..713f8f99d740 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -461,8 +461,8 @@ pub struct PackageManager { pub(crate) patched_dependencies_to_remove: ArrayHashMap, - // bun patch --commit: the package whose patch was just written; the isolated linker puts its links back. - pub(crate) committed_patch: Option, + // bun patch --commit: the folder that was diffed; the isolated linker puts its link back. + pub(crate) committed_patch: Option, pub(crate) active_lifecycle_scripts: crate::lifecycle_script_runner::List<'static>, pub(crate) last_reported_slow_lifecycle_script_at: u64, diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index f4e881732aad..ac799d531b9e 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -53,6 +53,40 @@ pub struct PatchCommitResult { pub(crate) not_in_workspace_root: bool, } +/// The folder that `bun patch --commit` diffed. With the isolated linker that folder took the +/// place of a link, and the install of the commit puts the link back. +pub struct CommittedPatch { + real_path: Box<[u8]>, + /// False when the diff was empty: the folder equals the package, and no patch is recorded. + pub(crate) has_changes: bool, +} + +impl CommittedPatch { + fn new(folder: &[u8]) -> Option { + let mut buf = bun_paths::path_buffer_pool::get(); + Some(CommittedPatch { + real_path: Box::from(real_path_of_folder(folder, &mut buf)?), + has_changes: true, + }) + } + + pub(crate) fn is_folder(&self, path: &[u8]) -> bool { + // The name rules out most paths without a syscall. + if bun_paths::basename(path) != bun_paths::basename(&self.real_path) { + return false; + } + let mut buf = bun_paths::path_buffer_pool::get(); + real_path_of_folder(path, &mut buf).is_some_and(|real_path| real_path == &*self.real_path) + } +} + +fn real_path_of_folder<'a>(folder: &[u8], buf: &'a mut PathBuffer) -> Option<&'a [u8]> { + let dir = Dir::cwd() + .open_dir(folder, sys::OpenDirOptions::default()) + .ok()?; + dir.get_fd_path(buf).ok().map(|real_path| &*real_path) +} + /// - Arg is the dir containing the package with changes OR name and version /// - Get the patch file contents by running git diff on the temp dir and the original package dir /// - Write the patch file to $PATCHES_DIR/$PKG_NAME_AND_VERSION.patch @@ -271,12 +305,16 @@ pub fn do_patch_commit( // link itself (`new file mode 120000`), and no install can apply that patch. if !is_real_dir_not_symlink(&changes_dir) { bun_core::pretty_errorln!( - "error: {} is not a folder that bun patch prepared. Run `bun patch {}` first.", + "error: {} is not a folder that bun patch prepared", bstr::BStr::new(&changes_dir), + ); + bun_core::note!( + "Run `bun patch {}` first", bstr::BStr::new(manager.options.positionals[1]), ); Global::crash(); } + manager.committed_patch = CommittedPatch::new(&changes_dir); // `compute_cache_dir_and_subpath` resolves `pkg.resolution`'s strings against `manager.lockfile`. manager.lockfile = lockfile; @@ -548,6 +586,9 @@ pub fn do_patch_commit( ); Output::flush(); drop(contents); + if let Some(committed) = &mut manager.committed_patch { + committed.has_changes = false; + } return Ok(None); } @@ -611,8 +652,6 @@ pub fn do_patch_commit( b".bun-patch-tag", ])); - manager.committed_patch = Some(string_hash(&patch_key)); - Ok(Some(PatchCommitResult { patch_key: patch_key.into_boxed_slice(), patchfile_path, diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 65128085d4be..128ed74a15df 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -2619,6 +2619,8 @@ pub(crate) fn install_isolated_packages( } } + installer.relink_committed_patch(); + if installer.manager().options.log_level.show_progress() { progress.root.end(); *progress = Progress::default(); diff --git a/src/install/isolated_install/Installer.rs b/src/install/isolated_install/Installer.rs index b9696c224004..0346e2165188 100644 --- a/src/install/isolated_install/Installer.rs +++ b/src/install/isolated_install/Installer.rs @@ -21,9 +21,8 @@ use crate::postinstall_optimizer; use crate::postinstall_optimizer::PostinstallOptimizer; use crate::resolution; use crate::{ - self as install, DependencyID, Lockfile, PackageID, PackageManager, PackageNameAndVersionHash, - PackageNameHash, Resolution, TaskCallbackContext, TruncatedPackageNameHash, bin, - invalid_dependency_id, + self as install, DependencyID, Lockfile, PackageID, PackageManager, PackageNameHash, + Resolution, TaskCallbackContext, TruncatedPackageNameHash, bin, invalid_dependency_id, }; // Bring `items_()` column accessors into scope for // `MultiArrayList` / `Slice`. @@ -38,6 +37,7 @@ use crate::bun_fs; use crate::lockfile_real::package::PackageColumns as _; use crate::package_manager_real::directories; use crate::package_manager_real::package_manager_options::Do; +use crate::package_manager_real::patch_package::CommittedPatch; /// The enum lives at module level in `crate::resolution`. type ResolutionTag = resolution::Tag; @@ -1538,13 +1538,6 @@ impl Task { Step::SymlinkDependencyBinaries => { let current_step = Step::SymlinkDependencyBinaries; - if matches!(pkg_res.tag, ResolutionTag::Root | ResolutionTag::Workspace) { - if let sys::Result::Err(err) = - installer.relink_committed_patch(self.entry_id) - { - return Ok(Yield::failure(TaskError::SymlinkDependencies(err))); - } - } if let Err(err) = installer.link_dependency_bins(self.entry_id) { return Ok(Yield::failure(TaskError::Binaries(err))); } @@ -2244,12 +2237,12 @@ impl<'a> Installer<'a> { } /// Ok(true) when at least one dependency link of the entry was written. - /// `only_patch` limits the links to that patched package, once the store holds it patched. + /// `only_committed` limits the links to the folder of that commit. fn symlink_dependencies( &self, entry_id: StoreEntryId, strategy: symlinker::Strategy, - only_patch: Option, + only_committed: Option<&CommittedPatch>, ) -> sys::Result { let lockfile = self.lockfile(); let string_buf = lockfile.buffers.string_bytes.as_slice(); @@ -2290,8 +2283,10 @@ impl<'a> Installer<'a> { self.append_store_path(&mut dep_store_path, dep.entry_id); } - if let Some(patch) = only_patch { - if !self.store_holds_patch(dep.entry_id, patch, &mut dep_store_path) { + if let Some(committed) = only_committed { + if !committed.is_folder(dest.slice()) + || !self.store_holds_commit(committed, dep.entry_id, &mut dep_store_path) + { continue; } } @@ -2315,31 +2310,31 @@ impl<'a> Installer<'a> { Ok(changed) } - /// True when `entry_id` is the package that `patch` applies to, and `store_path` (the - /// package directory of the entry) has the tag file of that patch. - fn store_holds_patch( + /// True when `store_path`, the package directory of `entry_id`, has what `committed` diffed: + /// the tag file of the new patch, or the package as it is when the diff was empty. + fn store_holds_commit( &self, + committed: &CommittedPatch, entry_id: StoreEntryId, - patch: PackageNameAndVersionHash, store_path: &mut AutoAbsPath, ) -> bool { + if !committed.has_changes { + return sys::directory_exists_at(Fd::cwd(), store_path.slice_z()).unwrap_or(false); + } + let node_id = self.store.entries.items_node_id()[entry_id.get() as usize]; let pkg_id = self.store.nodes.items_pkg_id()[node_id.get() as usize]; let pkgs = self.lockfile().packages.slice(); - - let Ok(PatchInfo::Patch(info)) = self.package_patch_info( + let Ok(PatchInfo::Patch(patch)) = self.package_patch_info( pkgs.items_name()[pkg_id as usize], pkgs.items_name_hash()[pkg_id as usize], &pkgs.items_resolution()[pkg_id as usize], ) else { return false; }; - if info.name_and_version_hash != patch { - return false; - } let mut tag_buf: install::BuntagHashBuf = Default::default(); - let tag = install::buntaghashbuf_make(&mut tag_buf, info.contents_hash); + let tag = install::buntaghashbuf_make(&mut tag_buf, patch.contents_hash); let store_path_len = store_path.len(); store_path.append(&*tag).assume_ok(); let has_tag = sys::exists_z(store_path.slice_z()); @@ -2349,14 +2344,30 @@ impl<'a> Installer<'a> { /// `bun patch` swaps the link of a root or workspace dependency for a detached copy of the /// package, and `Strategy::ExpectExisting` keeps a real directory. `bun patch --commit` puts - /// the link back here, after the dependencies of the entry are installed: a patch that did - /// not apply leaves no tag in the store, and then the copy with the edits stays. - fn relink_committed_patch(&self, entry_id: StoreEntryId) -> sys::Result<()> { - let Some(patch) = self.manager().committed_patch else { - return Ok(()); + /// the link back here, on the main thread after every task is done: a patch that did not + /// apply leaves no tag in the store, and then the copy with the edits stays. + pub(crate) fn relink_committed_patch(&mut self) { + let Some(committed) = self.manager().committed_patch.as_ref() else { + return; }; - self.symlink_dependencies(entry_id, symlinker::Strategy::ReplaceDirectory, Some(patch))?; - Ok(()) + let pkg_resolutions = self.lockfile().packages.items_resolution(); + let node_pkg_ids = self.store.nodes.items_pkg_id(); + + for (entry_id, node_id) in self.store.entries.items_node_id().iter().enumerate() { + let pkg_res = &pkg_resolutions[node_pkg_ids[node_id.get() as usize] as usize]; + if !matches!(pkg_res.tag, ResolutionTag::Root | ResolutionTag::Workspace) { + continue; + } + if let sys::Result::Err(err) = self.symlink_dependencies( + StoreEntryId::from(u32::try_from(entry_id).expect("int cast")), + symlinker::Strategy::ReplaceDirectory, + Some(committed), + ) { + Output::err(err, "failed to link the patched package again", ()); + Output::flush(); + self.summary.fail += 1; + } + } } pub(crate) fn link_dependency_bins(&self, parent_entry_id: StoreEntryId) -> crate::Result<()> { diff --git a/src/install/isolated_install/Symlinker.rs b/src/install/isolated_install/Symlinker.rs index f45f1a3c6847..031030cfcf26 100644 --- a/src/install/isolated_install/Symlinker.rs +++ b/src/install/isolated_install/Symlinker.rs @@ -1,5 +1,6 @@ use bun_core::strings; use bun_paths; +use bun_paths::path_options::AssumeOk as _; use bun_sys::{self, Errno, Fd, FdDirExt, FdExt}; pub(crate) struct Symlinker { @@ -31,6 +32,29 @@ impl Symlinker { } } + /// The directory moves aside before the link is written, and is deleted after. `dest` holds + /// all of the directory or the link at every point, so a failure leaves no partly deleted + /// copy for the next `bun patch --commit` to diff. + fn replace_directory(&mut self) -> bun_sys::Result<()> { + let mut aside = + bun_paths::Path::::from(self.dest.dirname().unwrap_or(b".")).assume_ok(); + aside + .append_fmt(format_args!( + ".{}.old-{:x}", + bstr::BStr::new(self.dest.basename()), + bun_core::fast_random(), + )) + .assume_ok(); + + bun_sys::renameat(Fd::cwd(), self.dest.slice_z(), Fd::cwd(), aside.slice_z())?; + if let Err(err) = self.symlink() { + let _ = bun_sys::renameat(Fd::cwd(), aside.slice_z(), Fd::cwd(), self.dest.slice_z()); + return Err(err); + } + let _ = Fd::cwd().delete_tree(aside.slice_z()); + Ok(()) + } + // Ok(true) when a link was written. pub(crate) fn ensure_symlink(&mut self, strategy: Strategy) -> bun_sys::Result { match strategy { @@ -101,10 +125,13 @@ impl Symlinker { } else { false }; - if is_dir && !matches!(strategy, Strategy::ReplaceDirectory) { - return Ok(false); + if is_dir { + if !matches!(strategy, Strategy::ReplaceDirectory) { + return Ok(false); + } + return self.replace_directory().map(|()| true); } - let _ = Fd::cwd().delete_tree(self.dest.slice_z()); + let _ = bun_sys::unlink(self.dest.slice_z()); return self.symlink().map(|()| true); } }; diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 60c41696d9a4..8465484bdc5d 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -1,6 +1,6 @@ import { $, ShellOutput } from "bun"; import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { existsSync, lstatSync, readFileSync, symlinkSync } from "fs"; +import { existsSync, lstatSync, readdirSync, readFileSync, symlinkSync } from "fs"; import { bunEnv, bunExe, isASAN, isWindows, tempDir, VerdaccioRegistry } from "harness"; import { isAbsolute, join, sep } from "path"; @@ -182,7 +182,7 @@ describe("packages whose label is longer than 1024 bytes", () => { // detached copy of the package, and a copy in a real directory cannot reach those siblings. describe("bun patch --commit with the isolated linker", () => { const isLink = (path: string) => lstatSync(path).isSymbolicLink(); - const NOT_PREPARED = "is not a folder that bun patch prepared."; + const NOT_PREPARED = "is not a folder that bun patch prepared\n"; async function install(globalStore: boolean, files: Record) { const { packageDir } = await registry.createTestDir({ @@ -248,10 +248,12 @@ describe("bun patch --commit with the isolated linker", () => { committed: isLink(committed), uncommitted: isLink(uncommitted), edit: await Bun.file(join(uncommitted, "edit.js")).text(), + nodeModules: readdirSync(join(packageDir, "node_modules")).sort(), }).toEqual({ committed: true, uncommitted: false, edit: "module.exports = 'in progress';\n", + nodeModules: [".bin", ".bun", "a-dep", "has-bin-entries"], }); const loaded = await load(packageDir); @@ -280,7 +282,7 @@ describe("bun patch --commit with the isolated linker", () => { for (const arg of ["has-bin-entries", "node_modules/has-bin-entries"]) { const commit = await runBun(packageDir, "patch", "--commit", arg); - expect(commit.stderr).toContain(`${NOT_PREPARED} Run \`bun patch ${arg}\` first.`); + expect(commit.stderr).toContain(`${NOT_PREPARED}note: Run \`bun patch ${arg}\` first\n`); expect(commit.exitCode).toBe(1); } @@ -290,6 +292,62 @@ describe("bun patch --commit with the isolated linker", () => { }).toEqual({ patches: false, packageJson }); }); + test.concurrent("links the folder again when --commit finds no changes", async () => { + const packageDir = await install(false, rootOnly); + const packageJson = await Bun.file(join(packageDir, "package.json")).json(); + const copy = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + + const commit = await runBun(packageDir, "patch", "--commit", "has-bin-entries"); + expect(commit.stderr).not.toContain("error:"); + expect(commit.stdout).toContain("No changes detected"); + expect(commit.exitCode).toBe(0); + + expect({ + copy: isLink(copy), + patches: existsSync(join(packageDir, "patches")), + packageJson: await Bun.file(join(packageDir, "package.json")).json(), + }).toEqual({ copy: true, patches: false, packageJson }); + const loaded = await load(packageDir); + expect(loaded.stderr).toBe(""); + expect(loaded.stdout).toBe("1.0.0 undefined 1.0.0\n"); + expect(loaded.exitCode).toBe(0); + }); + + // One patch exists per name@version, but the edits in the second copy were never diffed. + test.concurrent("keeps a second copy of the same package that was not committed", async () => { + const packageDir = await install(false, { + "package.json": JSON.stringify({ + name: "foo", + workspaces: ["packages/*"], + dependencies: { "has-bin-entries": "1.0.0" }, + }), + packages: { + w: { + "package.json": JSON.stringify({ name: "w", version: "1.0.0", dependencies: { "has-bin-entries": "1.0.0" } }), + }, + }, + }); + const committed = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + const other = "packages/w/node_modules/has-bin-entries"; + const uncommitted = await patch(packageDir, other, other); + await addPatchedExport(committed); + await Bun.write(join(uncommitted, "edit.js"), "module.exports = 'in progress';\n"); + + const commit = await runBun(packageDir, "patch", "--commit", "has-bin-entries"); + expect(commit.stderr).not.toContain("error:"); + expect(commit.exitCode).toBe(0); + + expect({ + committed: isLink(committed), + uncommitted: isLink(uncommitted), + edit: await Bun.file(join(uncommitted, "edit.js")).text(), + }).toEqual({ + committed: true, + uncommitted: false, + edit: "module.exports = 'in progress';\n", + }); + }); + test.concurrent("links the dependency of a workspace package again", async () => { const packageDir = await install(false, { "package.json": JSON.stringify({ From d9f1fea37121ee341e0ee90bb49005a8965e69d9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 20:57:57 +0000 Subject: [PATCH 3/7] Shorten the comments in the patch relink code to one line each --- src/install/PackageManager/patchPackage.rs | 6 ++---- src/install/isolated_install/Installer.rs | 8 ++------ src/install/isolated_install/Symlinker.rs | 10 +++------- 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index ac799d531b9e..697354e1d986 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -53,8 +53,7 @@ pub struct PatchCommitResult { pub(crate) not_in_workspace_root: bool, } -/// The folder that `bun patch --commit` diffed. With the isolated linker that folder took the -/// place of a link, and the install of the commit puts the link back. +/// The folder that `bun patch --commit` diffed. The isolated linker puts its link back. pub struct CommittedPatch { real_path: Box<[u8]>, /// False when the diff was empty: the folder equals the package, and no patch is recorded. @@ -301,8 +300,7 @@ pub fn do_patch_commit( } }; - // A link into the isolated store is not a copy from `bun patch`. `git diff` would record the - // link itself (`new file mode 120000`), and no install can apply that patch. + // `git diff` records a link as `new file mode 120000`, and no install can apply that. if !is_real_dir_not_symlink(&changes_dir) { bun_core::pretty_errorln!( "error: {} is not a folder that bun patch prepared", diff --git a/src/install/isolated_install/Installer.rs b/src/install/isolated_install/Installer.rs index 0346e2165188..54ec807ec2a5 100644 --- a/src/install/isolated_install/Installer.rs +++ b/src/install/isolated_install/Installer.rs @@ -2310,8 +2310,7 @@ impl<'a> Installer<'a> { Ok(changed) } - /// True when `store_path`, the package directory of `entry_id`, has what `committed` diffed: - /// the tag file of the new patch, or the package as it is when the diff was empty. + /// `store_path` has the tag file of the committed patch, or exists when the diff was empty. fn store_holds_commit( &self, committed: &CommittedPatch, @@ -2342,10 +2341,7 @@ impl<'a> Installer<'a> { has_tag } - /// `bun patch` swaps the link of a root or workspace dependency for a detached copy of the - /// package, and `Strategy::ExpectExisting` keeps a real directory. `bun patch --commit` puts - /// the link back here, on the main thread after every task is done: a patch that did not - /// apply leaves no tag in the store, and then the copy with the edits stays. + /// After every task: a patch that did not apply leaves no tag, and then the copy stays. pub(crate) fn relink_committed_patch(&mut self) { let Some(committed) = self.manager().committed_patch.as_ref() else { return; diff --git a/src/install/isolated_install/Symlinker.rs b/src/install/isolated_install/Symlinker.rs index 031030cfcf26..0dda5b3026bf 100644 --- a/src/install/isolated_install/Symlinker.rs +++ b/src/install/isolated_install/Symlinker.rs @@ -32,9 +32,7 @@ impl Symlinker { } } - /// The directory moves aside before the link is written, and is deleted after. `dest` holds - /// all of the directory or the link at every point, so a failure leaves no partly deleted - /// copy for the next `bun patch --commit` to diff. + /// The directory moves aside first, so a failure never leaves a partly deleted copy at `dest`. fn replace_directory(&mut self) -> bun_sys::Result<()> { let mut aside = bun_paths::Path::::from(self.dest.dirname().unwrap_or(b".")).assume_ok(); @@ -104,9 +102,7 @@ impl Symlinker { // directory, leave it: this is the `bun patch ` // workspace (a detached copy the user is editing // before `--commit`), and `deleteTree` here would - // silently destroy their in-progress edits. After - // `--commit` those edits are in the store, and - // `ReplaceDirectory` puts the link back. If it's + // silently destroy their in-progress edits. If it's // a regular file, replace it. _ => { #[cfg(windows)] @@ -182,6 +178,6 @@ impl Symlinker { pub enum Strategy { ExpectExisting, ExpectMissing, - /// `ExpectExisting`, except that a real directory at `dest` is deleted and replaced by the link. + /// `ExpectExisting`, but the link replaces a real directory that `bun patch --commit` diffed. ReplaceDirectory, } From 2f4e10d9fb048d97681d2f31119980f260d328f2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:43:16 +0000 Subject: [PATCH 4/7] bun patch --commit: relink before the scripts of the workspace entry run The postinstall script of a workspace package runs in every install. When it loads the committed package, the link has to be back before the script runs, or the script fails and the install exits before the relink after the tasks. The root or workspace entry now relinks in its task, once its dependencies are installed. The relink after the tasks stays for an entry in a dependency cycle, which does not wait. --- src/install/isolated_install.rs | 2 +- src/install/isolated_install/Installer.rs | 33 +++++++++++++++++------ test/cli/install/bun-patch.test.ts | 14 ++++++++-- 3 files changed, 38 insertions(+), 11 deletions(-) diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 128ed74a15df..c229674153f7 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -2619,7 +2619,7 @@ pub(crate) fn install_isolated_packages( } } - installer.relink_committed_patch(); + installer.relink_committed_patch_after_tasks(); if installer.manager().options.log_level.show_progress() { progress.root.end(); diff --git a/src/install/isolated_install/Installer.rs b/src/install/isolated_install/Installer.rs index 54ec807ec2a5..5ed07141cbd2 100644 --- a/src/install/isolated_install/Installer.rs +++ b/src/install/isolated_install/Installer.rs @@ -1538,6 +1538,13 @@ impl Task { Step::SymlinkDependencyBinaries => { let current_step = Step::SymlinkDependencyBinaries; + if matches!(pkg_res.tag, ResolutionTag::Root | ResolutionTag::Workspace) { + if let sys::Result::Err(err) = + installer.relink_committed_patch(self.entry_id) + { + return Ok(Yield::failure(TaskError::SymlinkDependencies(err))); + } + } if let Err(err) = installer.link_dependency_bins(self.entry_id) { return Ok(Yield::failure(TaskError::Binaries(err))); } @@ -2341,11 +2348,24 @@ impl<'a> Installer<'a> { has_tag } - /// After every task: a patch that did not apply leaves no tag, and then the copy stays. - pub(crate) fn relink_committed_patch(&mut self) { + /// For a root or workspace entry whose dependencies are installed, before its scripts run. + fn relink_committed_patch(&self, entry_id: StoreEntryId) -> sys::Result<()> { let Some(committed) = self.manager().committed_patch.as_ref() else { - return; + return Ok(()); }; + self.symlink_dependencies( + entry_id, + symlinker::Strategy::ReplaceDirectory, + Some(committed), + )?; + Ok(()) + } + + /// An entry in a dependency cycle does not wait for its dependencies, so its task can be early. + pub(crate) fn relink_committed_patch_after_tasks(&mut self) { + if self.manager().committed_patch.is_none() { + return; + } let pkg_resolutions = self.lockfile().packages.items_resolution(); let node_pkg_ids = self.store.nodes.items_pkg_id(); @@ -2354,11 +2374,8 @@ impl<'a> Installer<'a> { if !matches!(pkg_res.tag, ResolutionTag::Root | ResolutionTag::Workspace) { continue; } - if let sys::Result::Err(err) = self.symlink_dependencies( - StoreEntryId::from(u32::try_from(entry_id).expect("int cast")), - symlinker::Strategy::ReplaceDirectory, - Some(committed), - ) { + let entry_id = StoreEntryId::from(u32::try_from(entry_id).expect("int cast")); + if let sys::Result::Err(err) = self.relink_committed_patch(entry_id) { Output::err(err, "failed to link the patched package again", ()); Output::flush(); self.summary.fail += 1; diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 8465484bdc5d..a374739d6cb5 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -348,7 +348,8 @@ describe("bun patch --commit with the isolated linker", () => { }); }); - test.concurrent("links the dependency of a workspace package again", async () => { + // The postinstall script of a workspace package runs in every install, this one included. + test.concurrent("links the dependency of a workspace package again, before its scripts run", async () => { const packageDir = await install(false, { "package.json": JSON.stringify({ name: "foo", @@ -357,10 +358,18 @@ describe("bun patch --commit with the isolated linker", () => { }), packages: { w: { - "package.json": JSON.stringify({ name: "w", version: "1.0.0", dependencies: { "has-bin-entries": "1.0.0" } }), + "package.json": JSON.stringify({ + name: "w", + version: "1.0.0", + dependencies: { "has-bin-entries": "1.0.0" }, + scripts: { postinstall: `${bunExe()} postinstall.js` }, + }), + "postinstall.js": `require("fs").writeFileSync("postinstall.txt", String(require("has-bin-entries").patched));`, }, }, }); + const postinstall = join(packageDir, "packages", "w", "postinstall.txt"); + expect(await Bun.file(postinstall).text()).toBe("undefined"); // `node_modules/w` is a link to packages/w, so this is packages/w/node_modules/has-bin-entries. const folder = "node_modules/w/node_modules/has-bin-entries"; await addPatchedExport(await patch(packageDir, "has-bin-entries@1.0.0", folder)); @@ -370,6 +379,7 @@ describe("bun patch --commit with the isolated linker", () => { expect(commit.exitCode).toBe(0); expect(isLink(join(packageDir, "packages", "w", "node_modules", "has-bin-entries"))).toBe(true); + expect(await Bun.file(postinstall).text()).toBe("true"); const loaded = await load(join(packageDir, "packages", "w")); expect(loaded.stderr).toBe(""); expect(loaded.stdout).toBe("1.0.0 true 1.0.0\n"); From d4ed5d9cd3a9a992bfed5fe072714be3b97496de Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:01:27 +0000 Subject: [PATCH 5/7] bun patch --commit: keep the copy when the diff has binary files, report failed steps git prints `Binary files a/x and b/x differ` where a text diff cannot hold a change, and the patch parser drops that file. The folder then has edits that the patch lacks, so `--commit` warns and the isolated linker leaves the folder as it is. When the link cannot be written and the copy cannot move back either, the error of the move back is returned. It names the path of the copy. A folder whose real path cannot be read now fails the commit with the error, and no longer skips the relink in silence. The two parameter rows of the first test are a describe.each block. --- src/install/PackageManager/patchPackage.rs | 37 ++++++++++++++++------ src/install/isolated_install/Symlinker.rs | 3 +- test/cli/install/bun-patch.test.ts | 25 +++++++++++---- 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 697354e1d986..1aafb488d0ad 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -61,9 +61,9 @@ pub struct CommittedPatch { } impl CommittedPatch { - fn new(folder: &[u8]) -> Option { + fn new(folder: &[u8]) -> sys::Result { let mut buf = bun_paths::path_buffer_pool::get(); - Some(CommittedPatch { + Ok(CommittedPatch { real_path: Box::from(real_path_of_folder(folder, &mut buf)?), has_changes: true, }) @@ -75,15 +75,13 @@ impl CommittedPatch { return false; } let mut buf = bun_paths::path_buffer_pool::get(); - real_path_of_folder(path, &mut buf).is_some_and(|real_path| real_path == &*self.real_path) + real_path_of_folder(path, &mut buf).is_ok_and(|real_path| real_path == &*self.real_path) } } -fn real_path_of_folder<'a>(folder: &[u8], buf: &'a mut PathBuffer) -> Option<&'a [u8]> { - let dir = Dir::cwd() - .open_dir(folder, sys::OpenDirOptions::default()) - .ok()?; - dir.get_fd_path(buf).ok().map(|real_path| &*real_path) +fn real_path_of_folder<'a>(folder: &[u8], buf: &'a mut PathBuffer) -> sys::Result<&'a [u8]> { + let dir = Dir::cwd().open_dir(folder, sys::OpenDirOptions::default())?; + dir.get_fd_path(buf).map(|real_path| &*real_path) } /// - Arg is the dir containing the package with changes OR name and version @@ -312,7 +310,17 @@ pub fn do_patch_commit( ); Global::crash(); } - manager.committed_patch = CommittedPatch::new(&changes_dir); + manager.committed_patch = match CommittedPatch::new(&changes_dir) { + Ok(committed) => Some(committed), + Err(e) => { + Output::err( + e, + "failed to open directory {s}", + (bstr::BStr::new(&changes_dir),), + ); + Global::crash(); + } + }; // `compute_cache_dir_and_subpath` resolves `pkg.resolution`'s strings against `manager.lockfile`. manager.lockfile = lockfile; @@ -590,6 +598,17 @@ pub fn do_patch_commit( return Ok(None); } + // The patch parser drops such a file, so the folder has edits that the patch lacks. + if strings::split(&contents, b"\n") + .any(|line| line.starts_with(b"Binary files ") && line.ends_with(b" differ")) + { + bun_core::warn!( + "git cannot diff binary files as text. The patch does not include the changes to them in {}", + bstr::BStr::new(new_folder), + ); + manager.committed_patch = None; + } + break 'brk contents; }; diff --git a/src/install/isolated_install/Symlinker.rs b/src/install/isolated_install/Symlinker.rs index 0dda5b3026bf..6fc39d626fff 100644 --- a/src/install/isolated_install/Symlinker.rs +++ b/src/install/isolated_install/Symlinker.rs @@ -46,7 +46,8 @@ impl Symlinker { bun_sys::renameat(Fd::cwd(), self.dest.slice_z(), Fd::cwd(), aside.slice_z())?; if let Err(err) = self.symlink() { - let _ = bun_sys::renameat(Fd::cwd(), aside.slice_z(), Fd::cwd(), self.dest.slice_z()); + // When the copy cannot move back, this error names where it is. + bun_sys::renameat(Fd::cwd(), aside.slice_z(), Fd::cwd(), self.dest.slice_z())?; return Err(err); } let _ = Fd::cwd().delete_tree(aside.slice_z()); diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index a374739d6cb5..94e409a3ec08 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -227,12 +227,11 @@ describe("bun patch --commit with the isolated linker", () => { }), }; - test.concurrent.each([ + describe.each([ { globalStore: false, commitArg: "has-bin-entries" }, { globalStore: true, commitArg: "node_modules/has-bin-entries" }, - ])( - "links node_modules/ into node_modules/.bun again (globalStore: $globalStore, --commit $commitArg)", - async ({ globalStore, commitArg }) => { + ])("globalStore: $globalStore, --commit $commitArg", ({ globalStore, commitArg }) => { + test.concurrent("links node_modules/ into node_modules/.bun again", async () => { const packageDir = await install(globalStore, rootOnly); const committed = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); const uncommitted = await patch(packageDir, "a-dep", "node_modules/a-dep"); @@ -273,8 +272,8 @@ describe("bun patch --commit with the isolated linker", () => { expect(again.stderr).toContain(NOT_PREPARED); expect(again.exitCode).toBe(1); expect(await Bun.file(patchFile).text()).toBe(patchText); - }, - ); + }); + }); test.concurrent("refuses to commit a link that bun patch did not replace", async () => { const packageDir = await install(false, rootOnly); @@ -386,6 +385,20 @@ describe("bun patch --commit with the isolated linker", () => { expect(loaded.exitCode).toBe(0); }); + // git prints `Binary files ... differ` for it, and the patch parser drops that file. + test.concurrent("keeps the edited copy when the diff has a binary file", async () => { + const packageDir = await install(false, rootOnly); + const copy = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + await addPatchedExport(copy); + await Bun.write(join(copy, "data.bin"), new Uint8Array([0, 1, 2, 0, 255, 254, 0, 10])); + + const commit = await runBun(packageDir, "patch", "--commit", "has-bin-entries"); + expect(commit.stderr).toContain("The patch does not include the changes to them in"); + expect(commit.exitCode).toBe(0); + + expect({ copy: isLink(copy), data: existsSync(join(copy, "data.bin")) }).toEqual({ copy: false, data: true }); + }); + // A patch that adds a symlink does not apply (`bad_file_mode`). Windows is skipped: git records // a symlink as mode 120000 only with `core.symlinks`, which is off there by default. test.skipIf(isWindows).concurrent("keeps the edited copy when the patch does not apply", async () => { From d5dce50d333d0e1a6cd325fe7c8324dcade1c993 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:25:17 +0000 Subject: [PATCH 6/7] bun patch --commit: keep the copy when it has a nested node_modules folder The diff of `--commit` leaves the nested node_modules folder of the copy out. With the isolated linker that folder can hold the `bun patch` copy of a package that the hoisted layout nests under this one, with edits that are not committed. The relink deleted it with the rest of the copy. Such a folder now keeps the copy, as on main. --- src/install/PackageManager/patchPackage.rs | 4 ++++ test/cli/install/bun-patch.test.ts | 28 ++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/install/PackageManager/patchPackage.rs b/src/install/PackageManager/patchPackage.rs index 1aafb488d0ad..1b61888054eb 100644 --- a/src/install/PackageManager/patchPackage.rs +++ b/src/install/PackageManager/patchPackage.rs @@ -408,6 +408,10 @@ pub fn do_patch_commit( break 'has_nested_node_modules true; }; + // The diff leaves that folder out. It can hold the `bun patch` copy of a nested package. + if has_nested_node_modules { + manager.committed_patch = None; + } let patch_tag_tmpname = match bun_paths::fs::FileSystem::tmpname( b"patch_tmp", diff --git a/test/cli/install/bun-patch.test.ts b/test/cli/install/bun-patch.test.ts index 94e409a3ec08..e09ac39d4e13 100644 --- a/test/cli/install/bun-patch.test.ts +++ b/test/cli/install/bun-patch.test.ts @@ -385,6 +385,34 @@ describe("bun patch --commit with the isolated linker", () => { expect(loaded.exitCode).toBe(0); }); + // The hoisted layout nests no-deps@1.0.0 under has-bin-entries, so its copy lands inside the first copy. + test.concurrent("keeps the edited copy when it holds the copy of a nested package", async () => { + const packageDir = await install(false, { + "package.json": JSON.stringify({ + name: "foo", + dependencies: { "has-bin-entries": "1.0.0", "no-deps": "2.0.0" }, + }), + }); + const copy = await patch(packageDir, "has-bin-entries", "node_modules/has-bin-entries"); + await addPatchedExport(copy); + + const nested = "node_modules/has-bin-entries/node_modules/no-deps"; + const prepare = await runBun(packageDir, "patch", "no-deps@1.0.0"); + expect(prepare.stderr).not.toContain("error:"); + expect(prepare.stdout).toContain(`edit the following folder:\n\n ${nested}\n`); + expect(prepare.exitCode).toBe(0); + await Bun.write(join(packageDir, nested, "edit.js"), "module.exports = 'in progress';\n"); + + const commit = await runBun(packageDir, "patch", "--commit", "has-bin-entries"); + expect(commit.stderr).not.toContain("error:"); + expect(commit.exitCode).toBe(0); + + expect({ + copy: isLink(copy), + edit: await Bun.file(join(packageDir, nested, "edit.js")).text(), + }).toEqual({ copy: false, edit: "module.exports = 'in progress';\n" }); + }); + // git prints `Binary files ... differ` for it, and the patch parser drops that file. test.concurrent("keeps the edited copy when the diff has a binary file", async () => { const packageDir = await install(false, rootOnly); From 41e3b97ea4138e3fbb3e32a36e22dc19c2ab356c Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:09:55 +0000 Subject: [PATCH 7/7] ci: retrigger