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
6 changes: 2 additions & 4 deletions src/glob/GlobWalker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<SENTINEL>(&full_path))));
}
Ok(stat) => stat,
};
Expand Down
31 changes: 26 additions & 5 deletions src/install/PackageManager/package_json_write_back.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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.
Expand Down Expand Up @@ -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<Vec<(usize, Package)>> {
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());
Expand All @@ -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;

Expand Down
3 changes: 0 additions & 3 deletions src/install/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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"
}
Expand Down
63 changes: 34 additions & 29 deletions src/install/lockfile/Package/WorkspaceMap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<path::platform::Auto>(
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 <b>{}<r> due to error <b>{}<r> ({} \"{}\")",
BStr::new(user_pattern),
BStr::new(err.name()),
<&'static str>::from(err.syscall),
BStr::new(failed_path),
);
crate::Error::InstallFailed
Comment thread
robobun marked this conversation as resolved.
Resolved
}

impl WorkspaceMap {
pub(crate) fn process_names_array(
&mut self,
Expand Down Expand Up @@ -446,48 +477,22 @@ 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 <b>{}<r> due to error <b>{}<r>",
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 <b>{}<r> due to error <b>{}<r>",
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 {
let matched_path_owned = match iter.next()? {
Ok(Some(r)) => r,
Ok(None) => break,
Err(e) => {
let _ = bun_ast::add_error_pretty!(
log,
Some(source),
loc,
"Failed to run workspace pattern <b>{}<r> due to error <b>{}<r>",
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;
Expand Down
82 changes: 78 additions & 4 deletions test/cli/install/bad-workspace.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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);
});

Expand Down Expand Up @@ -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);
Expand Down
22 changes: 22 additions & 0 deletions test/js/bun/glob/scan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
Loading