-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
measure.js
160 lines (136 loc) · 4.32 KB
/
measure.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/**
* Copyright IBM Corp. 2018, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const chalk = require('chalk');
const Table = require('cli-table');
const filesize = require('filesize');
const fs = require('fs-extra');
const path = require('path');
const glob = require('../glob');
const gzipSize = require('gzip-size');
const { reporter } = require('@carbon/cli-reporter');
const compile = require('../tools/compile');
async function measure(pattern, { cwd, output, ignore = [] }) {
const outputFilename = 'results.json';
const outputFilepath = output
? path.join(output, outputFilename)
: path.join(cwd, outputFilename);
reporter.info(`Running in: ${cwd}`);
reporter.info(`Checking pattern: '${pattern}', ignoring: '${ignore}'`);
reporter.info(`Writing results to: ${outputFilepath}`);
const files = await glob(pattern, {
cwd,
ignore,
});
const results = await Promise.all(
compile(files.map(file => path.join(cwd, file)))
);
const errors = results.reduce((acc, result) => {
if (result.error) {
const error = result.error;
error.filepath = result.filepath;
return acc.concat(error);
}
return acc;
}, []);
if (errors.length > 0) {
errors.forEach(error => {
const { formatted, filepath } = error;
reporter.error(`Error compiling ${path.relative(cwd, filepath)}`);
console.log(chalk.gray(formatted));
});
process.exit(1);
return;
}
// At this point, we've successfully compiled all of our scss files and now we
// need to start getting the corresponding size values and compare them to
// previous results, if they exist.
const prevResults = (await fs.pathExists(outputFilepath))
? await fs.readJson(outputFilepath)
: {};
const nextResults = await Promise.all(
results.map(async ({ result, filepath }) => ({
filename: path.basename(filepath),
package: await findPackageFor(filepath),
size: Buffer.byteLength(result.css),
gzip: await gzipSize(result.css),
}))
);
await fs.writeJson(outputFilepath, nextResults, {
spaces: 2,
});
console.log(printResults(prevResults, nextResults));
}
// Rough heuristic used to find the package name for a given file. Idea is to
// move upwards looking for directories that have a `package.json` file. Once we
// find one, we report back the name from that file.
async function findPackageFor(filepath) {
let directory = filepath;
while (directory !== '/') {
const directoryToSearch = path.dirname(directory);
const files = await fs.readdir(directoryToSearch);
if (files.indexOf('package.json') !== -1) {
const packageJson = await fs.readJson(
path.join(directoryToSearch, 'package.json')
);
return packageJson.name;
}
directory = path.resolve(directory, '..');
}
throw new Error(`Unable to find package for: ${filepath}`);
}
function printResults(prevResults, results) {
const resultsHeaders = [
'Package',
'File',
'Prev Size',
'Current Size',
'Diff',
'Prev Gzip',
'Current Gzip',
'Diff',
];
const table = new Table({
head: resultsHeaders.map(label => chalk.gray.yellow(label)),
});
results.forEach(result => {
const prevResult =
prevResults.find(prevResult => {
return (
prevResult.filename === result.filename &&
prevResult.package === result.package
);
}) || {};
table.push([
chalk.white.bold(result.package),
chalk.white.bold(result.filename),
chalk.gray.bold(prevResult.size || 0),
chalk.white.bold(filesize(result.size)),
percentChangeString(fractionalChange(prevResult.size, result.size)),
chalk.gray.bold(prevResult.gzip || 0),
chalk.white.bold(filesize(result.gzip)),
percentChangeString(fractionalChange(prevResult.gzip, result.gzip)),
]);
});
return table.toString();
}
function fractionalChange(prev, current) {
return (current - prev) / prev;
}
function percentChangeString(change) {
if (!isFinite(change)) {
// When a new package is created
return 'n/a';
}
const formatted = (change * 100).toFixed(1);
if (/^-|^0(?:\.0+)$/.test(formatted)) {
return `${formatted}%`;
} else {
return `+${formatted}%`;
}
}
module.exports = measure;