Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

pr-size-history.mjs

153 lines5.1 KB

1#!/usr/bin/env node
2/**
3 * Rank recently merged pull requests by the bytes they added to a package.
4 *
5 * The Compressed size check comments on each pull request with a table of
6 * changed `packages/<package>/dist/esm/*.js` files, and edits that comment
7 * in place, so it holds the final numbers. This script sums one package's
8 * rows per pull request and prints the pull requests by net bytes added.
9 *
10 * Those numbers are the library's `dist/esm` files before an app's build, so
11 * they include development-only code that production builds strip. Use them
12 * to find where code was added; measure production weight with
13 * `pnpm size:compare --base <commit>^ --exact-base` at the merge commit.
14 *
15 * Usage:
16 * node scripts/pr-size-history.mjs [--count 300] [--package db] [--json out.json]
17 */
18import { execFile } from 'node:child_process'
19import { writeFileSync } from 'node:fs'
20import { promisify } from 'node:util'
21​
22const run = promisify(execFile)
23const args = process.argv.slice(2)
24// An option present without an operand is an error, not its default.
25const option = (name, fallback) => {
26 const index = args.indexOf(`--${name}`)
27 if (index === -1) return fallback
28 const value = args[index + 1]
29 if (value === undefined || value.startsWith(`--`)) {
30 console.error(`--${name} needs a value`)
31 process.exit(1)
32 }
33 return value
35const count = Number(option(`count`, `300`))
36if (!Number.isInteger(count) || count < 1) {
37 console.error(`--count needs a positive integer`)
38 process.exit(1)
40const pkg = option(`package`, `db`)
41const repo = option(`repo`, `TanStack/db`)
42const units = { B: 1, kB: 1000, MB: 1000_000 }
43const row = new RegExp(
44 `^\\|\\s*\`packages/${pkg}/dist/esm/([^\`]+)\`\\s*\\|[^|]*\\|\\s*([+-]?[\\d.]+)\\s*(B|kB|MB)\\b`,
46​
47const gh = async (path, { paginate = false } = {}) => {
48 const { stdout } = await run(
49 `gh`,
50 [`api`, ...(paginate ? [`--paginate`, `--slurp`] : []), path],
51 { maxBuffer: 64 * 1024 * 1024 },
52 )
53 // `--slurp` wraps each page's array in an outer array.
54 return paginate ? JSON.parse(stdout).flat() : JSON.parse(stdout)
56​
57// Pages come newest-updated first, and a pull request's update time is never
58// earlier than its merge time. So once a page's oldest update is earlier than
59// the count-th newest merge already collected, no later page can hold a newer
60// merge, and paging can stop.
61async function mergedPullRequests() {
62 const merged = []
63 for (let page = 1; ; page++) {
64 const batch = await gh(
65 `repos/${repo}/pulls?state=closed&base=main&sort=updated&direction=desc&per_page=100&page=${page}`,
66 )
67 if (batch.length === 0) break
68 for (const pr of batch)
69 if (pr.merged_at)
70 merged.push({
71 number: pr.number,
72 title: pr.title,
73 mergedAt: pr.merged_at,
74 })
75 const oldestUpdate = batch.at(-1).updated_at
76 const newestMerges = merged
77 .map(({ mergedAt }) => mergedAt)
78 .sort()
79 .reverse()
80 if (newestMerges.length >= count && oldestUpdate < newestMerges[count - 1])
81 break
82 }
83 return merged
84 .sort((a, b) => b.mergedAt.localeCompare(a.mergedAt))
85 .slice(0, count)
87​
88// The package's changed files and their byte deltas, from the size comment.
89async function sizeChange(number) {
90 const comments = await gh(
91 `repos/${repo}/issues/${number}/comments?per_page=100`,
92 { paginate: true },
93 )
94 const comment = comments.findLast(
95 (c) =>
96 c.user.login === `github-actions[bot]` &&
97 c.body.includes(`**Size Change:**`),
98 )
99 if (!comment) return undefined
100 // Only the "View Changed" table has a change column.
101 const files = comment.body
102 .split(`View Unchanged`)[0]
103 .split(`\n`)
104 .map((line) => line.match(row))
105 .filter(Boolean)
106 .map(([, file, value, unit]) => ({
107 file,
108 bytes: Math.round(Number(value) * units[unit]),
109 }))
110 .sort((a, b) => Math.abs(b.bytes) - Math.abs(a.bytes))
111 return {
112 bytes: files.reduce((sum, { bytes }) => sum + bytes, 0),
113 added: files.reduce((sum, { bytes }) => sum + Math.max(bytes, 0), 0),
114 files,
115 }
117​
118async function inBatches(items, size, task) {
119 const results = []
120 for (let i = 0; i < items.length; i += size)
121 results.push(...(await Promise.all(items.slice(i, i + size).map(task))))
122 return results
124​
125const prs = await mergedPullRequests()
126const sizes = await inBatches(prs, 8, (pr) => sizeChange(pr.number))
127const rows = prs
128 .map((pr, i) => ({ ...pr, ...sizes[i] }))
129 .filter((pr) => pr.files?.length)
130 .sort((a, b) => b.bytes - a.bytes)
131const json = option(`json`)
132if (json) writeFileSync(json, JSON.stringify(rows, null, 2))
133​
134const signed = (n) => (n > 0 ? `+${n}` : `${n}`)
135console.log(
136 `${prs.length} merged pull requests, ${rows.length} change packages/${pkg}, ${
137 sizes.filter((size) => size === undefined).length
138 } without a size comment\n`,
140console.log(` net B added PR title`)
141for (const pr of rows) {
142 console.log(
143 `${signed(pr.bytes).padStart(7)} ${String(pr.added).padStart(7)} #${String(
144 pr.number,
145 ).padEnd(5)} ${pr.title.slice(0, 64)}`,
146 )
147 console.log(
148 `${``.padStart(24)}${pr.files
149 .slice(0, 3)
150 .map(({ file, bytes }) => `${file} ${signed(bytes)}`)
151 .join(`, `)}`,
152 )