@@ -16,11 +16,6 @@ const patchName = path.basename(__filename);
16
16
const HEFT_JEST_DISABLE_CACHE_ENV_VARIABLE = 'HEFT_JEST_DISABLE_CACHE' ;
17
17
18
18
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
-
24
19
try {
25
20
let contextFolder = __dirname ;
26
21
// Resolve the "@jest/core" package relative to heft-jest-plugin
@@ -54,7 +49,20 @@ function patchScriptTransformer(scriptPath) {
54
49
const functionsToReplace = [ 'readCacheFile' , 'writeCacheFile' ] ;
55
50
56
51
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' ) ) ;
58
66
if ( ! match ) {
59
67
throw new Error (
60
68
`The ${ JSON . stringify ( functionName ) } function was not found in the file ${ JSON . stringify ( scriptPath ) } `
@@ -63,9 +71,23 @@ function patchScriptTransformer(scriptPath) {
63
71
64
72
const startIndex = match . index ;
65
73
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
+
66
82
scriptContent =
67
83
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
+ '};' +
69
91
scriptContent . slice ( endIndex ) ;
70
92
}
71
93
0 commit comments