.github/workflows/pr-comment.yml
320 lines · 12411 bytes
1name: PR Comment
2
3on:
4 workflow_run:
5 workflows: ["PR Check"]
6 types: [completed]
7 pull_request_review:
8 types: [submitted]
9 pull_request_target:
10 types: [opened, edited, reopened]
11
12permissions:
13 actions: read
14 checks: read
15 contents: read
16 pull-requests: write
17
18jobs:
19 comment:
20 name: Post PR comment
21 runs-on: ubuntu-latest
22 if: github.event.workflow_run.event == 'pull_request'
23
24 steps:
25 - uses: actions/checkout@v5
26
27 - name: Download PR metadata
28 id: download
29 continue-on-error: true
30 uses: actions/download-artifact@v7
31 with:
32 name: pr-meta
33 path: pr-meta
34 run-id: ${{ github.event.workflow_run.id }}
35 github-token: ${{ secrets.GITHUB_TOKEN }}
36
37 - name: Resolve PR context
38 id: context
39 uses: actions/github-script@v8
40 with:
41 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
42 script: |
43 const fs = require('fs');
44
45 // Determine the PR number
46 let prNumber;
47 const numberFile = 'pr-meta/number.txt';
48 if (fs.existsSync(numberFile)) {
49 prNumber = parseInt(fs.readFileSync(numberFile, 'utf8').trim());
50 }
51 if (!prNumber) {
52 const prs = context.payload.workflow_run.pull_requests;
53 if (prs && prs.length > 0) {
54 prNumber = prs[0].number;
55 } else {
56 const headSha = context.payload.workflow_run.head_sha;
57 const { data: prList } = await github.rest.pulls.list({
58 owner: context.repo.owner,
59 repo: context.repo.repo,
60 state: 'open',
61 sort: 'updated',
62 direction: 'desc',
63 per_page: 100,
64 });
65 const match = prList.find(pr => pr.head.sha === headSha);
66 if (!match) {
67 console.log(`No open PR found for SHA ${headSha} — skipping.`);
68 return;
69 }
70 prNumber = match.number;
71 }
72 }
73
74 // Fetch existing bot comment (if any) and write to file for Python
75 const marker = '<!-- pr-check-bot -->';
76 const { data: comments } = await github.rest.issues.listComments({
77 owner: context.repo.owner,
78 repo: context.repo.repo,
79 issue_number: prNumber,
80 per_page: 100,
81 });
82 const existing = comments.find(c => c.body.includes(marker));
83 if (existing) {
84 fs.mkdirSync('pr-meta', { recursive: true });
85 fs.writeFileSync('pr-meta/existing-comment.md', existing.body);
86 fs.writeFileSync('pr-meta/existing-comment-id.txt', String(existing.id));
87 }
88
89 core.setOutput('pr_number', prNumber);
90
91 - name: Prepare comment
92 if: steps.context.outputs.pr_number
93 env:
94 CHECK_RUN_ID: ${{ github.event.workflow_run.id }}
95 GITHUB_REPOSITORY: ${{ github.repository }}
96 run: python lib/checks/prepare-comment.py
97
98 - name: Post or update comment
99 if: steps.context.outputs.pr_number
100 uses: actions/github-script@v8
101 with:
102 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
103 script: |
104 const fs = require('fs');
105 const actionFile = 'pr-meta/action.txt';
106 if (!fs.existsSync(actionFile)) return;
107
108 const action = fs.readFileSync(actionFile, 'utf8').trim();
109 if (action === 'skip') {
110 console.log('Nothing to do — skipping.');
111 return;
112 }
113
114 const bodyFile = 'pr-meta/final-comment.md';
115 if (!fs.existsSync(bodyFile)) {
116 console.log('No comment body found — skipping.');
117 return;
118 }
119 const body = fs.readFileSync(bodyFile, 'utf8').trim();
120 const prNumber = parseInt('${{ steps.context.outputs.pr_number }}');
121
122 if (action === 'create') {
123 await github.rest.issues.createComment({
124 owner: context.repo.owner,
125 repo: context.repo.repo,
126 issue_number: prNumber,
127 body,
128 });
129 console.log('Created bot comment.');
130 } else if (action === 'update') {
131 const commentId = parseInt(fs.readFileSync('pr-meta/existing-comment-id.txt', 'utf8').trim());
132 await github.rest.issues.updateComment({
133 owner: context.repo.owner,
134 repo: context.repo.repo,
135 comment_id: commentId,
136 body,
137 });
138 console.log('Updated bot comment.');
139 }
140
141 // Auto-assign Lissy93 for review when appropriate (non-critical)
142 try {
143 const readInt = (f) => fs.existsSync(f) ? parseInt(fs.readFileSync(f, 'utf8').trim()) : NaN;
144 const errors = readInt('pr-meta/error-count.txt');
145 const total = readInt('pr-meta/findings-count.txt');
146 const shouldAssign =
147 (action === 'create' && errors === 0 && total === 0) ||
148 (action === 'update' && errors === 0);
149 if (shouldAssign) {
150 await github.rest.issues.addAssignees({
151 owner: context.repo.owner,
152 repo: context.repo.repo,
153 issue_number: prNumber,
154 assignees: ['Lissy93'],
155 });
156 console.log('Assigned Lissy93 for review.');
157 }
158 } catch (err) {
159 console.log(`Failed to auto-assign: ${err.message}`);
160 }
161
162 review-notify:
163 name: Notify maintainer
164 runs-on: ubuntu-latest
165 if: github.event_name == 'pull_request_review'
166
167 steps:
168 - uses: actions/checkout@v5
169
170 - name: Fetch review and CI context
171 id: context
172 uses: actions/github-script@v8
173 with:
174 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
175 script: |
176 const fs = require('fs');
177 const pr = context.payload.pull_request;
178 const { owner, repo } = context.repo;
179
180 // Fetch reviews — extract user login and state
181 const { data: reviews } = await github.rest.pulls.listReviews({
182 owner, repo, pull_number: pr.number, per_page: 100,
183 });
184 const reviewData = reviews.map(r => ({
185 user: r.user.login,
186 state: r.state,
187 }));
188
189 // Fetch check runs for the PR head SHA
190 const { data: { check_runs } } = await github.rest.checks.listForRef({
191 owner, repo, ref: pr.head.sha, per_page: 100,
192 });
193 const checkData = check_runs.map(cr => ({
194 status: cr.status,
195 conclusion: cr.conclusion,
196 }));
197
198 // Check if we already posted the notification
199 const marker = '<!-- pr-review-ready -->';
200 const { data: comments } = await github.rest.issues.listComments({
201 owner, repo, issue_number: pr.number, per_page: 100,
202 });
203 const alreadyNotified = comments.some(c => c.body.includes(marker));
204
205 // Write data for Python
206 fs.mkdirSync('pr-meta', { recursive: true });
207 fs.writeFileSync('pr-meta/reviews.json', JSON.stringify(reviewData));
208 fs.writeFileSync('pr-meta/check-runs.json', JSON.stringify(checkData));
209 fs.writeFileSync('pr-meta/already-notified.txt', String(alreadyNotified));
210
211 core.setOutput('pr_number', pr.number);
212
213 - name: Check review readiness
214 run: python lib/checks/check-review-ready.py
215
216 - name: Post notification
217 uses: actions/github-script@v8
218 with:
219 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
220 script: |
221 const fs = require('fs');
222 const actionFile = 'pr-meta/action.txt';
223 if (!fs.existsSync(actionFile)) return;
224
225 const action = fs.readFileSync(actionFile, 'utf8').trim();
226 if (action !== 'notify') {
227 console.log('Not ready for review — skipping.');
228 return;
229 }
230
231 const body = [
232 '<!-- pr-review-ready -->',
233 'This PR is now ready to be merged, pending maintainer review. All checks are passing and it has been peer-reviewed.',
234 '',
235 '@Lissy93 - Please evaluate, and either merge or leave feedback.',
236 ].join('\n');
237
238 const prNumber = parseInt('${{ steps.context.outputs.pr_number }}');
239
240 await github.rest.issues.createComment({
241 owner: context.repo.owner,
242 repo: context.repo.repo,
243 issue_number: prNumber,
244 body,
245 });
246
247 // Once all checks pass, assign the PR to myself, so i get notiifcation to review
248 try {
249 await github.rest.issues.addAssignees({
250 owner: context.repo.owner,
251 repo: context.repo.repo,
252 issue_number: prNumber,
253 assignees: ['Lissy93'],
254 });
255 } catch (err) {
256 console.log(`Failed to assign Lissy93: ${err.message}`);
257 }
258
259 # Applies a label matching the "Type" picked in the PR template. Non-critical and
260 # fully self-contained: it never fails the run, and runs independently of the checks.
261 label-type:
262 name: Apply type label
263 runs-on: ubuntu-latest
264 if: github.event_name == 'pull_request_target'
265 permissions:
266 issues: write
267 pull-requests: write
268 concurrency:
269 group: label-type-${{ github.event.pull_request.number }}
270 cancel-in-progress: true
271 steps:
272 - name: Apply label from PR type
273 continue-on-error: true
274 uses: actions/github-script@v8
275 with:
276 github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }}
277 script: |
278 try {
279 const { owner, repo } = context.repo;
280 const pr = context.payload.pull_request;
281
282 // Template "Type" token -> label to apply
283 const TYPES = [
284 ['Addition', 'Addition'],
285 ['Amendment', 'Amendment'],
286 ['Removal', 'Removal'],
287 ['Spelling or Grammar', 'Grammar'],
288 ['Website', 'Website'],
289 ['Scripts', 'Scripts'],
290 ['Misc', 'Misc'],
291 ];
292 const managed = [...TYPES.map(t => t[1]), 'Uncategorized'];
293
294 // Isolate the "### Type" section, drop HTML comments, lowercase for matching
295 const body = pr.body || '';
296 const m = body.match(/###\s*Type\b([\s\S]*?)(?:\n\s*###|\n\s*---|$)/i);
297 const section = (m ? m[1] : '').replace(/<!--[\s\S]*?-->/g, '').toLowerCase();
298
299 // A correctly filled template leaves exactly one type; otherwise Uncategorized
300 const matched = TYPES.filter(t => section.includes(t[0].toLowerCase())).map(t => t[1]);
301 const desired = matched.length === 1 ? matched[0] : 'Uncategorized';
302
303 const current = (pr.labels || []).map(l => l.name);
304 for (const name of current.filter(l => managed.includes(l) && l !== desired)) {
305 await github.rest.issues.removeLabel({ owner, repo, issue_number: pr.number, name })
306 .catch(e => console.log(`Skip remove ${name}: ${e.message}`));
307 }
308
309 if (!current.includes(desired)) {
310 await github.rest.issues.getLabel({ owner, repo, name: desired }).catch(async e => {
311 if (e.status === 404) {
312 await github.rest.issues.createLabel({ owner, repo, name: desired, color: 'ededed' });
313 }
314 });
315 await github.rest.issues.addLabels({ owner, repo, issue_number: pr.number, labels: [desired] });
316 }
317 console.log(`Type label: ${desired} (matched ${matched.length})`);
318 } catch (err) {
319 console.log(`Type labeling skipped: ${err.message}`);
320 }