-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-GitHubPullRequest.ps1
More file actions
630 lines (519 loc) · 21.6 KB
/
Copy pathGet-GitHubPullRequest.ps1
File metadata and controls
630 lines (519 loc) · 21.6 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
function Get-GitHubPullRequest
{
<#
.SYNOPSIS
Retrieves GitHub pull requests for the current user or a specified GitHub scope.
.DESCRIPTION
Searches GitHub pull requests and returns matching results with repository, author, state,
URL, and timestamp metadata.
By default, the function retrieves open pull requests authored by the authenticated GitHub
user. Use -Author to search pull requests authored by another user. Use -Organization,
-Owner, or -Repository to narrow the search to a GitHub organization, repository owner, or
repository.
Current-user author filtering remains the default even when scope filters are supplied. Use
-AllAuthors with -Organization, -Owner, or -Repository to return pull requests from every
author in that scope.
The function prefers the GitHub CLI-backed API transport when `gh` is available and falls
back to the REST API otherwise. Results are retrieved page by page up to GitHub Search API
limits.
.PARAMETER State
Pull request state to retrieve. Valid values are Open, Closed, Merged, and All.
Defaults to Open.
Closed returns closed pull requests that were not merged. Merged returns pull requests that
were merged. All returns open, closed, and merged pull requests.
.PARAMETER Author
GitHub username whose pull requests should be returned.
When omitted, the authenticated GitHub user is used by default. Use -AllAuthors with a scope
filter to omit author filtering.
The value @me is accepted and resolves to the authenticated GitHub user.
.PARAMETER AllAuthors
Returns pull requests from all authors in the specified -Organization, -Owner, or -Repository
scope.
This switch cannot be combined with -Author and requires at least one scope filter.
.PARAMETER Organization
GitHub organization whose repositories should be searched.
Combine with -Author to find pull requests authored by a user within an organization, or use
-AllAuthors to return pull requests from every author in the organization.
.PARAMETER Owner
GitHub user or organization account whose repositories should be searched.
This uses GitHub's `user:` search qualifier and can be used for repositories owned by a
personal account. Use -Organization for organization-specific searches.
.PARAMETER Repository
The target repository in OWNER/REPO or HOST/OWNER/REPO format.
When supplied, the search is limited to that repository. HOST/OWNER/REPO can be used for
GitHub Enterprise hosts.
Examples:
- octo-org/service-api
- github.example.com/platform/service-api
.PARAMETER GitHubHost
GitHub host to query for user, owner, or organization searches.
Defaults to github.com. Repository searches derive the host from -Repository unless
-GitHubHost is explicitly supplied, in which case the values must agree.
.PARAMETER Token
Optional GitHub personal access token as a SecureString.
If supplied, the token is used only for the outbound `gh` or REST request and is never
written to command output.
When omitted, the function checks the environment variable named by
-TokenEnvironmentVariableName. If the GitHub CLI is installed, its existing authenticated
session can also be used when no token is supplied. If `gh` is not available and the
function falls back to REST, a token or token environment variable is required.
.PARAMETER TokenEnvironmentVariableName
The environment variable name to check for a GitHub token when -Token is not supplied.
Defaults to GH_TOKEN.
This environment variable is read only when -Token is not supplied. It is used for `gh`
authentication and REST fallback.
.EXAMPLE
PS > Get-GitHubPullRequest
Retrieves open pull requests authored by the authenticated GitHub user.
.EXAMPLE
PS > Get-GitHubPullRequest | Select-Object -ExpandProperty PullRequests
Repository : github/github-mcp-server
Number : 576
Title : feat: my new feature
State : open
IsMerged : False
IsDraft : False
Author : fake-user
Url : https://github.com/github/github-mcp-server/pull/576
ApiUrl : https://api.github.com/repos/github/github-mcp-server/pulls/576
Labels : {}
Comments : 0
CreatedAt : 2/26/2026 3:31:09 PM
UpdatedAt : 2/26/2026 3:31:09 PM
ClosedAt :
MergedAt :
Repository : github/github-mcp-server
Number : 577
Title : fix: my bug fix
State : open
IsMerged : False
IsDraft : False
Author : fake-user
Url : https://github.com/github/github-mcp-server/pull/577
ApiUrl : https://api.github.com/repos/github/github-mcp-server/pulls/577
Labels : {}
Comments : 0
CreatedAt : 5/16/2021 4:06:49 AM
UpdatedAt : 5/16/2021 4:06:49 AM
ClosedAt :
MergedAt :
Retrieves open pull requests authored by the authenticated GitHub user and expands the list of pull requests.
.EXAMPLE
PS > Get-GitHubPullRequest -State Merged
Retrieves merged pull requests authored by the authenticated GitHub user.
.EXAMPLE
PS > Get-GitHubPullRequest -Author 'octocat' -State Closed
Retrieves closed, unmerged pull requests authored by octocat.
.EXAMPLE
PS > Get-GitHubPullRequest -Organization 'octo-org' -AllAuthors -State All
Retrieves open, closed, and merged pull requests in repositories owned by octo-org.
.EXAMPLE
PS > Get-GitHubPullRequest -Repository 'octo-org/service-api' -AllAuthors
Retrieves open pull requests in the octo-org/service-api repository from every author.
.EXAMPLE
PS > $token = ConvertTo-SecureString $env:GITHUB_ADMIN_TOKEN -AsPlainText -Force
PS > Get-GitHubPullRequest -Author 'octocat' -Owner 'octo-org' -Token $token
Retrieves open pull requests authored by octocat in repositories owned by octo-org, using an
explicit token.
.EXAMPLE
PS > Get-GitHubPullRequest -State Merged -Author 'some-github-username' -Organization 'some-github-org' |
Select-Object -ExpandProperty PullRequests |
Export-Csv -Path 'merged-pull-requests.csv' -UseQuotes AsNeeded
Retrieves merged pull requests by author and organization and exports the results to a CSV file.
.OUTPUTS
GitHub.PullRequestSearch
Returns a search result object with matching pull requests, query metadata, transport
details, and counts.
.NOTES
Pull request searches prefer the GitHub CLI-backed transport and fall back to direct REST API
requests when necessary.
GitHub Search API results are limited by GitHub's search result cap. The
SearchResultLimitReached property indicates when GitHub reported more matches than were
returned.
.LINK
https://docs.github.com/search-github/searching-on-github/searching-issues-and-pull-requests
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Get-GitHubPullRequest.ps1
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
[Parameter()]
[ValidateSet('Open', 'Closed', 'Merged', 'All')]
[String]$State = 'Open',
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub author cannot be empty or whitespace.'
}
$true
})]
[String]$Author,
[Parameter()]
[Switch]$AllAuthors,
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub organization cannot be empty or whitespace.'
}
$true
})]
[String]$Organization,
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub owner cannot be empty or whitespace.'
}
$true
})]
[String]$Owner,
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub repository cannot be empty or whitespace.'
}
$true
})]
[String]$Repository,
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if ([string]::IsNullOrWhiteSpace($_))
{
throw 'GitHub host cannot be empty or whitespace.'
}
$true
})]
[String]$GitHubHost = 'github.com',
[Parameter()]
[SecureString]$Token,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$TokenEnvironmentVariableName = 'GH_TOKEN'
)
function Import-GitHubConfigurationHelpersIfNeeded
{
if (-not (Get-Variable -Name 'PwshProfileGitHubConfigurationHelpers' -Scope Script -ErrorAction SilentlyContinue))
{
$dependencyDirectory = Join-Path -Path $PSScriptRoot -ChildPath 'Private'
$dependencyPath = Join-Path -Path $dependencyDirectory -ChildPath 'GitHubConfigurationHelpers.ps1'
$dependencyPath = [System.IO.Path]::GetFullPath($dependencyPath)
if (-not (Test-Path -LiteralPath $dependencyPath -PathType Leaf))
{
throw "Required dependency could not be found. Expected location: $dependencyPath"
}
try
{
. $dependencyPath
Write-Verbose "Loaded GitHub configuration helpers from: $dependencyPath"
}
catch
{
throw "Failed to load GitHub configuration helpers from '$dependencyPath': $($_.Exception.Message)"
}
}
}
function Resolve-GitHubPullRequestSearchHost
{
param(
[String]$RequestedHost,
[PSCustomObject]$RepositoryContext,
[Boolean]$GitHubHostWasSpecified
)
$normalizedRequestedHost = $RequestedHost.Trim()
if ($normalizedRequestedHost -match '^https?://')
{
$normalizedRequestedHost = ([Uri]$normalizedRequestedHost).Host
}
if ($RepositoryContext)
{
if (
$GitHubHostWasSpecified -and
-not [string]::IsNullOrWhiteSpace($normalizedRequestedHost) -and
$normalizedRequestedHost.ToLowerInvariant() -ne $RepositoryContext.Host.ToLowerInvariant()
)
{
throw "Repository '$Repository' resolves to host '$($RepositoryContext.Host)', which does not match -GitHubHost '$RequestedHost'."
}
return [PSCustomObject]@{
Host = $RepositoryContext.Host
BaseUri = $RepositoryContext.ApiBaseUri
}
}
return [PSCustomObject]@{
Host = $normalizedRequestedHost
BaseUri = (& $script:PwshProfileGitHubConfigurationHelpers.BuildGitHubApiBaseUri $normalizedRequestedHost)
}
}
function Resolve-GitHubCurrentUserLogin
{
param(
[String]$BaseUri,
[PSCustomObject]$Transport,
[PSCustomObject]$AuthContext,
[Int]$MaxRetryCount,
[Int]$InitialRetryDelaySeconds
)
$invokeGitHubRequestParams = @{
Method = 'GET'
BaseUri = $BaseUri
Path = '/user'
Transport = $Transport
AuthContext = $AuthContext
Body = $null
MaxRetryCount = $MaxRetryCount
InitialRetryDelaySeconds = $InitialRetryDelaySeconds
Activity = 'Resolve authenticated GitHub user'
}
$user = & $script:PwshProfileGitHubConfigurationHelpers.InvokeGitHubRequest @invokeGitHubRequestParams
if ($null -eq $user -or [string]::IsNullOrWhiteSpace($user.login))
{
throw 'Unable to determine the authenticated GitHub user.'
}
return [string]$user.login
}
function Get-GitHubPullRequestRepositoryName
{
param([String]$RepositoryUrl)
if ([string]::IsNullOrWhiteSpace($RepositoryUrl))
{
return $null
}
if ($RepositoryUrl -match '/repos/(?<owner>[^/]+)/(?<repo>[^/]+)$')
{
return "$($matches['owner'])/$($matches['repo'])"
}
return $null
}
function ConvertTo-GitHubPullRequestResult
{
param([PSCustomObject]$Item)
$repositoryName = Get-GitHubPullRequestRepositoryName -RepositoryUrl $Item.repository_url
$mergedAt = if ($Item.pull_request) { $Item.pull_request.merged_at } else { $null }
$isMerged = -not [string]::IsNullOrWhiteSpace([string]$mergedAt)
$labels = @($Item.labels | ForEach-Object { $_.name } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
$result = [PSCustomObject]@{
Repository = $repositoryName
Number = $Item.number
Title = $Item.title
State = $Item.state
IsMerged = $isMerged
IsDraft = [bool]$Item.draft
Author = $Item.user.login
Url = $Item.html_url
ApiUrl = if ($Item.pull_request) { $Item.pull_request.url } else { $null }
Labels = $labels
Comments = $Item.comments
CreatedAt = $Item.created_at
UpdatedAt = $Item.updated_at
ClosedAt = $Item.closed_at
MergedAt = $mergedAt
}
$result.PSObject.TypeNames.Insert(0, 'GitHub.PullRequest')
return $result
}
Import-GitHubConfigurationHelpersIfNeeded
$helpers = $script:PwshProfileGitHubConfigurationHelpers
$maxRetryCount = $helpers.DefaultRetryCount
$initialRetryDelaySeconds = $helpers.DefaultInitialRetryDelaySeconds
if ($PSBoundParameters.ContainsKey('Owner') -and $PSBoundParameters.ContainsKey('Organization'))
{
throw 'Use only one of -Owner or -Organization.'
}
if ($AllAuthors -and $PSBoundParameters.ContainsKey('Author'))
{
throw 'Use either -Author or -AllAuthors, not both.'
}
if (
$AllAuthors -and
-not $PSBoundParameters.ContainsKey('Owner') -and
-not $PSBoundParameters.ContainsKey('Organization') -and
-not $PSBoundParameters.ContainsKey('Repository')
)
{
throw 'Use -AllAuthors only with -Owner, -Organization, or -Repository.'
}
$repositoryContext = if ($PSBoundParameters.ContainsKey('Repository'))
{
& $helpers.ParseRepositorySpecifier $Repository
}
else
{
$null
}
$resolveGitHubPullRequestSearchHostParams = @{
RequestedHost = $GitHubHost
RepositoryContext = $repositoryContext
GitHubHostWasSpecified = $PSBoundParameters.ContainsKey('GitHubHost')
}
$searchHost = Resolve-GitHubPullRequestSearchHost @resolveGitHubPullRequestSearchHostParams
$transport = & $helpers.ResolveTransport
$targetDisplay = 'GitHub pull requests'
$stateDisplay = $State.ToLowerInvariant()
try
{
$resolveAuthContextParams = @{
Token = $Token
TokenEnvironmentVariableName = $TokenEnvironmentVariableName
RequireToken = ($transport.Name -ne 'GhCli')
}
$authContext = & $helpers.ResolveAuthContext @resolveAuthContextParams
$effectiveAuthor = $null
if (-not $AllAuthors)
{
$effectiveAuthor = if ($PSBoundParameters.ContainsKey('Author')) { $Author.Trim() } else { $null }
if ([string]::IsNullOrWhiteSpace($effectiveAuthor) -or $effectiveAuthor -eq '@me')
{
$resolveGitHubCurrentUserLoginParams = @{
BaseUri = $searchHost.BaseUri
Transport = $transport
AuthContext = $authContext
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
}
$effectiveAuthor = Resolve-GitHubCurrentUserLogin @resolveGitHubCurrentUserLoginParams
}
}
$queryParts = New-Object System.Collections.Generic.List[String]
$queryParts.Add('is:pr') | Out-Null
switch ($State)
{
'Open'
{
$queryParts.Add('state:open') | Out-Null
}
'Closed'
{
$queryParts.Add('state:closed') | Out-Null
$queryParts.Add('-is:merged') | Out-Null
}
'Merged'
{
$queryParts.Add('is:merged') | Out-Null
}
}
if (-not [string]::IsNullOrWhiteSpace($effectiveAuthor))
{
$queryParts.Add("author:$effectiveAuthor") | Out-Null
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
$queryParts.Add("org:$($Organization.Trim())") | Out-Null
}
if ($PSBoundParameters.ContainsKey('Owner'))
{
$queryParts.Add("user:$($Owner.Trim())") | Out-Null
}
if ($repositoryContext)
{
$queryParts.Add("repo:$($repositoryContext.NameWithOwner)") | Out-Null
}
$query = $queryParts -join ' '
$targetParts = New-Object System.Collections.Generic.List[String]
if (-not [string]::IsNullOrWhiteSpace($effectiveAuthor))
{
$targetParts.Add("authored by $effectiveAuthor") | Out-Null
}
elseif ($AllAuthors)
{
$targetParts.Add('from all authors') | Out-Null
}
if ($PSBoundParameters.ContainsKey('Organization'))
{
$targetParts.Add("in organization $($Organization.Trim())") | Out-Null
}
if ($PSBoundParameters.ContainsKey('Owner'))
{
$targetParts.Add("in repositories owned by $($Owner.Trim())") | Out-Null
}
if ($repositoryContext)
{
$targetParts.Add("in repository $($repositoryContext.NameWithOwner)") | Out-Null
}
$targetDisplay = if ($targetParts.Count -gt 0)
{
$targetParts -join ' '
}
else
{
'GitHub pull requests'
}
$allItems = New-Object System.Collections.Generic.List[Object]
$perPage = 100
$page = 1
$totalCount = 0
$incompleteResults = $false
$searchResultLimit = 1000
do
{
$encodedQuery = [Uri]::EscapeDataString($query)
$path = "/search/issues?q=$encodedQuery&sort=updated&order=desc&per_page=$perPage&page=$page"
$invokeGitHubRequestParams = @{
Method = 'GET'
BaseUri = $searchHost.BaseUri
Path = $path
Transport = $transport
AuthContext = $authContext
Body = $null
MaxRetryCount = $maxRetryCount
InitialRetryDelaySeconds = $initialRetryDelaySeconds
Activity = "Search $stateDisplay pull requests"
}
$searchResult = & $helpers.InvokeGitHubRequest @invokeGitHubRequestParams
$pageItems = @($searchResult.items)
if ($page -eq 1)
{
$totalCount = [int]$searchResult.total_count
$incompleteResults = [bool]$searchResult.incomplete_results
}
foreach ($item in $pageItems)
{
$allItems.Add($item) | Out-Null
}
$page++
} while (
$pageItems.Count -eq $perPage -and
$allItems.Count -lt $totalCount -and
$allItems.Count -lt $searchResultLimit
)
$pullRequests = @($allItems | ForEach-Object { ConvertTo-GitHubPullRequestResult -Item $_ })
$searchResultLimitReached = ($totalCount -gt $pullRequests.Count)
return & $helpers.NewOperationResult -TypeName 'GitHub.PullRequestSearch' -Properties @{
PullRequests = $pullRequests
PullRequestCount = $pullRequests.Count
TotalCount = $totalCount
State = $State
Query = $query
Target = $targetDisplay
Author = $effectiveAuthor
AllAuthors = [bool]$AllAuthors
Organization = if ($PSBoundParameters.ContainsKey('Organization')) { $Organization.Trim() } else { $null }
Owner = if ($PSBoundParameters.ContainsKey('Owner')) { $Owner.Trim() } else { $null }
Repository = if ($repositoryContext) { $repositoryContext.GhRepository } else { $null }
GitHubHost = $searchHost.Host
SearchResultLimitReached = $searchResultLimitReached
IncompleteResults = $incompleteResults
Transport = $transport.Name
Authentication = $authContext.Source
}
}
catch
{
$getFriendlyErrorMessageParams = @{
Operation = 'get pull requests'
Name = $stateDisplay
Target = $targetDisplay
Exception = $_.Exception
}
$friendlyMessage = & $helpers.GetFriendlyErrorMessage @getFriendlyErrorMessageParams
throw $friendlyMessage
}
}