-
Notifications
You must be signed in to change notification settings - Fork 19
chore: safe copy mechanism #480
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| 'use strict'; | ||
|
|
||
| import { readFile, writeFile, stat, readdir } from 'node:fs/promises'; | ||
| import { join } from 'node:path'; | ||
|
|
||
| /** | ||
| * Safely copies files from source to target directory, skipping files that haven't changed | ||
| * based on file stats (size and modification time) | ||
| * | ||
| * @param {string} srcDir - Source directory path | ||
| * @param {string} targetDir - Target directory path | ||
| */ | ||
| export async function safeCopy(srcDir, targetDir) { | ||
| const files = await readdir(srcDir); | ||
|
|
||
| for (const file of files) { | ||
ovflowd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| const sourcePath = join(srcDir, file); | ||
| const targetPath = join(targetDir, file); | ||
|
|
||
| const [sStat, tStat] = await Promise.allSettled([ | ||
| stat(sourcePath), | ||
| stat(targetPath), | ||
| ]); | ||
|
|
||
| const shouldWrite = | ||
| tStat.status === 'rejected' || | ||
| sStat.value.size !== tStat.value.size || | ||
| sStat.value.mtimeMs > tStat.value.mtimeMs; | ||
|
|
||
| if (!shouldWrite) { | ||
| continue; | ||
| } | ||
|
|
||
| const fileContent = await readFile(sourcePath); | ||
|
|
||
| await writeFile(targetPath, fileContent); | ||
|
Comment on lines
+17
to
+36
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is not "safe", there's still a TOCTOU: you call
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, this PR doesn't prevent concurrent reads/writes, it just "prevents" the fs issues you were facing. It's safe in the sense that it shouldn't fail due to concurrency issues, or very unlikely.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Well I'm still getting |
||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.