import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { syncBuiltinESMExports } from "node:module"; import { makeLinker } from "./link-or-copy.mjs"; test("links when it can", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "loc-")); try { await writeFile(path.join(dir, "a"), "frame"); const linkOne = makeLinker(); assert.equal(await linkOne(path.join(dir, "a"), path.join(dir, "b")), "link"); assert.equal((await stat(path.join(dir, "a"))).ino, (await stat(path.join(dir, "b"))).ino); assert.equal(linkOne.copies(), 0); } finally { await rm(dir, { recursive: true, force: true }); } }); test("a source at the link cap is copied once; later links of it go to the copy", async (t) => { const dir = await mkdtemp(path.join(os.tmpdir(), "loc-")); const capped = path.join(dir, "blank.png"); await writeFile(capped, "blank"); const realLink = fs.link; // Simulate ext4's cap: any link of the capped inode fails EMLINK. const cappedIno = (await stat(capped)).ino; t.mock.method(fs, "link", async (src, dst) => { if ((await stat(src)).ino === cappedIno) throw Object.assign(new Error("EMLINK: too many links"), { code: "EMLINK" }); return realLink(src, dst); }); syncBuiltinESMExports(); // the named `link` import follows the mock const fresh = makeLinker; try { const linkOne = fresh(); const outs = ["f1", "f2", "f3", "f4"].map((f) => path.join(dir, f)); const how = await Promise.all(outs.map((o) => linkOne(capped, o))); assert.equal(how.filter((h) => h === "copy").length, linkOne.copies()); assert.ok(linkOne.copies() >= 1); for (const o of outs) assert.equal(await readFile(o, "utf8"), "blank"); // sequentially, after the first copy, everything links to the stand-in const seq = fresh(); const a = path.join(dir, "s1"), b = path.join(dir, "s2"), c = path.join(dir, "s3"); assert.equal(await seq(capped, a), "copy"); assert.equal(await seq(capped, b), "link"); assert.equal(await seq(capped, c), "link"); assert.equal((await stat(b)).ino, (await stat(a)).ino); assert.equal(seq.copies(), 1); } finally { t.mock.restoreAll(); syncBuiltinESMExports(); await rm(dir, { recursive: true, force: true }); } }); test("other errors still throw", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "loc-")); try { await assert.rejects(makeLinker()(path.join(dir, "missing"), path.join(dir, "x")), { code: "ENOENT" }); } finally { await rm(dir, { recursive: true, force: true }); } });