Skip to content

Commit

Permalink
[ci] Proper dangerJS report
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon committed Feb 19, 2019
1 parent cefd80b commit ccce192
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 41 deletions.
147 changes: 136 additions & 11 deletions dangerfile.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// inspire by reacts dangerfile
const { exec } = require('child_process');
// 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
Expand All @@ -19,22 +23,143 @@ function git(args) {
});
}

const upstreamRemote = 'danger-upstream';

async function cleanup() {
await git(`remote remove ${upstreamRemote}`);
}

function createComparisonFilter(parsedThreshold, gzipThreshold) {
return ([, { parsed, gzip }]) => {
return (
Math.abs(parsed.absoluteDiff) >= parsedThreshold ||
Math.abs(gzip.absoluteDiff) >= gzipThreshold
);
};
}

/**
* checks if the bundle is of a package e.b. `@material-ui/core` but not
* `@material-ui/core/Paper`
* @param {[string]} comparison entry
*/
function isPackageComparison([bundle]) {
return /^@[\w-]+\/[\w-]+$/.test(bundle);
}

/**
* Generates a user-readable string from a percentage change
* @param {number} change
* @param {boolean} includeEmoji
*/
function addPercent(change, includeEmoji) {
if (!Number.isFinite(change)) {
// When a new package is created
return 'n/a';
}
const formatted = (change * 100).toFixed(2);
if (/^-|^0(?:\.0+)$/.test(formatted)) {
return `${formatted}%`;
}
if (includeEmoji) {
return `:small_red_triangle:+${formatted}%`;
}
return `+${formatted}%`;
}

/**
* Generates a Markdown table
* @param {string[]} headers
* @param {string[][]} body
*/
function generateMDTable(headers, body) {
const tableHeaders = [headers.join(' | '), headers.map(() => ' --- ').join(' | ')];

const tablebody = body.map(r => r.join(' | '));
return `${tableHeaders.join('\n')}\n${tablebody.join('\n')}`;
}

function generateEmphasizedChange([bundle, { parsed, gzip }]) {
const changeParsed = addPercent(parsed.relativeDiff, true);
const changeGzip = addPercent(gzip.relativeDiff, true);

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;
await git(`remote add upstream https://github.com/${upstreamRepo}.git`);
await git('fetch upstream');
const mergeBaseCommit = await git(`merge-base HEAD upstream/${upstreamRef}`);
try {
await git(`remote add ${upstreamRemote} https://github.com/${upstreamRepo}.git`);
} catch (err) {
// ignore if it already exist for local testing
}
await git(`fetch ${upstreamRemote}`);
const mergeBaseCommit = await git(`merge-base HEAD ${upstreamRemote}/${upstreamRef}`);

markdown('```json\n' + JSON.stringify(danger.github.pr.base.ref, null, 2) + '\n```');
const comparison = await loadComparison(mergeBaseCommit, upstreamRef);
const results = Object.entries(comparison.bundles);
const anyResultsChanges = results.filter(createComparisonFilter(0, 0));

const comparison = await loadComparison(mergeBaseCommit);
console.log(comparison);
if (anyResultsChanges.length > 0) {
markdown('This PR introduced some changes to the bundle size.');

const importantChanges = results
.filter(createComparisonFilter(parsedSizeChangeThreshold, gzipSizeChangeThreshold))
.filter(isPackageComparison)
.map(generateEmphasizedChange);
markdown(importantChanges.join('\n'));

const detailsTable = generateMDTable(
[
'bundle',
'parsed diff',
'gzip diff',
'prev parsed',
'current parsed',
'prev gzip',
'current gzip',
],
results.map(([bundle, { parsed, gzip }]) => {
return [
bundle,
addPercent(parsed.relativeDiff, true),
addPercent(gzip.relativeDiff, true),
parsed.previous,
parsed.current,
gzip.previous,
gzip.current,
];
}),
);

const details = `
<details>
<summary>Details of bundle changes.</summary>
<p>Comparing: ${mergeBaseCommit}...${danger.github.pr.head.sha}</p>
${detailsTable}
</details>`;

markdown(details);
}
}

run().catch(err => {
console.error(err);
process.exit(1);
});
run()
.then(() => {
process.exit(0);
})
.catch(err => {
console.error(err);
return cleanup();
})
.catch(err => {
console.error(err);
})
.finally(() => {
process.exit(1);
});
25 changes: 0 additions & 25 deletions scripts/compareSizeSnapshot.js

This file was deleted.

14 changes: 9 additions & 5 deletions scripts/sizeSnapshot/loadComparison.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ async function loadCurrentSnapshot() {

/**
* @param {string} commitId the sha of a commit
* @param {string} branch the branch containing that commit
* @param {string} ref the branch containing that commit
*/
async function loadSnapshot(commitId, branch = 'master') {
const response = await fetch(`${artifactServer}/artifacts/${branch}/${commitId}`);
async function loadSnapshot(commitId, ref = 'master') {
const response = await fetch(`${artifactServer}/artifacts/${ref}/${commitId}/size-snapshot.json`);
return response.json();
}

Expand All @@ -37,10 +37,10 @@ function uniqueKeys(...objects) {

const nullSnapshot = { gzip: Number.NaN, parsed: Number.NaN };

module.exports = async function loadComparison(parrentId) {
module.exports = async function loadComparison(parrentId, ref) {
const [currentSnapshot, previousSnapshot] = await Promise.all([
loadCurrentSnapshot(),
loadSnapshot(parrentId),
loadSnapshot(parrentId, ref),
]);

const bundleKeys = uniqueKeys(currentSnapshot, previousSnapshot);
Expand All @@ -56,10 +56,14 @@ module.exports = async function loadComparison(parrentId) {
parsed: {
previous: previousSize.parsed,
current: currentSize.parsed,
absoluteDiff: currentSize.parsed - previousSize.parsed,
relativeDiff: (currentSize.parsed / previousSize.parsed) - 1
},
gzip: {
previous: previousSize.gzip,
current: currentSize.gzip,
absoluteDiff: currentSize.gzip - previousSize.gzip,
relativeDiff: (currentSize.gzip / previousSize.gzip) - 1
},
},
];
Expand Down

0 comments on commit ccce192

Please sign in to comment.