Skip to content
Closed
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
160 changes: 70 additions & 90 deletions src/install/PackageManager/patchPackage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ pub fn do_patch_commit(
)
.expect("formatting into a Vec is infallible");

let patchfile_contents: Vec<u8> = 'brk: {
let patchfile_contents: Option<Vec<u8>> = 'brk: {
let new_folder = changes_dir;
let mut buf2 = bun_paths::path_buffer_pool::get();
let mut buf3 = bun_paths::path_buffer_pool::get();
Expand Down Expand Up @@ -318,25 +318,62 @@ pub fn do_patch_commit(
}
};

let patch_tag_tmpname = match bun_paths::fs::FileSystem::tmpname(
b"patch_tmp",
&mut buf3[..],
bun_core::fast_random(),
) {
Ok(s) => s,
Err(e) => {
Output::err(e, "failed to make tempdir", ());
Global::crash();
}
};

let mut cwdbuf = bun_paths::path_buffer_pool::get();
let cwd = match sys::getcwd_z(&mut cwdbuf) {
Ok(fd) => fd,
Err(e) => {
bun_core::pretty_error!("<r><red>error<r>: failed to get cwd path {}<r>\n", e);
Global::crash();
}
};
let mut gitbuf = bun_paths::path_buffer_pool::get();
let git = match bun_which::which(
&mut gitbuf,
bun_core::env_var::PATH.get().unwrap_or(b""),
cwd.as_bytes(),
b"git",
) {
Some(g) => g,
None => {
bun_core::pretty_error!(
"<r><red>error<r>: git must be installed to use `bun patch --commit` <r>\n",
);
Global::crash();
}
};

// From here on a failure leaves `'brk`: `Global::crash()` would skip the deferred restore.
let new_folder_handle =
match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
Ok(h) => h,
Err(e) => {
Output::err(
e,
"failed to open directory <b>{s}<r>",
(bstr::BStr::new(new_folder),),
);
Global::crash();
}
};

// If the package has nested a node_modules folder, we don't want this to
// appear in the patch file when we run git diff.
//
// There isn't an option to exclude it with `git diff --no-index`, so we
// will `rename()` it out and back again.
let has_nested_node_modules: bool = 'has_nested_node_modules: {
let new_folder_handle =
match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
Ok(h) => h,
Err(e) => {
Output::err(
e,
"failed to open directory <b>{s}<r>",
(bstr::BStr::new(new_folder),),
);
Global::crash();
}
};

if sys::renameat_concurrently_a(
new_folder_handle.fd,
b"node_modules",
Expand All @@ -354,18 +391,6 @@ pub fn do_patch_commit(
break 'has_nested_node_modules true;
};

let patch_tag_tmpname = match bun_paths::fs::FileSystem::tmpname(
b"patch_tmp",
&mut buf3[..],
bun_core::fast_random(),
) {
Ok(s) => s,
Err(e) => {
Output::err(e, "failed to make tempdir", ());
Global::crash();
}
};

let mut bunpatchtagbuf: BuntagHashBuf = BuntagHashBuf::default();
// If the package was already patched then it might have a ".bun-tag-XXXXXXXX"
// we need to rename this out and back too.
Expand All @@ -379,19 +404,6 @@ pub fn do_patch_commit(
}
break 'has_bun_patch_tag None;
};
let new_folder_handle =
match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
Ok(h) => h,
Err(e) => {
Output::err(
e,
"failed to open directory <b>{s}<r>",
(bstr::BStr::new(new_folder),),
);
Global::crash();
}
};

if let Err(e) = sys::renameat_concurrently_a(
new_folder_handle.fd,
patch_tag,
Expand All @@ -413,18 +425,6 @@ pub fn do_patch_commit(
// path of `'brk`. Captures borrow into stack buffers.
scopeguard::defer! {
if has_nested_node_modules || bun_patch_tag.is_some() {
let new_folder_handle = match Dir::cwd().open_dir(new_folder, sys::OpenDirOptions::default()) {
Ok(h) => h,
Err(e) => {
bun_core::pretty_error!(
"<r><red>error<r>: failed to open directory <b>{}<r> {}<r>\n",
bstr::BStr::new(new_folder),
e,
);
Global::crash();
}
};

if has_nested_node_modules {
if let Err(e) = sys::renameat_concurrently_a(
root_node_modules.fd,
Expand All @@ -451,42 +451,19 @@ pub fn do_patch_commit(
}
}

let mut cwdbuf = bun_paths::path_buffer_pool::get();
let cwd = match sys::getcwd_z(&mut cwdbuf) {
Ok(fd) => fd,
Err(e) => {
bun_core::pretty_error!("<r><red>error<r>: failed to get cwd path {}<r>\n", e);
Global::crash();
}
};
let mut gitbuf = bun_paths::path_buffer_pool::get();
let git = match bun_which::which(
&mut gitbuf,
bun_core::env_var::PATH.get().unwrap_or(b""),
cwd.as_bytes(),
b"git",
) {
Some(g) => g,
None => {
bun_core::pretty_error!(
"<r><red>error<r>: git must be installed to use `bun patch --commit` <r>\n",
);
Global::crash();
}
};
let paths = bun_patch::git_diff_preprocess_paths(old_folder, new_folder);
let (opts, _envp_guard) =
bun_patch::spawn_opts(&paths[0], &paths[1], cwd, git, &mut manager.event_loop);

let mut spawn_result = match bun_spawn::sync::spawn(&opts) {
Err(e) => {
bun_core::pretty_error!("<r><red>error<r>: failed to make diff {}<r>\n", e.name(),);
Global::crash();
break 'brk None;
}
Ok(Ok(r)) => r,
Ok(Err(e)) => {
bun_core::pretty_error!("<r><red>error<r>: failed to make diff {}<r>\n", e);
Global::crash();
break 'brk None;
}
};

Expand All @@ -497,7 +474,7 @@ pub fn do_patch_commit(
"<r><red>error<r>: failed to make diff {}<r>\n",
e.name(),
);
Global::crash();
break 'brk None;
}
Ok(Ok(stdout)) => stdout,
Ok(Err(stderr)) => {
Expand Down Expand Up @@ -525,7 +502,7 @@ pub fn do_patch_commit(
Truncate { stderr: &stderr }
);
drop(stderr);
Global::crash();
break 'brk None;
}
};

Expand All @@ -540,7 +517,10 @@ pub fn do_patch_commit(
return Ok(None);
}

break 'brk contents;
break 'brk Some(contents);
};
let Some(patchfile_contents) = patchfile_contents else {
Global::crash();
};

// write the patch contents to temp file then rename
Expand Down Expand Up @@ -954,8 +934,6 @@ pub fn prepare_patch(manager: &mut PackageManager) -> Result<(), crate::Error> {
// edits into the shared cache. Detach first: walk up `module_folder` to
// find the first symlink ancestor, replace it with a real directory, and
// recreate the path below it so the copy lands in a project-local tree.
detach_module_folder_from_shared_store(module_folder);

if let Err(e) =
overwrite_package_in_node_modules_folder(cache_dir, cache_dir_subpath, module_folder)
{
Expand Down Expand Up @@ -1144,7 +1122,14 @@ fn overwrite_package_in_node_modules_folder(
cache_dir_subpath: &[u8],
node_modules_folder_path: &[u8],
) -> Result<(), crate::Error> {
let _ = Fd::cwd().delete_tree(node_modules_folder_path);
// Open the source first: if it is missing, the installed package stays as it was.
let cached_package_folder = Dir::borrow(&cache_dir).open_dir(
cache_dir_subpath,
sys::OpenDirOptions {
iterate: true,
..Default::default()
},
)?;

// FileCopier's path fields are `.unit = .os` (u16 on Windows). `Path::from`
// is generic over the *input* width and converts internally, so accepting
Expand Down Expand Up @@ -1184,14 +1169,6 @@ fn overwrite_package_in_node_modules_folder(
}
};

let cached_package_folder = Dir::borrow(&cache_dir).open_dir(
cache_dir_subpath,
sys::OpenDirOptions {
iterate: true,
..Default::default()
},
)?;

let ignore_directories: &[&bun_paths::OSPathSlice] = &[
bun_paths::os_path_literal!("node_modules"),
bun_paths::os_path_literal!(".git"),
Expand All @@ -1205,6 +1182,9 @@ fn overwrite_package_in_node_modules_folder(
ignore_directories,
)?;

detach_module_folder_from_shared_store(node_modules_folder_path);
let _ = Fd::cwd().delete_tree(node_modules_folder_path);
Comment thread
robobun marked this conversation as resolved.
Resolved

copier.copy()?;
Comment thread
robobun marked this conversation as resolved.
Resolved
Ok(())
}
Expand Down
96 changes: 95 additions & 1 deletion test/cli/install/bun-patch.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
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 { chmod, readdir, rm } from "fs/promises";
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");
Expand Down Expand Up @@ -1234,3 +1235,96 @@ describe.concurrent("bun patch --commit for non-registry dependencies", () => {
expect(patchKey).toBe("pkg-to-patch@./dep.tgz");
});
});

// `bun patch` deletes the package's folder in node_modules and copies it again. `bun patch
// --commit` moves the package's nested node_modules out of the way while it runs `git diff`.
// Both used to do that first and to exit on a later failure, so the files were gone.
describe("a step that fails leaves node_modules as it was", () => {
const registry = new VerdaccioRegistry();

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

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

// CI exports BUN_INSTALL_CACHE_DIR, which overrides the harness bunfig's per-test `cache`.
async function runBun(cwd: string, args: string[], env: Record<string, string | undefined> = bunEnv) {
await using proc = Bun.spawn({
cmd: [bunExe(), ...args],
cwd,
env: { ...env, 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 installedProject(dependencies: Record<string, string>) {
const { packageDir } = await registry.createTestDir({
bunfigOpts: { linker: "hoisted" },
files: { "package.json": JSON.stringify({ name: "foo", dependencies }) },
});
const { stderr, exitCode } = await runBun(packageDir, ["install"]);
expect(stderr).not.toContain("error:");
expect(exitCode).toBe(0);
return packageDir;
}

test.concurrent("bun patch when the package is not in the cache", async () => {
const packageDir = await installedProject({ "no-deps": "1.0.0" });
await rm(join(packageDir, ".bun-cache"), { recursive: true, force: true });

const { stderr, exitCode } = await runBun(packageDir, ["patch", "no-deps"]);
expect(stderr).toContain("error: error overwriting folder in node_modules: ENOENT");
expect(await Bun.file(join(packageDir, "node_modules", "no-deps", "package.json")).json()).toEqual({
name: "no-deps",
version: "1.0.0",
});
expect(exitCode).toBe(1);
});

// one-dep needs no-deps@1.0.1, so the hoisted linker nests it under one-dep.
async function commitWithPath(path: string) {
const packageDir = await installedProject({ "one-dep": "1.0.0", "no-deps": "2.0.0" });
const nested = Bun.file(join(packageDir, "node_modules", "one-dep", "node_modules", "no-deps", "package.json"));
expect(await nested.json()).toEqual({ name: "no-deps", version: "1.0.1" });

const env: Record<string, string | undefined> = { ...bunEnv };
for (const key of Object.keys(env)) {
if (key.toUpperCase() === "PATH") delete env[key];
}
env.PATH = path;

const { stderr, exitCode } = await runBun(packageDir, ["patch", "--commit", "node_modules/one-dep"], env);
return {
stderr,
exitCode,
nested: await nested.exists(),
rootNodeModules: (await readdir(join(packageDir, "node_modules"))).sort(),
};
}

test.concurrent("bun patch --commit when git is not installed", async () => {
using emptyPath = tempDir("bun-patch-no-git", {});

const { stderr, exitCode, ...nodeModules } = await commitWithPath(String(emptyPath));
expect(stderr).toContain("error: git must be installed to use `bun patch --commit`");
expect(nodeModules).toEqual({ nested: true, rootNodeModules: ["no-deps", "one-dep"] });
expect(exitCode).toBe(1);
});

// The git that fails is a shell script.
test.concurrent.skipIf(isWindows)("bun patch --commit when git diff fails", async () => {
using fakeGit = tempDir("bun-patch-fake-git", { "git": "#!/bin/sh\necho 'fatal: not today' >&2\nexit 128\n" });
await chmod(join(String(fakeGit), "git"), 0o755);

const { stderr, exitCode, ...nodeModules } = await commitWithPath(String(fakeGit));
expect(stderr).toContain("error: failed to make diff fatal: not today");
expect(nodeModules).toEqual({ nested: true, rootNodeModules: ["no-deps", "one-dep"] });
expect(exitCode).toBe(1);
});
});
Loading