Skip to content
Merged
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
35 changes: 35 additions & 0 deletions .github/workflows/pr-size.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: pr-size

# Labels every PR size:XS..size:XXL by changed lines, not counting tests,
# fixtures, snapshots, or the lockfile (scripts/pr-size/label.ts).
# pull_request_target so fork PRs get a token that can label; the checkout is
# the base branch's script, never PR code.
on:
pull_request_target:
types: [opened, reopened, synchronize]

permissions:
contents: read
issues: write
pull-requests: write

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true

jobs:
label:
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
sparse-checkout: scripts/pr-size
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 26
- name: Label the PR
env:
GITHUB_TOKEN: ${{ github.token }}
run: node scripts/pr-size/label.ts
70 changes: 70 additions & 0 deletions scripts/pr-size/label.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Gives a pull request one `size:*` label from its changed lines
* (`.github/workflows/pr-size.yml`, on every open and push).
*
* Reads the PR number from the `pull_request_target` payload at
* `GITHUB_EVENT_PATH` and the changed files and labels live, over `fetch`
* with `GITHUB_TOKEN` against `GITHUB_REPOSITORY`. Never checks out or runs
* the PR's code. `--dry-run` prints the size and changes nothing.
*/

import { readFileSync } from 'node:fs';
import { SIZE_LABELS, sizeOf, type ChangedFile } from './size.ts';

const API = 'https://api.github.com';
const token = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
const repo = process.env.GITHUB_REPOSITORY;
const eventPath = process.env.GITHUB_EVENT_PATH;
if (!token || !repo || !eventPath) {
process.stderr.write('GITHUB_TOKEN, GITHUB_REPOSITORY, and GITHUB_EVENT_PATH are required\n');
process.exit(2);
}
const dryRun = process.argv.includes('--dry-run');
const { number } = (JSON.parse(readFileSync(eventPath, 'utf8')) as { pull_request: { number: number } }).pull_request;

/** One authenticated request under `/repos/{owner}/{name}`; throws on a non-2xx response. */
async function rest(path: string, init: { method?: string; body?: unknown } = {}): Promise<unknown> {
const response = await fetch(`${API}/repos/${repo}${path}`, {
method: init.method ?? 'GET',
headers: {
authorization: `Bearer ${token}`,
accept: 'application/vnd.github+json',
'x-github-api-version': '2022-11-28',
...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
},
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
});
if (!response.ok) throw new Error(`${init.method ?? 'GET'} ${path}: ${response.status} ${await response.text()}`);
return response.status === 204 ? undefined : response.json();
}

/** Every file the PR changes; GitHub lists at most 3,000, already past `size:XXL`. */
async function changedFiles(): Promise<ChangedFile[]> {
const all: ChangedFile[] = [];
for (let page = 1; ; page++) {
const batch = (await rest(`/pulls/${number}/files?per_page=100&page=${page}`)) as ChangedFile[];
all.push(...batch);
if (batch.length < 100) return all;
}
}

const size = sizeOf(await changedFiles());
console.log(`#${number}: ${size.counted} counted of ${size.total} changed lines -> ${size.label.name}`);
if (dryRun) process.exit(0);

const current = ((await rest(`/issues/${number}/labels?per_page=100`)) as { name: string }[]).map(({ name }) => name);
for (const name of current) {
if (name !== size.label.name && SIZE_LABELS.some((label) => label.name === name)) {
await rest(`/issues/${number}/labels/${encodeURIComponent(name)}`, { method: 'DELETE' });
}
}
if (!current.includes(size.label.name)) {
const { name, max, color } = size.label;
const description = `${max === Infinity ? '1,000+' : `Up to ${max}`} changed lines, not counting tests, fixtures, or the lockfile`;
try {
await rest('/labels', { method: 'POST', body: { name, color, description } });
} catch (error) {
if (!String(error).includes(': 422 ')) throw error;
}
await rest(`/issues/${number}/labels`, { method: 'POST', body: { labels: [name] } });
}
35 changes: 35 additions & 0 deletions scripts/pr-size/size.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { isExcluded, sizeOf, type ChangedFile } from './size.ts';

const file = (filename: string, additions: number, deletions = 0): ChangedFile => ({ filename, additions, deletions });

test('leaves tests, fixtures, snapshots, and the lockfile out of the count', () => {
for (const path of [
'packages/e2e/tests/unit/config.test.ts',
'packages/web/src/locator.test.ts',
'apps/testbed/tests-agent/login.e2e.ts',
'apps/testbed/tests/visual.e2e.ts-snapshots/home.png',
'packages/e2e/schema/fixtures/report.json',
'pnpm-lock.yaml',
]) {
assert.equal(isExcluded(path), true, path);
}
for (const path of ['packages/e2e/src/run/fixture.ts', 'packages/e2e/src/run/execute.ts', 'docs/guide.mdx', 'packages/web/pnpm-lock.yaml.md']) {
assert.equal(isExcluded(path), false, path);
}
});

test('sizes a mixed PR by its non-test lines', () => {
const size = sizeOf([file('packages/e2e/src/a.ts', 12, 3), file('packages/e2e/tests/unit/a.test.ts', 400), file('pnpm-lock.yaml', 900, 200)]);
assert.deepEqual({ total: size.total, counted: size.counted, label: size.label.name }, { total: 1515, counted: 15, label: 'size:S' });
});

test('sizes a test-only PR by all of its lines', () => {
assert.equal(sizeOf([file('packages/e2e/tests/unit/a.test.ts', 120, 30)]).label.name, 'size:L');
});

test('puts each boundary in the right label', () => {
const labels = [0, 9, 10, 29, 30, 99, 100, 499, 500, 999, 1000].map((lines) => sizeOf([file('src/a.ts', lines)]).label.name);
assert.deepEqual(labels, ['size:XS', 'size:XS', 'size:S', 'size:S', 'size:M', 'size:M', 'size:L', 'size:L', 'size:XL', 'size:XL', 'size:XXL']);
});
64 changes: 64 additions & 0 deletions scripts/pr-size/size.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* How big a pull request is, for the `size:*` labels (`label.ts`). Counts
* added plus deleted lines, leaving out tests, fixtures, snapshots, and the
* lockfile unless a PR changes nothing else.
*/

import { matchesGlob } from 'node:path';

export interface SizeLabel {
name: string;
/** Largest effective line count that still gets this label. */
max: number;
color: string;
}

export const SIZE_LABELS: readonly SizeLabel[] = [
{ name: 'size:XS', max: 9, color: '0e8a16' },
{ name: 'size:S', max: 29, color: '5ebd3e' },
{ name: 'size:M', max: 99, color: 'fbca04' },
{ name: 'size:L', max: 499, color: 'fe7d37' },
{ name: 'size:XL', max: 999, color: 'd93f0b' },
{ name: 'size:XXL', max: Infinity, color: 'b60205' },
];

const EXCLUDED: readonly string[] = [
'**/*.test.*',
'**/*.spec.*',
'**/*.e2e.*',
'**/tests/**',
'**/tests-*/**',
'**/__tests__/**',
'**/__snapshots__/**',
'**/*-snapshots/**',
'**/fixtures/**',
'pnpm-lock.yaml',
];

export interface ChangedFile {
filename: string;
additions: number;
deletions: number;
}

export interface Size {
total: number;
counted: number;
label: SizeLabel;
}

/** Whether a path is left out of the count. */
export function isExcluded(path: string): boolean {
return EXCLUDED.some((glob) => matchesGlob(path, glob));
}

/** Sizes a PR by its counted lines, or by all of them when every changed file is excluded. */
export function sizeOf(files: readonly ChangedFile[]): Size {
const lines = ({ additions, deletions }: ChangedFile) => additions + deletions;
const total = files.reduce((sum, file) => sum + lines(file), 0);
const counted = files.filter(({ filename }) => !isExcluded(filename)).reduce((sum, file) => sum + lines(file), 0);
const effective = counted === 0 ? total : counted;
const label = SIZE_LABELS.find(({ max }) => effective <= max);
if (label === undefined) throw new Error(`no size label for ${effective} lines`);
return { total, counted, label };
}
Loading