/
file-hasher-base.ts
80 lines (69 loc) · 2 KB
/
file-hasher-base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { workspaceRoot } from 'nx/src/utils/app-root';
import { performance } from 'perf_hooks';
import { defaultHashing } from './hashing-impl';
import { FileData } from 'nx/src/shared/project-graph';
import { joinPathFragments } from 'nx/src/utils/path';
export abstract class FileHasherBase {
protected fileHashes: Map<string, string>;
protected isInitialized = false;
clear(): void {
this.fileHashes = new Map<string, string>();
this.isInitialized = false;
}
abstract init(): Promise<void>;
abstract hashFiles(files: string[]): Promise<Map<string, string>>;
async ensureInitialized() {
if (!this.isInitialized) {
await this.init();
}
}
allFileData(): FileData[] {
const res = [];
this.fileHashes.forEach((hash, file) => {
res.push({
file,
hash,
});
});
res.sort((x, y) => x.file.localeCompare(y.file));
return res;
}
incrementalUpdate(
updatedFiles: Map<string, string>,
deletedFiles: string[] = []
): void {
performance.mark('incremental hashing:start');
updatedFiles.forEach((hash, filename) => {
this.fileHashes.set(filename, hash);
});
for (const deletedFile of deletedFiles) {
this.fileHashes.delete(deletedFile);
}
performance.mark('incremental hashing:end');
performance.measure(
'incremental hashing',
'incremental hashing:start',
'incremental hashing:end'
);
}
hashFile(path: string): string {
if (!this.fileHashes) {
throw new Error('FileHasher is invoked before being initialized');
}
const relativePath = path.startsWith(workspaceRoot)
? path.substr(workspaceRoot.length + 1)
: path;
if (this.fileHashes.has(relativePath)) {
return this.fileHashes.get(relativePath);
} else {
try {
// this has to be absolute to avoid issues with cwd
return defaultHashing.hashFile(
joinPathFragments(workspaceRoot, relativePath)
);
} catch {
return '';
}
}
}
}