|
4 | 4 | import { FileSystem } from '@rushstack/node-core-library'; |
5 | 5 | import path from 'path'; |
6 | 6 |
|
7 | | -export function copyFiles(originPaths: string[], outputPath: string) { |
8 | | - let destinationPath = path.resolve(outputPath); |
| 7 | +export function copyFiles(originPaths: string[], outputPath: string, skipIfPossible: boolean = true) { |
| 8 | + const destinationPath = path.resolve(outputPath); |
| 9 | + const MTIME_TOLERANCE_MS = 1000; // 1 second tolerance, avoid the case when file copying across system get delayed |
9 | 10 | for (const originPath of originPaths) { |
10 | 11 | const inputPath = path.resolve(originPath); |
11 | 12 | const pathStats = FileSystem.getLinkStatistics(inputPath); |
12 | 13 | if (pathStats.isDirectory()) { |
13 | 14 | console.log(`Copying folder ${inputPath} to ${destinationPath}`); |
14 | 15 | } else { |
15 | 16 | const filename = path.parse(inputPath).base; |
16 | | - destinationPath = path.resolve(destinationPath, filename); |
17 | | - console.log(`Copying file ${inputPath} to ${destinationPath}`); |
| 17 | + const fileDestinationPath = path.resolve(destinationPath, filename); |
| 18 | + |
| 19 | + let shouldCopy = true; |
| 20 | + if (skipIfPossible) { |
| 21 | + try { |
| 22 | + const destFileStats = FileSystem.getStatistics(fileDestinationPath); |
| 23 | + // If sizes differ => must copy |
| 24 | + if (destFileStats.size !== pathStats.size) { |
| 25 | + shouldCopy = true; |
| 26 | + } else { |
| 27 | + // sizes equal -> check mtimes within tolerance |
| 28 | + const srcMtime = pathStats.mtimeMs ?? pathStats.mtime.getTime(); |
| 29 | + const destMtime = destFileStats.mtimeMs ?? destFileStats.mtime.getTime(); |
| 30 | + if (Math.abs(srcMtime - destMtime) > MTIME_TOLERANCE_MS) { |
| 31 | + shouldCopy = true; |
| 32 | + } else { |
| 33 | + // sizes equal and mtimes within tolerance -> skip copy |
| 34 | + shouldCopy = false; |
| 35 | + } |
| 36 | + } |
| 37 | + } catch { |
| 38 | + shouldCopy = true; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if (!shouldCopy) { |
| 43 | + console.log(`Skipping copy for ${inputPath}; no change detected`); |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + console.log(`Copying file ${inputPath} to ${fileDestinationPath}`); |
| 48 | + FileSystem.copyFiles({ |
| 49 | + sourcePath: inputPath, |
| 50 | + destinationPath: fileDestinationPath, |
| 51 | + preserveTimestamps: true, |
| 52 | + }); |
| 53 | + continue; |
18 | 54 | } |
19 | 55 |
|
20 | 56 | FileSystem.copyFiles({ |
21 | 57 | sourcePath: inputPath, |
22 | 58 | destinationPath: destinationPath, |
| 59 | + preserveTimestamps: true, |
23 | 60 | }); |
24 | 61 | } |
25 | 62 | } |
0 commit comments