From 02c227fb558bdc8f13d5a59a17faa95725bb3903 Mon Sep 17 00:00:00 2001 From: yoyo930021 Date: Wed, 6 Nov 2019 16:25:45 +0800 Subject: [PATCH] fix(typescript-estree): record code hash for only update when necessary --- .../src/create-program/createWatchProgram.ts | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/packages/typescript-estree/src/create-program/createWatchProgram.ts b/packages/typescript-estree/src/create-program/createWatchProgram.ts index beabcdd68886..9223107986af 100644 --- a/packages/typescript-estree/src/create-program/createWatchProgram.ts +++ b/packages/typescript-estree/src/create-program/createWatchProgram.ts @@ -45,7 +45,7 @@ const programFileListCache = new Map>(); */ const tsconfigLastModifiedTimestampCache = new Map(); -const parsedFilesSeen = new Set(); +const parsedFilesSeenHash = new Map(); /** * Clear all of the parser caches. @@ -55,7 +55,7 @@ function clearCaches(): void { knownWatchProgramMap.clear(); fileWatchCallbackTrackingMap.clear(); folderWatchCallbackTrackingMap.clear(); - parsedFilesSeen.clear(); + parsedFilesSeenHash.clear(); programFileListCache.clear(); tsconfigLastModifiedTimestampCache.clear(); } @@ -104,6 +104,19 @@ function diagnosticReporter(diagnostic: ts.Diagnostic): void { ); } +/** + * Hash content for compare content. + * @param content hashed contend + * @returns hashed result + */ +function createHash(content: string): string { + // No ts.sys in browser environments. + if (ts.sys && ts.sys.createHash) { + return ts.sys.createHash(content); + } + return content; +} + /** * Calculate project environments using options provided by consumer and paths from config * @param code The code being linted @@ -125,10 +138,10 @@ function getProgramsForProjects( currentLintOperationState.filePath = filePath; // Update file version if necessary - // TODO: only update when necessary, currently marks as changed on every lint const fileWatchCallbacks = fileWatchCallbackTrackingMap.get(filePath); + const codeHash = createHash(code); if ( - parsedFilesSeen.has(filePath) && + parsedFilesSeenHash.get(filePath) !== codeHash && fileWatchCallbacks && fileWatchCallbacks.size > 0 ) { @@ -232,11 +245,15 @@ function createWatchProgram( const oldReadFile = watchCompilerHost.readFile; watchCompilerHost.readFile = (filePathIn, encoding): string | undefined => { const filePath = getCanonicalFileName(filePathIn); - parsedFilesSeen.add(filePath); - return path.normalize(filePath) === + const fileContent = + path.normalize(filePath) === path.normalize(currentLintOperationState.filePath) - ? currentLintOperationState.code - : oldReadFile(filePath, encoding); + ? currentLintOperationState.code + : oldReadFile(filePath, encoding); + if (fileContent) { + parsedFilesSeenHash.set(filePath, createHash(fileContent)); + } + return fileContent; }; // ensure process reports error on failure instead of exiting process immediately