-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcache.ts
63 lines (51 loc) · 1.47 KB
/
cache.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
import fsp from 'fs/promises';
import { hashElement } from 'folder-hash';
import { exists } from './common.ts';
export class Cache {
folder: string;
generatedFiles: string[];
filesToCache: string[];
cacheFile: string;
constructor({
folder,
generatedFiles,
filesToCache,
cacheFile,
}: {
folder: string;
generatedFiles: string[];
filesToCache: string[];
cacheFile: string;
}) {
this.folder = folder;
this.generatedFiles = generatedFiles;
this.filesToCache = filesToCache;
this.cacheFile = cacheFile;
}
async computeHash(): Promise<string> {
let hash = '';
for (const generatedFile of this.generatedFiles) {
hash += (await hashElement(`${this.folder}/${generatedFile}`)).hash;
}
for (const fileToCache of this.filesToCache) {
hash += (await hashElement(`${this.folder}/${fileToCache}`)).hash;
}
return hash;
}
async isValid(): Promise<boolean> {
if (!(await exists(this.cacheFile))) {
return false;
}
// hashElement throws when the folder is missing, we need to make sure it exists.
for (const generatedFiles of this.generatedFiles) {
if (!(await exists(`${this.folder}/${generatedFiles}`))) {
return false;
}
}
const storedHash = (await fsp.readFile(this.cacheFile)).toString();
return storedHash === (await this.computeHash());
}
async store(): Promise<void> {
await fsp.writeFile(this.cacheFile, await this.computeHash());
}
}