Skip to content

Commit

Permalink
fix!: writeFileSafely関数をmove-file非依存にし、テストを追加 (#2502)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroshiba authored Jan 24, 2025
1 parent 8c4f742 commit 39d2948
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
9 changes: 3 additions & 6 deletions src/backend/electron/fileHelper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import fs from "fs";
import { moveFileSync } from "move-file";
import { uuid4 } from "@/helpers/random";
import { createLogger } from "@/helpers/log";

Expand All @@ -14,15 +13,13 @@ export function writeFileSafely(
data: string | NodeJS.ArrayBufferView,
) {
const tmpPath = `${path}-${uuid4()}.tmp`;
fs.writeFileSync(tmpPath, data, { flag: "wx" });

try {
moveFileSync(tmpPath, path, {
overwrite: true,
});
fs.writeFileSync(tmpPath, data, { flag: "wx" });
fs.renameSync(tmpPath, path);
} catch (error) {
if (fs.existsSync(tmpPath)) {
fs.promises.unlink(tmpPath).catch((reason) => {
void fs.promises.unlink(tmpPath).catch((reason) => {
log.warn("Failed to remove %s\n %o", tmpPath, reason);
});
}
Expand Down
45 changes: 45 additions & 0 deletions tests/unit/backend/electron/fileHelper.node.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import fs from "fs";
import path from "path";
import os from "os";
import { test, expect, beforeAll, afterAll } from "vitest";
import { writeFileSafely } from "@/backend/electron/fileHelper";
import { uuid4 } from "@/helpers/random";

let tmpDir: string;

beforeAll(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), uuid4()));
});

afterAll(() => {
fs.rmdirSync(tmpDir, { recursive: true });
});

describe("writeFileSafely", () => {
test("ファイルを書き込める", async () => {
const filePath = path.join(tmpDir, uuid4());
const content = "Hello World";
writeFileSafely(filePath, content);
expect(fs.readFileSync(filePath, "utf-8")).toBe(content);
});

test("ファイルを上書きできる", async () => {
const filePath = path.join(tmpDir, uuid4());
fs.writeFileSync(filePath, "old content");
const newContent = "new content";
writeFileSafely(filePath, newContent);
expect(fs.readFileSync(filePath, "utf-8")).toBe(newContent);
});

test("存在しないディレクトリに書き込もうとするとエラー", async () => {
const nonExistentDir = path.join(tmpDir, uuid4(), "not-exist");
const filePath = path.join(nonExistentDir, "test.txt");
expect(() => writeFileSafely(filePath, "data")).toThrow();
});

test("指定したパスにディレクトリが存在するとエラー", async () => {
const filePath = path.join(tmpDir, uuid4());
fs.mkdirSync(filePath);
expect(() => writeFileSafely(filePath, "data")).toThrow();
});
});

0 comments on commit 39d2948

Please sign in to comment.