|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -import { copyFile, readdir, stat, constants } from 'node:fs/promises'; |
| 3 | +import { copyFile, readdir, stat } from 'node:fs/promises'; |
4 | 4 | import { join } from 'node:path'; |
5 | 5 |
|
6 | 6 | /** |
7 | | - * Attempts to copy a file forcibly (`COPYFILE_FICLONE_FORCE`. Otherwise, falls back to a time-based check approach) |
| 7 | + * Copies files from source to target directory, skipping files that haven't changed. |
| 8 | + * Uses synchronous stat checks for simplicity and copyFile for atomic operations. |
8 | 9 | * |
9 | 10 | * @param {string} srcDir - Source directory path |
10 | 11 | * @param {string} targetDir - Target directory path |
11 | 12 | */ |
12 | 13 | export async function safeCopy(srcDir, targetDir) { |
13 | | - try { |
14 | | - await copyFile(srcDir, targetDir, constants.COPYFILE_FICLONE); |
15 | | - } catch (err) { |
16 | | - if (err?.syscall !== 'copyfile') { |
17 | | - throw err; |
18 | | - } |
19 | | - |
20 | | - const files = await readdir(srcDir); |
| 14 | + const files = await readdir(srcDir); |
21 | 15 |
|
22 | | - for (const file of files) { |
23 | | - const sourcePath = join(srcDir, file); |
24 | | - const targetPath = join(targetDir, file); |
| 16 | + for (const file of files) { |
| 17 | + const sourcePath = join(srcDir, file); |
| 18 | + const targetPath = join(targetDir, file); |
25 | 19 |
|
26 | | - const [sStat, tStat] = await Promise.all([ |
27 | | - stat(sourcePath), |
28 | | - stat(targetPath), |
29 | | - ]).catch(() => []); |
| 20 | + const tStat = await stat(targetPath).catch(() => undefined); |
30 | 21 |
|
31 | | - const shouldWrite = |
32 | | - !tStat || sStat.size !== tStat.size || sStat.mtimeMs > tStat.mtimeMs; |
| 22 | + // If target doesn't exist, copy immediately |
| 23 | + if (!tStat) { |
| 24 | + await copyFile(sourcePath, targetPath); |
| 25 | + continue; |
| 26 | + } |
33 | 27 |
|
34 | | - if (!shouldWrite) { |
35 | | - continue; |
36 | | - } |
| 28 | + // Target exists, check if we need to update |
| 29 | + const sStat = await stat(sourcePath); |
37 | 30 |
|
| 31 | + // Skip if target has same size and source is not newer |
| 32 | + if (sStat.size !== tStat.size || sStat.mtimeMs > tStat.mtimeMs) { |
38 | 33 | await copyFile(sourcePath, targetPath); |
39 | 34 | } |
40 | 35 | } |
|
0 commit comments