-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-pr-message.ps1
More file actions
executable file
·414 lines (354 loc) · 12.9 KB
/
generate-pr-message.ps1
File metadata and controls
executable file
·414 lines (354 loc) · 12.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<#
.SYNOPSIS
Fetches a GitHub PR and uses an AI agent to generate a PR title, PR message body, and/or squash-merge commit message.
.USAGE
.\generate-pr-message.ps1 <PR_URL> [-Mode <all|title|message|squash>] [-OutputFile <path>] [-Agent <command>] [-MaxDiffLength <int>]
.EXAMPLE
.\generate-pr-message.ps1 https://github.com/ROCm/rocm-systems/pull/3423
.\generate-pr-message.ps1 https://github.com/ROCm/rocm-systems/pull/3423 -Mode title
.\generate-pr-message.ps1 https://github.com/ROCm/rocm-systems/pull/3423 -Mode message
.\generate-pr-message.ps1 https://github.com/ROCm/rocm-systems/pull/3423 -Mode squash
.\generate-pr-message.ps1 https://github.com/ROCm/rocm-systems/pull/3423 -OutputFile pr-message.md
.NOTES
Requires agent.cmd (or the command specified by -Agent) to be available in PATH.
#>
param(
[Parameter(Mandatory=$true, Position=0)]
[string]$PrUrl,
[Parameter(Mandatory=$false)]
[ValidateSet("all", "title", "message", "squash")]
[string]$Mode = "all",
[Parameter(Mandatory=$false)]
[string]$OutputFile,
[Parameter(Mandatory=$false)]
[string]$Agent = "agent.cmd",
[Parameter(Mandatory=$false)]
[int]$MaxDiffLength = 12000
)
# --- Validate agent command ---
if (-not (Get-Command $Agent -ErrorAction SilentlyContinue)) {
Write-Error "'$Agent' command not found in PATH."
exit 127
}
# --- Parse PR URL ---
if ($PrUrl -match "github\.com/([^/]+)/([^/]+)/pull/(\d+)") {
$owner = $Matches[1]
$repo = $Matches[2]
$prNum = $Matches[3]
} else {
Write-Error "Invalid PR URL. Expected: https://github.com/{owner}/{repo}/pull/{number}"
exit 1
}
Write-Host "Fetching PR #$prNum from $owner/$repo ..." -ForegroundColor Cyan
# --- GitHub API helpers ---
$ghHeaders = @{
"Accept" = "application/vnd.github.v3+json"
"User-Agent" = "PR-Message-Generator"
}
$token = $env:GITHUB_TOKEN
if (-not $token -and (Get-Command "gh" -ErrorAction SilentlyContinue)) {
$token = gh auth token 2>$null
}
if ($token) {
$ghHeaders["Authorization"] = "Bearer $token"
}
$apiBase = "https://api.github.com/repos/$owner/$repo/pulls/$prNum"
try {
$pr = Invoke-RestMethod -Uri $apiBase -Headers $ghHeaders -Method Get
} catch {
Write-Error "Failed to fetch PR: $_"
exit 1
}
# --- Fetch changed file list (paginated) ---
Write-Host "Fetching file list ..." -ForegroundColor Cyan
$fileList = ""
$fileListCount = 0
try {
for ($page = 1; $page -le 3; $page++) {
$pageFiles = Invoke-RestMethod -Uri "$apiBase/files?per_page=100&page=$page" -Headers $ghHeaders -Method Get
if (-not $pageFiles -or $pageFiles.Count -eq 0) { break }
$pageList = ($pageFiles | ForEach-Object {
"$($_.status): $($_.filename) (+$($_.additions)/-$($_.deletions))"
}) -join "`n"
if ($fileList) { $fileList += "`n" }
$fileList += $pageList
$fileListCount += $pageFiles.Count
if ($pageFiles.Count -lt 100) { break }
}
} catch {
$fileList = "(could not fetch file list)"
}
if (-not $fileList) { $fileList = "(could not fetch file list)" }
$fileListNote = ""
if ($fileListCount -gt 0 -and $changedFiles -gt $fileListCount) {
$fileListNote = " (showing $fileListCount of $changedFiles files)"
}
# --- Fetch commit list (paginated) ---
Write-Host "Fetching commits ..." -ForegroundColor Cyan
$commitList = ""
$commitCount = 0
try {
for ($page = 1; $page -le 3; $page++) {
$pageCommits = Invoke-RestMethod -Uri "$apiBase/commits?per_page=100&page=$page" -Headers $ghHeaders -Method Get
if (-not $pageCommits -or $pageCommits.Count -eq 0) { break }
$pageList = ($pageCommits | ForEach-Object {
"$($_.sha.Substring(0,8)) $($_.commit.message.Split("`n")[0])"
}) -join "`n"
if ($commitList) { $commitList += "`n" }
$commitList += $pageList
$commitCount += $pageCommits.Count
if ($pageCommits.Count -lt 100) { break }
}
} catch {
$commitList = "(could not fetch commits)"
}
if (-not $commitList) { $commitList = "(could not fetch commits)" }
# --- Fetch diff ---
Write-Host "Fetching diff ..." -ForegroundColor Cyan
$diffHeaders = $ghHeaders.Clone()
$diffHeaders["Accept"] = "application/vnd.github.v3.diff"
$diffTruncated = $false
$diffFullLength = 0
try {
$diff = Invoke-RestMethod -Uri $apiBase -Headers $diffHeaders -Method Get
$diffFullLength = $diff.Length
if ($diff.Length -gt $MaxDiffLength) {
$diff = $diff.Substring(0, $MaxDiffLength) + "`n... [diff truncated at $MaxDiffLength of $diffFullLength chars] ..."
$diffTruncated = $true
}
} catch {
$diff = "(could not fetch diff)"
}
# --- Fetch first comment ---
Write-Host "Fetching comments ..." -ForegroundColor Cyan
$issueCommentsUrl = "https://api.github.com/repos/$owner/$repo/issues/$prNum/comments?per_page=1"
try {
$comments = Invoke-RestMethod -Uri $issueCommentsUrl -Headers $ghHeaders -Method Get
if ($comments -and $comments.Count -gt 0) {
$firstComment = $comments[0].body
$firstCommentAuthor = $comments[0].user.login
} else {
$firstComment = $null
}
} catch {
$firstComment = $null
}
# --- PR metadata ---
$title = $pr.title
$author = $pr.user.login
$baseBranch = $pr.base.ref
$headBranch = $pr.head.ref
$additions = $pr.additions
$deletions = $pr.deletions
$changedFiles = $pr.changed_files
$body = if ($pr.body) { $pr.body } else { "(no description provided)" }
# --- Fetch PR template (needed for "message" and "all" modes) ---
$template = $null
if ($Mode -eq "all" -or $Mode -eq "message") {
$templateUrl = "https://raw.githubusercontent.com/$owner/$repo/$baseBranch/.github/pull_request_template.md"
Write-Host "Fetching PR template from $owner/$repo ($baseBranch) ..." -ForegroundColor Cyan
try {
$template = Invoke-RestMethod -Uri $templateUrl -Headers @{ "User-Agent" = "PR-Message-Generator" } -Method Get
} catch {
Write-Warning "Could not fetch PR template from repo, using built-in fallback."
$template = @"
## Motivation
## Technical Details
## JIRA ID
## Test Plan
## Test Result
## Submission Checklist
- [ ] Look over the contributing guidelines at https://github.com/ROCm/ROCm/blob/develop/CONTRIBUTING.md#pull-requests.
"@
}
}
# --- Build prompt ---
$firstCommentSection = if ($firstComment) {
"`n## First Comment (by @$firstCommentAuthor)`n`n$firstComment"
} else { "" }
$commitSection = ""
if ($commitList -ne "(could not fetch commits)") {
$commitSection = "`n`n## Commits ($commitCount total)`n`n$commitList"
}
$dataNote = ""
if ($diffTruncated) {
$dataNote = "`n`nNOTE: The diff is truncated (showing $MaxDiffLength of $diffFullLength chars). Rely on the commit list and file list for full scope."
}
$prContext = @"
# PR Information
- Current Title: $title
- Author: @$author
- Branch: $headBranch -> $baseBranch
- Changed files: $changedFiles (+$additions/-$deletions)
- URL: $PrUrl
## Original PR Description
$body
$firstCommentSection
$commitSection
## Changed Files${fileListNote}
$fileList
${dataNote}
## Diff
$diff
"@
# --- Extract JIRA ID from title or body (ignore HTML comment examples) ---
$jiraId = $null
$bodyNoComments = $body -replace '(?s)<!--.*?-->', ''
if ($title -match '([A-Z][A-Z0-9]+-\d+)') {
$jiraId = $Matches[1]
} elseif ($bodyNoComments -match '([A-Z][A-Z0-9]+-\d+)') {
$jiraId = $Matches[1]
}
if ($jiraId) {
Write-Host "Detected JIRA ID: $jiraId" -ForegroundColor Cyan
$titleRules = @"
- Use the JIRA ID as the title prefix instead of a type prefix
- Format: ${jiraId}: <short description>
- Capitalize first letter of description, imperative mood, no period, max 72 characters
"@
$messageRules = @"
- Be brief and concise — use short sentences, no filler, no repetition
- Each section should be 1-3 sentences or a short bullet list at most
- For the JIRA ID section, output exactly: $jiraId
"@
$squashRules = @"
- Use the JIRA ID as the subject line prefix instead of a type prefix
- Subject line format: ${jiraId}: <short description> (#$prNum)
- Capitalize first letter of description, imperative mood, no period, max 72 characters
- Include the PR number (#$prNum) at the end of the subject line
- Body: 1-3 short bullet points summarizing the key changes, separated from subject by a blank line
- Wrap body lines at 72 characters; break mid-sentence if needed to stay within the limit
"@
} else {
$titleRules = @"
- Start with a type prefix: feat, fix, refactor, docs, test, chore, style, perf, ci, build
- Format: <type>: <short description>
- Capitalize first letter of description, imperative mood, no period, max 72 characters
"@
$messageRules = @"
- Be brief and concise — use short sentences, no filler, no repetition
- Each section should be 1-3 sentences or a short bullet list at most
- For the JIRA ID section, output ONLY the JIRA ticket ID if one exists in the PR title or description — no prefix like Resolves, Fixes, Closes, etc.
- Ignore any example/placeholder JIRA IDs in the template HTML comments (e.g., SWDEV-12345 is NOT a real ID)
"@
$squashRules = @"
- type is one of: feat, fix, refactor, docs, test, chore, style, perf, ci, build
- Subject line: capitalize first letter, imperative mood, no period, max 72 characters
- Include the PR number (#$prNum) at the end of the subject line
- Body: 1-3 short bullet points summarizing the key changes, separated from subject by a blank line
- Wrap body lines at 72 characters; break mid-sentence if needed to stay within the limit
"@
}
switch ($Mode) {
"title" {
$prompt = @"
Generate a PR title for the following pull request.
Rules:
$titleRules
- Output ONLY the title line, nothing else — no explanation, no quotes, no markdown fences
$prContext
"@
}
"message" {
$prompt = @"
Fill in the PR template below for the following pull request.
Rules:
$messageRules
- Output ONLY the filled template, nothing else — no title, no explanation, no quotes, no markdown fences
$prContext
## Template to Fill
$template
"@
}
"squash" {
$prompt = @"
Generate a squash-merge commit message for this GitHub PR.
Format:
<type>: <short description> (#$prNum)
- bullet 1
- bullet 2
Rules:
$squashRules
- Output ONLY the commit message, nothing else — no explanation, no quotes, no markdown fences
$prContext
"@
}
"all" {
$prompt = @"
Generate three outputs for this GitHub PR, separated by the exact delimiters shown below.
===TITLE===
A single PR title line.
===MESSAGE===
A filled-in PR template body.
===SQUASH===
A squash-merge commit message.
Rules for TITLE:
$titleRules
Rules for MESSAGE:
$messageRules
Rules for SQUASH (format: <type>: <short description> (#$prNum)\n\n- bullet 1\n- bullet 2):
$squashRules
Output ONLY the three sections with delimiters. No explanation, no quotes, no markdown fences.
$prContext
## Template to Fill (for MESSAGE section)
$template
"@
}
}
# --- Call agent ---
Write-Host "Generating via $Agent (mode: $Mode) ..." -ForegroundColor Cyan
try {
$raw = $prompt | & $Agent -p --trust
$message = if ($raw -is [array]) { $raw -join "`n" } else { "$raw" }
} catch {
Write-Error "Agent call failed: $_"
exit 1
}
# --- Parse and display ---
function Show-Section($header, $color, $content) {
Write-Host ""
Write-Host "--- $header ---" -ForegroundColor $color
Write-Host ""
$content -split "`n" | ForEach-Object { Write-Host $_ }
}
if ($Mode -eq "all") {
$titleContent = ""
$msgContent = ""
$squashContent = ""
if ($message -match '(?s)===TITLE===\s*(.+?)===MESSAGE===\s*(.+?)===SQUASH===\s*(.+)$') {
$titleContent = $Matches[1].Trim()
$msgContent = $Matches[2].Trim()
$squashContent = $Matches[3].Trim()
} else {
Write-Warning "Could not parse delimited output; showing raw response."
$titleContent = $message
}
if ($titleContent) { Show-Section "PR Title" Green $titleContent }
if ($msgContent) { Show-Section "PR Message" Green $msgContent }
if ($squashContent) { Show-Section "Squash Merge Message" Green $squashContent }
$output = @()
if ($titleContent) { $output += "===TITLE==="; $output += $titleContent; $output += "" }
if ($msgContent) { $output += "===MESSAGE==="; $output += $msgContent; $output += "" }
if ($squashContent) { $output += "===SQUASH==="; $output += $squashContent }
$message = $output -join "`n"
} elseif ($Mode -eq "title") {
Show-Section "PR Title" Green $message
} elseif ($Mode -eq "message") {
Show-Section "PR Message" Green $message
} elseif ($Mode -eq "squash") {
Show-Section "Squash Merge Message" Green $message
}
# --- Output to file or clipboard ---
if ($OutputFile) {
$message | Out-File -FilePath $OutputFile -Encoding utf8
Write-Host ""
Write-Host "Saved to $OutputFile" -ForegroundColor Yellow
} else {
try {
$message | Set-Clipboard
Write-Host ""
Write-Host "Copied to clipboard." -ForegroundColor Yellow
} catch {
# clipboard not available, no-op
}
}