|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -import { readFile, writeFile, stat, readdir } from 'node:fs/promises'; |
| 3 | +import { statSync, constants } from 'node:fs'; |
| 4 | +import { copyFile, readdir } from 'node:fs/promises'; |
4 | 5 | import { join } from 'node:path'; |
5 | 6 |
|
6 | 7 | /** |
7 | | - * Safely copies files from source to target directory, skipping files that haven't changed |
8 | | - * based on file stats (size and modification time) |
| 8 | + * Copies files from source to target directory, skipping files that haven't changed. |
| 9 | + * Uses synchronous stat checks for simplicity and copyFile for atomic operations. |
9 | 10 | * |
10 | 11 | * @param {string} srcDir - Source directory path |
11 | 12 | * @param {string} targetDir - Target directory path |
12 | 13 | */ |
13 | 14 | export async function safeCopy(srcDir, targetDir) { |
14 | 15 | const files = await readdir(srcDir); |
15 | 16 |
|
16 | | - for (const file of files) { |
| 17 | + const promises = files.map(file => { |
17 | 18 | const sourcePath = join(srcDir, file); |
18 | 19 | const targetPath = join(targetDir, file); |
19 | 20 |
|
20 | | - const [sStat, tStat] = await Promise.allSettled([ |
21 | | - stat(sourcePath), |
22 | | - stat(targetPath), |
23 | | - ]); |
| 21 | + const tStat = statSync(targetPath, { throwIfNoEntry: false }); |
24 | 22 |
|
25 | | - const shouldWrite = |
26 | | - tStat.status === 'rejected' || |
27 | | - sStat.value.size !== tStat.value.size || |
28 | | - sStat.value.mtimeMs > tStat.value.mtimeMs; |
29 | | - |
30 | | - if (!shouldWrite) { |
31 | | - continue; |
| 23 | + if (tStat === undefined) { |
| 24 | + return copyFile(sourcePath, targetPath, constants.COPYFILE_FICLONE); |
32 | 25 | } |
33 | 26 |
|
34 | | - const fileContent = await readFile(sourcePath); |
| 27 | + const sStat = statSync(sourcePath); |
| 28 | + |
| 29 | + if (sStat.size !== tStat.size || sStat.mtimeMs > tStat.mtimeMs) { |
| 30 | + return copyFile(sourcePath, targetPath, constants.COPYFILE_FICLONE); |
| 31 | + } |
| 32 | + }); |
35 | 33 |
|
36 | | - await writeFile(targetPath, fileContent); |
37 | | - } |
| 34 | + await Promise.all(promises); |
38 | 35 | } |
0 commit comments