Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 2 additions & 1 deletion docs/pm/workspaces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ For that workspace `bun install` then behaves as a hoisting barrier — nothing
directly or transitively (including through other workspaces it depends on), is placed above
`apps/desktop/node_modules`, so that directory is a complete tree — and materializes those
packages as real copies instead of hardlinks / clones from the cache, so tools that rewrite them
cannot affect the cache or other projects. All other workspaces keep hoisting to the root as usual. The setting is recorded in `bun.lock` for the workspace, so installs from the lockfile reproduce the same layout.
cannot affect the cache or other projects. All other workspaces keep hoisting to the root as usual. The setting is recorded in the lockfile (`bun.lock` or `bun.lockb`) for the workspace, so installs from the lockfile reproduce the same layout.
A `--frozen-lockfile` install uses the recorded setting. After you add or remove the setting, run `bun install` once to update the lockfile.
This setting has no effect with the isolated linker, where every package already resolves only its
own dependencies.

Expand Down
31 changes: 21 additions & 10 deletions src/install/PackageManager/install_with_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,16 +235,27 @@ pub fn install_with_manager(
};

had_any_diffs = manager.summary.has_diffs();
// Which workspaces asked for a self-contained node_modules is a property
// of their manifests, not of the dependency graph: mirror the freshly
// parsed manifests whether or not anything else changed, so the copy
// loaded from bun.lock never goes stale.
manager
.lockfile
.self_contained_workspaces
.clear_retaining_capacity();
for key in lockfile.self_contained_workspaces.keys() {
manager.lockfile.self_contained_workspaces.put(*key, ())?;
// A frozen install keeps the self-contained set the lockfile recorded.
// Every other install records the manifests' set, and saves the
// lockfile when only that set changed.
Comment thread
robobun marked this conversation as resolved.
Resolved
if !manager.options.enable.frozen_lockfile() {
let recorded = &manager.lockfile.self_contained_workspaces;
let declared = &lockfile.self_contained_workspaces;
let changed = recorded.count() != declared.count()
|| declared.keys().iter().any(|key| !recorded.contains(key));
if changed {
manager
.lockfile
.self_contained_workspaces
.clear_retaining_capacity();
for key in lockfile.self_contained_workspaces.keys() {
manager.lockfile.self_contained_workspaces.put(*key, ())?;
}
manager
.options
.enable
.set(Enable::FORCE_SAVE_LOCKFILE, true);
}
}
if manager.subcommand == Subcommand::Dedupe {
crate::dedupe::dedupe_after_differ(manager);
Expand Down
39 changes: 3 additions & 36 deletions src/install/lockfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,11 +180,9 @@ pub struct Lockfile {
pub(crate) scripts: Scripts,
pub(crate) workspace_paths: NameHashMap,
pub workspace_versions: VersionHashMap,
/// Workspaces (by name hash) that must get a self-contained node_modules: those
/// listed in the root manifest's `workspaces.selfContained` and those declaring
/// `installConfig.hoistingLimits = "workspaces"`. Mirrored from the manifests on
/// every install and persisted per workspace in bun.lock (`"hoistingLimits"`), so a
/// tree rebuilt from the lockfile is hoisted the same way.
/// Workspaces (by name hash) that must get a self-contained node_modules, from
/// `workspaces.selfContained` and `installConfig.hoistingLimits = "workspaces"`.
/// bun.lock and bun.lockb record the set, so a rebuilt tree is hoisted the same way.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub self_contained_workspaces: ArrayHashMap<PackageNameHash, (), ArrayIdentityContextU64>,

/// Optional because `trustedDependencies` in package.json might be an
Expand Down Expand Up @@ -2974,30 +2972,6 @@ impl Lockfile {
string_builder.count(SCRIPTS_END);
}

// Self-contained workspaces change the hoisted layout without changing any
// resolution; include them (sorted, only when present) so bun.lockb's
// frozen-lockfile check notices. Text lockfiles compare the tree itself.
const SELF_CONTAINED_BEGIN: &[u8] = b"\n-- BEGIN SELF-CONTAINED WORKSPACES --\n";
let mut self_contained_names: Vec<&[u8]> = Vec::new();
if self.self_contained_workspaces.count() > 0 {
for i in 0..packages_len {
if resolutions[i].tag == crate::resolution::Tag::Workspace
&& self
.self_contained_workspaces
.contains(&self.packages.items_name_hash()[i])
{
self_contained_names.push(names[i].slice(bytes));
}
}
self_contained_names.sort_unstable();
if !self_contained_names.is_empty() {
string_builder.count(SELF_CONTAINED_BEGIN);
for n in &self_contained_names {
string_builder.fmt_count(format_args!("{}\n", bstr::BStr::new(n)));
}
}
}

{
let alphabetizer = package::Alphabetizer::<u64> {
names: names.into(),
Expand Down Expand Up @@ -3036,13 +3010,6 @@ impl Lockfile {
let _ = string_builder.append(SCRIPTS_END);
}

if !self_contained_names.is_empty() {
let _ = string_builder.append(SELF_CONTAINED_BEGIN);
for n in &self_contained_names {
let _ = string_builder.fmt(format_args!("{}\n", bstr::BStr::new(n)));
}
}

let _ = string_builder.append(HASH_SUFFIX);

let len = string_builder.len;
Expand Down
24 changes: 24 additions & 0 deletions src/install/lockfile/bun.lockb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const HAS_OVERRIDES_TAG: u64 = u64::from_ne_bytes(*b"oVeRriDs");
const HAS_CATALOGS_TAG: u64 = u64::from_ne_bytes(*b"cAtAlOgS");
const HAS_CONFIG_VERSION_TAG: u64 = u64::from_ne_bytes(*b"cNfGvRsN");
const HAS_SCOPED_OVERRIDES_TAG: u64 = u64::from_ne_bytes(*b"sCoPdOvR");
const HAS_SELF_CONTAINED_WORKSPACES_TAG: u64 = u64::from_ne_bytes(*b"sElFcOnT");

/// Wraps a growing `Vec<u8>` to provide both positional-write semantics
/// (`get_pos`/`pwrite`) and append semantics (`write_all`/`write_int_*`) for
Expand Down Expand Up @@ -375,6 +376,13 @@ pub(crate) fn save(
write_array::<dependency::External>(&mut stream, &externals, PREFIX_DEP_EXTERNAL)?;
}

if this.self_contained_workspaces.count() > 0 {
stream.write_all(&HAS_SELF_CONTAINED_WORKSPACES_TAG.to_ne_bytes())?;
let mut name_hashes: Vec<PackageNameHash> = this.self_contained_workspaces.keys().to_vec();
name_hashes.sort_unstable();
write_array::<PackageNameHash>(&mut stream, &name_hashes, PREFIX_U64)?;
}

*total_size = stream.get_pos()?;

stream.write_all(&ALIGNMENT_BYTES_TO_REPEAT_BUFFER)?;
Expand Down Expand Up @@ -808,6 +816,22 @@ pub(crate) fn load(
}
}

{
let remaining_in_buffer = total_buffer_size.saturating_sub(stream.pos as u64);

if remaining_in_buffer > 8 && total_buffer_size <= stream.buffer.len() as u64 {
let next_num = stream.read_int_le::<u64>()?;
if next_num == HAS_SELF_CONTAINED_WORKSPACES_TAG {
let name_hashes: Vec<PackageNameHash> = buffers::read_array(stream)?;
for name_hash in name_hashes {
lockfile.self_contained_workspaces.put(name_hash, ())?;
}
} else {
stream.pos -= 8;
}
}
}

lockfile.scratch = Scratch::init();
lockfile.package_index = PackageIndex::Map::default();
lockfile.string_pool = StringPool::default();
Expand Down
145 changes: 143 additions & 2 deletions test/cli/install/bun-workspaces-self-contained.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ async function install(cwd: string, args: string[] = []) {
return { out, err, code };
}

async function writeProject(desktopExtra: object, workspacesExtra: object) {
async function writeProject(desktopExtra: object, workspacesExtra: object, saveTextLockfile = true) {
await writeFile(
join(package_dir, "bunfig.toml"),
Bun.TOML.stringify({
install: { cache: false, registry: root_url + "/", saveTextLockfile: true, linker: "hoisted" },
install: { cache: false, registry: root_url + "/", saveTextLockfile, linker: "hoisted" },
}),
);
await mkdir(join(package_dir, "apps", "desktop"), { recursive: true });
Expand Down Expand Up @@ -176,3 +176,144 @@ it("without either setting the workspace is hoisted normally", async () => {
expect(existsSync(join(package_dir, "node_modules", "@barn", "moo", "package.json"))).toBeTrue();
expect(existsSync(join(package_dir, "node_modules", "baz", "package.json"))).toBeTrue();
});

// A frozen install installs the layout the lockfile recorded. Bun 1.4.0 ignored
// `installConfig.hoistingLimits`, so a lockfile it wrote has no record of the setting
// while the manifest still carries it; CI must accept that lockfile as-is.
describe.each([
["hoisted", "bun.lock"],
["isolated", "bun.lock"],
["hoisted", "bun.lockb"],
] as const)("--frozen-lockfile with the %s linker and %s", (linker, lockfileName) => {
const text = lockfileName === "bun.lock";
const readLockfile = () => Bun.file(join(package_dir, lockfileName)).bytes();
const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes);
const desktopNm = () => join(package_dir, "apps", "desktop", "node_modules");
const cleanTree = async () => {
await rm(join(package_dir, "node_modules"), { recursive: true, force: true });
await rm(desktopNm(), { recursive: true, force: true });
};
// the isolated linker has no hoisting to limit, so only the hoisted layout differs
const expectLayout = async (layout: "hoisted" | "self-contained") => {
if (linker !== "hoisted") return;
if (layout === "hoisted") {
expect(existsSync(desktopNm())).toBeFalse();
expect(existsSync(join(package_dir, "node_modules", "@barn", "moo", "package.json"))).toBeTrue();
} else {
expect(await readdirSorted(desktopNm())).toEqual(["@barn", "bar", "baz", "shared"]);
}
};

it("accepts a lockfile that does not record the manifest's hoistingLimits yet", async () => {
// the lockfile that bun 1.4.0 writes for this project
await writeProject({}, {}, text);
let r = await install(package_dir, [`--linker=${linker}`]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
const before = await readLockfile();

// the manifest declares the setting (it always did; 1.4.0 ignored the key)
await writeProject({ installConfig: { hoistingLimits: "workspaces" } }, {}, text);
await cleanTree();
r = await install(package_dir, [`--linker=${linker}`, "--frozen-lockfile"]);
expect(r.err).not.toContain("lockfile had changes");
expect(r.code).toBe(0);
expect(await readLockfile()).toEqual(before);
await expectLayout("hoisted");

// a plain install records the setting and applies it …
r = await install(package_dir, [`--linker=${linker}`]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
const after = await readLockfile();
expect(after).not.toEqual(before);
if (text) expect(decode(after)).toContain('"hoistingLimits": "workspaces"');
await expectLayout("self-contained");

// … and from then on a frozen install reproduces that layout
await cleanTree();
r = await install(package_dir, [`--linker=${linker}`, "--frozen-lockfile"]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
expect(await readLockfile()).toEqual(after);
await expectLayout("self-contained");
});

it("keeps the recorded layout after the manifest drops hoistingLimits", async () => {
await writeProject({ installConfig: { hoistingLimits: "workspaces" } }, {}, text);
let r = await install(package_dir, [`--linker=${linker}`]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
const recorded = await readLockfile();
if (text) expect(decode(recorded)).toContain('"hoistingLimits": "workspaces"');

await writeProject({}, {}, text);
await cleanTree();
r = await install(package_dir, [`--linker=${linker}`, "--frozen-lockfile"]);
expect(r.err).not.toContain("lockfile had changes");
expect(r.code).toBe(0);
expect(await readLockfile()).toEqual(recorded);
await expectLayout("self-contained");

// a plain install drops the record …
r = await install(package_dir, [`--linker=${linker}`]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
const dropped = await readLockfile();
expect(dropped).not.toEqual(recorded);
if (text) expect(decode(dropped)).not.toContain("hoistingLimits");

// … so a frozen install hoists the workspace again
await cleanTree();
r = await install(package_dir, [`--linker=${linker}`, "--frozen-lockfile"]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
expect(await readLockfile()).toEqual(dropped);
await expectLayout("hoisted");
});
});

it("bun install records hoistingLimits when the hoisted tree does not change", async () => {
// `solo` gets its own copy of baz with or without the setting: the root pins another version
setHandler(dummyRegistry([], { "0.0.3": {}, "0.0.5": {}, latest: "0.0.5" }));
const soloBaz = join(package_dir, "apps", "solo", "node_modules", "baz", "package.json");
const writeSolo = (extra: object) =>
writeFile(
join(package_dir, "apps", "solo", "package.json"),
JSON.stringify({ name: "solo", version: "1.0.0", ...extra, dependencies: { baz: "0.0.5" } }),
);
await writeFile(
join(package_dir, "bunfig.toml"),
Bun.TOML.stringify({
install: { cache: false, registry: root_url + "/", saveTextLockfile: true, linker: "hoisted" },
}),
);
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({ name: "root", private: true, workspaces: ["apps/*"], dependencies: { baz: "0.0.3" } }),
);
await mkdir(join(package_dir, "apps", "solo"), { recursive: true });
await writeSolo({});
let r = await install(package_dir);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
expect(existsSync(soloBaz)).toBeTrue();

await writeSolo({ installConfig: { hoistingLimits: "workspaces" } });
r = await install(package_dir);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
expect(await Bun.file(join(package_dir, "bun.lock")).text()).toContain('"hoistingLimits": "workspaces"');

// so a frozen install copies solo's packages instead of linking them from the cache
await rm(join(package_dir, "node_modules"), { recursive: true, force: true });
await rm(join(package_dir, "apps", "solo", "node_modules"), { recursive: true, force: true });
r = await install(package_dir, ["--frozen-lockfile"]);
expect(r.err).not.toContain("error:");
expect(r.code).toBe(0);
expect(existsSync(soloBaz)).toBeTrue();
if (!isWindows) {
expect(statSync(soloBaz).nlink).toBe(1);
expect(statSync(join(package_dir, "node_modules", "baz", "package.json")).nlink).toBeGreaterThan(1);
}
});
Loading