@@ -5,14 +5,30 @@ import { Range } from "./Range";
5
5
const sanitizeFilePath = ( filePath : string ) =>
6
6
JSON . stringify ( path . resolve ( filePath ) ) ;
7
7
8
- const getDiffForFile = ( filePath : string , staged = false ) : string =>
9
- child_process
10
- . execSync (
11
- `git diff --diff-filter=ACM --unified=0 HEAD ${
12
- staged ? " --staged" : ""
13
- } -- ${ sanitizeFilePath ( filePath ) } `
14
- )
15
- . toString ( ) ;
8
+ const diffCacheKey = ( filePath : string , staged : boolean ) : string =>
9
+ JSON . stringify ( [ path . resolve ( filePath ) , staged ] ) ;
10
+
11
+ const diffCache = new Map < string , string > ( ) ;
12
+
13
+ const getDiffForFile = ( filePath : string , staged = false ) : string => {
14
+ // Get diff entry from cache
15
+ const cachedDiff = diffCache . get ( diffCacheKey ( filePath , staged ) ) ;
16
+ if ( cachedDiff ) {
17
+ // If entry is not falsy return it
18
+ return cachedDiff ;
19
+ } else {
20
+ // Otherwise spawn child_process set it in cache and return it
21
+ const diff = child_process
22
+ . execSync (
23
+ `git diff --diff-filter=ACM --unified=0 HEAD ${
24
+ staged ? " --staged" : ""
25
+ } -- ${ sanitizeFilePath ( filePath ) } `
26
+ )
27
+ . toString ( ) ;
28
+ diffCache . set ( diffCacheKey ( filePath , staged ) , diff ) ;
29
+ return diff ;
30
+ }
31
+ } ;
16
32
17
33
const isHunkHeader = ( input : string ) => {
18
34
const hunkHeaderRE = new RegExp ( / ^ @ @ .* @ @ / g) ;
0 commit comments