|
| 1 | +import { rmSync, statSync } from "node:fs"; |
| 2 | +import { tmpdir } from "node:os"; |
| 3 | +import { basename, join } from "node:path"; |
| 4 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 5 | +import * as fs from "node:fs"; |
| 6 | +import { createStagingDir } from "./stagingDir.js"; |
| 7 | + |
| 8 | +vi.mock("node:fs", async (importOriginal) => { |
| 9 | + const original = await importOriginal<typeof fs>(); |
| 10 | + return { |
| 11 | + ...original, |
| 12 | + mkdtempSync: vi.fn(() => { |
| 13 | + throw Object.assign(new Error("path too long"), { code: "ENOENT" }); |
| 14 | + }), |
| 15 | + }; |
| 16 | +}); |
| 17 | + |
| 18 | +const roots: string[] = []; |
| 19 | +const root = () => { |
| 20 | + const made = join(tmpdir(), `hf-staging-${process.pid}-${roots.length}`); |
| 21 | + fs.mkdirSync(made, { recursive: true }); |
| 22 | + roots.push(made); |
| 23 | + return made; |
| 24 | +}; |
| 25 | +afterEach(() => { |
| 26 | + for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true }); |
| 27 | +}); |
| 28 | + |
| 29 | +describe("createStagingDir", () => { |
| 30 | + it("makes a fresh private directory without mkdtemp, which fails on long Windows paths", () => { |
| 31 | + const parent = root(); |
| 32 | + const first = createStagingDir(parent, ".stage-"); |
| 33 | + const second = createStagingDir(parent, ".stage-"); |
| 34 | + expect(first).not.toBe(second); |
| 35 | + expect(basename(first)).toMatch(/^\.stage-[0-9a-f]{8}$/); |
| 36 | + expect(statSync(first).isDirectory()).toBe(true); |
| 37 | + if (process.platform !== "win32") expect(statSync(first).mode & 0o777).toBe(0o700); |
| 38 | + expect(fs.mkdtempSync).not.toHaveBeenCalled(); |
| 39 | + }); |
| 40 | + |
| 41 | + it("tries another name when one is taken, and gives up after five", () => { |
| 42 | + const parent = root(); |
| 43 | + const taken = createStagingDir(parent, ".s-", () => "same"); |
| 44 | + expect(taken).toBe(join(parent, ".s-same")); |
| 45 | + const names = ["same", "same", "next"]; |
| 46 | + expect(createStagingDir(parent, ".s-", () => names.shift() ?? "x")).toBe( |
| 47 | + join(parent, ".s-next"), |
| 48 | + ); |
| 49 | + expect(() => createStagingDir(parent, ".s-", () => "same")).toThrow(/EEXIST/); |
| 50 | + }); |
| 51 | +}); |
0 commit comments