Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pr-size.yml

351 lines12.7 KB

1name: PR Size
2​
3on:
4 pull_request_target:
5 types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
6​
7permissions:
8 contents: read
9​
10# Run-level, not job-level: runs join the group when their event arrives, so a newer push
11# always supersedes an older one. A job-level group is joined when the job starts, which
12# let an older run's slower job cancel the newer head's job and label from a stale diff.
13concurrency:
14 group: pr-size-${{ github.event.pull_request.number }}
15 cancel-in-progress: true
16​
17jobs:
18 prepare-config:
19 name: Prepare PR size config
20 runs-on: ubuntu-24.04
21 outputs:
22 labels_json: ${{ steps.config.outputs.labels_json }}
23 steps:
24 - id: config
25 name: Build PR size label config
26 uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
27 with:
28 result-encoding: string
29 script: |
30 const managedLabels = [
31 {
32 name: "size:XS",
33 color: "0e8a16",
34 description: "0-9 effective changed lines (test files excluded in mixed PRs).",
35 },
36 {
37 name: "size:S",
38 color: "5ebd3e",
39 description: "10-29 effective changed lines (test files excluded in mixed PRs).",
40 },
41 {
42 name: "size:M",
43 color: "fbca04",
44 description: "30-99 effective changed lines (test files excluded in mixed PRs).",
45 },
46 {
47 name: "size:L",
48 color: "fe7d37",
49 description: "100-499 effective changed lines (test files excluded in mixed PRs).",
50 },
51 {
52 name: "size:XL",
53 color: "d93f0b",
54 description: "500-999 effective changed lines (test files excluded in mixed PRs).",
55 },
56 {
57 name: "size:XXL",
58 color: "b60205",
59 description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
60 },
61 ];
62​
63 core.setOutput("labels_json", JSON.stringify(managedLabels));
64 sync-label-definitions:
65 name: Sync PR size label definitions
66 needs: prepare-config
67 if: github.event_name != 'pull_request_target'
68 runs-on: ubuntu-24.04
69 permissions:
70 contents: read
71 issues: write
72 steps:
73 - name: Ensure PR size labels exist
74 uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
75 env:
76 PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
77 with:
78 script: |
79 const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
80​
81 for (const label of managedLabels) {
82 try {
83 const { data: existing } = await github.rest.issues.getLabel({
84 owner: context.repo.owner,
85 repo: context.repo.repo,
86 name: label.name,
87 });
88​
89 if (
90 existing.color !== label.color ||
91 (existing.description ?? "") !== label.description
92 ) {
93 await github.rest.issues.updateLabel({
94 owner: context.repo.owner,
95 repo: context.repo.repo,
96 name: label.name,
97 color: label.color,
98 description: label.description,
99 });
100 }
101 } catch (error) {
102 if (error.status !== 404) {
103 throw error;
104 }
105​
106 try {
107 await github.rest.issues.createLabel({
108 owner: context.repo.owner,
109 repo: context.repo.repo,
110 name: label.name,
111 color: label.color,
112 description: label.description,
113 });
114 } catch (createError) {
115 if (createError.status !== 422) {
116 throw createError;
117 }
118 }
119 }
120 }
121 label:
122 name: Label PR size
123 needs: prepare-config
124 if: github.event_name == 'pull_request_target'
125 runs-on: ubuntu-24.04
126 permissions:
127 contents: read
128 issues: read
129 pull-requests: write
130 steps:
131 # This pull_request_target job may fetch untrusted PR commits only as passive
132 # git data. Do not add dependency installs, build/test scripts, or cache
133 # actions here; use pull_request plus workflow_run for that pattern instead.
134 - name: Checkout base repository
135 uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
136 with:
137 fetch-depth: 0
138 - name: Sync PR size label
139 uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
140 env:
141 PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
142 with:
143 script: |
144 const { execFileSync } = require("node:child_process");
145​
146 const issueNumber = context.payload.pull_request.number;
147 const baseSha = context.payload.pull_request.base.sha;
148 const headSha = context.payload.pull_request.head.sha;
149 const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
150 const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
151 const managedLabelNames = new Set(managedLabels.map((label) => label.name));
152 // Keep this aligned with the repo's test entrypoints and test-only support files.
153 const testExcludePathspecs = [
154 ":(glob,exclude)**/__tests__/**",
155 ":(glob,exclude)**/test/**",
156 ":(glob,exclude)**/tests/**",
157 ":(glob,exclude)apps/server/integration/**",
158 ":(glob,exclude)**/*.test.*",
159 ":(glob,exclude)**/*.spec.*",
160 ":(glob,exclude)**/*.browser.*",
161 ":(glob,exclude)**/*.integration.*",
162 ];
163​
164 const sumNumstat = (text) =>
165 text
166 .split("\n")
167 .filter(Boolean)
168 .reduce((total, line) => {
169 const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
170 const additions =
171 insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
172 const deletions =
173 deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
174​
175 return total + additions + deletions;
176 }, 0);
177​
178 const resolveSizeLabel = (totalChangedLines) => {
179 if (totalChangedLines < 10) {
180 return "size:XS";
181 }
182​
183 if (totalChangedLines < 30) {
184 return "size:S";
185 }
186​
187 if (totalChangedLines < 100) {
188 return "size:M";
189 }
190​
191 if (totalChangedLines < 500) {
192 return "size:L";
193 }
194​
195 if (totalChangedLines < 1000) {
196 return "size:XL";
197 }
198​
199 return "size:XXL";
200 };
201​
202 execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
203 stdio: "inherit",
204 });
205​
206 execFileSync(
207 "git",
208 ["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
209 {
210 stdio: "inherit",
211 },
212 );
213​
214 const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
215 encoding: "utf8",
216 }).trim();
217​
218 if (resolvedHeadSha !== headSha) {
219 core.warning(
220 `Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
221 );
222 }
223​
224 execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
225 stdio: "inherit",
226 });
227​
228 const diffArgs = [
229 "diff",
230 "--numstat",
231 "--ignore-all-space",
232 "--ignore-blank-lines",
233 `${baseSha}...${resolvedHeadSha}`,
234 ];
235​
236 const totalChangedLines = sumNumstat(
237 execFileSync(
238 "git",
239 diffArgs,
240 { encoding: "utf8" },
241 ),
242 );
243 const nonTestChangedLines = sumNumstat(
244 execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
245 encoding: "utf8",
246 }),
247 );
248 const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
249​
250 const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
251 const nextLabelName = resolveSizeLabel(changedLines);
252​
253 const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
254 owner: context.repo.owner,
255 repo: context.repo.repo,
256 issue_number: issueNumber,
257 per_page: 100,
258 });
259​
260 for (const label of currentLabels) {
261 if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
262 continue;
263 }
264​
265 try {
266 await github.rest.issues.removeLabel({
267 owner: context.repo.owner,
268 repo: context.repo.repo,
269 issue_number: issueNumber,
270 name: label.name,
271 });
272 } catch (removeError) {
273 if (removeError.status !== 404) {
274 throw removeError;
275 }
276 }
277 }
278​
279 if (!currentLabels.some((label) => label.name === nextLabelName)) {
280 await github.rest.issues.addLabels({
281 owner: context.repo.owner,
282 repo: context.repo.repo,
283 issue_number: issueNumber,
284 labels: [nextLabelName],
285 });
286 }
287​
288 const classification =
289 nonTestChangedLines === 0
290 ? testChangedLines > 0
291 ? "test-only PR"
292 : "no line changes"
293 : testChangedLines > 0
294 ? "test lines excluded"
295 : "all non-test changes";
296​
297 core.info(
298 `PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
299 );
300 # Reads the script from the base checkout above; the PR's own commits are only diffed.
301 - name: Report test suite growth
302 uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
303 with:
304 script: |
305 const { execFileSync } = require("node:child_process");
306 const { MARKER, countTestDelta, render } = require(
307 `${process.env.GITHUB_WORKSPACE}/.github/scripts/test-delta.cjs`,
308 );
309​
310 const issueNumber = context.payload.pull_request.number;
311 const diff = execFileSync(
312 "git",
313 ["diff", "-U0", `${context.payload.pull_request.base.sha}...refs/remotes/pr-size/${issueNumber}`],
314 { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 },
315 );
316 const delta = countTestDelta(diff);
317 const body = render(delta);
318 core.info(`PR #${issueNumber}: test cases ${JSON.stringify(delta.kinds)}, net ${delta.net}`);
319​
320 const comments = await github.paginate(github.rest.issues.listComments, {
321 owner: context.repo.owner,
322 repo: context.repo.repo,
323 issue_number: issueNumber,
324 per_page: 100,
325 });
326 const existing = comments.find(
327 (comment) => comment.user?.type === "Bot" && comment.body?.startsWith(MARKER),
328 );
329 if (body && existing) {
330 if (existing.body !== body) {
331 await github.rest.issues.updateComment({
332 owner: context.repo.owner,
333 repo: context.repo.repo,
334 comment_id: existing.id,
335 body,
336 });
337 }
338 } else if (body) {
339 await github.rest.issues.createComment({
340 owner: context.repo.owner,
341 repo: context.repo.repo,
342 issue_number: issueNumber,
343 body,
344 });
345 } else if (existing) {
346 await github.rest.issues.deleteComment({
347 owner: context.repo.owner,
348 repo: context.repo.repo,
349 comment_id: existing.id,
350 });
351 }