8000 Update patch to check the env var in real-time · GitklcHub/rushstack@72c2550 · GitHub
[go: up one dir, main page]

Skip to content

Commit 72c2550

Browse files
committed
Update patch to check the env var in real-time
1 parent 2a6cb08 commit 72c2550

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

heft-plugins/heft-jest-plugin/includes/jestScriptTransformerPatch.js

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,6 @@ const patchName = path.basename(__filename);
1616
const HEFT_JEST_DISABLE_CACHE_ENV_VARIABLE = 'HEFT_JEST_DISABLE_CACHE';
1717

1818
function applyPatch() {
19-
// Only apply the patch if the environment variable is set
20-
if (!process.env[HEFT_JEST_DISABLE_CACHE_ENV_VARIABLE]) {
21-
return;
22-
}
23-
2419
try {
2520
let contextFolder = __dirname;
2621
// Resolve the "@jest/core" package relative to heft-jest-plugin
@@ -54,7 +49,20 @@ function patchScriptTransformer(scriptPath) {
5449
const functionsToReplace = ['readCacheFile', 'writeCacheFile'];
5550

5651
for (const functionName of functionsToReplace) {
57-
const match = scriptContent.match(new RegExp(`^\\s*const ${functionName} =`, 'm'));
52+
const originalFunctionName = `${functionName}Original`;
53+
54+
// First, attempt to remove the existing patch, if one is present
55+
let match = scriptContent.match(new RegExp(`^\\s*const ${originalFunctionName} =`, 'm'));
56+
let originalFunctionContent;
57+
if (match) {
58+
const startIndex = match.index;
59+
const endIndex = scriptContent.indexOf('};', startIndex) + 2;
60+
originalFunctionContent = scriptContent.slice(startIndex, endIndex);
61+
scriptContent = scriptContent.slice(0, startIndex) + scriptContent.slice(endIndex);
62+
}
63+
64+
// Then, attempt to find the function to patch
65+
match = scriptContent.match(new RegExp(`^\\s*const ${functionName} =`, 'm'));
5866
if (!match) {
5967
throw new Error(
6068
`The ${JSON.stringify(functionName)} function was not found in the file ${JSON.stringify(scriptPath)}`
@@ -63,9 +71,23 @@ function patchScriptTransformer(scriptPath) {
6371

6472
const startIndex = match.index;
6573
const endIndex = scriptContent.indexOf('};', startIndex) + 2;
74+
75+
// If we already have the original function content, no need to extract it again
76+
if (originalFunctionContent === undefined) {
77+
originalFunctionContent = scriptContent
78+
.slice(startIndex, endIndex)
79+
.replace(`const ${functionName} =`, `const ${originalFunctionName} =`);
80+
}
81+
6682
scriptContent =
6783
scriptContent.slice(0, startIndex) +
68-
`const ${functionName} = () => {};` +
84+
`${originalFunctionContent}\n` +
85+
`const ${functionName} = (...args) => {\n` +
86+
` if (process.env['${HEFT_JEST_DISABLE_CACHE_ENV_VARIABLE}']) {\n` +
87+
` return;\n` +
88+
` }\n` +
89+
` return ${originalFunctionName}(...args);\n` +
90+
'};' +
6991
scriptContent.slice(endIndex);
7092
}
7193

0 commit comments

Comments
 (0)
0