forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dangerfile.js
195 lines (170 loc) · 5.57 KB
/
dangerfile.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// inspire by reacts dangerfile
// danger has to be the first thing required!
const { danger, markdown } = require('danger');
const { exec } = require('child_process');
const { loadComparison } = require('./scripts/sizeSnapshot');
const parsedSizeChangeThreshold = 300;
const gzipSizeChangeThreshold = 100;
/**
* executes a git subcommand
* @param {any} args
*/
function git(args) {
return new Promise((resolve, reject) => {
exec(`git ${args}`, (err, stdout) => {
if (err) {
reject(err);
} else {
resolve(stdout.trim());
}
});
});
}
const UPSTREAM_REMOTE = 'danger-upstream';
/**
* This is mainly used for local development. It should be executed before the
* scripts exit to avoid adding internal remotes to the local machine. This is
* not an issue in CI.
*/
async function cleanup() {
await git(`remote remove ${UPSTREAM_REMOTE}`);
}
/**
* creates a callback for Object.entries(comparison).filter that excludes every
* entry that does not exceed the given threshold values for parsed and gzip size
*
* @param {number} parsedThreshold
* @param {number} gzipThreshold
*/
function createComparisonFilter(parsedThreshold, gzipThreshold) {
return comparisonEntry => {
const [, snapshot] = comparisonEntry;
return (
Math.abs(snapshot.parsed.absoluteDiff) >= parsedThreshold ||
Math.abs(snapshot.gzip.absoluteDiff) >= gzipThreshold
);
};
}
/**
* checks if the bundle is of a package e.b. `@material-ui/core` but not
* `@material-ui/core/Paper`
* @param {[string, any]} comparisonEntry
*/
function isPackageComparison(comparisonEntry) {
const [bundleKey] = comparisonEntry;
return /^@[\w-]+\/[\w-]+$/.test(bundleKey);
}
/**
* Generates a user-readable string from a percentage change
* @param {number} change
* @param {string} goodEmoji emoji on reduction
* @param {string} badEmoji emoji on increase
*/
function addPercent(change, goodEmoji = '', badEmoji = ':small_red_triangle:') {
const formatted = (change * 100).toFixed(2);
if (/^-|^0(?:\.0+)$/.test(formatted)) {
return `${formatted}% ${goodEmoji}`;
}
return `+${formatted}% ${badEmoji}`;
}
/**
* Generates a Markdown table
* @param {{ label: string, align: 'left' | 'center' | 'right'}[]} headers
* @param {string[][]} body
* @returns {string}
*/
function generateMDTable(headers, body) {
const headerRow = headers.map(header => header.label);
const alignmentRow = headers.map(header => {
if (header.align === 'right') {
return ' ---:';
}
if (header.align === 'center') {
return ':---:';
}
return ' --- ';
});
return [headerRow, alignmentRow, ...body].map(row => row.join(' | ')).join('\n');
}
function generateEmphasizedChange([bundle, { parsed, gzip }]) {
// increase might be a bug fix which is a nice thing. reductions are always nice
const changeParsed = addPercent(parsed.relativeDiff, ':heart_eyes:', '');
const changeGzip = addPercent(gzip.relativeDiff, ':heart_eyes:', '');
return `**${bundle}**: parsed: ${changeParsed}, gzip: ${changeGzip}`;
}
async function run() {
// Use git locally to grab the commit which represents the place
// where the branches differ
const upstreamRepo = danger.github.pr.base.repo.full_name;
const upstreamRef = danger.github.pr.base.ref;
try {
await git(`remote add ${UPSTREAM_REMOTE} https://github.com/${upstreamRepo}.git`);
} catch (err) {
// ignore if it already exist for local testing
}
await git(`fetch ${UPSTREAM_REMOTE}`);
const mergeBaseCommit = await git(`merge-base HEAD ${UPSTREAM_REMOTE}/${upstreamRef}`);
const commitRange = `${mergeBaseCommit}...${danger.github.pr.head.sha}`;
const comparison = await loadComparison(mergeBaseCommit, upstreamRef);
const results = Object.entries(comparison.bundles);
const anyResultsChanges = results.filter(createComparisonFilter(1, 1));
if (anyResultsChanges.length > 0) {
const importantChanges = results
.filter(createComparisonFilter(parsedSizeChangeThreshold, gzipSizeChangeThreshold))
.filter(isPackageComparison)
.map(generateEmphasizedChange);
// have to guard against empty strings
if (importantChanges.length > 0) {
markdown(importantChanges.join('\n'));
}
const detailsTable = generateMDTable(
[
{ label: 'bundle' },
{ label: 'parsed diff', align: 'right' },
{ label: 'gzip diff', align: 'right' },
{ label: 'prev parsed', align: 'right' },
{ label: 'current parsed', align: 'right' },
{ label: 'prev gzip', align: 'right' },
{ label: 'current gzip', align: 'right' },
],
results.map(([bundle, { parsed, gzip }]) => {
return [
bundle,
addPercent(parsed.relativeDiff),
addPercent(gzip.relativeDiff),
parsed.previous.toLocaleString(),
parsed.current.toLocaleString(),
gzip.previous.toLocaleString(),
gzip.current.toLocaleString(),
];
}),
);
const details = `
<details>
<summary>Details of bundle changes.</summary>
<p>Comparing: ${commitRange}</p>
${detailsTable}
</details>`;
markdown(details);
} else {
// this can later be removed to reduce PR noise. It is kept for now for debug
// purposes only. DangerJS will swallow console.logs if it completes successfully
markdown(`No bundle size changes comparing ${commitRange}`);
}
}
(async () => {
let exitCode = 0;
try {
await run();
} catch (err) {
console.error(err);
exitCode = 1;
}
try {
await cleanup();
} catch (err) {
console.error(err);
exitCode = 1;
}
process.exit(exitCode);
})();