|
| 1 | +// @vitest-environment node |
| 2 | +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { basename, join } from "node:path"; |
| 5 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 6 | +import type { HistoryWho } from "./historyLog"; |
| 7 | +import { openProjectHistory } from "./projectHistory"; |
| 8 | + |
| 9 | +// Windows refuses a rename onto a file another process has open for a moment (an indexer, antivirus). |
| 10 | +const held = vi.hoisted(() => ({ name: null as string | null, refused: 0 })); |
| 11 | +vi.mock("node:fs", async (importOriginal) => { |
| 12 | + const original = await importOriginal<typeof import("node:fs")>(); |
| 13 | + const renameSync = ((from: string, to: string) => { |
| 14 | + if (held.name && basename(String(to)) === held.name && held.refused === 0) { |
| 15 | + held.refused += 1; |
| 16 | + throw Object.assign(new Error(`EPERM: operation not permitted, rename '${from}'`), { |
| 17 | + code: "EPERM", |
| 18 | + syscall: "rename", |
| 19 | + }); |
| 20 | + } |
| 21 | + return original.renameSync(from, to); |
| 22 | + }) as typeof original.renameSync; |
| 23 | + return { ...original, renameSync }; |
| 24 | +}); |
| 25 | + |
| 26 | +const you: HistoryWho = { kind: "person", name: "You" }; |
| 27 | +const cleanup: Array<() => unknown> = []; |
| 28 | + |
| 29 | +afterEach(async () => { |
| 30 | + held.name = null; |
| 31 | + held.refused = 0; |
| 32 | + for (const step of cleanup.splice(0).reverse()) await step(); |
| 33 | +}); |
| 34 | + |
| 35 | +function tempDir(prefix: string): string { |
| 36 | + const dir = mkdtempSync(join(tmpdir(), prefix)); |
| 37 | + cleanup.push(() => rmSync(dir, { recursive: true, force: true })); |
| 38 | + return dir; |
| 39 | +} |
| 40 | + |
| 41 | +describe("a project file held open for a moment", () => { |
| 42 | + it("still takes Undo and Redo: the file is put back once the hold lets go", async () => { |
| 43 | + const projectDir = tempDir("hf-history-held-"); |
| 44 | + const historyRoot = tempDir("hf-history-held-root-"); |
| 45 | + const file = join(projectDir, "index.html"); |
| 46 | + writeFileSync(file, "v1"); |
| 47 | + const history = await openProjectHistory({ projectDir, historyRoot }); |
| 48 | + cleanup.push(() => history.close()); |
| 49 | + const window = await history.beginWindow(you, "Your edit"); |
| 50 | + writeFileSync(file, "v2"); |
| 51 | + await window.close(); |
| 52 | + |
| 53 | + held.name = "index.html"; |
| 54 | + expect(await history.step("back", you)).toMatchObject({ ok: true }); |
| 55 | + expect(held.refused).toBe(1); |
| 56 | + expect(readFileSync(file, "utf-8")).toBe("v1"); |
| 57 | + |
| 58 | + held.refused = 0; |
| 59 | + expect(await history.step("forward", you)).toMatchObject({ ok: true }); |
| 60 | + expect(held.refused).toBe(1); |
| 61 | + expect(readFileSync(file, "utf-8")).toBe("v2"); |
| 62 | + }); |
| 63 | +}); |
0 commit comments