-
Notifications
You must be signed in to change notification settings - Fork 106
/
Cache.ts
46 lines (36 loc) · 1.3 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
import debug from 'debug';
import envPaths from 'env-paths';
import * as fs from 'fs-extra';
import * as path from 'path';
import * as url from 'url';
import * as sanitize from 'sanitize-filename';
const d = debug('@electron/get:cache');
const defaultCacheRoot = envPaths('electron', {
suffix: '',
}).cache;
export class Cache {
constructor(private cacheRoot = defaultCacheRoot) {}
public getCachePath(downloadUrl: string, fileName: string): string {
const { search, hash, ...rest } = url.parse(downloadUrl);
const strippedUrl = url.format(rest);
const sanitizedUrl = sanitize(strippedUrl);
return path.resolve(this.cacheRoot, sanitizedUrl, fileName);
}
public async getPathForFileInCache(url: string, fileName: string): Promise<string | null> {
const cachePath = this.getCachePath(url, fileName);
if (await fs.pathExists(cachePath)) {
return cachePath;
}
return null;
}
public async putFileInCache(url: string, currentPath: string, fileName: string): Promise<string> {
const cachePath = this.getCachePath(url, fileName);
d(`Moving ${currentPath} to ${cachePath}`);
if (await fs.pathExists(cachePath)) {
d('* Replacing existing file');
await fs.remove(cachePath);
}
await fs.move(currentPath, cachePath);
return cachePath;
}
}