Skip to content

Commit a066d55

Browse files
committed
fix(safeWriteJson): propagate non-ENOENT read errors during merge
1 parent a9367b6 commit a066d55

2 files changed

Lines changed: 41 additions & 2 deletions

File tree

‎src/utils/__tests__/safeWriteJson.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,41 @@ describe("safeWriteJson", () => {
497497
expect(content).toEqual({ value: 42 })
498498
})
499499

500+
test("should propagate non-ENOENT read errors during merge instead of silently losing data", async () => {
501+
const initial = { a: 1, b: 2 }
502+
await safeWriteJson(currentTestFilePath, initial)
503+
504+
const eio = Object.assign(new Error("I/O error"), { code: "EIO" })
505+
vi.mocked(fs.readFile).mockRejectedValueOnce(eio)
506+
507+
await expect(
508+
safeWriteJson(
509+
currentTestFilePath,
510+
{ b: 99 },
511+
{
512+
merge: (existing, incoming) => ({
513+
...(existing as Record<string, unknown>),
514+
...(incoming as Record<string, unknown>),
515+
}),
516+
},
517+
),
518+
).rejects.toThrow("I/O error")
519+
520+
const content = await readFileContent(currentTestFilePath)
521+
expect(content).toEqual({ a: 1, b: 2 })
522+
})
523+
524+
test("should treat corrupt JSON as null during merge", async () => {
525+
await fs.writeFile(currentTestFilePath, "not valid json", "utf8")
526+
527+
const mergeFn = vi.fn((_existing, incoming) => incoming)
528+
await safeWriteJson(currentTestFilePath, { value: 1 }, { merge: mergeFn })
529+
530+
expect(mergeFn).toHaveBeenCalledWith(null, { value: 1 })
531+
const content = await readFileContent(currentTestFilePath)
532+
expect(content).toEqual({ value: 1 })
533+
})
534+
500535
test("should write incoming data directly when no merge callback is provided", async () => {
501536
const initial = { a: 1, b: 2 }
502537
await safeWriteJson(currentTestFilePath, initial)

‎src/utils/safeWriteJson.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,12 @@ async function safeWriteJson(filePath: string, data: any, options?: SafeWriteJso
100100
let existing: unknown = null
101101
try {
102102
existing = JSON.parse(await fs.readFile(absoluteFilePath, "utf8"))
103-
} catch {
104-
// No readable file yet, so the merge receives null.
103+
} catch (error: unknown) {
104+
const code =
105+
error && typeof error === "object" && "code" in error ? (error as { code: string }).code : undefined
106+
if (!(error instanceof SyntaxError) && code !== "ENOENT") {
107+
throw error
108+
}
105109
}
106110
data = options.merge(existing, data)
107111
}

0 commit comments

Comments
 (0)