gunk-dev/the-valley

reviewer.go

source9ee95920e399main's published tip history
4.4 KiB
1package github
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os/exec"
11 "strings"
12 "sync"
13)
14
15// ReviewerResolver picks the GitHub user a launched agent requests PR review
16// from. Agents open PRs as the gh-authenticated user, and GitHub silently drops
17// a review request aimed at a PR's author, so the reviewer has to be someone
18// else who can approve.
19type ReviewerResolver struct {
20 // Run runs gh with args and returns its stdout. Tests replace it.
21 Run func(ctx context.Context, args ...string) ([]byte, error)
22
23 authorOnce sync.Once
24 author string
25 authorErr error
26}
27
28// NewReviewerResolver returns a ReviewerResolver that runs the real gh CLI.
29func NewReviewerResolver() *ReviewerResolver {
30 return &ReviewerResolver{Run: runGH}
31}
32
33func runGH(ctx context.Context, args ...string) ([]byte, error) {
34 ctx, cancel := ensureTimeout(ctx)
35 defer cancel()
36
37 cmd := exec.CommandContext(ctx, "gh", args...)
38 var stdout, stderr bytes.Buffer
39 cmd.Stdout = &stdout
40 cmd.Stderr = &stderr
41 if err := cmd.Run(); err != nil {
42 err = wrapTimeoutErr(ctx, "gh "+strings.Join(args, " "), err)
43 if msg := strings.TrimSpace(stderr.String()); msg != "" {
44 return nil, fmt.Errorf("%w: %s", err, msg)
45 }
46 return nil, err
47 }
48 return stdout.Bytes(), nil
49}
50
51// Resolve returns the reviewer for PRs on repo ("owner/name"). A configured
52// login is returned as given, without running gh. Otherwise the reviewer is
53// chosen from the repo's collaborators with push access, leaving out the
54// gh-authenticated user (the PR's author) and bots: the repo owner if they are
55// one, else the only one. When there is no reviewer, warning says why in one
56// line; a failed gh call ends up there too, never as an error.
57func (r *ReviewerResolver) Resolve(ctx context.Context, repo, configured string) (reviewer, warning string) {
58 if configured != "" {
59 return configured, ""
60 }
61 reviewer, err := r.fromCollaborators(ctx, repo)
62 if err != nil {
63 return "", "no PR reviewer: " + oneLine(err) + "; set pr_reviewer to name one"
64 }
65 return reviewer, ""
66}
67
68func (r *ReviewerResolver) fromCollaborators(ctx context.Context, repo string) (string, error) {
69 owner, _, ok := strings.Cut(repo, "/")
70 if !ok || owner == "" {
71 return "", fmt.Errorf("cannot tell the GitHub repo from origin")
72 }
73 author, err := r.authenticatedUser(ctx)
74 if err != nil {
75 return "", fmt.Errorf("looking up the gh user: %w", err)
76 }
77 out, err := r.Run(ctx, "api", "--paginate", "repos/"+repo+"/collaborators?permission=push&affiliation=all")
78 if err != nil {
79 return "", fmt.Errorf("listing collaborators of %s: %w", repo, err)
80 }
81 collaborators, err := parseCollaborators(out)
82 if err != nil {
83 return "", fmt.Errorf("reading collaborators of %s: %w", repo, err)
84 }
85
86 var candidates []string
87 for _, c := range collaborators {
88 if c.Type != "User" || strings.EqualFold(c.Login, author) {
89 continue
90 }
91 if strings.EqualFold(c.Login, owner) {
92 return c.Login, nil
93 }
94 candidates = append(candidates, c.Login)
95 }
96 switch len(candidates) {
97 case 1:
98 return candidates[0], nil
99 case 0:
100 return "", fmt.Errorf("no user but %s has push access to %s", author, repo)
101 default:
102 return "", fmt.Errorf("%s has several possible reviewers (%s)", repo, strings.Join(candidates, ", "))
103 }
104}
105
106// authenticatedUser returns the gh-authenticated login, looked up once per
107// resolver.
108func (r *ReviewerResolver) authenticatedUser(ctx context.Context) (string, error) {
109 r.authorOnce.Do(func() {
110 out, err := r.Run(ctx, "api", "user", "-q", ".login")
111 if err != nil {
112 r.authorErr = err
113 return
114 }
115 r.author = strings.TrimSpace(string(out))
116 if r.author == "" {
117 r.authorErr = errors.New("gh api user returned an empty login")
118 }
119 })
120 return r.author, r.authorErr
121}
122
123type collaborator struct {
124 Login string `json:"login"`
125 Type string `json:"type"`
126}
127
128// parseCollaborators reads `gh api --paginate` output, which is one JSON array
129// per page written back to back.
130func parseCollaborators(out []byte) ([]collaborator, error) {
131 var all []collaborator
132 dec := json.NewDecoder(bytes.NewReader(out))
133 for {
134 var page []collaborator
135 if err := dec.Decode(&page); errors.Is(err, io.EOF) {
136 return all, nil
137 } else if err != nil {
138 return nil, err
139 }
140 all = append(all, page...)
141 }
142}
143
144// oneLine collapses err's message onto a single line, since gh can print
145// multi-line errors.
146func oneLine(err error) string {
147 return strings.Join(strings.Fields(err.Error()), " ")
148}