Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ jobs:
job_size_check:
name: Size Check
needs: [job_get_metadata, job_get_test_matrix]
timeout-minutes: 15
timeout-minutes: 25
runs-on: ubuntu-24.04-arm
if:
github.event_name == 'pull_request' || needs.job_get_metadata.outputs.is_base_branch == 'true' ||
Expand Down
143 changes: 112 additions & 31 deletions dev-packages/size-limit-gh-action/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getExecOutput } from '@actions/exec';
import { context, getOctokit } from '@actions/github';
import { markdownTable } from 'markdown-table';
import sizeConfig from '../../.size-limit.js';
import { getArtifactForBranch } from './utils/artifacts.mjs';
import { getArtifactForBranch, getArtifactForCommit, waitForSizeCheck } from './utils/artifacts.mjs';
import { formatResults, getSizeIncreases, MAX_INCREASE_BYTES, parseResults } from './utils/results.mjs';

const OVERRIDE_LABEL = 'Accept Bundlesize Increase';
Expand All @@ -16,6 +16,7 @@ const SIZE_LIMIT_HEADING = '## size-limit report 📦 ';
const ARTIFACT_NAME = 'size-limit-action';
const ACTION_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
const RESULTS_FILE_PATH = path.join(ACTION_DIRECTORY, 'size-limit-results.json');
const BASE_PR_WAIT_MS = 10 * 60_000;
const WORKFLOW_FILE = path.basename(process.env.GITHUB_WORKFLOW_REF.split('@')[0]);
const REPO_URL = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`;

Expand All @@ -40,20 +41,23 @@ async function run() {
const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']);
const current = parseResults(stdout);

// PRs store their results too, so PRs stacked on top of them can use them as their baseline
await uploadResults(current, { required: !comparisonBranch });

if (!comparisonBranch) {
await uploadResults(current);
return;
}

const mergedBaseSha = await getMergedBaseSha(octokit);
const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch });
const basePr = mergedBaseSha && (await findBasePr(octokit, mergedBaseSha, pr));
const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch, basePr });

const hasIncrease = baseline ? getSizeIncreases(baseline.results, current, sizeConfig).length > 0 : false;
const bodyParts = [SIZE_LIMIT_HEADING];
let failure;

if (baseline) {
bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch })));
bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch, basePr })));
}

if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) {
Expand All @@ -80,9 +84,21 @@ async function run() {
}
}

async function uploadResults(results) {
await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(results), 'utf8');
await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY);
/**
* `sha` is the commit that was measured. On PRs, that is the merge commit GitHub checks out (`refs/pull/<number>/merge`),
* not the PR's head commit. Only `required` results fail the run when the upload fails, i.e. on develop where they are
* the baseline for PRs.
*/
async function uploadResults(results, { required }) {
try {
await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify({ sha: context.sha, results }), 'utf8');
await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY);
} catch (error) {
if (required) {
throw error;
}
core.warning(`Unable to upload size-limit results: ${error.message}`);
}
}

/**
Expand All @@ -99,13 +115,65 @@ async function getMergedBaseSha(octokit) {
}
}

async function downloadBaseline(octokit, githubToken, { comparisonBranch }) {
/**
* Find the open PR this PR is stacked on, and the commit of it that this PR was tested on. With GitHub stacks, a PR is
* tested on top of its base PR's test merge, whose second parent is the base PR's head. With a plain base branch, the
* merge base is the base PR's head itself. Re-runs keep their original test merge, so the base PR may have moved on
* since. Open PRs that contain this PR's head are this PR itself or stacked on top of it.
*
* The baseline is looked up by the returned commit, so a wrong guess between sibling PRs stacked on the same base only
* affects the PR number in the report. Base PRs are usually opened before the PRs stacked on them.
*/
async function findBasePr(octokit, mergedBaseSha, pr) {
try {
const found = await getArtifactForBranch(octokit, {
workflow: WORKFLOW_FILE,
branch: comparisonBranch,
artifactName: ARTIFACT_NAME,
});
const { data } = await octokit.rest.repos.getCommit({ ...context.repo, ref: mergedBaseSha });
const candidates = [mergedBaseSha, ...data.parents.slice(1).map(({ sha }) => sha)];
const prsAbove = new Set((await listOpenPrsWithCommit(octokit, pr.head.sha)).map(({ number }) => number));

for (const sha of candidates) {
const prs = (await listOpenPrsWithCommit(octokit, sha)).filter(({ number }) => !prsAbove.has(number));
const basePr =
prs.find(({ head }) => head.sha === sha) ??
prs
.filter(({ head, base }) => head.ref === pr.base.ref || base.ref === pr.base.ref)
.sort((a, b) => a.number - b.number)[0];
if (basePr) {
return { number: basePr.number, sha };
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
} catch (error) {
core.warning(`Unable to check whether this PR is stacked: ${error.message}`);
}

return undefined;
}

async function listOpenPrsWithCommit(octokit, sha) {
const { data } = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({ ...context.repo, commit_sha: sha });
return data.filter(
pr => pr.state === 'open' && pr.head.repo?.full_name === `${context.repo.owner}/${context.repo.repo}`,
);
}

/**
* A stacked PR compares only against its base PR's results, because the comparison branch would also count the base
* PR's changes. The base PR's Size Check usually runs at the same time as ours, so we wait for it.
*/
async function downloadBaseline(octokit, githubToken, { comparisonBranch, basePr }) {
try {
let found;
if (basePr) {
core.info(`Waiting for the results of base PR #${basePr.number}`);
const { sha } = basePr;
await waitForSizeCheck(octokit, { workflow: WORKFLOW_FILE, sha, timeoutMs: BASE_PR_WAIT_MS });
found = await getArtifactForCommit(octokit, { workflow: WORKFLOW_FILE, sha, artifactName: ARTIFACT_NAME });
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
} else {
found = await getArtifactForBranch(octokit, {
workflow: WORKFLOW_FILE,
branch: comparisonBranch,
artifactName: ARTIFACT_NAME,
});
}

if (!found) {
throw new Error('No artifacts found');
Expand All @@ -121,9 +189,11 @@ async function downloadBaseline(octokit, githubToken, { comparisonBranch }) {
},
});

const data = JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8'));
// Older artifacts store only the results, measured on the run's head commit
return {
results: JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')),
sha: found.workflowRun.head_sha,
results: data.results ?? data,
sha: data.sha ?? found.workflowRun.head_sha,
workflowRun: found.workflowRun,
};
} catch (error) {
Expand All @@ -135,43 +205,42 @@ async function downloadBaseline(octokit, githubToken, { comparisonBranch }) {
/**
* Report which commits were compared, and whether the baseline contains exactly what this PR was tested against.
*/
async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }) {
async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch, basePr }) {
const unverified = '⚠️ Unable to verify whether the baseline matches the PR build.';
if (!mergedBaseSha) {
return [unverified];
}

const { sha, workflowRun } = baseline;
const base = basePr ? `base PR #${basePr.number}` : comparisonBranch;
const parts = [
`Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`,
`Against: ${commitLink(sha)} (${comparisonBranch}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`,
`Compared: ${commitLink(context.sha)} (PR test merge using ${base} at ${commitLink(mergedBaseSha)})`,
`Against: ${commitLink(sha)} (${base}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`,
];

if (sha === mergedBaseSha) {
parts.push("✅ Baseline matches: this diff contains only this PR's changes.");
return parts;
}

try {
if (sha === mergedBaseSha || (await haveSameTree(octokit, sha, mergedBaseSha))) {
parts.push("✅ Baseline matches: this diff contains only this PR's changes.");
return parts;
}

const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({
...context.repo,
basehead: `${sha}...${mergedBaseSha}`,
});
const differences = [];
if (comparison.ahead_by > 0) {
differences.push(
`${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`,
);
differences.push(`${comparison.ahead_by} commit(s) in the PR build are missing from the baseline`);
}
if (comparison.behind_by > 0) {
differences.push(
`${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`,
);
differences.push(`${comparison.behind_by} commit(s) in the baseline are missing from the PR build`);
}
const guidance =
comparison.behind_by > 0
? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.`
: `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`;
? basePr
? `Update this PR and ${base} with their base branches to compare against an up-to-date baseline.`
: `Rebase your PR onto the latest ${base} to compare against an up-to-date baseline.`
: `Re-run once the baseline build for ${commitLink(mergedBaseSha)} finishes.`;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
parts.push(
`⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` +
`[Compare commits](${comparison.html_url}). ${guidance}`,
Expand All @@ -184,6 +253,18 @@ async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBr
return parts;
}

/**
* A base PR is measured on its own test merge commit. With a plain base branch, that commit differs from the one this
* PR was tested against, but has the same tree when the base branch is up to date with develop.
*/
async function haveSameTree(octokit, shaA, shaB) {
const [{ data: a }, { data: b }] = await Promise.all([
octokit.rest.repos.getCommit({ ...context.repo, ref: shaA }),
octokit.rest.repos.getCommit({ ...context.repo, ref: shaB }),
]);
return a.commit.tree.sha === b.commit.tree.sha;
}

async function hasLabel(octokit, pr, label) {
const { data } = await octokit.rest.pulls.get({ ...context.repo, pull_number: pr.number });
return data.labels.some(({ name }) => name === label);
Expand Down
30 changes: 29 additions & 1 deletion dev-packages/size-limit-gh-action/utils/artifacts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as core from '@actions/core';
import { context } from '@actions/github';

const MAX_COMMITS = 50;
const SIZE_CHECK_JOB_NAME = 'Size Check';
const POLL_INTERVAL_MS = 30_000;

/**
* Find the newest `artifactName` artifact on `branch`. This walks the branch's commits, because listing workflow runs by
Expand All @@ -28,7 +30,7 @@ export async function getArtifactForBranch(octokit, { workflow, branch, artifact
return null;
}

async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) {
export async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) {
for (const workflowRun of await listRunsForCommit(octokit, { workflow, sha })) {
const { data } = await octokit.rest.actions.listWorkflowRunArtifacts({ ...context.repo, run_id: workflowRun.id });
const artifact = data.artifacts.find(({ name }) => name === artifactName);
Expand All @@ -41,6 +43,32 @@ async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) {
return null;
}

export async function waitForSizeCheck(octokit, { workflow, sha, timeoutMs }) {
const deadline = Date.now() + timeoutMs;

while (Date.now() < deadline) {
const jobs = [];
for (const { id } of await listRunsForCommit(octokit, { workflow, sha })) {
const { data } = await octokit.rest.actions.listJobsForWorkflowRun({
...context.repo,
run_id: id,
filter: 'latest',
per_page: 100,
});
jobs.push(...data.jobs.filter(({ name }) => name === SIZE_CHECK_JOB_NAME));
}

if (jobs.length > 0 && jobs.every(({ status }) => status === 'completed')) {
return;
}

core.info(`Waiting for the ${SIZE_CHECK_JOB_NAME} job of commit ${sha}...`);
await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
}

core.warning(`Timed out waiting for the ${SIZE_CHECK_JOB_NAME} job of commit ${sha}.`);
}

/**
* Newest first. Runs from forks are never trusted.
*/
Expand Down
Loading