Repository navigation
Expand file tree
/
Copy pathgit-pr
More file actions
executable file
·500 lines (475 loc) · 24.6 KB
/
Copy pathgit-pr
File metadata and controls
executable file
·500 lines (475 loc) · 24.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
#!/usr/bin/env bash
# Prints the URL of the PR for the current branch, or for an explicit
# <number>/<url> argument (passed straight to `gh pr view` unchanged).
# On a terminal the script prints the PR's status after the URL: Draft, Review
# required, Not approved, Approved, Changes requested, Merged, or Closed.
# Review required means the base branch requires an approval that the PR lacks.
# Not approved means the base branch requires no approval and the PR has no
# current approval.
# An open PR that a Trunk merge queue has taken also shows its queue status,
# such as "Approved, Submitted to Trunk Queue". A draft PR shows no queue status.
# Trunk never rewrites its "Submitted" comment when it drops the PR, and a draft
# conversion drops it. That status is therefore also hidden when the PR was
# converted to draft after the comment was posted. One GraphQL call checks that,
# and only for that status. If the call fails, the status stays. A PR that is
# resubmitted after it is marked ready shows no queue status if Trunk edits the
# old comment in place instead of posting a new one, until Trunk's text changes.
# An open PR whose base branch requires code owner review also lists the code
# owners that GitHub still asks to review, such as "Review required, Code owners
# pending: @PostHog/hogql". Branch protection or a ruleset can set that
# requirement. One GraphQL call reads it, and only for an open PR. If the call
# fails, the status lists no code owners. An Approved or Not approved PR skips
# the call. GitHub counts every required review of an approved PR as done. Not
# approved means that the base branch requires no review. The list comes from
# GitHub's open code owner review requests. It can name a co-owner of a path
# whose other owner already approved. It misses a code owner whose request was
# removed, by hand or by a review that did not approve. A code owner team that
# GitHub does not show the signed-in user lists as "(hidden team)".
# When other open PRs target this PR's branch, or this PR targets another open
# PR's branch, the stack follows on separate lines, top-down: the PRs stacked on
# this one, this PR marked with ">", the PRs it sits on, and the bottom base
# branch.
# --json prints the PR as one JSON object instead: url, number, state, head,
# base, status, queue, mergeable, mergedAt, body, approvers, commenters, and
# codeOwners.
# queue holds the Trunk queue status, or null. It is "unknown" for an open PR
# when the lookup could not read the PR's comments. mergeable holds GitHub's
# MERGEABLE, CONFLICTING, or UNKNOWN for an open PR, or null for a closed or
# merged one. mergedAt is the time the PR merged, or null. body is the PR
# description. approvers lists the logins of the reviewers whose last verdict
# approves the PR, bots such as stamphog included. commenters lists the logins
# of the people, not bots, who left a comment that the PR still shows: a PR
# comment, a review with a body, or a comment in an unresolved review thread.
# The PR's author and the user that gh signs in as do not count. A bot opens a
# cloud agent's PR, so the author alone would not leave out the user. A hidden comment does not count. commenters is null
# for a closed or merged PR, and null when GitHub does not answer. The lookup
# reads only the newest 100 PR comments, reviews, and review threads, and the
# first 100 comments in each thread. commenters is also null when the PR has
# more than the lookup read and nothing it read names a person. Both lists are
# sorted.
# codeOwners holds required and pending. required says whether the base branch
# requires code owner review. pending lists the code owners that the terminal
# status names, sorted. codeOwners is null for a closed or merged PR, and null
# when GitHub does not answer. The commenters lookup also reads codeOwners, so
# --json makes no extra call for it.
# --json skips the stack lookups.
# Otherwise piped or captured output is the bare URL, which bin/lib/github.sh
# parses.
# Without a PR it prints "No PR" to stderr and exits 1. A branch that was never
# pushed, and the remote's default branch, get that answer without a gh call.
# --include-default-prs looks the default branch up anyway.
# Usage: git pr [--include-default-prs] [--json] [<number>|<url>]
#
# `gh pr view` with no argument resolves the head ref from the local
# branch name, not branch.<name>.merge, so it misses a fork PR checked out
# under a different local name (e.g. via `gh pr checkout`).
# This resolves the real branch name instead, then looks it up with
# `gh pr list --head`, which matches bare names across every fork, so a
# same-named branch in an unrelated fork (e.g. "main", "patch-1") can
# outrank the right one.
# The push remote's owner narrows that match back down to the right fork.
#
# An agent harness (PostHog Desktop, cloud runners) checks the PR head out
# detached, so there is no branch name to resolve. That case asks the
# commit-to-PR endpoint for HEAD's SHA instead. Code search is index-lagged and
# would miss a PR pushed moments ago.
set -e
include_default_prs=
json=
while :; do
case "$1" in
--include-default-prs) include_default_prs=1 ;;
--json) json=1 ;;
*) break ;;
esac
shift
done
with_status=$json
[ -t 1 ] && with_status=1
# The `gh pr list` lookup below sorts on state.
# Both field sets include state for that lookup.
if [ -n "$with_status" ]; then
# GitHub leaves reviewDecision empty when the base branch requires no reviews.
# The status then comes from each reviewer's last review that approved,
# requested changes, or was dismissed. latestReviews would hide an approval
# that the same reviewer followed with a comment.
# `gh pr list` returns only the oldest 100 reviews of a PR. An approval after
# those 100 does not count.
# Trunk posts an un-submitted control comment and edits that comment in place
# into the queue status. The first line of the status names the queue state.
# Trunk posts replies and submission errors as new comments that it does not
# edit.
# The status comment is therefore the last edited trunk-io comment whose first
# line is not an HTML marker. The control comment and the test analytics
# comment start with a marker.
# A status that offers the unchecked submit checkbox again means that Trunk
# dropped the PR. Trunk rewords its statuses. Any other status with no known
# phrase therefore means that the queue holds the PR.
# A PR in a stack can lack that status. Trunk posts a stack submission on the
# stack's top PR as a new comment whose first line is the
# `<!-- Trunk Merge -->` marker. Trunk edits that comment into the stack's
# status later. Each PR below the top gets a reply when the stack enters the
# queue. Trunk replies again with a line that starts "Stacked PR" when the
# stack fails, is cancelled, or returns to waiting. A "Stacked PR" reply with
# no known phrase means that the queue holds the PR, as a status does.
# gh gives no edit time. Nothing therefore orders the last status against the
# last reply. Trunk runs a PR through one queue run at a time. Trunk ends each
# run with a removal or a merge. A queued state from either kind of comment
# therefore outranks a removal from the other.
format='def verdicts:
reduce (.reviews[] | select(.state != "COMMENTED" and .state != "PENDING")) as $r
({}; .[$r.author.login // ""] = $r.state);
def review_status:
verdicts
| if any(.[]; . == "CHANGES_REQUESTED") then "Changes requested"
elif any(.[]; . == "APPROVED") then "Approved"
else "Not approved" end;
def status_comment_queue:
.body | . as $body | split("\n")[0] | ascii_downcase
| if startswith("<!-- trunk") then empty
elif contains("removed from the merge queue") or contains("will not be merged")
or ($body | contains("- [ ] <!-- End PR Submit Checkbox -->")) then "Removed from Trunk Queue"
elif contains("running tests") then "Testing in Trunk Queue"
elif contains("waiting to start tests") then "Waiting in Trunk Queue"
elif contains("will be merged soon") then "Passed Trunk Queue"
elif contains("submitted to merge") then "Submitted to Trunk Queue"
elif test("the required check .* has failed") then "Failing in Trunk Queue"
else "In Trunk Queue" end;
def stack_reply_queue:
.body | ascii_downcase
| if test("^<!-- trunk merge -->\n[^\n]*stack submitted to merge") then "Submitted to Trunk Queue"
elif startswith("this pull request is queued for merge as part of") then "In Trunk Queue"
elif startswith("stacked pr ") | not then empty
elif contains("returned to waiting") then "Waiting in Trunk Queue"
elif contains("failed testing") or contains("was cancelled") then "Removed from Trunk Queue"
else "In Trunk Queue" end;
def queue:
[select(.state == "OPEN" and (.isDraft | not)) | .comments[]? | select(.author.login == "trunk-io")]
| [([.[] | select(.includesCreatedEdit) | status_comment_queue] | last),
([.[] | select(.includesCreatedEdit | not) | stack_reply_queue] | last)]
| map(values)
| (map(select(. != "Removed from Trunk Queue")) | first) // first;
def status($queue):
[if .state == "MERGED" then "Merged"
elif .state == "CLOSED" then "Closed"
elif .isDraft then "Draft"
elif .reviewDecision == "APPROVED" then "Approved"
elif .reviewDecision == "CHANGES_REQUESTED" then "Changes requested"
elif .reviewDecision == "REVIEW_REQUIRED" then "Review required"
else review_status end, ($queue | values)]
| join(", ");'
if [ -n "$json" ]; then
format+='
queue as $queue
| {url, number, state, head: .headRefName, base: .baseRefName, status: status($queue),
queue: (if has("comments") then $queue elif .state == "OPEN" then "unknown" else null end),
mergeable: (if .state == "OPEN" then .mergeable else null end), mergedAt, body,
approvers: [verdicts | to_entries[] | select(.key != "" and .value == "APPROVED") | .key] | sort}'
else
# Branch names hold no spaces, so only the status in a format line can
# contain one.
format+='
"\(.url) \(.state) \(.isCrossRepository) \(.number) \(.headRefName) \(.baseRefName) \(status(queue))"'
fi
# The retry below drops the trailing comments field, so it stays last.
fields=url,number,state,isDraft,reviewDecision,reviews,headRefName,baseRefName,isCrossRepository${json:+,mergeable,mergedAt,body},comments
else
fields=url,state
format=.url
fi
no_pr() { echo "No PR" >&2; exit 1; }
# Prints a format line for each open PR in $repo whose head or base branch is
# <branch>.
stack_lookup() { # stack_lookup --head|--base <branch>
env GH_PAGER= gh pr list --repo "$repo" "$1" "$2" --state open --limit 100 \
--json "$fields" -q ".[] | $format" 2>/dev/null
}
# Prints the open PRs stacked on <head> top-down. Each PR prints below the PRs
# stacked on it. A PR with siblings prints above the next sibling's PRs rather
# than above its base, so every sibling but the last names its base.
above() { # above <head> <number>
local children i last cross n head status
local -a kids
# Every PR into the default branch would count as stacked on it.
[ "$1" != "$default_branch" ] || return 0
children=$(stack_lookup --base "$1") || return
[ -n "$children" ] || return 0
mapfile -t kids <<< "$children"
last=$((${#kids[@]} - 1))
for i in "${!kids[@]}"; do
read -r _ _ cross n head _ status <<< "${kids[i]}"
[ -z "${seen[$n]}" ] || continue
seen[$n]=1
# A fork PR's head branch is not in this repo, so no PR here can target it.
if [ "$cross" = false ]; then above "$head" "$n" || return; fi
[ "$i" -eq "$last" ] || status+=" (on #$2)"
echo " #$n $status"
done
}
# Prints the open PRs under <base> top-down, then the bottom base branch.
# A base branch belongs to this repo, so the walk skips a fork PR whose head
# branch has the same name.
below() { # below <base>
local base=$1 parent n status
while [ "$base" != "$default_branch" ]; do
parent=$(stack_lookup --head "$base") || return
parent=$(grep -m1 '^[^ ]* [^ ]* false ' <<< "$parent") || break
read -r _ _ _ n _ parent status <<< "$parent"
[ -z "${seen[$n]}" ] || break
seen[$n]=1
echo " #$n $status"
base=$parent
done
echo " $base"
}
# The pull request fields that code_owners reads.
# refUpdateRule is the read-only view of classic branch protection. It does not
# include rulesets. rules lists the rules of every ruleset that applies.
code_owner_fields='reviewDecision
baseRef {
refUpdateRule { requiresCodeOwnerReviews }
rules(first: 100) {
nodes { type parameters { ... on PullRequestParameters { requireCodeOwnerReview } } }
}
}
reviewRequests(first: 100) {
nodes { asCodeOwner requestedReviewer { ... on Team { combinedSlug } ... on User { login } } }
}'
# Turns a pull request with code_owner_fields into {required, pending}, or null
# without its base branch.
# A null requestedReviewer is a team that the signed-in user cannot see, such as
# a secret team or a team in an org that gh's token cannot read.
code_owners_def='def code_owners:
if .baseRef == null then null
else (.baseRef.refUpdateRule.requiresCodeOwnerReviews == true
or any(.baseRef.rules.nodes[]?; .type == "PULL_REQUEST" and .parameters.requireCodeOwnerReview == true)) as $required
| {required: $required,
pending: (if $required and .reviewDecision != "APPROVED"
then [.reviewRequests.nodes[]? | select(.asCodeOwner) | .requestedReviewer
| if . == null then "(hidden team)" else .combinedSlug // .login | values | "@" + . end] | sort
else [] end)}
end;'
# Prints <jq> applied to the PR at <url>, which GraphQL answers with <fields>.
# The response also holds the signed-in user's login at .data.viewer.login.
# <jq> may start with jq definitions. Prints nothing when GitHub does not answer.
# gh prints the raw response of a failed call to stdout and skips <jq>.
pr_graphql() { # pr_graphql <PR url> <fields> <jq>
local owner name number out
IFS=/ read -r _ _ _ owner name _ number <<< "$1"
out=$(env GH_PAGER= gh api graphql -f owner="$owner" -f name="$name" -F number="$number" -f query='
query($owner: String!, $name: String!, $number: Int!) {
viewer { login }
repository(owner: $owner, name: $name) {
pullRequest(number: $number) { '"$2"' }
}
}' --jq "$3" 2>/dev/null) || return
printf '%s\n' "$out"
}
# Prints the code owners that the open PR at <url> still needs, separated by
# spaces. Prints nothing when it needs none or GitHub does not answer.
pending_code_owners() { # pending_code_owners <PR url>
pr_graphql "$1" "$code_owner_fields" \
"$code_owners_def"' .data.repository.pullRequest | code_owners | .pending // [] | join(" ")' || true
}
# Succeeds when the PR was converted to draft after the newest Trunk "submitted
# to merge" comment. Trunk removes a draft from the queue and leaves that
# comment as it was.
submission_is_stale() { # submission_is_stale <PR url>
[ "$(pr_graphql "$1" '
timelineItems(last: 100, itemTypes: [CONVERT_TO_DRAFT_EVENT]) {
nodes { ... on ConvertToDraftEvent { createdAt } }
}
comments(last: 100) {
nodes { author { login } createdAt body }
}' '.data.repository.pullRequest
| ([.comments.nodes[]
| select(.author.login == "trunk-io" and (.body | ascii_downcase | contains("submitted to merge")))
| .createdAt] | max) as $submitted
| ([.timelineItems.nodes[].createdAt] | max) as $drafted
| $submitted != null and $drafted != null and $drafted > $submitted')" = true ]
}
# Prints the --json object with commenters and codeOwners added. Only GitHub's
# GraphQL API tells a bot from a person, through the author's __typename.
# `gh pr list` gives the author's login alone.
with_graphql_fields() { # with_graphql_fields <--json object>
local state url found=
{ read -r state; read -r url; } <<< "$(jq -r '.state, .url' <<< "$1")"
if [ "$state" = OPEN ]; then
found=$(pr_graphql "$url" "$code_owner_fields"'
author { login }
comments(last: 100) {
pageInfo { hasPreviousPage }
nodes { author { __typename login } isMinimized }
}
reviews(last: 100) {
pageInfo { hasPreviousPage }
nodes { author { __typename login } body isMinimized }
}
reviewThreads(last: 100) {
pageInfo { hasPreviousPage }
nodes {
isResolved
comments(first: 100) {
pageInfo { hasNextPage }
nodes { author { __typename login } isMinimized }
}
}
}' "$code_owners_def"'
.data.viewer.login as $me
| .data.repository.pullRequest
| code_owners as $code_owners
| .author.login as $author
| ([.comments, .reviews, .reviewThreads | .pageInfo.hasPreviousPage]
+ [.reviewThreads.nodes[].comments.pageInfo.hasNextPage] | any) as $truncated
| [.comments.nodes[], (.reviews.nodes[] | select(.body | test("\\S"))),
(.reviewThreads.nodes[] | select(.isResolved | not) | .comments.nodes[])]
| map(select(.isMinimized | not) | .author
| select(.__typename == "User" and .login != $author and .login != $me) | .login)
| unique
| {commenters: (if . == [] and $truncated then null else . end), codeOwners: $code_owners}') || found=
fi
jq -c -M --arg found "$found" '. + ($found | fromjson? // {commenters: null, codeOwners: null})' <<< "$1"
}
# Prints a lookup's output. Without the status, the output is the URL. With
# --json, it is the JSON object. Otherwise it is a format line, which prints as
# "<url> (<status>)", and the stack follows when the PR is open and other open
# PRs share its stack.
show() { # show <lookup output>
if [ -n "$json" ]; then
local obj=$1
if [ "$(jq -r .queue <<< "$obj")" = "Submitted to Trunk Queue" ] \
&& submission_is_stale "$(jq -r .url <<< "$obj")"; then
obj=$(jq -c '.queue = null | .status |= sub(", Submitted to Trunk Queue$"; "")' <<< "$obj")
fi
with_graphql_fields "$obj"
return
fi
if [ -z "$with_status" ]; then echo "$1"; return; fi
local url state cross number head base status owners='' up='' down n
read -r url state cross number head base status <<< "$1"
case "$status" in
*", Submitted to Trunk Queue")
! submission_is_stale "$url" || status=${status%, Submitted to Trunk Queue} ;;
esac
case "$state $status" in
"OPEN Approved"* | "OPEN Not approved"*) ;;
OPEN*) owners=$(pending_code_owners "$url") ;;
esac
echo "$url ($status${owners:+, Code owners pending: $owners})"
[ "$state" = OPEN ] || return 0
repo=${url#https://}
repo=${repo%/pull/*}
default_branch=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)
default_branch=${default_branch#origin/}
# Without the default branch, the walks would treat a PR from it as part of
# the stack.
[ -n "$default_branch" ] || return 0
# Two open PRs can each target the other's head branch.
local -A seen=(["$number"]=1)
if [ "$cross" = false ]; then
up=$(above "$head" "$number") || { echo "Stack lookup failed" >&2; return 0; }
fi
# above() marks PRs in its own subshell, so below() would list them again.
[ -z "$up" ] || while read -r n _; do seen[${n#\#}]=1; done <<< "$up"
down=$(below "$base") || { echo "Stack lookup failed" >&2; return 0; }
# Without a PR under this one, $down holds only the base branch.
[ -n "$up" ] || [ "$down" != " $base" ] || return 0
[ -z "$up" ] || echo "$up"
echo "> #$number $status"
echo "$down"
}
# gh queries the terminal's colors when its stdout is a terminal.
# Capturing its output avoids those queries.
# gh exits 1 for a missing PR and for an auth or network failure alike.
pr_view() {
local pr
err=$(mktemp)
trap 'rm -f "$err"' EXIT
if pr=$(env GH_PAGER= gh pr view "$@" --json "$fields" -q "$format" 2>"$err"); then
show "$pr"
return
fi
grep -qE 'Could not resolve to a PullRequest|no pull requests found' "$err" && no_pr
cat "$err" >&2
exit 1
}
if [ -n "$1" ]; then
pr_view "$1"
exit
fi
current_branch=$(git branch --show-current)
if [ -z "$current_branch" ]; then
head_sha=$(git rev-parse HEAD 2>/dev/null || true)
if [ -n "$head_sha" ]; then
# The endpoint also lists PRs this commit merged *into*, so a detached
# main would resolve to whatever landed last. Only an exact head.sha
# match is this commit's own PR. The REST state is lowercase; the
# `gh pr list` path below reads it uppercase.
url=$(env GIT_PR_HEAD_SHA="$head_sha" GH_PAGER= gh api "repos/{owner}/{repo}/commits/${head_sha}/pulls" \
--jq '[.[] | select(.head.sha == $ENV.GIT_PR_HEAD_SHA)] | sort_by(.state != "open") | .[0].html_url' 2>/dev/null || true)
if [ -n "$url" ] && [ "$url" != "null" ]; then
# The REST response has no reviewDecision.
# The status therefore needs a second lookup.
if [ -n "$with_status" ]; then pr_view "$url"; else echo "$url"; fi
exit
fi
fi
# The commit lookup is the only one that works on a detached HEAD.
# `gh pr view` with no argument fails there before it asks GitHub.
no_pr
fi
branch=$(git config "branch.$current_branch.merge" 2>/dev/null || true)
# Mirrors gh's own push-remote resolution order.
remote=$(git config "branch.$current_branch.pushRemote" 2>/dev/null || true)
[ -n "$remote" ] || remote=$(git config remote.pushDefault 2>/dev/null || true)
[ -n "$remote" ] || remote=$(git config "branch.$current_branch.remote" 2>/dev/null || true)
# "." means the branch tracks a local branch, not a remote one.
[ "$remote" = "." ] && { remote=""; branch=""; }
[ -n "$remote" ] || remote=origin
case "$branch" in
refs/pull/*/head)
# gh's own no-argument lookup already resolves this merge-ref form.
pr_view
exit
;;
esac
branch=${branch#refs/heads/}
if [ -z "$branch" ]; then
# Without an upstream, only a remote-tracking ref shows that the branch
# was pushed. A branch that was never pushed has no PR.
git rev-parse --quiet --verify "refs/remotes/$remote/$current_branch" >/dev/null || no_pr
branch=$current_branch
fi
# A PR rarely comes from the default branch of $remote.
# Skipping that lookup also avoids the slowest one, because many forks open PRs
# from a branch named main or master.
# The skip hides a PR from the default branch into another base branch. It also
# hides a PR from a fork's default branch into its upstream when $remote is the
# fork.
default=$(git symbolic-ref --quiet --short "refs/remotes/$remote/HEAD" 2>/dev/null || true)
[ -n "$include_default_prs" ] || [ "$default" != "$remote/$branch" ] || no_pr
# gh pr checkout writes the fork's URL, not a remote name, into
# branch.<name>.remote when the fork has no configured remote.
remote_url=$(git remote get-url "$remote" 2>/dev/null || echo "$remote")
remote_url=${remote_url%.git}
remote_url=${remote_url%/}
owner=${remote_url%/*}
owner=${owner##*[:/]}
owner=${owner,,}
# Prefers an OPEN PR over a merged one when both exist for the branch.
list_prs() { # list_prs <fields>
env GIT_PR_OWNER="$owner" GH_PAGER= gh pr list --head "$branch" --state all --limit 100 \
--json "$1,headRepositoryOwner" \
-q '[.[] | select(((.headRepositoryOwner.login // "") | ascii_downcase) == $ENV.GIT_PR_OWNER)] | sort_by(.state != "OPEN") | .[0] // empty | '"$format"
}
if [ -n "$with_status" ]; then
# A lookup on a branch name that many forks share fetches the comments of
# all their PRs. GitHub sometimes fails that lookup with a 502.
# The retry's status has no queue status.
# A gh failure for any other reason also costs this second attempt.
pr=$(list_prs "$fields" 2>/dev/null) || pr=$(list_prs "${fields%,comments}")
else
pr=$(list_prs "$fields")
fi
[ -n "$pr" ] || no_pr
show "$pr"