diff --git a/src/glob/GlobWalker.rs b/src/glob/GlobWalker.rs index a1a13ec2d096..3c7238746409 100644 --- a/src/glob/GlobWalker.rs +++ b/src/glob/GlobWalker.rs @@ -673,10 +673,8 @@ impl<'a, A: Accessor, const SENTINEL: bool> Iterator<'a, A, SENTINEL> { self.iter_state = IterState::GetNext; return Ok(Ok(())); } - return Ok(Err(e.with_path( - self.walker.pattern_components[idx as usize] - .pattern_slice(&self.walker.pattern), - ))); + let full_path = self.walker.join(&[dir_path.as_bytes(), &pat_slice])?; + return Ok(Err(e.with_path(matched_as_slice::(&full_path)))); } Ok(stat) => stat, }; diff --git a/src/install/PackageManager/package_json_write_back.rs b/src/install/PackageManager/package_json_write_back.rs index becf4d246f84..d0f4dc60be5e 100644 --- a/src/install/PackageManager/package_json_write_back.rs +++ b/src/install/PackageManager/package_json_write_back.rs @@ -1,6 +1,6 @@ use bun_collections::DynamicBitSet; use bun_collections::bit_set::Range as BitRange; -use bun_core::{Global, strings}; +use bun_core::{Global, Output, strings}; use bun_paths::path_buffer_pool; use bun_paths::resolve_path::{join_abs_string_buf, platform}; use bun_sys::{Fd, File}; @@ -20,6 +20,7 @@ use super::add_remove_with_filter::{ use super::options::Do; use super::package_json_editor::{self as PackageJSONEditor, EditOptions}; use super::update_package_json_and_install::print_package_json_into_cache_entry; +use super::workspace_manifests::ScratchManifests; use super::{PackageManager, Subcommand, UpdateRequest}; /// A package.json whose cache entry was re-printed; `target.name_hash == None` is the root. @@ -264,9 +265,12 @@ fn target_package_ids(lockfile: &Lockfile, edited: &[EditedPackageJson]) -> Vec< ids } -/// Re-parses the edited files the way `bun install` would and copies every declared literal that differs (and, for the root, `overrides` + `catalogs`) into `manager.lockfile`, so the next install's differ sees no change. -fn sync_lockfile(manager: &mut PackageManager, edited: &[EditedPackageJson]) -> crate::Result<()> { - let mut scratch = super::workspace_manifests::ScratchManifests::new(); +/// The root and every edited member, indexed by position in `edited`. +fn parse_edited( + manager: &mut PackageManager, + scratch: &mut ScratchManifests, + edited: &[EditedPackageJson], +) -> crate::Result> { scratch.parse_root(manager)?; let mut root_pkg = Some(core::mem::take(&mut scratch.root)); let mut parsed: Vec<(usize, Package)> = Vec::with_capacity(edited.len()); @@ -277,7 +281,24 @@ fn sync_lockfile(manager: &mut PackageManager, edited: &[EditedPackageJson]) -> } parsed.push((i, scratch.parse_member(manager, &e.target)?)); } - let super::workspace_manifests::ScratchManifests { + Ok(parsed) +} + +/// Re-parses the edited files the way `bun install` would and copies every declared literal that differs (and, for the root, `overrides` + `catalogs`) into `manager.lockfile`, so the next install's differ sees no change. +fn sync_lockfile(manager: &mut PackageManager, edited: &[EditedPackageJson]) -> crate::Result<()> { + let mut scratch = ScratchManifests::new(); + let parsed = match parse_edited(manager, &mut scratch, edited) { + Ok(parsed) => parsed, + Err(err) => { + if scratch.log.has_errors() { + let _ = scratch + .log + .print(std::ptr::from_mut(Output::error_writer())); + } + return Err(err); + } + }; + let ScratchManifests { lockfile: scratch, .. } = scratch; diff --git a/src/install/error.rs b/src/install/error.rs index 1b2e2e464587..46f41b78879b 100644 --- a/src/install/error.rs +++ b/src/install/error.rs @@ -174,8 +174,6 @@ pub enum Error { LockfileIsMissingResolutionData, #[error("MissingPackageName")] MissingPackageName, - #[error("GlobError")] - GlobError, #[error("Lockfile validation failed: list is impossibly long")] LockfileValidationFailedListIsImpossiblyLong, #[error("Lockfile validation failed: alignment mismatch")] @@ -334,7 +332,6 @@ impl Error { Self::CorruptLockfile => "CorruptLockfile", Self::LockfileIsMissingResolutionData => "Lockfile is missing resolution data", Self::MissingPackageName => "MissingPackageName", - Self::GlobError => "GlobError", Self::LockfileValidationFailedListIsImpossiblyLong => { "Lockfile validation failed: list is impossibly long" } diff --git a/src/install/lockfile/Package/WorkspaceMap.rs b/src/install/lockfile/Package/WorkspaceMap.rs index a971fc83635e..38e6f30eec2b 100644 --- a/src/install/lockfile/Package/WorkspaceMap.rs +++ b/src/install/lockfile/Package/WorkspaceMap.rs @@ -246,6 +246,37 @@ fn relative_workspace_path<'b>( &buf[..len] } +/// `err.path` is relative to `cwd`, or absolute when the pattern is. +fn add_glob_error( + log: &mut bun_ast::Log, + source: &bun_ast::Source, + loc: bun_ast::Loc, + user_pattern: &[u8], + cwd: &[u8], + err: &bun_sys::Error, +) -> crate::Error { + let mut buf = path::path_buffer_pool::get(); + let failed_path = path::string_paths::without_trailing_slash_windows_path( + resolve_path::join_abs_string_buf_checked::( + cwd, + &mut buf.0[..], + &[&err.path], + ) + .unwrap_or(&err.path), + ); + let _ = bun_ast::add_error_pretty!( + log, + Some(source), + loc, + "Failed to run workspace pattern {} due to error {} ({} \"{}\")", + BStr::new(user_pattern), + BStr::new(err.name()), + <&'static str>::from(err.syscall), + BStr::new(failed_path), + ); + crate::Error::InstallFailed +} + impl WorkspaceMap { pub(crate) fn process_names_array( &mut self, @@ -446,32 +477,14 @@ impl WorkspaceMap { Some(ignored_workspace_paths), )? { Ok(w) => w, - Err(e) => { - let _ = bun_ast::add_error_pretty!( - log, - Some(source), - loc, - "Failed to run workspace pattern {} due to error {}", - BStr::new(user_pattern), - BStr::new(e.name()), - ); - return Err(crate::Error::GlobError); - } + Err(e) => return Err(add_glob_error(log, source, loc, user_pattern, cwd, &e)), }; // walker dropped at end of loop iter; GlobWalker is heap-backed with no // arena, and its Drop only logs + frees owned Vec/Box fields. let mut iter = glob::walk::Iterator::new(&mut walker); if let Err(e) = iter.init()? { - let _ = bun_ast::add_error_pretty!( - log, - Some(source), - loc, - "Failed to run workspace pattern {} due to error {}", - BStr::new(user_pattern), - BStr::new(e.name()), - ); - return Err(crate::Error::GlobError); + return Err(add_glob_error(log, source, loc, user_pattern, cwd, &e)); } 'next_match: loop { @@ -479,15 +492,7 @@ impl WorkspaceMap { Ok(Some(r)) => r, Ok(None) => break, Err(e) => { - let _ = bun_ast::add_error_pretty!( - log, - Some(source), - loc, - "Failed to run workspace pattern {} due to error {}", - BStr::new(user_pattern), - BStr::new(e.name()), - ); - return Err(crate::Error::GlobError); + return Err(add_glob_error(log, source, loc, user_pattern, cwd, &e)); } }; let matched_path: &[u8] = &matched_path_owned; diff --git a/test/cli/install/bad-workspace.test.ts b/test/cli/install/bad-workspace.test.ts index 81c5a2af0bf4..159b7cdb92b4 100644 --- a/test/cli/install/bad-workspace.test.ts +++ b/test/cli/install/bad-workspace.test.ts @@ -1,7 +1,7 @@ import { spawn, spawnSync } from "bun"; import { install_test_helpers } from "bun:internal-for-testing"; import { beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { mkdirSync, writeFileSync } from "fs"; +import { chmodSync, mkdirSync, rmSync, writeFileSync } from "fs"; import { bunEnv, bunExe, isLinux, isWindows, tempDir, tmpdirSync } from "harness"; import { dirname, join } from "path"; @@ -41,15 +41,85 @@ test("bad workspace path", () => { // The glob walker opens the literal prefix of an absolute pattern before it walks it. When // that directory is missing, the error names the errno by its node spelling on every -// platform (Windows used to print the bare variant name, "NOENT"). -test("glob entry under a missing directory reports the errno name", async () => { +// platform (Windows used to print the bare variant name, "NOENT") and the directory. No +// other error line follows it. +test.concurrent("glob entry under a missing directory reports the errno name and the directory", async () => { using dir = tempDir("bad-workspace-glob-missing-root", {}); const entry = `${String(dir).replaceAll("\\", "/")}/missing/*`; writeFileSync(join(String(dir), "package.json"), rootPackageJson([entry])); const { stderr, exitCode } = await runInstall(String(dir)); - expect(stderr).toContain(`error: Failed to run workspace pattern ${entry} due to error ENOENT`); + expect(errorLines(stderr)).toEqual([ + `error: Failed to run workspace pattern ${entry} due to error ENOENT (open "${join(String(dir), "missing")}")`, + ]); + expect(exitCode).toBe(1); +}); + +// npm, pnpm and yarn 1 fail here too. Root ignores the mode bits, and chmod on Windows +// cannot make a directory unreadable or unsearchable. +test.concurrent.skipIf(isWindows || process.getuid?.() === 0).each([ + ["unreadable", 0o000, "open", "secret"], + ["unsearchable", 0o444, "fstatat", join("secret", "package.json")], +])("glob entry that reaches an %s directory names what it failed on", async (_, mode, syscall, failedOn) => { + using dir = tempDir("bad-workspace-glob-eacces", { + "package.json": rootPackageJson(["pkgs/*"]), + ...PKG1, + "pkgs/secret/package.json": JSON.stringify({ name: "secret" }), + }); + const secret = join(String(dir), "pkgs", "secret"); + chmodSync(secret, mode); + try { + const { stderr, exitCode } = await runInstall(String(dir)); + + expect(errorLines(stderr)).toEqual([ + `error: Failed to run workspace pattern pkgs/* due to error EACCES (${syscall} "${join(String(dir), "pkgs", failedOn)}")`, + ]); + expect(exitCode).toBe(1); + } finally { + chmodSync(secret, 0o755); + } +}); + +// `bun add` walks the glob again when it writes package.json back. The registry removes the +// directory between the two walks. +test.concurrent("glob entry that fails when bun add writes package.json back is reported", async () => { + using dir = tempDir("bad-workspace-glob-write-back", { "extra/.keep": "" }); + const extra = join(String(dir), "extra"); + const entry = `${String(dir).replaceAll("\\", "/")}/extra/*`; + let tarballRequested = false; + await using registry = Bun.serve({ + port: 0, + fetch(req) { + if (req.url.endsWith(".tgz")) { + tarballRequested = true; + return new Response(Bun.file(join(import.meta.dir, "baz-0.0.3.tgz"))); + } + rmSync(extra, { recursive: true, force: true }); + return Response.json({ + name: "baz", + versions: { "0.0.3": { name: "baz", version: "0.0.3", dist: { tarball: `${registry.url}baz-0.0.3.tgz` } } }, + "dist-tags": { latest: "0.0.3" }, + }); + }, + }); + writeFileSync(join(String(dir), "package.json"), rootPackageJson([entry])); + writeFileSync(join(String(dir), "bunfig.toml"), `[install]\ncache = false\nregistry = "${registry.url}"\n`); + + await using proc = spawn({ + cmd: [bunExe(), "add", "baz"], + cwd: String(dir), + env: bunEnv, + stdout: "ignore", + stderr: "pipe", + }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + + // bun asked for the tarball, so the first walk passed. + expect(tarballRequested).toBe(true); + expect(errorLines(stderr)).toEqual([ + `error: Failed to run workspace pattern ${entry} due to error ENOENT (open "${extra}")`, + ]); expect(exitCode).toBe(1); }); @@ -186,6 +256,10 @@ async function runInstall(cwd: string) { return { stdout, stderr, exitCode }; } +function errorLines(stderr: string) { + return stderr.split(/\r?\n/).filter(line => line.startsWith("error:")); +} + // Installs and asserts that pkgs/pkg1 is the only workspace package that was found. async function expectOnlyPkg1Found(dir: string) { const { stderr, exitCode } = await runInstall(dir); diff --git a/test/js/bun/glob/scan.test.ts b/test/js/bun/glob/scan.test.ts index ab1536606dfb..8690ebf81811 100644 --- a/test/js/bun/glob/scan.test.ts +++ b/test/js/bun/glob/scan.test.ts @@ -617,6 +617,28 @@ describe("literal fast path", async () => { const entries = await Array.fromAsync(glob.scan({ cwd: tempdir })); expect(entries.sort()).toEqual([`packages${path.sep}foo`].sort()); }); + + // The fast path stats the literal in each matched directory. Mode 444 fails that stat. + // Root ignores the mode bits, and chmod on Windows cannot make a directory unsearchable. + test.skipIf(isWindows || process.getuid?.() === 0)("a failed stat reports the path from cwd", () => { + using dir = tempDir("glob-scan-literal-fast-path-eacces", { "packages/a/package.json": "hi" }); + const unsearchable = path.join(String(dir), "packages", "a"); + fs.chmodSync(unsearchable, 0o444); + try { + expect(() => [...new Glob("packages/*/package.json").scanSync({ cwd: String(dir) })]).toThrow( + expect.objectContaining({ code: "EACCES", syscall: "fstatat", path: "packages/a/package.json" }), + ); + expect(() => [...new Glob("packages/*/package.json").scanSync({ cwd: String(dir), absolute: true })]).toThrow( + expect.objectContaining({ + code: "EACCES", + syscall: "fstatat", + path: path.join(unsearchable, "package.json"), + }), + ); + } finally { + fs.chmodSync(unsearchable, 0o755); + } + }); }); describe("trailing directory separator", async () => {