-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate-pr-body.cjs
More file actions
272 lines (241 loc) · 6.9 KB
/
Copy pathvalidate-pr-body.cjs
File metadata and controls
272 lines (241 loc) · 6.9 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
/**
* Validate a GitHub PR body against the fluent-mobile PR template.
*
* Required (human + agent PRs):
* - ### TLDR with non-placeholder prose
* - Refs #NNN (non-closing issue link) OR `Refs: none` for explicit no-ticket chores
* - ### How to verify with at least one real step or an explicit waiver
*
* Soft-fails templates that are empty, HTML-comment-only, or CodeRabbit-only.
*
* CLI:
* node .github/scripts/validate-pr-body.cjs --body-file path.md
* node .github/scripts/validate-pr-body.cjs --body "..." [--author login]
*
* Env (Actions):
* PR_BODY, PR_AUTHOR
*/
'use strict';
const fs = require('fs');
const DEPENDABOT_LOGINS = new Set([
'dependabot',
'dependabot[bot]',
'dependabot-preview[bot]',
]);
/**
* @param {string | null | undefined} author
* @returns {boolean}
*/
function isExemptAuthor(author) {
if (!author || typeof author !== 'string') return false;
return DEPENDABOT_LOGINS.has(author.trim().toLowerCase());
}
/**
* Strip HTML comments and normalize newlines.
* @param {string} text
* @returns {string}
*/
function stripHtmlComments(text) {
return String(text || '')
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/\r\n/g, '\n');
}
/**
* Remove CodeRabbit auto-summary blocks (common empty-body filler).
* @param {string} text
* @returns {string}
*/
function stripCodeRabbitSummary(text) {
return String(text || '')
.replace(
/##\s*Summary by CodeRabbit[\s\S]*?(?=\n##\s|\n###\s|$)/gi,
'\n',
)
.replace(/\n{3,}/g, '\n\n')
.trim();
}
/**
* Extract markdown section body after a ### heading until the next ###/##.
* @param {string} text
* @param {string} headingTitle e.g. "TLDR"
* @returns {string | null} null if heading missing
*/
function extractSection(text, headingTitle) {
const escaped = headingTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(
`^###\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=\\n###\\s|\\n##\\s|$)`,
'im',
);
const match = String(text || '').match(re);
return match ? match[1].trim() : null;
}
/**
* @param {string} text
* @returns {boolean}
*/
function hasRefsIssueLink(text) {
return /(?:^|\n)\s*Refs\s*:?\s*#\d+\b/im.test(String(text || ''));
}
/**
* Explicit no-ticket waiver for chore / infra PRs (e.g. process-only changes).
* Must be `Refs: none` (or `Refs none`) on its own line — not a missing Refs.
*
* @param {string} text
* @returns {boolean}
*/
function hasRefsNoneWaiver(text) {
return /(?:^|\n)\s*Refs\s*:?\s*none\s*$/im.test(String(text || ''));
}
/**
* True when section text is empty or only checklist/placeholder chrome.
* @param {string} sectionBody
* @returns {boolean}
*/
function isPlaceholderOrEmpty(sectionBody) {
const cleaned = stripHtmlComments(sectionBody)
.replace(/^\s*[-*]\s*\[[ xX]\]\s*$/gm, '')
.replace(/^\s*[-*]\s*$/gm, '')
.replace(/^\s*\d+\.\s*$/gm, '')
.replace(/\*\*Expected:\*\*\s*/gi, '')
.replace(/\s+/g, ' ')
.trim();
if (!cleaned) return true;
// Unfilled template crumbs
if (/^issue number this PR implements$/i.test(cleaned)) return true;
return cleaned.length < 12;
}
/**
* @typedef {{ ok: true, skipped?: boolean, reason?: string } | { ok: false, errors: string[] }} ValidateResult
*/
/**
* @param {{ body?: string | null, author?: string | null }} input
* @returns {ValidateResult}
*/
function validatePrBody(input) {
const author = input?.author ?? null;
if (isExemptAuthor(author)) {
return {
ok: true,
skipped: true,
reason: `Exempt author (${author}) — skipping PR description check`,
};
}
const raw = input?.body ?? '';
const errors = [];
if (!String(raw).trim()) {
return {
ok: false,
errors: [
'PR body is empty. Fill `.github/PULL_REQUEST_TEMPLATE.md` (TLDR, Refs #NNN, How to verify).',
],
};
}
const withoutBot = stripCodeRabbitSummary(raw);
// Normalized author content — required-field checks must use this, not raw,
// so HTML-comment-only "fake" TLDR / Refs / How to verify do not pass.
const body = stripHtmlComments(withoutBot).trim();
if (!body) {
errors.push(
'PR body has no author content after removing HTML comments / CodeRabbit summary.',
);
}
const tldr = extractSection(body, 'TLDR');
if (tldr === null) {
errors.push('Missing `### TLDR` section.');
} else if (isPlaceholderOrEmpty(tldr)) {
errors.push(
'`### TLDR` is empty or still has template placeholders — write 2–4 sentences.',
);
}
if (!hasRefsIssueLink(body) && !hasRefsNoneWaiver(body)) {
errors.push(
'Missing `Refs #NNN` on its own line (or `Refs: none` for an explicit no-ticket chore). Do not use Closes/Fixes/Resolves.',
);
}
const howToVerify = extractSection(body, 'How to verify');
if (howToVerify === null) {
errors.push('Missing `### How to verify` section.');
} else if (isPlaceholderOrEmpty(howToVerify)) {
errors.push(
'`### How to verify` is empty — add numbered steps or an explicit waiver.',
);
}
// Catch CodeRabbit-only bodies that happen to lack our headings entirely
if (
body.length > 0 &&
/summary by coderabbit/i.test(raw) &&
tldr === null &&
howToVerify === null
) {
errors.push(
'Body looks CodeRabbit-only. Replace with the team PR template.',
);
}
if (errors.length > 0) {
return { ok: false, errors: [...new Set(errors)] };
}
return { ok: true };
}
/**
* @param {string[]} argv
* @returns {{ body: string, author: string | null }}
*/
function parseCliArgs(argv) {
let body = process.env.PR_BODY ?? '';
let author = process.env.PR_AUTHOR ?? null;
let bodyFile = null;
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--body-file' && argv[i + 1]) {
bodyFile = argv[i + 1];
i += 1;
} else if (arg === '--body' && argv[i + 1]) {
body = argv[i + 1];
i += 1;
} else if (arg === '--author' && argv[i + 1]) {
author = argv[i + 1];
i += 1;
}
}
if (bodyFile) {
body = fs.readFileSync(bodyFile, 'utf8');
}
return { body, author };
}
function main(argv = process.argv.slice(2)) {
const { body, author } = parseCliArgs(argv);
const result = validatePrBody({ body, author });
if (result.ok) {
if (result.skipped) {
console.log(result.reason);
} else {
console.log('PR description check passed.');
}
process.exitCode = 0;
return result;
}
console.error('PR description check failed:\n');
for (const err of result.errors) {
console.error(`- ${err}`);
}
console.error(
'\nFill `.github/PULL_REQUEST_TEMPLATE.md` (same content as `.cursor/templates/pr-template.md`).',
);
process.exitCode = 1;
return result;
}
if (require.main === module) {
main();
}
module.exports = {
validatePrBody,
isExemptAuthor,
stripHtmlComments,
stripCodeRabbitSummary,
extractSection,
hasRefsIssueLink,
hasRefsNoneWaiver,
isPlaceholderOrEmpty,
parseCliArgs,
main,
};