-
-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathchangelog-bump-comment
More file actions
executable file
·388 lines (314 loc) · 13 KB
/
changelog-bump-comment
File metadata and controls
executable file
·388 lines (314 loc) · 13 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#!/usr/bin/env php
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\SingleCommandApplication;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\Process;
/*
* Posts comments on open PRs in symfony/ai that have CHANGELOG.md or UPGRADE.md entries
* under a released version heading, asking authors to move entries to the next version.
*
* Usage:
* ./changelog-bump-comment # Auto-detect version from latest git tag
* ./changelog-bump-comment 0.7 # Specify released version explicitly
* ./changelog-bump-comment 0.7 --dry-run # Preview without posting comments
*
* @author Christopher Hertel <mail@christopher-hertel.de>
*/
(new SingleCommandApplication())
->setName('Changelog Bump Comment')
->setDescription('Posts comments on open PRs that have changelog entries under a released version heading.')
->addArgument('version', InputArgument::OPTIONAL, 'The released version (e.g., 0.7). Auto-detected from latest git tag if omitted.')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Preview affected PRs without posting comments')
->addOption('repo', null, InputOption::VALUE_REQUIRED, 'GitHub repository', 'symfony/ai')
->setCode(static function (InputInterface $input, OutputInterface $output): int {
$io = new SymfonyStyle($input, $output);
$repo = $input->getOption('repo');
$dryRun = $input->getOption('dry-run');
// Step 1: Determine versions
$releasedVersion = $input->getArgument('version');
if (null === $releasedVersion) {
$releasedVersion = detectVersionFromTag($io);
if (null === $releasedVersion) {
return Command::FAILURE;
}
}
if (!preg_match('/^(\d+)\.(\d+)$/', $releasedVersion, $matches)) {
$io->error(sprintf('Invalid version format "%s". Expected format: X.Y (e.g., 0.7)', $releasedVersion));
return Command::FAILURE;
}
$nextVersion = sprintf('%d.%d', (int) $matches[1], (int) $matches[2] + 1);
$io->title('Changelog Bump Comment');
$io->writeln(sprintf('Released version: <info>%s</info>', $releasedVersion));
$io->writeln(sprintf('Next version: <info>%s</info>', $nextVersion));
$io->newLine();
if ($dryRun) {
$io->note('Dry-run mode — no comments will be posted.');
$io->newLine();
}
// Step 2: List open PRs
$io->section('Scanning open PRs');
$prs = ghJson($repo, 'pr', 'list', '--state', 'open', '--json', 'number,title', '--limit', '300');
if (null === $prs) {
$io->error('Failed to list open PRs.');
return Command::FAILURE;
}
$io->writeln(sprintf('Found <info>%d</info> open PRs', count($prs)));
// Step 3: Find candidate PRs (touching CHANGELOG.md or UPGRADE.md)
$io->section('Finding PRs that touch CHANGELOG.md or UPGRADE.md');
$candidates = [];
$progressBar = $io->createProgressBar(count($prs));
$progressBar->start();
foreach ($prs as $pr) {
$number = $pr['number'];
$files = ghExec($repo, 'pr', 'diff', (string) $number, '--name-only');
if (null !== $files) {
$changelogFiles = [];
foreach (explode("\n", trim($files)) as $file) {
if (str_ends_with($file, 'CHANGELOG.md') || 'UPGRADE.md' === $file) {
$changelogFiles[] = $file;
}
}
if ([] !== $changelogFiles) {
$candidates[] = [
'number' => $number,
'title' => $pr['title'],
'files' => $changelogFiles,
];
}
}
$progressBar->advance();
}
$progressBar->finish();
$io->newLine(2);
$io->writeln(sprintf('Found <info>%d</info> candidate PRs', count($candidates)));
if ([] === $candidates) {
$io->success('No PRs touch CHANGELOG.md or UPGRADE.md. Nothing to do.');
return Command::SUCCESS;
}
// Step 4: Analyze diffs for entries under released version
$io->section('Analyzing diffs for entries under '.$releasedVersion.' heading');
$affected = [];
$progressBar = $io->createProgressBar(count($candidates));
$progressBar->start();
foreach ($candidates as $candidate) {
$diff = ghExec($repo, 'pr', 'diff', (string) $candidate['number']);
if (null === $diff) {
$progressBar->advance();
continue;
}
$affectedFiles = analyzeChangelog($diff, $releasedVersion);
$affectedUpgrade = analyzeUpgrade($diff, $releasedVersion);
$allAffected = array_merge($affectedFiles, $affectedUpgrade);
if ([] !== $allAffected) {
$affected[] = [
'number' => $candidate['number'],
'title' => $candidate['title'],
'affected_files' => $allAffected,
];
}
$progressBar->advance();
}
$progressBar->finish();
$io->newLine(2);
if ([] === $affected) {
$io->success('No PRs have entries under the '.$releasedVersion.' heading. Nothing to do.');
return Command::SUCCESS;
}
$io->writeln(sprintf('Found <info>%d</info> affected PRs:', count($affected)));
$io->newLine();
foreach ($affected as $pr) {
$io->writeln(sprintf(' <info>#%d</info> %s', $pr['number'], $pr['title']));
foreach ($pr['affected_files'] as $file) {
$io->writeln(sprintf(' - %s', $file));
}
}
$io->newLine();
if ($dryRun) {
$io->success(sprintf('Dry-run complete. %d PRs would receive a comment.', count($affected)));
return Command::SUCCESS;
}
// Step 5: Check for duplicates and post comments
$io->section('Posting comments');
$marker = sprintf('<!-- changelog-version-bump:%s -->', $releasedVersion);
$commented = 0;
$skippedDuplicate = 0;
foreach ($affected as $pr) {
$number = $pr['number'];
// Check for existing comment
$existingComments = ghExec($repo, 'pr', 'view', (string) $number, '--json', 'comments');
if (null !== $existingComments && str_contains($existingComments, 'changelog-version-bump:'.$releasedVersion)) {
$io->writeln(sprintf(' <comment>⊘</comment> #%d — already commented, skipping', $number));
++$skippedDuplicate;
continue;
}
// Build file list
$fileList = implode("\n", array_map(static fn (string $f) => sprintf('- `%s`', $f), $pr['affected_files']));
$body = <<<COMMENT
{$marker}
Hi! Version **{$releasedVersion}** has been released. This PR has changelog/upgrade entries under the `{$releasedVersion}` heading, which is now a released version.
Please update the following files to place your entries under the next version **{$nextVersion}**:
{$fileList}
**For `CHANGELOG.md` files**: change the version heading from `{$releasedVersion}` to `{$nextVersion}`
**For `UPGRADE.md`**: place entries under `UPGRADE FROM {$releasedVersion} to {$nextVersion}`
Thank you!
---
<sub>🤖 This comment was generated automatically.</sub>
COMMENT;
$result = ghExec($repo, 'pr', 'comment', (string) $number, '--body', $body);
if (null !== $result) {
$io->writeln(sprintf(' <info>✓</info> #%d — commented', $number));
++$commented;
} else {
$io->writeln(sprintf(' <error>✗</error> #%d — failed to post comment', $number));
}
}
// Step 6: Summary
$io->newLine();
$io->success(sprintf(
"Done!\n Affected PRs: %d\n Comments posted: %d\n Skipped (already commented): %d",
count($affected),
$commented,
$skippedDuplicate,
));
return Command::SUCCESS;
})
->run();
function detectVersionFromTag(SymfonyStyle $io): ?string
{
$process = new Process(['git', 'tag', '--sort=-v:refname']);
$process->run();
if (!$process->isSuccessful()) {
$io->error('Failed to list git tags.');
return null;
}
$tags = array_filter(explode("\n", trim($process->getOutput())));
if ([] === $tags) {
$io->error('No git tags found.');
return null;
}
$latestTag = $tags[0];
if (!preg_match('/^v?(\d+)\.(\d+)/', $latestTag, $matches)) {
$io->error(sprintf('Could not parse version from tag "%s".', $latestTag));
return null;
}
return sprintf('%d.%d', (int) $matches[1], (int) $matches[2]);
}
/**
* Analyze diff for CHANGELOG.md files with entries under the released version heading.
*
* @return list<string> List of affected file paths
*/
function analyzeChangelog(string $diff, string $releasedVersion): array
{
$affected = [];
$currentFile = null;
$inReleasedSection = false;
$escapedVersion = preg_quote($releasedVersion, '/');
foreach (explode("\n", $diff) as $line) {
// Track current file
if (preg_match('#^diff --git a/(.+) b/#', $line, $m)) {
$currentFile = $m[1];
$inReleasedSection = false;
continue;
}
if (null === $currentFile || !str_ends_with($currentFile, 'CHANGELOG.md')) {
continue;
}
// Strip diff prefix for heading detection (context lines start with ' ', added with '+')
$stripped = ltrim($line, ' +-');
// Detect version headings
if (preg_match('/^'.$escapedVersion.'\s*$/', $stripped)) {
$inReleasedSection = true;
continue;
}
if (preg_match('/^\d+\.\d+\s*$/', $stripped) && !preg_match('/^'.$escapedVersion.'\s*$/', $stripped)) {
$inReleasedSection = false;
continue;
}
// Check for added bullet entries under released version
if ($inReleasedSection && str_starts_with($line, '+') && !str_starts_with($line, '+++') && preg_match('/^\+\s+\*\s/', $line)) {
if (!in_array($currentFile, $affected, true)) {
$affected[] = $currentFile;
}
}
}
return $affected;
}
/**
* Analyze diff for UPGRADE.md entries under the released version heading.
*
* @return list<string> List of affected file paths (will be ['UPGRADE.md'] or empty)
*/
function analyzeUpgrade(string $diff, string $releasedVersion): array
{
$inUpgradeFile = false;
$inReleasedSection = false;
$escapedVersion = preg_quote($releasedVersion, '/');
foreach (explode("\n", $diff) as $line) {
if (preg_match('#^diff --git a/(.+) b/#', $line, $m)) {
$inUpgradeFile = 'UPGRADE.md' === $m[1];
$inReleasedSection = false;
continue;
}
if (!$inUpgradeFile) {
continue;
}
$stripped = ltrim($line, ' +-');
// Detect UPGRADE headings
if (preg_match('/^UPGRADE FROM .+ to '.$escapedVersion.'\s*$/', $stripped)) {
$inReleasedSection = true;
continue;
}
if (preg_match('/^UPGRADE FROM /', $stripped) && !preg_match('/to '.$escapedVersion.'\s*$/', $stripped)) {
$inReleasedSection = false;
continue;
}
// Check for added content under released version
if ($inReleasedSection && str_starts_with($line, '+') && !str_starts_with($line, '+++') && '' !== trim(substr($line, 1))) {
return ['UPGRADE.md'];
}
}
return [];
}
/**
* Execute a gh CLI command and return stdout.
*/
function ghExec(string $repo, string ...$args): ?string
{
$command = array_merge(['gh'], $args, ['--repo', $repo]);
$process = new Process($command);
$process->setTimeout(60);
$process->run();
if (!$process->isSuccessful()) {
return null;
}
return $process->getOutput();
}
/**
* Execute a gh CLI command and return parsed JSON.
*
* @return list<array<string, mixed>>|null
*/
function ghJson(string $repo, string ...$args): ?array
{
$output = ghExec($repo, ...$args);
if (null === $output) {
return null;
}
$data = json_decode($output, true);
return is_array($data) ? $data : null;
}