|
| 1 | +/** |
| 2 | + * Attempt to get an Utimes function for the compiler's output filesystem. |
| 3 | + */ |
| 4 | +function getUtimesFunction(compiler) { |
| 5 | + if (compiler.outputFileSystem.utimes) { |
| 6 | + // Webpack 5+ on Node will use graceful-fs for outputFileSystem so utimes is always there. |
| 7 | + // Other custom outputFileSystems could also have utimes. |
| 8 | + return compiler.outputFileSystem.utimes.bind(compiler.outputFileSystem); |
| 9 | + } else if ( |
| 10 | + compiler.outputFileSystem.constructor && |
| 11 | + compiler.outputFileSystem.constructor.name === 'NodeOutputFileSystem' |
| 12 | + ) { |
| 13 | + // Default NodeOutputFileSystem can just use fs.utimes, but we need to late-import it in case |
| 14 | + // we're running in a web context and statically importing `fs` might be a bad idea. |
| 15 | + // eslint-disable-next-line global-require |
| 16 | + return require('fs').utimes; |
| 17 | + } |
| 18 | + return null; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Update the times of disk files for which we have recorded a source time |
| 23 | + * @param compiler |
| 24 | + * @param compilation |
| 25 | + * @param logger |
| 26 | + */ |
| 27 | +function updateTimes(compiler, compilation, logger) { |
| 28 | + const utimes = getUtimesFunction(compiler); |
| 29 | + let nUpdated = 0; |
| 30 | + for (const [name, asset] of Object.entries(compilation.assets)) { |
| 31 | + // eslint-disable-next-line no-underscore-dangle |
| 32 | + const times = asset.copyPluginTimes; |
| 33 | + if (times) { |
| 34 | + const targetPath = |
| 35 | + asset.existsAt || |
| 36 | + compiler.outputFileSystem.join(compiler.outputPath, name); |
| 37 | + if (!utimes) { |
| 38 | + logger.warn( |
| 39 | + `unable to update time for ${targetPath} using current file system` |
| 40 | + ); |
| 41 | + } else { |
| 42 | + // TODO: process these errors in a better way and/or wait for completion? |
| 43 | + utimes(targetPath, times.atime, times.mtime, (err) => { |
| 44 | + if (err) { |
| 45 | + logger.warn(`${targetPath}: utimes: ${err}`); |
| 46 | + } |
| 47 | + }); |
| 48 | + nUpdated += 1; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + if (nUpdated > 0) { |
| 53 | + logger.info(`times updated for ${nUpdated} copied files`); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +export default updateTimes; |
0 commit comments