gunk-dev/the-valley

gh_cli_client.go

source672eff5ffaecmain's published tip history
24.1 KiB
1package github
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "net/url"
9 "os/exec"
10 "strconv"
11 "strings"
12 "time"
13)
14
15// Verify GHCLIClient implements Client at compile time.
16var _ Client = (*GHCLIClient)(nil)
17
18// defaultTimeout is the timeout for gh CLI calls (API operations).
19const defaultTimeout = 30 * time.Second
20
21// GHCLIClient implements Client by shelling out to the gh CLI.
22type GHCLIClient struct {
23 repo string // owner/repo, may be empty
24}
25
26// NewGHCLIClient creates a GHCLIClient. If repo is empty, gh will infer the
27// repo from the current git directory for commands that need one.
28func NewGHCLIClient(repo string) *GHCLIClient {
29 return &GHCLIClient{repo: repo}
30}
31
32// Repo returns the configured owner/repo string.
33func (c *GHCLIClient) Repo() string {
34 return c.repo
35}
36
37// ghArgs builds a base arg list with --repo injected when set.
38func (c *GHCLIClient) ghArgs(base []string, prRef string) []string {
39 args := make([]string, len(base))
40 copy(args, base)
41 if c.repo != "" {
42 args = append(args, "--repo", c.repo)
43 }
44 args = append(args, "--", prRef)
45 return args
46}
47
48// ensureTimeout returns a context with defaultTimeout applied if the parent
49// context has no deadline set. If ctx is nil, a background context is used.
50func ensureTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
51 if ctx == nil {
52 ctx = context.Background()
53 }
54 if _, ok := ctx.Deadline(); ok {
55 return ctx, func() {}
56 }
57 return context.WithTimeout(ctx, defaultTimeout)
58}
59
60// wrapTimeoutErr checks if an error is due to a context deadline and returns
61// a clearer message.
62func wrapTimeoutErr(ctx context.Context, cmdName string, err error) error {
63 if ctx.Err() == context.DeadlineExceeded {
64 return fmt.Errorf("%s timed out after %s", cmdName, defaultTimeout)
65 }
66 return err
67}
68
69// GetRepoOwnerAndName returns owner/repo by querying gh.
70func (c *GHCLIClient) GetRepoOwnerAndName(ctx context.Context) (string, string, error) {
71 ctx, cancel := ensureTimeout(ctx)
72 defer cancel()
73
74 cmd := exec.CommandContext(ctx, "gh", "repo", "view", "--json", "owner,name", "-q", ".owner.login + \"/\" + .name")
75 var stdout bytes.Buffer
76 cmd.Stdout = &stdout
77 if err := cmd.Run(); err != nil {
78 return "", "", wrapTimeoutErr(ctx, "gh repo view", err)
79 }
80 parts := strings.SplitN(strings.TrimSpace(stdout.String()), "/", 2)
81 if len(parts) != 2 {
82 return "", "", fmt.Errorf("unexpected repo format")
83 }
84 return parts[0], parts[1], nil
85}
86
87// GetRepoOwnerAndNameFromDir returns owner/repo for the git repo at the given directory.
88func (c *GHCLIClient) GetRepoOwnerAndNameFromDir(ctx context.Context, dir string) (string, string, error) {
89 ctx, cancel := ensureTimeout(ctx)
90 defer cancel()
91
92 cmd := exec.CommandContext(ctx, "gh", "repo", "view", "--json", "owner,name", "-q", ".owner.login + \"/\" + .name")
93 cmd.Dir = dir
94 var stdout bytes.Buffer
95 cmd.Stdout = &stdout
96 if err := cmd.Run(); err != nil {
97 return "", "", fmt.Errorf("resolving repo for %s: %w", dir, wrapTimeoutErr(ctx, "gh repo view", err))
98 }
99 parts := strings.SplitN(strings.TrimSpace(stdout.String()), "/", 2)
100 if len(parts) != 2 {
101 return "", "", fmt.Errorf("unexpected repo format for %s", dir)
102 }
103 return parts[0], parts[1], nil
104}
105
106// GetCI checks CI status by running "gh pr checks" and summarizing pass/fail/pending.
107func (c *GHCLIClient) GetCI(ctx context.Context, prRef string) string {
108 ctx, cancel := ensureTimeout(ctx)
109 defer cancel()
110
111 args := c.ghArgs([]string{"pr", "checks"}, prRef)
112 cmd := exec.CommandContext(ctx, "gh", args...)
113 var stdout, stderr bytes.Buffer
114 cmd.Stdout = &stdout
115 cmd.Stderr = &stderr
116 err := cmd.Run()
117 output := stdout.String()
118
119 if err != nil && output == "" {
120 if strings.Contains(stderr.String(), "no checks reported") {
121 return "passing" // no checks configured — nothing to fail
122 }
123 return "unknown"
124 }
125
126 return ParseCIStatus(output)
127}
128
129// GetConflicts checks if a PR has merge conflicts.
130func (c *GHCLIClient) GetConflicts(ctx context.Context, prRef string) string {
131 ctx, cancel := ensureTimeout(ctx)
132 defer cancel()
133
134 args := c.ghArgs([]string{"pr", "view", "--json", "mergeable", "-q", ".mergeable"}, prRef)
135 cmd := exec.CommandContext(ctx, "gh", args...)
136 var stdout bytes.Buffer
137 cmd.Stdout = &stdout
138 if err := cmd.Run(); err != nil {
139 return "unknown"
140 }
141 val := strings.TrimSpace(stdout.String())
142 if strings.EqualFold(val, "CONFLICTING") {
143 return "yes"
144 }
145 if strings.EqualFold(val, "MERGEABLE") {
146 return "none"
147 }
148 return "unknown"
149}
150
151// GetCommitsBehind returns how many commits the PR's base branch has that the
152// PR head lacks (0 on any error). Detects behind-but-non-conflicting branches,
153// which GitHub reports as MERGEABLE so GetConflicts never flags them. Two gh
154// calls: refs from `pr view`, then `compare/base...head`'s .behind_by.
155func (c *GHCLIClient) GetCommitsBehind(ctx context.Context, prRef string) int {
156 ctx, cancel := ensureTimeout(ctx)
157 defer cancel()
158
159 args := c.ghArgs([]string{"pr", "view", "--json", "baseRefName,headRefName,headRepositoryOwner",
160 "-q", `.baseRefName + "\t" + .headRefName + "\t" + (.headRepositoryOwner.login // "")`}, prRef)
161 cmd := exec.CommandContext(ctx, "gh", args...)
162 var out bytes.Buffer
163 cmd.Stdout = &out
164 if err := cmd.Run(); err != nil {
165 return 0
166 }
167 base, head, headOwner, ok := parseRefsLine(out.String())
168 if !ok {
169 return 0
170 }
171
172 // Base repo owner/repo: prefer the PR URL (correct in multi-repo dashboards),
173 // then the constructor slug, then gh's inferred repo. NOT TargetRepo.
174 owner, repo := "", ""
175 if slug := OwnerRepoFromPRURL(prRef); slug != "" {
176 owner, repo, _ = strings.Cut(slug, "/")
177 } else if strings.Contains(c.repo, "/") {
178 owner, repo, _ = strings.Cut(c.repo, "/")
179 } else if o, r, err := c.GetRepoOwnerAndName(ctx); err == nil {
180 owner, repo = o, r
181 }
182 if owner == "" || repo == "" {
183 return 0
184 }
185
186 // Fork heads compare as headOwner:headRef.
187 if headOwner != "" && headOwner != owner {
188 head = headOwner + ":" + head
189 }
190 cmpCmd := exec.CommandContext(ctx, "gh", "api",
191 fmt.Sprintf("repos/%s/%s/compare/%s...%s", owner, repo, base, head), "-q", ".behind_by")
192 var cmpOut bytes.Buffer
193 cmpCmd.Stdout = &cmpOut
194 if err := cmpCmd.Run(); err != nil {
195 return 0
196 }
197 return parseBehindBy(cmpOut.String())
198}
199
200// parseRefsLine parses the tab-joined "base\thead\theadOwner" from GetCommitsBehind's
201// pr-view query. ok is false when base or head is missing.
202func parseRefsLine(s string) (base, head, headOwner string, ok bool) {
203 parts := strings.SplitN(strings.TrimSpace(s), "\t", 3)
204 if len(parts) < 2 || parts[0] == "" || parts[1] == "" {
205 return "", "", "", false
206 }
207 if len(parts) == 3 {
208 headOwner = parts[2]
209 }
210 return parts[0], parts[1], headOwner, true
211}
212
213// parseBehindBy parses the .behind_by integer from `gh api compare` output,
214// returning 0 for blank/non-numeric input.
215func parseBehindBy(s string) int {
216 n, err := strconv.Atoi(strings.TrimSpace(s))
217 if err != nil {
218 return 0
219 }
220 return n
221}
222
223// GetReviewDecision fetches the review decision for a PR.
224func (c *GHCLIClient) GetReviewDecision(ctx context.Context, prRef string) string {
225 ctx, cancel := ensureTimeout(ctx)
226 defer cancel()
227
228 args := c.ghArgs([]string{"pr", "view", "--json", "reviewDecision", "-q", ".reviewDecision"}, prRef)
229 cmd := exec.CommandContext(ctx, "gh", args...)
230 var stdout bytes.Buffer
231 cmd.Stdout = &stdout
232 if err := cmd.Run(); err != nil {
233 return "unknown"
234 }
235 return strings.TrimSpace(stdout.String())
236}
237
238// GetLabels returns the names of all labels currently applied to the PR.
239// Returns an empty slice on error (including when the PR has no labels).
240func (c *GHCLIClient) GetLabels(ctx context.Context, prRef string) []string {
241 ctx, cancel := ensureTimeout(ctx)
242 defer cancel()
243
244 args := c.ghArgs([]string{"pr", "view", "--json", "labels", "-q", ".labels[].name"}, prRef)
245 cmd := exec.CommandContext(ctx, "gh", args...)
246 var stdout bytes.Buffer
247 cmd.Stdout = &stdout
248 if err := cmd.Run(); err != nil {
249 return nil
250 }
251 out := strings.TrimSpace(stdout.String())
252 if out == "" {
253 return nil
254 }
255 var labels []string
256 for _, line := range strings.Split(out, "\n") {
257 if name := strings.TrimSpace(line); name != "" {
258 labels = append(labels, name)
259 }
260 }
261 return labels
262}
263
264// StateNoAccess is the PR state GetState reports when GitHub says the PR
265// doesn't exist or can't be read with the current credentials. A transient
266// failure (network, timeout, rate limit) reports "UNKNOWN" instead.
267const StateNoAccess = "NOACCESS"
268
269// GetState returns the PR state (e.g. "OPEN", "MERGED", "CLOSED"),
270// StateNoAccess when the PR can't be read, or "UNKNOWN" on other failures.
271func (c *GHCLIClient) GetState(ctx context.Context, prRef string) string {
272 ctx, cancel := ensureTimeout(ctx)
273 defer cancel()
274
275 args := c.ghArgs([]string{"pr", "view", "--json", "state", "-q", ".state"}, prRef)
276 cmd := exec.CommandContext(ctx, "gh", args...)
277 var stdout, stderr bytes.Buffer
278 cmd.Stdout = &stdout
279 cmd.Stderr = &stderr
280 if err := cmd.Run(); err != nil {
281 if ctx.Err() == nil && IsNoAccess(stderr.String()) {
282 return StateNoAccess
283 }
284 return "UNKNOWN"
285 }
286 val := strings.TrimSpace(stdout.String())
287 if val == "" {
288 return "UNKNOWN"
289 }
290 return strings.ToUpper(val)
291}
292
293// IsNoAccess reports whether gh's stderr says the PR (or its repo) doesn't
294// exist or can't be read: GraphQL's "Could not resolve to a PullRequest" or
295// "... to a Repository", or an HTTP 404 or 403. A 403 for a rate limit is
296// transient, not a lack of access.
297func IsNoAccess(stderr string) bool {
298 if strings.Contains(strings.ToLower(stderr), "rate limit") {
299 return false
300 }
301 for _, marker := range []string{
302 "Could not resolve to a PullRequest",
303 "Could not resolve to a Repository",
304 "HTTP 404",
305 "HTTP 403",
306 } {
307 if strings.Contains(stderr, marker) {
308 return true
309 }
310 }
311 return false
312}
313
314// IsDraft reports whether a PR is a draft (false on any error).
315func (c *GHCLIClient) IsDraft(ctx context.Context, prRef string) bool {
316 ctx, cancel := ensureTimeout(ctx)
317 defer cancel()
318
319 args := c.ghArgs([]string{"pr", "view", "--json", "isDraft", "-q", ".isDraft"}, prRef)
320 cmd := exec.CommandContext(ctx, "gh", args...)
321 var stdout bytes.Buffer
322 cmd.Stdout = &stdout
323 if err := cmd.Run(); err != nil {
324 return false
325 }
326 return strings.TrimSpace(stdout.String()) == "true"
327}
328
329// GetBranch returns the head branch name for a PR.
330func (c *GHCLIClient) GetBranch(ctx context.Context, prRef string) (string, error) {
331 ctx, cancel := ensureTimeout(ctx)
332 defer cancel()
333
334 args := c.ghArgs([]string{"pr", "view", "--json", "headRefName", "-q", ".headRefName"}, prRef)
335 cmd := exec.CommandContext(ctx, "gh", args...)
336 var stdout, stderr bytes.Buffer
337 cmd.Stdout = &stdout
338 cmd.Stderr = &stderr
339 if err := cmd.Run(); err != nil {
340 return "", fmt.Errorf("gh pr view: %w", wrapTimeoutErr(ctx, "gh pr view", err))
341 }
342 branch := strings.TrimSpace(stdout.String())
343 if branch == "" {
344 return "", fmt.Errorf("could not determine branch for PR %s", prRef)
345 }
346 return branch, nil
347}
348
349// GetURL returns the HTML URL for a PR.
350func (c *GHCLIClient) GetURL(ctx context.Context, prRef string) (string, error) {
351 ctx, cancel := ensureTimeout(ctx)
352 defer cancel()
353
354 args := c.ghArgs([]string{"pr", "view", "--json", "url", "-q", ".url"}, prRef)
355 cmd := exec.CommandContext(ctx, "gh", args...)
356 var stdout, stderr bytes.Buffer
357 cmd.Stdout = &stdout
358 cmd.Stderr = &stderr
359 if err := cmd.Run(); err != nil {
360 return "", fmt.Errorf("gh pr view: %w", wrapTimeoutErr(ctx, "gh pr view", err))
361 }
362 return strings.TrimSpace(stdout.String()), nil
363}
364
365// GetTitle fetches the title of a PR.
366// GetIssueTitle returns the title of an issue (number or URL).
367func (c *GHCLIClient) GetIssueTitle(ctx context.Context, issueRef string) (string, error) {
368 ctx, cancel := ensureTimeout(ctx)
369 defer cancel()
370
371 args := c.ghArgs([]string{"issue", "view", "--json", "title", "-q", ".title"}, issueRef)
372 cmd := exec.CommandContext(ctx, "gh", args...)
373 var stdout, stderr bytes.Buffer
374 cmd.Stdout = &stdout
375 cmd.Stderr = &stderr
376 if err := cmd.Run(); err != nil {
377 return "", fmt.Errorf("gh issue view: %w: %s", wrapTimeoutErr(ctx, "gh issue view", err), strings.TrimSpace(stderr.String()))
378 }
379 return strings.TrimSpace(stdout.String()), nil
380}
381
382func (c *GHCLIClient) GetTitle(ctx context.Context, prRef string) string {
383 ctx, cancel := ensureTimeout(ctx)
384 defer cancel()
385
386 args := c.ghArgs([]string{"pr", "view", "--json", "title", "-q", ".title"}, prRef)
387 cmd := exec.CommandContext(ctx, "gh", args...)
388 var stdout bytes.Buffer
389 cmd.Stdout = &stdout
390 if err := cmd.Run(); err != nil {
391 return "(unknown)"
392 }
393 title := strings.TrimSpace(stdout.String())
394 if title == "" {
395 return "(unknown)"
396 }
397 return title
398}
399
400// Merge merges a PR with the given method.
401func (c *GHCLIClient) Merge(ctx context.Context, prNumber, mergeMethod string, deleteBranch bool) error {
402 ctx, cancel := ensureTimeout(ctx)
403 defer cancel()
404
405 args := MergeArgs(prNumber, mergeMethod, deleteBranch, c.repo)
406 cmd := exec.CommandContext(ctx, "gh", args...)
407 var stderr bytes.Buffer
408 cmd.Stderr = &stderr
409 if err := cmd.Run(); err != nil {
410 // Include stderr: GitHub explains *why* it refused (out-of-date branch,
411 // failing required checks, ...) and callers branch on that text.
412 if msg := strings.TrimSpace(stderr.String()); msg != "" {
413 return fmt.Errorf("gh pr merge: %w: %s", wrapTimeoutErr(ctx, "gh pr merge", err), msg)
414 }
415 return fmt.Errorf("gh pr merge: %w", wrapTimeoutErr(ctx, "gh pr merge", err))
416 }
417 return nil
418}
419
420// UpdateBranch merges the base branch into the PR's head branch server-side,
421// the same thing GitHub's "Update branch" button does. Unlike a local rebase
422// and force-push it adds a merge commit instead of rewriting the head, which is
423// what lets an existing approval survive where the repo's policy allows it.
424func (c *GHCLIClient) UpdateBranch(ctx context.Context, prNumber string) error {
425 ctx, cancel := ensureTimeout(ctx)
426 defer cancel()
427
428 args := UpdateBranchArgs(prNumber, c.repo)
429 cmd := exec.CommandContext(ctx, "gh", args...)
430 var stderr bytes.Buffer
431 cmd.Stderr = &stderr
432 if err := cmd.Run(); err != nil {
433 if msg := strings.TrimSpace(stderr.String()); msg != "" {
434 return fmt.Errorf("gh pr update-branch: %w: %s", wrapTimeoutErr(ctx, "gh pr update-branch", err), msg)
435 }
436 return fmt.Errorf("gh pr update-branch: %w", wrapTimeoutErr(ctx, "gh pr update-branch", err))
437 }
438 return nil
439}
440
441// FetchPRReviewComments fetches review comments for a PR.
442func (c *GHCLIClient) FetchPRReviewComments(ctx context.Context, owner, repo, prNumber string) ([]PRReviewComment, error) {
443 path := fmt.Sprintf("repos/%s/%s/pulls/%s/comments", owner, repo, prNumber)
444 data, err := c.APIGet(ctx, path)
445 if err != nil {
446 return nil, err
447 }
448 var comments []PRReviewComment
449 if err := json.Unmarshal(data, &comments); err != nil {
450 return nil, fmt.Errorf("parsing review comments: %w", err)
451 }
452 return comments, nil
453}
454
455// ReplyToReviewComment posts a reply to a specific PR review comment.
456func (c *GHCLIClient) ReplyToReviewComment(ctx context.Context, owner, repo, prNumber string, commentID int64, body string) error {
457 path := fmt.Sprintf("repos/%s/%s/pulls/%s/comments/%d/replies", owner, repo, prNumber, commentID)
458 return c.APIPost(ctx, path, map[string]string{"body": body})
459}
460
461// FetchReviewThreads fetches review threads for a PR using the GraphQL API.
462func (c *GHCLIClient) FetchReviewThreads(ctx context.Context, owner, repo string, prNumber int) ([]ReviewThread, error) {
463 query := fmt.Sprintf(`{ repository(owner:%q, name:%q) { pullRequest(number: %d) { reviewThreads(first: 100) { nodes { id isResolved } } } } }`, owner, repo, prNumber)
464 return fetchReviewThreadsImpl(query, func(q string) ([]byte, error) {
465 return c.runGraphQL(ctx, q)
466 })
467}
468
469// ResolveReviewThread resolves a review thread by its GraphQL node ID.
470func (c *GHCLIClient) ResolveReviewThread(ctx context.Context, threadID string) error {
471 return resolveReviewThreadImpl(threadID, func(q string) ([]byte, error) {
472 return c.runGraphQL(ctx, q)
473 })
474}
475
476// runGraphQL executes a GraphQL query via gh api.
477func (c *GHCLIClient) runGraphQL(ctx context.Context, query string) ([]byte, error) {
478 ctx, cancel := ensureTimeout(ctx)
479 defer cancel()
480
481 cmd := exec.CommandContext(ctx, "gh", "api", "graphql", "-f", "query="+query)
482 var stdout, stderr bytes.Buffer
483 cmd.Stdout = &stdout
484 cmd.Stderr = &stderr
485 if err := cmd.Run(); err != nil {
486 return nil, fmt.Errorf("gh api graphql: %w", wrapTimeoutErr(ctx, "gh api graphql", err))
487 }
488 return stdout.Bytes(), nil
489}
490
491// fetchReviewThreadsImpl parses a GraphQL response for review threads.
492func fetchReviewThreadsImpl(query string, runner graphQLRunner) ([]ReviewThread, error) {
493 data, err := runner(query)
494 if err != nil {
495 return nil, err
496 }
497 var result struct {
498 Data struct {
499 Repository struct {
500 PullRequest struct {
501 ReviewThreads struct {
502 Nodes []ReviewThread `json:"nodes"`
503 } `json:"reviewThreads"`
504 } `json:"pullRequest"`
505 } `json:"repository"`
506 } `json:"data"`
507 }
508 if err := json.Unmarshal(data, &result); err != nil {
509 return nil, fmt.Errorf("parsing review threads: %w", err)
510 }
511 return result.Data.Repository.PullRequest.ReviewThreads.Nodes, nil
512}
513
514// resolveReviewThreadImpl performs a resolve mutation and parses the response.
515func resolveReviewThreadImpl(threadID string, runner graphQLRunner) error {
516 query := fmt.Sprintf(`mutation { resolveReviewThread(input: {threadId: %q}) { thread { isResolved } } }`, threadID)
517 data, err := runner(query)
518 if err != nil {
519 return err
520 }
521 var result struct {
522 Data struct {
523 ResolveReviewThread struct {
524 Thread struct {
525 IsResolved bool `json:"isResolved"`
526 } `json:"thread"`
527 } `json:"resolveReviewThread"`
528 } `json:"data"`
529 Errors []struct {
530 Message string `json:"message"`
531 } `json:"errors"`
532 }
533 if err := json.Unmarshal(data, &result); err != nil {
534 return fmt.Errorf("parsing resolve response: %w", err)
535 }
536 if len(result.Errors) > 0 {
537 return fmt.Errorf("GraphQL error: %s", result.Errors[0].Message)
538 }
539 return nil
540}
541
542// FetchCollaborators returns the list of collaborator logins for a repo.
543func (c *GHCLIClient) FetchCollaborators(ctx context.Context, owner, repo string) ([]string, error) {
544 ctx, cancel := ensureTimeout(ctx)
545 defer cancel()
546
547 cmd := exec.CommandContext(ctx, "gh", "api", fmt.Sprintf("repos/%s/%s/collaborators", owner, repo), "--jq", ".[].login")
548 var stdout, stderr bytes.Buffer
549 cmd.Stdout = &stdout
550 cmd.Stderr = &stderr
551 if err := cmd.Run(); err != nil {
552 return nil, fmt.Errorf("fetching collaborators: %w", wrapTimeoutErr(ctx, "gh api collaborators", err))
553 }
554 var logins []string
555 for _, line := range strings.Split(strings.TrimSpace(stdout.String()), "\n") {
556 if line != "" {
557 logins = append(logins, line)
558 }
559 }
560 return logins, nil
561}
562
563// APIGet runs gh api with the given path and returns raw bytes.
564func (c *GHCLIClient) APIGet(ctx context.Context, path string) ([]byte, error) {
565 ctx, cancel := ensureTimeout(ctx)
566 defer cancel()
567
568 cmd := exec.CommandContext(ctx, "gh", "api", path)
569 var stdout, stderr bytes.Buffer
570 cmd.Stdout = &stdout
571 cmd.Stderr = &stderr
572 if err := cmd.Run(); err != nil {
573 return nil, fmt.Errorf("gh api %s: %w", path, wrapTimeoutErr(ctx, "gh api "+path, err))
574 }
575 return stdout.Bytes(), nil
576}
577
578// PRsForBranch returns the URLs of the PRs in slug (owner/repo), open or
579// not, whose head is branch in that repo, newest first, by the REST API.
580func (c *GHCLIClient) PRsForBranch(ctx context.Context, slug, branch string) ([]string, error) {
581 owner, _, _ := strings.Cut(slug, "/")
582 data, err := c.APIGet(ctx, "repos/"+slug+"/pulls?state=all&per_page=5&head="+url.QueryEscape(owner+":"+branch))
583 if err != nil {
584 return nil, err
585 }
586 var prs []struct {
587 HTMLURL string `json:"html_url"`
588 }
589 if err := json.Unmarshal(data, &prs); err != nil {
590 return nil, fmt.Errorf("reading the PRs of branch %s: %w", branch, err)
591 }
592 urls := make([]string, 0, len(prs))
593 for _, pr := range prs {
594 urls = append(urls, pr.HTMLURL)
595 }
596 return urls, nil
597}
598
599// APIPost runs gh api with POST method and field arguments.
600func (c *GHCLIClient) APIPost(ctx context.Context, path string, fields map[string]string) error {
601 ctx, cancel := ensureTimeout(ctx)
602 defer cancel()
603
604 args := []string{"api", path, "-X", "POST"}
605 for k, v := range fields {
606 args = append(args, "-f", k+"="+v)
607 }
608 cmd := exec.CommandContext(ctx, "gh", args...)
609 var stderr bytes.Buffer
610 cmd.Stderr = &stderr
611 if err := cmd.Run(); err != nil {
612 return fmt.Errorf("gh api POST %s: %w", path, wrapTimeoutErr(ctx, "gh api POST "+path, err))
613 }
614 return nil
615}
616
617// APIPostJSON runs gh api with POST method and a raw JSON body via --input.
618func (c *GHCLIClient) APIPostJSON(ctx context.Context, path string, body interface{}) ([]byte, error) {
619 ctx, cancel := ensureTimeout(ctx)
620 defer cancel()
621
622 payload, err := json.Marshal(body)
623 if err != nil {
624 return nil, fmt.Errorf("marshaling request body: %w", err)
625 }
626 cmd := exec.CommandContext(ctx, "gh", "api", path, "-X", "POST", "--input", "-")
627 cmd.Stdin = bytes.NewReader(payload)
628 var stdout, stderr bytes.Buffer
629 cmd.Stdout = &stdout
630 cmd.Stderr = &stderr
631 if err := cmd.Run(); err != nil {
632 return nil, fmt.Errorf("gh api POST %s: %w: %s", path, wrapTimeoutErr(ctx, "gh api POST "+path, err), strings.TrimSpace(stderr.String()))
633 }
634 return stdout.Bytes(), nil
635}
636
637// PRDiff returns the uncolored `gh pr diff` output for prRef.
638func (c *GHCLIClient) PRDiff(ctx context.Context, prRef string) (string, error) {
639 ctx, cancel := ensureTimeout(ctx)
640 defer cancel()
641
642 cmd := exec.CommandContext(ctx, "gh", c.ghArgs([]string{"pr", "diff", "--color", "never"}, prRef)...)
643 var stdout, stderr bytes.Buffer
644 cmd.Stdout = &stdout
645 cmd.Stderr = &stderr
646 if err := cmd.Run(); err != nil {
647 return "", wrapTimeoutErr(ctx, "gh pr diff", fmt.Errorf("gh pr diff %s: %s", prRef, strings.TrimSpace(stderr.String())))
648 }
649 return stdout.String(), nil
650}
651
652// FetchPRMetadata fetches PR URL, title, head branch, and state from GitHub via gh CLI.
653func (c *GHCLIClient) FetchPRMetadata(ctx context.Context, prNumber, repo string) (prURL, title, headBranch, state string, err error) {
654 ctx, cancel := ensureTimeout(ctx)
655 defer cancel()
656
657 args := []string{
658 "pr", "view", prNumber,
659 "--repo", repo,
660 "--json", "url,title,headRefName,state",
661 "-q", `(.url) + "\t" + (.title) + "\t" + (.headRefName) + "\t" + (.state)`,
662 }
663 cmd := exec.CommandContext(ctx, "gh", args...)
664 var stdout, stderr bytes.Buffer
665 cmd.Stdout = &stdout
666 cmd.Stderr = &stderr
667 if err := cmd.Run(); err != nil {
668 return "", "", "", "", wrapTimeoutErr(ctx, "gh pr view", fmt.Errorf("gh pr view: %s", strings.TrimSpace(stderr.String())))
669 }
670
671 parts := strings.SplitN(strings.TrimSpace(stdout.String()), "\t", 4)
672 if len(parts) < 4 {
673 return "", "", "", "", fmt.Errorf("unexpected gh output: %s", stdout.String())
674 }
675 return parts[0], parts[1], parts[2], parts[3], nil
676}
677
678// GetAuthenticatedUser returns the login of the currently authenticated GitHub user.
679func (c *GHCLIClient) GetAuthenticatedUser(ctx context.Context) (string, error) {
680 ctx, cancel := ensureTimeout(ctx)
681 defer cancel()
682
683 cmd := exec.CommandContext(ctx, "gh", "api", "user", "-q", ".login")
684 var stdout bytes.Buffer
685 cmd.Stdout = &stdout
686 if err := cmd.Run(); err != nil {
687 return "", fmt.Errorf("gh api user: %w", wrapTimeoutErr(ctx, "gh api user", err))
688 }
689 login := strings.TrimSpace(stdout.String())
690 if login == "" {
691 return "", fmt.Errorf("empty login from gh api user")
692 }
693 return login, nil
694}
695
696// ChecksArgs returns arguments for "gh pr checks". Exported for testing.
697func (c *GHCLIClient) ChecksArgs(prRef string) []string {
698 return c.ghArgs([]string{"pr", "checks"}, prRef)
699}
700
701// ViewStateArgs returns arguments for "gh pr view --json state". Exported for testing.
702func (c *GHCLIClient) ViewStateArgs(prRef string) []string {
703 return c.ghArgs([]string{"pr", "view", "--json", "state", "-q", ".state"}, prRef)
704}
705
706// ViewConflictsArgs returns arguments for "gh pr view --json mergeable". Exported for testing.
707func (c *GHCLIClient) ViewConflictsArgs(prRef string) []string {
708 return c.ghArgs([]string{"pr", "view", "--json", "mergeable", "-q", ".mergeable"}, prRef)
709}
710
711// ViewReviewDecisionArgs returns arguments for "gh pr view --json reviewDecision". Exported for testing.
712func (c *GHCLIClient) ViewReviewDecisionArgs(prRef string) []string {
713 return c.ghArgs([]string{"pr", "view", "--json", "reviewDecision", "-q", ".reviewDecision"}, prRef)
714}
715
716// ViewTitleArgs returns arguments for "gh pr view --json title". Exported for testing.
717func (c *GHCLIClient) ViewTitleArgs(prRef string) []string {
718 return c.ghArgs([]string{"pr", "view", "--json", "title", "-q", ".title"}, prRef)
719}