Repository navigation
327 lines (320 loc) · 14 KB
/
Copy pathpr-api-doc-comment.yml
File metadata and controls
327 lines (320 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
name: PR Documentation Summary
on:
workflow_run:
workflows: ["PR Documentation Checks"]
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
jobs:
comment:
concurrency:
group: pr-documentation-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_sha }}
cancel-in-progress: false
if: >-
github.event.workflow_run.event == 'pull_request' &&
github.event.workflow_run.conclusion != 'skipped'
continue-on-error: true
runs-on: ubuntu-latest
steps:
- name: Resolve pull request number
id: pr
uses: actions/github-script@v7
env:
CANDIDATE_PR: ${{ github.event.workflow_run.pull_requests[0].number }}
HEAD_REPOSITORY: ${{ github.event.workflow_run.head_repository.full_name }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
with:
result-encoding: string
script: |
const candidate = String(process.env.CANDIDATE_PR || '').trim();
const { owner, repo } = context.repo;
const headSha = process.env.HEAD_SHA;
if (/^[1-9][0-9]*$/.test(candidate)) {
try {
const { data: candidatePr } = await github.rest.pulls.get({
owner,
repo,
pull_number: Number(candidate),
});
if (candidatePr.state === 'open' && candidatePr.head.sha === headSha) {
return candidate;
}
core.info(`Ignoring stale pull request candidate #${candidate}`);
} catch (error) {
core.warning(`Could not validate pull request #${candidate}: ${error.message}`);
}
}
const headRepository = process.env.HEAD_REPOSITORY || `${owner}/${repo}`;
const [headOwner, headRepo] = headRepository.split('/', 2);
let associated = [];
try {
const response = await github.rest.repos.listPullRequestsAssociatedWithCommit({
owner: headOwner,
repo: headRepo,
commit_sha: headSha,
});
associated = response.data;
} catch (error) {
core.warning(`Could not query associated PRs in ${headRepository}: ${error.message}`);
}
let matches = associated.filter((pr) =>
pr.state === 'open'
&& pr.head.sha === headSha
&& pr.base.repo.full_name === `${owner}/${repo}`
);
if (!matches.length) {
const openPullRequests = await github.paginate(github.rest.pulls.list, {
owner,
repo,
state: 'open',
per_page: 100,
});
matches = openPullRequests.filter((pr) => pr.head.sha === headSha);
}
const pullRequest = matches.find((pr) => pr.base.ref === 'main') || matches[0];
if (!pullRequest) {
core.warning(`No open pull request found for workflow head ${headSha}`);
return '';
}
return String(pullRequest.number);
- name: Download untrusted report data
if: steps.pr.outputs.result != ''
continue-on-error: true
uses: actions/download-artifact@v4
with:
name: pr-documentation-report
path: reports
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Update PR documentation summary
if: steps.pr.outputs.result != ''
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ steps.pr.outputs.result }}
RUN_URL: ${{ github.event.workflow_run.html_url }}
with:
script: |
const fs = require('fs');
const marker = '<!-- flashinfer-pr-documentation-summary -->';
const prNumber = Number(process.env.PR_NUMBER);
const runUrl = process.env.RUN_URL;
const { owner, repo } = context.repo;
const escape = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\r?\n/g, ' ')
.slice(0, 500);
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: prNumber, per_page: 100,
});
const previous = comments.find((comment) =>
comment.user?.login === 'github-actions[bot]'
&& comment.body.includes(marker)
);
const publicApiFindings = [];
const documentationFindings = [];
const reportErrors = [];
const reportTargets = [
['reports/public-api.json', publicApiFindings],
['reports/static-documentation.json', documentationFindings],
];
for (const [file, target] of reportTargets) {
if (!fs.existsSync(file)) {
reportErrors.push(`${file} is missing`);
continue;
}
try {
const report = JSON.parse(fs.readFileSync(file, 'utf8'));
for (const finding of report.findings || []) target.push(finding);
} catch (error) {
core.warning(`Ignoring malformed report ${file}: ${error.message}`);
reportErrors.push(`${file} is malformed`);
}
}
let executionStatus = {};
if (fs.existsSync('reports/execution-status.json')) {
try {
executionStatus = JSON.parse(fs.readFileSync('reports/execution-status.json', 'utf8'));
} catch (error) {
reportErrors.push('execution-status.json is malformed');
}
} else {
reportErrors.push('execution-status.json is missing');
}
const failedChecks = Object.entries(executionStatus)
.filter(([, outcome]) => outcome !== 'success')
.map(([name]) => name);
const findings = [...publicApiFindings, ...documentationFindings];
const hasProblems = Boolean(
findings.length || failedChecks.length || reportErrors.length
);
if (!hasProblems) {
if (previous) {
await github.rest.issues.deleteComment({
owner,
repo,
comment_id: previous.id,
});
core.info('Documentation findings resolved; removed the existing summary.');
} else {
core.info('Clean PR with no existing documentation summary; no comment needed.');
}
return;
}
const publicRows = publicApiFindings.slice(0, 20);
const documentationRows = documentationFindings.slice(0, 20);
const sections = [marker];
if (publicApiFindings.length) {
sections.push(
'# 🚨 POTENTIAL BREAKING PUBLIC API CHANGE DETECTED 🚨',
'',
'> [!CAUTION]',
'> **THIS PR APPEARS TO BREAK THE PUBLIC API. AUTHORS AND REVIEWERS: DO NOT MISS THIS.**',
'>',
'> This is an advisory warning and does not gate merging. Confirm compatibility and provide a deprecation or migration path, or track the fix in a follow-up PR.',
'',
`${publicApiFindings.length} public API finding(s):`,
'',
publicRows.map((f) => `- \`${escape(f.path)}:${Number(f.line) || 1}\` — ${escape(f.message)}`).join('\n'),
);
}
if (documentationFindings.length) {
sections.push(
'## Documentation checks ⚠️',
'',
`${documentationFindings.length} new documentation finding(s):`,
'',
documentationRows.map((f) => `- \`${escape(f.path)}:${Number(f.line) || 1}\` — ${escape(f.message)}`).join('\n'),
);
}
if (failedChecks.length || reportErrors.length) {
const problems = [
...failedChecks.map((name) => `${name} did not complete`),
...reportErrors,
];
sections.push(
'# 🚨 ADVISORY CHECKER REPORT IS INCOMPLETE 🚨',
'',
'> [!WARNING]',
`> ${escape(problems.join('; '))}. The checker remains non-blocking, but this run must not be treated as a clean result.`,
);
}
sections.push('', `[View the full check run](${runUrl})`);
const body = sections.join('\n');
if (previous) {
await github.rest.issues.updateComment({ owner, repo, comment_id: previous.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: prNumber, body });
}
- name: Post inline documentation findings
if: steps.pr.outputs.result != ''
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ steps.pr.outputs.result }}
with:
script: |
const fs = require('fs');
const crypto = require('crypto');
const marker = 'flashinfer-pr-documentation-inline';
const prNumber = Number(process.env.PR_NUMBER);
const escape = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\r?\n/g, ' ')
.slice(0, 500);
const findings = [];
for (const [file, category] of [
['reports/public-api.json', 'public_api'],
['reports/static-documentation.json', 'documentation'],
]) {
if (!fs.existsSync(file)) continue;
try {
const report = JSON.parse(fs.readFileSync(file, 'utf8'));
findings.push(...(report.findings || []).map((finding) => ({
...finding,
category,
})));
} catch (error) {
core.warning(`Ignoring malformed report ${file}: ${error.message}`);
}
}
const { owner, repo } = context.repo;
const [pr, changedFiles, existingComments] = await Promise.all([
github.rest.pulls.get({ owner, repo, pull_number: prNumber }),
github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: prNumber, per_page: 100 }),
github.paginate(github.rest.pulls.listReviewComments, { owner, repo, pull_number: prNumber, per_page: 100 }),
]);
const changedPaths = new Set(changedFiles.map((file) => file.filename));
const existingKeys = new Set(
existingComments
.filter((comment) =>
comment.user?.login === 'github-actions[bot]'
&& comment.body.includes(marker)
)
.map((comment) => comment.body.match(/<!-- key:(.*?) -->/)?.[1])
.filter(Boolean),
);
const candidates = [];
const candidateKeys = new Set();
for (const finding of findings) {
const path = String(finding.path || '');
const line = Number(finding.line);
const key = crypto.createHash('sha256')
.update(JSON.stringify([finding.check, path, finding.message]))
.digest('hex');
if (!path || !Number.isInteger(line) || line < 1 || !changedPaths.has(path)) continue;
if (!existingKeys.has(key) && !candidateKeys.has(key)) {
candidates.push({ finding, key, path, line });
candidateKeys.add(key);
}
}
const reviewComments = candidates.slice(0, 20).map(
({ finding, key, path, line }) => ({
path,
line,
side: 'RIGHT',
body: finding.category === 'public_api'
? `<!-- ${marker} --><!-- key:${key} -->\n🚨🚨🚨 **POTENTIAL BREAKING PUBLIC API CHANGE:** ${escape(finding.message)}`
: `<!-- ${marker} --><!-- key:${key} -->\n⚠️ **Documentation check:** ${escape(finding.message)}`,
})
);
if (!reviewComments.length) {
core.info('No new inline documentation findings to post.');
return;
}
try {
await github.rest.pulls.createReview({
owner,
repo,
pull_number: prNumber,
commit_id: pr.data.head.sha,
event: 'COMMENT',
body: `<!-- ${marker} -->\n${reviewComments.length} new documentation finding(s) generated from the static PR check.`,
comments: reviewComments,
});
} catch (error) {
core.warning(`Could not post inline documentation review: ${error.message}`);
// A line may no longer be commentable after a concurrent push.
// Retry individually so one stale location does not hide the rest.
for (const comment of reviewComments) {
try {
await github.rest.pulls.createReview({
owner,
repo,
pull_number: prNumber,
commit_id: pr.data.head.sha,
event: 'COMMENT',
body: `<!-- ${marker} -->\nDocumentation finding generated from the static PR check.`,
comments: [comment],
});
} catch (commentError) {
core.warning(
`Could not post inline finding for ${comment.path}:${comment.line}: ${commentError.message}`
);
}
}
}