Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: writeFileSafelyの一時ファイルが既存のファイルを上書きしないようにする #2454

Merged
merged 3 commits into from
Jan 1, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions src/backend/electron/fileHelper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fs from "fs";
import log from "electron-log/main";
import { moveFileSync } from "move-file";

/**
Expand All @@ -9,10 +10,34 @@ export function writeFileSafely(
path: string,
data: string | NodeJS.ArrayBufferView,
) {
const tmpPath = `${path}.tmp`;
fs.writeFileSync(tmpPath, data);
let tmpPath: string;
let maxRetries = 16;
while (true) {
maxRetries--;
try {
// ランダムな文字列を8文字生成
const randStr = Math.floor(Math.random() * 36 ** 8)
.toString(36)
.padStart(8, "0");
tmpPath = `${path}-${randStr}.tmp`;
fs.writeFileSync(tmpPath, data, { flag: "wx" });
break;
} catch (error) {
const e = error as NodeJS.ErrnoException;
if (e.code !== "EEXIST" || maxRetries <= 0) {
throw e;
}
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

結構ややこしさが上がってしまうので、重ならないランダムであるuuid4を使っちゃいますか!!
こうなるはず!

Suggested change
let tmpPath: string;
let maxRetries = 16;
while (true) {
maxRetries--;
try {
// ランダムな文字列を8文字生成
const randStr = Math.floor(Math.random() * 36 ** 8)
.toString(36)
.padStart(8, "0");
tmpPath = `${path}-${randStr}.tmp`;
fs.writeFileSync(tmpPath, data, { flag: "wx" });
break;
} catch (error) {
const e = error as NodeJS.ErrnoException;
if (e.code !== "EEXIST" || maxRetries <= 0) {
throw e;
}
}
}
const tmpPath = `${path}-${uuid4()}.tmp`;
fs.writeFileSync(tmpPath, data, { flag: "wx" });

(8桁数字を提案したのは僕なのですみません 🙇 )


moveFileSync(tmpPath, path, {
overwrite: true,
});
try {
moveFileSync(tmpPath, path, {
overwrite: true,
});
} catch (error) {
fs.promises.unlink(tmpPath).catch((reason) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

「ファイルが存在していたら」も足しても良いかも?

log.warn("Fail to remove %s\n %o", tmpPath, reason);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こうかも

Suggested change
log.warn("Fail to remove %s\n %o", tmpPath, reason);
log.warn("Failed to remove %s\n %o", tmpPath, reason);

});
throw error;
}
}
Loading