Skip to content

Commit

Permalink
Write tmp files to the OS tmp directory (#9580)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcompiles authored Mar 14, 2024
1 parent e9bf419 commit d56bf45
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion packages/core/fs/src/NodeFS.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type {
import fs from 'graceful-fs';
import nativeFS from 'fs';
import ncp from 'ncp';
import path from 'path';
import {tmpdir} from 'os';
import {promisify} from 'util';
import {registerSerializableClass} from '@parcel/core';
import {hashFile} from '@parcel/utils';
Expand Down Expand Up @@ -222,11 +224,43 @@ try {
//
}

let useOsTmpDir;
function shouldUseOsTmpDir(filePath) {
if (useOsTmpDir != null) {
return useOsTmpDir;
}
try {
const tmpDir = tmpdir();
nativeFS.accessSync(
tmpDir,
nativeFS.constants.R_OK | nativeFS.constants.W_OK,
);
const tmpDirStats = nativeFS.statSync(tmpDir);
const filePathStats = nativeFS.statSync(filePath);
// Check the tmpdir is on the same partition as the target directory.
// This is required to ensure renaming is an atomic operation.
useOsTmpDir = tmpDirStats.dev === filePathStats.dev;
} catch (e) {
// We don't have read/write access to the OS tmp directory
useOsTmpDir = false;
}
return useOsTmpDir;
}

// Generate a temporary file path used for atomic writing of files.
function getTempFilePath(filePath: FilePath) {
writeStreamCalls = writeStreamCalls % Number.MAX_SAFE_INTEGER;

let tmpFilePath = filePath;

// If possible, write the tmp file to the OS tmp directory
// This reduces the amount of FS events the watcher needs to process during the build
if (shouldUseOsTmpDir(filePath)) {
tmpFilePath = path.join(tmpdir(), path.basename(filePath));
}

return (
filePath +
tmpFilePath +
'.' +
process.pid +
(threadId != null ? '.' + threadId : '') +
Expand Down

0 comments on commit d56bf45

Please sign in to comment.