diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 84d4732a53bf..8549e3e7897e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -308,7 +308,7 @@ jobs: uses: ./dev-packages/size-limit-gh-action with: github_token: ${{ secrets.GITHUB_TOKEN }} - # Only run comparison against develop if this is a PR + # Only compare on PRs. Other runs only store their results as a baseline. comparison_branch: ${{ (github.event_name == 'pull_request' && github.base_ref) || ''}} job_lint: diff --git a/dev-packages/size-limit-gh-action/index.mjs b/dev-packages/size-limit-gh-action/index.mjs index b23a752b1e94..8331e61e6b15 100644 --- a/dev-packages/size-limit-gh-action/index.mjs +++ b/dev-packages/size-limit-gh-action/index.mjs @@ -7,8 +7,8 @@ import { getExecOutput } from '@actions/exec'; import { context, getOctokit } from '@actions/github'; import { markdownTable } from 'markdown-table'; import sizeConfig from '../../.size-limit.js'; -import { getArtifactsForBranchAndWorkflow } from './utils/getArtifactsForBranchAndWorkflow.mjs'; -import { MAX_INCREASE_BYTES, SizeLimitFormatter } from './utils/SizeLimitFormatter.mjs'; +import { getArtifactForBranch } from './utils/artifacts.mjs'; +import { formatResults, getSizeIncreases, MAX_INCREASE_BYTES, parseResults } from './utils/results.mjs'; const OVERRIDE_LABEL = 'Accept Bundlesize Increase'; const RELEASE_BRANCH_PREFIX = 'prepare-release/'; @@ -16,196 +16,210 @@ 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 WORKFLOW_FILE = path.basename(process.env.GITHUB_WORKFLOW_REF.split('@')[0]); +const REPO_URL = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`; -const { getInput, setFailed } = core; +const NO_BASELINE_FAILURE = 'No baseline size measurements found. Re-run after the base build completes.'; +const INCREASE_FAILURE = + `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` + + `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`; + +const artifactClient = new DefaultArtifactClient(); async function run() { - try { - const { payload, repo } = context; - const pr = payload.pull_request; + // Only set on PRs, where it is the PR's base branch + const comparisonBranch = core.getInput('comparison_branch'); + const githubToken = core.getInput('github_token'); + const octokit = getOctokit(githubToken); + const pr = context.payload.pull_request; + + if (comparisonBranch && !pr) { + throw new Error('No PR found. Only pull_request workflows are supported.'); + } - // The comparison branch is the base branch we are comparing against (in our case usually develop) - const comparisonBranch = getInput('comparison_branch'); - const githubToken = getInput('github_token'); + const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']); + const current = parseResults(stdout); - if (comparisonBranch && !pr) { - throw new Error('No PR found. Only pull_request workflows are supported.'); - } + if (!comparisonBranch) { + await uploadResults(current); + return; + } - const octokit = getOctokit(githubToken); - let increaseAccepted = false; + const mergedBaseSha = await getMergedBaseSha(octokit); + const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch }); - if (comparisonBranch) { - const { data: currentPr } = await octokit.rest.pulls.get({ - ...repo, - pull_number: pr.number, - }); - increaseAccepted = currentPr.labels.some(label => label.name === OVERRIDE_LABEL); - } + const hasIncrease = baseline ? getSizeIncreases(baseline.results, current, sizeConfig).length > 0 : false; + const bodyParts = [SIZE_LIMIT_HEADING]; + let failure; - const limit = new SizeLimitFormatter(); - const artifactClient = new DefaultArtifactClient(); + if (baseline) { + bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }))); + } - // Build and measure each bundle defined in .size-limit.js for the current branch - const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']); - const current = limit.parseResults(stdout); + if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) { + // Release PRs target master, which has no baseline and would include every change since the last release anyway + core.info('Release PR detected. Reporting bundle sizes without enforcing limits.'); + } else if (!baseline) { + failure = NO_BASELINE_FAILURE; + bodyParts.push(failure); + } else if (hasIncrease && !(await hasLabel(octokit, pr, OVERRIDE_LABEL))) { + failure = INCREASE_FAILURE; + } - // If we have no comparison branch, we only store the results as artifacts (likely running on develop) - if (!comparisonBranch) { - await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(current), 'utf8'); - await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); - return; - } + bodyParts.push(markdownTable(formatResults(baseline?.results, current))); + if (baseline) { + bodyParts.push(`[View base workflow run](${baseline.workflowRun.html_url})`); + } - // Else, we fetch the results for the comparison branch and compare them with the current branch (likely running on a PR) - let base; - let baseWorkflowRun; - - try { - const workflowName = process.env.GITHUB_WORKFLOW; - core.startGroup(`getArtifactsForBranchAndWorkflow - workflow:"${workflowName}", branch:"${comparisonBranch}"`); - const artifacts = await getArtifactsForBranchAndWorkflow(octokit, { - ...repo, - artifactName: ARTIFACT_NAME, - branch: comparisonBranch, - workflowName, - }); - core.endGroup(); - - if (!artifacts) { - throw new Error('No artifacts found'); - } - - baseWorkflowRun = artifacts.workflowRun; - - await artifactClient.downloadArtifact(artifacts.artifact.id, { - path: ACTION_DIRECTORY, - findBy: { - token: githubToken, - workflowRunId: artifacts.workflowRun.id, - repositoryOwner: repo.owner, - repositoryName: repo.repo, - }, - }); - - base = JSON.parse(await fs.readFile(RESULTS_FILE_PATH, { encoding: 'utf8' })); - } catch (error) { - core.startGroup('Warning, unable to find base results'); - core.error(error); - core.endGroup(); - } + const body = bodyParts.join('\n\n'); + await core.summary.addRaw(body).write(); + await updatePrComments(octokit, pr, { body, failure }); - const increases = base ? limit.getSizeIncreases(base, current, sizeConfig) : []; - const bodyParts = [SIZE_LIMIT_HEADING]; - - // Check if our baseline build is up to date with the target branch (likely develop) and report any mismatches - if (base) { - const baselineSha = baseWorkflowRun.head_sha; // The commit SHA of the baseline build (where we pull the size-limit results from) - const repoUrl = `${context.serverUrl}/${repo.owner}/${repo.repo}`; - const commitLink = sha => `[${sha.slice(0, 7)}](${repoUrl}/commit/${sha})`; - - try { - const { data: mergeCommit } = await octokit.rest.repos.getCommit({ ...repo, ref: context.sha }); - const mergedBaseSha = mergeCommit.parents[0].sha; // The SHA of the target branch (likely develop) base commit that was used to test this PR - - bodyParts.push( - `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`, - `Against: ${commitLink(baselineSha)} (${comparisonBranch}) · [base run #${baseWorkflowRun.run_number}](${baseWorkflowRun.html_url})`, - ); - - if (baselineSha === mergedBaseSha) { - bodyParts.push("✅ Baseline matches: this diff contains only this PR's changes."); - } else { - const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({ - ...repo, - basehead: `${baselineSha}...${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`, - ); - } - if (comparison.behind_by > 0) { - differences.push( - `${comparison.behind_by} ${comparisonBranch} 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.`; - bodyParts.push( - `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` + - `[Compare commits](${comparison.html_url}). ${guidance}`, - ); - } - } catch (error) { - core.warning(`Unable to check baseline alignment: ${error.message}`); - bodyParts.push('⚠️ Unable to verify whether the baseline matches the PR build.'); - } - } + if (failure) { + core.setFailed(failure); + } +} - let failure; - if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) { - // Release PRs target master, which has no baseline and would include every change since the last release anyway - core.info('Release PR detected. Reporting bundle sizes without enforcing limits.'); - } else if (!base) { - failure = 'No baseline size measurements found. Re-run after the base build completes.'; - bodyParts.push(failure); - } else if (increases.length > 0 && !increaseAccepted) { - failure = - `One or more gzipped bundles increased by more than ${MAX_INCREASE_BYTES} bytes. ` + - `If this increase is intentional, add the **${OVERRIDE_LABEL}** label to this PR to rerun and accept the check.`; +async function uploadResults(results) { + await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(results), 'utf8'); + await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); +} + +/** + * On PRs, GitHub checks out a merge of the PR into its base branch (`refs/pull//merge`). Its first parent is the + * base branch commit this PR is compared against. + */ +async function getMergedBaseSha(octokit) { + try { + const { data } = await octokit.rest.repos.getCommit({ ...context.repo, ref: context.sha }); + return data.parents[0].sha; + } catch (error) { + core.warning(`Unable to resolve the base commit of the PR test merge: ${error.message}`); + return undefined; + } +} + +async function downloadBaseline(octokit, githubToken, { comparisonBranch }) { + try { + const found = await getArtifactForBranch(octokit, { + workflow: WORKFLOW_FILE, + branch: comparisonBranch, + artifactName: ARTIFACT_NAME, + }); + + if (!found) { + throw new Error('No artifacts found'); } - bodyParts.push(markdownTable(limit.formatResults(base, current))); - if (baseWorkflowRun) { - bodyParts.push(`[View base workflow run](${baseWorkflowRun.html_url})`); + await artifactClient.downloadArtifact(found.artifact.id, { + path: ACTION_DIRECTORY, + findBy: { + token: githubToken, + workflowRunId: found.workflowRun.id, + repositoryOwner: context.repo.owner, + repositoryName: context.repo.repo, + }, + }); + + return { + results: JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')), + sha: found.workflowRun.head_sha, + workflowRun: found.workflowRun, + }; + } catch (error) { + core.warning(`Unable to find base results: ${error.message}`); + return undefined; + } +} + +/** + * Report which commits were compared, and whether the baseline contains exactly what this PR was tested against. + */ +async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }) { + const unverified = '⚠️ Unable to verify whether the baseline matches the PR build.'; + if (!mergedBaseSha) { + return [unverified]; + } + + const { sha, workflowRun } = baseline; + 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})`, + ]; + + if (sha === mergedBaseSha) { + parts.push("✅ Baseline matches: this diff contains only this PR's changes."); + return parts; + } + + try { + 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`, + ); + } + if (comparison.behind_by > 0) { + differences.push( + `${comparison.behind_by} ${comparisonBranch} 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.`; + parts.push( + `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` + + `[Compare commits](${comparison.html_url}). ${guidance}`, + ); + } catch (error) { + core.warning(`Unable to check baseline alignment: ${error.message}`); + parts.push(unverified); + } + + return parts; +} + +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); +} - const body = bodyParts.join('\n\n'); - await core.summary.addRaw(body).write(); - - try { - const comments = await octokit.paginate(octokit.rest.issues.listComments, { - ...repo, - issue_number: pr.number, - per_page: 100, - }); - const sizeLimitComment = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING)); - if (sizeLimitComment) { - await octokit.rest.issues.updateComment({ - ...repo, - comment_id: sizeLimitComment.id, - body, - }); - } else { - await octokit.rest.issues.createComment({ - ...repo, - issue_number: pr.number, - body, - }); - } - - if (failure && increases.length > 0 && !comments.some(comment => comment.body === failure)) { - await octokit.rest.issues.createComment({ - ...repo, - issue_number: pr.number, - body: failure, - }); - } - } catch { - core.warning('Unable to update PR comments. The size report is available in the job summary.'); +/** + * Keep one size report comment up to date. A size increase also gets its own comment, which notifies the author. + */ +async function updatePrComments(octokit, pr, { body, failure }) { + try { + const comments = await octokit.paginate(octokit.rest.issues.listComments, { + ...context.repo, + issue_number: pr.number, + per_page: 100, + }); + + const report = comments.find(comment => comment.body.startsWith(SIZE_LIMIT_HEADING)); + if (report) { + await octokit.rest.issues.updateComment({ ...context.repo, comment_id: report.id, body }); + } else { + await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body }); } - if (failure) { - setFailed(failure); + if (failure === INCREASE_FAILURE && !comments.some(comment => comment.body === failure)) { + await octokit.rest.issues.createComment({ ...context.repo, issue_number: pr.number, body: failure }); } - } catch (error) { - core.error(error); - setFailed(error.message); + } catch { + core.warning('Unable to update PR comments. The size report is available in the job summary.'); } } -await run(); +function commitLink(sha) { + return `[${sha.slice(0, 7)}](${REPO_URL}/commit/${sha})`; +} + +await run().catch(error => { + core.error(error); + core.setFailed(error.message); +}); diff --git a/dev-packages/size-limit-gh-action/package.json b/dev-packages/size-limit-gh-action/package.json index 828f16819b39..ed6d2eaa289c 100644 --- a/dev-packages/size-limit-gh-action/package.json +++ b/dev-packages/size-limit-gh-action/package.json @@ -1,6 +1,6 @@ { "name": "@sentry-internal/size-limit-gh-action", - "description": "An internal Github Action to compare the current size of a PR against the one on develop.", + "description": "An internal Github Action to compare the bundle sizes of a PR against its base.", "version": "11.17.0", "license": "MIT", "engines": { diff --git a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs b/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs deleted file mode 100644 index 8e1449f2df7a..000000000000 --- a/dev-packages/size-limit-gh-action/utils/SizeLimitFormatter.mjs +++ /dev/null @@ -1,106 +0,0 @@ -import bytes from 'bytes-iec'; - -export const MAX_INCREASE_BYTES = 500; - -const SIZE_RESULTS_HEADER = ['Path', 'Size', '% Change', 'Change']; - -const EmptyResult = { - name: '-', - size: 0, -}; - -export class SizeLimitFormatter { - formatBytes(size) { - return bytes.format(size, { unitSeparator: ' ' }); - } - - formatPercentageChange(base = 0, current = 0) { - if (base === 0) { - return 'added'; - } - - if (current === 0) { - return 'removed'; - } - - const value = ((current - base) / base) * 100; - const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100; - - if (value > 0) { - return `+${formatted}%`; - } - - if (value === 0) { - return '-'; - } - - return `${formatted}%`; - } - - formatChange(base = 0, current = 0) { - if (base === 0) { - return 'added'; - } - - if (current === 0) { - return 'removed'; - } - - const value = current - base; - const formatted = this.formatBytes(value); - - if (value > 0) { - return `+${formatted} 🔺`; - } - - if (value === 0) { - return '-'; - } - - return `${formatted} 🔽`; - } - - formatSizeResult(name, base, current) { - return [ - name, - this.formatBytes(current.size), - this.formatPercentageChange(base.size, current.size), - this.formatChange(base.size, current.size), - ]; - } - - parseResults(output) { - const results = JSON.parse(output); - - return results.reduce( - (current, result) => ({ - ...current, - [result.name]: { - name: result.name, - size: result.size, - }, - }), - {}, - ); - } - - getSizeIncreases(base, current, config) { - return config - .filter(({ name, gzip }) => gzip === true && base[name]) - .map(({ name }) => ({ name, increase: current[name].size - base[name].size })) - .filter(({ increase }) => increase > MAX_INCREASE_BYTES); - } - - formatResults(base, current) { - const names = [...new Set([...(base ? Object.keys(base) : []), ...Object.keys(current)])]; - const header = SIZE_RESULTS_HEADER; - const fields = names.map(name => { - const baseResult = base?.[name] || EmptyResult; - const currentResult = current[name] || EmptyResult; - - return this.formatSizeResult(name, baseResult, currentResult); - }); - - return [header, ...fields]; - } -} diff --git a/dev-packages/size-limit-gh-action/utils/artifacts.mjs b/dev-packages/size-limit-gh-action/utils/artifacts.mjs new file mode 100644 index 000000000000..0dbe1ee48178 --- /dev/null +++ b/dev-packages/size-limit-gh-action/utils/artifacts.mjs @@ -0,0 +1,58 @@ +import * as core from '@actions/core'; +import { context } from '@actions/github'; + +const MAX_COMMITS = 50; + +/** + * Find the newest `artifactName` artifact on `branch`. This walks the branch's commits, because listing workflow runs by + * branch is eventually consistent and can silently skip the most recent runs. + */ +export async function getArtifactForBranch(octokit, { workflow, branch, artifactName }) { + const { data: commits } = await octokit.rest.repos.listCommits({ + ...context.repo, + sha: branch, + per_page: MAX_COMMITS, + }); + + for (const [index, { sha }] of commits.entries()) { + const found = await getArtifactForCommit(octokit, { workflow, sha, artifactName }); + if (found) { + if (index > 0) { + core.info(`Using results from ${sha}, which is ${index} commit(s) behind the tip of "${branch}".`); + } + return found; + } + } + + core.warning(`No "${artifactName}" artifact found in the last ${commits.length} commits of "${branch}".`); + return null; +} + +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); + if (artifact) { + core.info(`Found "${artifactName}" for commit ${sha} in ${workflowRun.html_url}`); + return { artifact, workflowRun }; + } + } + + return null; +} + +/** + * Newest first. Runs from forks are never trusted. + */ +async function listRunsForCommit(octokit, { workflow, sha }) { + const { data } = await octokit.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: workflow, + head_sha: sha, + per_page: 100, + }); + + return data.workflow_runs + .filter(run => run.head_repository?.full_name === `${context.repo.owner}/${context.repo.repo}`) + .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); +} diff --git a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs b/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs deleted file mode 100644 index 7e0b28d4c278..000000000000 --- a/dev-packages/size-limit-gh-action/utils/getArtifactsForBranchAndWorkflow.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import * as core from '@actions/core'; - -// How many commits to walk back on the branch before giving up on finding a build with a size-limit artifact. -const DEFAULT_MAX_COMMITS = 50; -const COMMITS_PER_PAGE = 100; -const RUNS_PER_PAGE = 100; - -/** - * Find the most recent build artifact for a branch by walking its git history. - * - * We deliberately drive this from `repos.listCommits` (authoritative, strictly ordered git history) rather than from - * `listWorkflowRuns` filtered by branch + event. That listing is backed by an eventually-consistent index that can omit - * or reorder very recent runs, which previously made us silently compare against a days-old baseline while still - * reporting it as the latest one. Walking commits newest-first and pinning each run by `head_sha` sidesteps that: the - * order is exact, and if the tip commit has no artifact yet we fall back to its parent and correctly report the baseline - * as not-latest. - */ -export async function getArtifactsForBranchAndWorkflow(octokit, { owner, repo, workflowName, branch, artifactName }) { - const workflowId = await findWorkflowId(octokit, { owner, repo, workflowName }); - - if (!workflowId) { - return null; - } - - let commitsChecked = 0; - - for await (const response of octokit.paginate.iterator(octokit.rest.repos.listCommits, { - owner, - repo, - sha: branch, - per_page: COMMITS_PER_PAGE, - })) { - for (const { sha } of response.data) { - const isLatest = commitsChecked === 0; - commitsChecked++; - - const found = await findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName }); - - if (found) { - if (!isLatest) { - core.info( - `Base artifact comes from commit ${sha}, which is ${commitsChecked - 1} commit(s) behind the tip of "${branch}".`, - ); - } - return { ...found, isLatest }; - } - - if (commitsChecked >= DEFAULT_MAX_COMMITS) { - core.warning( - `No "${artifactName}" artifact found within the last ${DEFAULT_MAX_COMMITS} commits of "${branch}".`, - ); - return null; - } - } - } - - core.warning(`No "${artifactName}" artifact found on branch "${branch}".`); - return null; -} - -/** - * Resolve a workflow's numeric id from its display name. - */ -async function findWorkflowId(octokit, { owner, repo, workflowName }) { - const allWorkflows = []; - - for await (const response of octokit.paginate.iterator(octokit.rest.actions.listRepoWorkflows, { owner, repo })) { - const targetWorkflow = response.data.find(({ name }) => name === workflowName); - allWorkflows.push(...response.data.map(({ name }) => name)); - - if (targetWorkflow) { - return targetWorkflow.id; - } - } - - core.info( - `Unable to find workflow with name "${workflowName}" in the repository. Found workflows: ${allWorkflows.join(', ')}`, - ); - return null; -} - -/** - * Return the first `artifactName` artifact produced by any run of `workflowId` for the exact `sha`, preferring the most - * recent run (in case of re-runs). Runs originating from a fork are never trusted. - */ -async function findArtifactForCommit(octokit, { owner, repo, workflowId, sha, artifactName }) { - const { - data: { workflow_runs: workflowRuns }, - } = await octokit.rest.actions.listWorkflowRuns({ - owner, - repo, - workflow_id: workflowId, - head_sha: sha, - per_page: RUNS_PER_PAGE, - }); - - const runs = workflowRuns - .filter(workflowRun => workflowRun.head_repository?.full_name === `${owner}/${repo}`) - .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()); - - for (const workflowRun of runs) { - const { - data: { artifacts }, - } = await octokit.rest.actions.listWorkflowRunArtifacts({ - owner, - repo, - run_id: workflowRun.id, - }); - - const artifact = artifacts?.find(({ name }) => name === artifactName); - if (artifact) { - core.info(`Found suitable artifact for commit ${sha}: ${artifact.url} (run ${workflowRun.html_url})`); - return { artifact, workflowRun }; - } - } - - return null; -} diff --git a/dev-packages/size-limit-gh-action/utils/results.mjs b/dev-packages/size-limit-gh-action/utils/results.mjs new file mode 100644 index 000000000000..9cbdfc145bb6 --- /dev/null +++ b/dev-packages/size-limit-gh-action/utils/results.mjs @@ -0,0 +1,69 @@ +import bytes from 'bytes-iec'; + +export const MAX_INCREASE_BYTES = 500; + +export function parseResults(output) { + return Object.fromEntries(JSON.parse(output).map(({ name, size }) => [name, { name, size }])); +} + +export function getSizeIncreases(base, current, config) { + return config + .filter(({ name, gzip }) => gzip === true && base[name]) + .map(({ name }) => ({ name, increase: current[name].size - base[name].size })) + .filter(({ increase }) => increase > MAX_INCREASE_BYTES); +} + +export function formatResults(base, current) { + const names = [...new Set([...Object.keys(base ?? {}), ...Object.keys(current)])]; + + return [ + ['Path', 'Size', '% Change', 'Change'], + ...names.map(name => { + const baseSize = base?.[name]?.size ?? 0; + const currentSize = current[name]?.size ?? 0; + return [ + name, + formatBytes(currentSize), + formatPercentageChange(baseSize, currentSize), + formatChange(baseSize, currentSize), + ]; + }), + ]; +} + +function formatBytes(size) { + return bytes.format(size, { unitSeparator: ' ' }); +} + +function formatPercentageChange(base, current) { + if (base === 0) { + return 'added'; + } + if (current === 0) { + return 'removed'; + } + + const value = ((current - base) / base) * 100; + const formatted = (Math.sign(value) * Math.ceil(Math.abs(value) * 100)) / 100; + + if (value > 0) { + return `+${formatted}%`; + } + return value === 0 ? '-' : `${formatted}%`; +} + +function formatChange(base, current) { + if (base === 0) { + return 'added'; + } + if (current === 0) { + return 'removed'; + } + + const value = current - base; + + if (value > 0) { + return `+${formatBytes(value)} 🔺`; + } + return value === 0 ? '-' : `${formatBytes(value)} 🔽`; +}