-
Notifications
You must be signed in to change notification settings - Fork 67
/
packageInfo.ts
89 lines (80 loc) · 2.6 KB
/
packageInfo.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
81
82
83
84
85
86
87
88
89
import * as fs from 'fs';
import * as path from 'path';
import * as workerFarm from 'worker-farm';
import * as pkgDir from 'pkg-dir';
import {debouncePromise, DebounceError} from './debouncePromise';
import {workspace} from 'vscode';
const workers = workerFarm(require.resolve('./webpack'), ['calcSize']);
const extensionVersion = getVersion(pkgDir.sync(__dirname));
const cacheFile = path.join(__dirname, `ic-cache-${extensionVersion}`);
let sizeCache = {};
const versionsCache = {};
readSizeCache();
export async function getSize(pkg) {
try {
versionsCache[pkg.string] = versionsCache[pkg.string] || getPackageVersion(pkg);
} catch (e) {
return {...pkg, size: 0};
}
const key = `${pkg.string}#${versionsCache[pkg.string]}`;
if (sizeCache[key] === undefined || sizeCache[key] instanceof Promise) {
try {
sizeCache[key] = sizeCache[key] || calcPackageSize(pkg);
sizeCache[key] = await sizeCache[key];
saveSizeCache();
} catch (e) {
if (e === DebounceError) {
delete sizeCache[key];
throw e;
} else {
sizeCache[key] = 0;
}
}
}
return {...pkg, size: sizeCache[key]};
}
function calcPackageSize(packageInfo) {
return debouncePromise(`${packageInfo.fileName}#${packageInfo.line}`, (resolve, reject) => {
const debug = false;
const calcSize = debug ? require('./webpack').calcSize : workers.calcSize;
calcSize(
packageInfo,
result => (result.err ? reject(result.err) : resolve(result.size))
);
});
}
function readSizeCache() {
try {
if (fs.existsSync(cacheFile)) {
sizeCache = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
}
} catch (e) {
// silent error
}
}
function saveSizeCache() {
try {
const keys = Object.keys(sizeCache).filter(key => typeof sizeCache[key] === 'number' && sizeCache[key] > 0);
const cache = keys.reduce((obj, key) => ({...obj, [key]: sizeCache[key]}), {});
fs.writeFileSync(cacheFile, JSON.stringify(cache, null, 2), 'utf-8');
} catch (e) {
// silent error
}
}
function getVersion(dir) {
const pkg = path.join(dir, 'package.json');
return JSON.parse(fs.readFileSync(pkg, 'utf-8')).version;
}
function getPackageVersion(pkg): string {
const modulesDirectory = path.join(pkgDir.sync(path.dirname(pkg.fileName)), 'node_modules');
const pkgParts = pkg.name.split('/');
let pkgName = pkgParts.shift();
if (pkgName.startsWith('@')) {
pkgName = path.join(pkgName, pkgParts.shift());
}
const version = getVersion(path.join(modulesDirectory, pkgName));
return `${pkgName}@${version}`;
}
export function cleanup() {
workerFarm.end(workers);
}