@electron/get
Version:
Utility for downloading artifacts from different versions of Electron
63 lines • 2.34 kB
JavaScript
import debug from 'debug';
import envPaths from 'env-paths';
import fs from 'graceful-fs';
import crypto from 'node:crypto';
import path from 'node:path';
import url from 'node:url';
const d = debug('@electron/get:cache');
const defaultCacheRoot = envPaths('electron', {
suffix: '',
}).cache;
export class Cache {
cacheRoot;
constructor(cacheRoot = defaultCacheRoot) {
this.cacheRoot = cacheRoot;
}
static getCacheDirectory(downloadUrl) {
const parsedDownloadUrl = url.parse(downloadUrl);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { search, hash, pathname, ...rest } = parsedDownloadUrl;
const strippedUrl = url.format({ ...rest, pathname: path.dirname(pathname || 'electron') });
return crypto.createHash('sha256').update(strippedUrl).digest('hex');
}
getCachePath(downloadUrl, fileName) {
return path.resolve(this.cacheRoot, Cache.getCacheDirectory(downloadUrl), fileName);
}
getPathForFileInCache(url, fileName) {
const cachePath = this.getCachePath(url, fileName);
if (fs.existsSync(cachePath)) {
return cachePath;
}
return null;
}
async putFileInCache(url, currentPath, fileName) {
const cachePath = this.getCachePath(url, fileName);
d(`Moving ${currentPath} to ${cachePath}`);
if (!fs.existsSync(path.dirname(cachePath))) {
await fs.promises.mkdir(path.dirname(cachePath), { recursive: true });
}
if (fs.existsSync(cachePath)) {
d('* Replacing existing file');
await fs.promises.rm(cachePath, { recursive: true, force: true });
}
try {
await fs.promises.rename(currentPath, cachePath);
}
catch (err) {
if (err.code === 'EXDEV') {
// Cross-device link, fallback to copy and delete
await fs.promises.cp(currentPath, cachePath, {
force: true,
recursive: true,
verbatimSymlinks: true,
});
await fs.promises.rm(currentPath, { force: true, recursive: true });
}
else {
throw err;
}
}
return cachePath;
}
}
//# sourceMappingURL=Cache.js.map