feat(watchpr): poll GitHub PRs alongside Gitea
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
ci/woodpecker/pr/test Pipeline was successful

This commit is contained in:
2026-11-22 01:51:26 +11:00
parent 10d93aaa90
commit 161a33c2ed
11 changed files with 983 additions and 32 deletions
+12 -2
View File
@@ -14,6 +14,8 @@ import (
// so callers can react to specific failures (e.g. tolerate a 404 for a commit
// whose branch was deleted after a merge) instead of parsing error strings.
type APIError struct {
// Service names the forge that answered; empty means Gitea.
Service string
Method string
Path string
StatusCode int
@@ -21,7 +23,15 @@ type APIError struct {
}
func (e *APIError) Error() string {
return fmt.Sprintf("gitea %s %s: HTTP %d: %s", e.Method, e.Path, e.StatusCode, e.Body)
return fmt.Sprintf("%s %s %s: HTTP %d: %s", e.ServiceName(), e.Method, e.Path, e.StatusCode, e.Body)
}
// ServiceName returns Service, defaulting to "gitea".
func (e *APIError) ServiceName() string {
if e.Service == "" {
return "gitea"
}
return e.Service
}
// IsNotFound reports whether err is a Gitea 404. Gitea hides repositories a
@@ -43,7 +53,7 @@ func IsAuthError(err error) bool {
// ErrNoCredential marks a 401/403 on a request that carried no token at all.
// Anonymous polling of a public repo is supported, so this is not a rejected
// credential: the resource simply is not public and no token was available.
var ErrNoCredential = errors.New("gitea requires authentication and no token was available")
var ErrNoCredential = errors.New("authentication required and no token was available")
// IsNoCredential reports whether err is an auth failure on an anonymous request.
func IsNoCredential(err error) bool {
+26 -6
View File
@@ -81,10 +81,15 @@ type GitHubApp struct {
APIURL string
HTTP *http.Client
mu sync.Mutex
token string
mu sync.Mutex
token string
expires time.Time
}
// tokenRefreshMargin is how long before expiry a cached installation token is
// re-minted, so a request never goes out with one about to lapse.
const tokenRefreshMargin = 5 * time.Minute
// ParseRSAPrivateKey decodes a PEM RSA key in PKCS#1 or PKCS#8 form. Errors
// never include key material.
func ParseRSAPrivateKey(pemData string) (*rsa.PrivateKey, error) {
@@ -155,19 +160,31 @@ func (a *GitHubApp) do(method, path, bearer string, out any) error {
}
// InstallationToken returns an installation access token, minted on first call
// and cached for the life of the process.
// and cached until it is within tokenRefreshMargin of expiry.
func (a *GitHubApp) InstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.token != "" {
if a.token != "" && time.Now().Before(a.expires.Add(-tokenRefreshMargin)) {
return a.token, nil
}
return a.mint()
}
// RefreshInstallationToken discards the cached token and mints a new one.
func (a *GitHubApp) RefreshInstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.mint()
}
func (a *GitHubApp) mint() (string, error) {
jwt, err := a.JWT(time.Now())
if err != nil {
return "", err
}
var out struct {
Token string `json:"token"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
path := "/app/installations/" + url.PathEscape(a.InstallationID) + "/access_tokens"
if err := a.do(http.MethodPost, path, jwt, &out); err != nil {
@@ -176,7 +193,10 @@ func (a *GitHubApp) InstallationToken() (string, error) {
if out.Token == "" {
return "", fmt.Errorf("github token mint for installation %s: no token in response", a.InstallationID)
}
a.token = out.Token
if out.ExpiresAt.IsZero() {
out.ExpiresAt = time.Now().Add(time.Hour)
}
a.token, a.expires = out.Token, out.ExpiresAt
return a.token, nil
}
+302
View File
@@ -0,0 +1,302 @@
package agent
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
)
// DefaultGitHubAgentLogins are the GitHub identities whose activity watchpr
// ignores when GITHUB_AGENT_LOGINS is unset.
var DefaultGitHubAgentLogins = []string{"iuclabs-coder[bot]", "iuclabs-reviewer[bot]", "github-actions[bot]", "dependabot[bot]"}
// GitHubAgentLogins returns GITHUB_AGENT_LOGINS (comma-separated) or the default.
func GitHubAgentLogins() []string {
var out []string
for _, l := range strings.Split(os.Getenv("GITHUB_AGENT_LOGINS"), ",") {
if l = strings.TrimSpace(l); l != "" {
out = append(out, l)
}
}
if len(out) == 0 {
return DefaultGitHubAgentLogins
}
return out
}
// GitHubClient reads pull request state from the GitHub REST API.
type GitHubClient struct {
APIURL string
HTTP *http.Client
AgentLogins []string
// Token returns the current token; nil means anonymous.
Token func() (string, error)
// Refresh mints a replacement when GitHub rejects the current token.
Refresh func() (string, error)
}
// NewGitHubClient builds an anonymous client for GITHUB_API_URL.
func NewGitHubClient(agentLogins []string) (*GitHubClient, error) {
apiURL, err := GitHubAPIURL()
if err != nil {
return nil, err
}
return &GitHubClient{APIURL: apiURL, HTTP: httpClient, AgentLogins: agentLogins}, nil
}
// UseApp authenticates the client as the app's installation.
func (c *GitHubClient) UseApp(a *GitHubApp) {
c.Token, c.Refresh = a.InstallationToken, a.RefreshInstallationToken
}
// do mirrors GiteaClient.do: a rejected token is re-minted once and the request
// replayed; anonymous and permission failures are returned as they are.
func (c *GitHubClient) do(path string, out any) error {
token := ""
if c.Token != nil {
t, err := c.Token()
if err != nil {
return fmt.Errorf("github token: %w", err)
}
token = t
}
err := c.attempt(path, token, out)
if !IsAuthError(err) {
return err
}
if token == "" {
return fmt.Errorf("%w: %w", ErrNoCredential, err)
}
if !IsCredentialRejected(err) || c.Refresh == nil {
return err
}
token, refreshErr := c.Refresh()
if refreshErr != nil {
return fmt.Errorf("%w; re-minting token: %v", err, refreshErr)
}
if token == "" {
return fmt.Errorf("%w; re-minting token yielded an empty token", err)
}
return c.attempt(path, token, out)
}
func (c *GitHubClient) attempt(path, token string, out any) error {
req, err := http.NewRequest(http.MethodGet, c.APIURL+path, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
data, _ := io.ReadAll(resp.Body)
body := strings.TrimSpace(string(data))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// A rate limit is a 403/429 that clears on its own, so it must not end a watch as an auth failure.
if resp.StatusCode == http.StatusTooManyRequests || resp.Header.Get("X-RateLimit-Remaining") == "0" ||
(resp.StatusCode == http.StatusForbidden && strings.Contains(strings.ToLower(body), "rate limit")) {
return fmt.Errorf("github GET %s: rate limited (HTTP %d)", path, resp.StatusCode)
}
return &APIError{Service: "github", Method: http.MethodGet, Path: path, StatusCode: resp.StatusCode, Body: body}
}
if err := json.Unmarshal(data, out); err != nil {
return fmt.Errorf("github GET %s: decoding response: %w", path, err)
}
return nil
}
const githubPageSize = 100
// listAll fetches every page of a list endpoint.
func listAll[T any](c *GitHubClient, path string) ([]T, error) {
var all []T
for page := 1; ; page++ {
var items []T
if err := c.do(path+"?per_page="+strconv.Itoa(githubPageSize)+"&page="+strconv.Itoa(page), &items); err != nil {
return nil, err
}
all = append(all, items...)
if len(items) < githubPageSize {
return all, nil
}
}
}
type githubPR struct {
State string `json:"state"`
Title string `json:"title"`
Merged bool `json:"merged"`
Mergeable *bool `json:"mergeable"`
MergeableState string `json:"mergeable_state"`
HTMLURL string `json:"html_url"`
Head struct {
Sha string `json:"sha"`
} `json:"head"`
Base struct {
Sha string `json:"sha"`
} `json:"base"`
}
type githubCheckRun struct {
Status string `json:"status"`
Conclusion string `json:"conclusion"`
}
// githubActivity covers issue comments, review comments and reviews alike.
type githubActivity struct {
User struct {
Login string `json:"login"`
} `json:"user"`
State string `json:"state"`
}
// githubMergeability maps GitHub's mergeable flag, which is null while GitHub
// is still computing it.
func githubMergeability(m *bool) Mergeability {
switch {
case m == nil:
return MergeUnknown
case *m:
return MergeYes
}
return MergeNo
}
var failedCheckConclusions = map[string]bool{
"failure": true, "timed_out": true, "cancelled": true, "action_required": true, "startup_failure": true,
}
// mergeGitHubCI combines the commit-status state with the check runs: any
// failure wins, then anything still running, then success. "" means no CI.
func mergeGitHubCI(status string, statusCount int, runs []githubCheckRun) string {
failed, pending, ok := false, false, false
if statusCount > 0 {
switch status {
case "failure", "error":
return status
case "pending":
pending = true
case "success":
ok = true
}
}
for _, r := range runs {
switch {
case r.Status != "completed":
pending = true
case failedCheckConclusions[r.Conclusion]:
failed = true
default:
ok = true
}
}
switch {
case failed:
return "failure"
case pending:
return "pending"
case ok:
return "success"
}
return ""
}
// countNonAgentActivity counts items not authored by an agent login. Pending
// reviews are drafts visible only to their author, so they never count.
func countNonAgentActivity(items []githubActivity, agentLogins []string) int {
n := 0
for _, it := range items {
if it.State == "PENDING" {
continue
}
isAgent := false
for _, l := range agentLogins {
if strings.EqualFold(it.User.Login, l) {
isAgent = true
break
}
}
if !isAgent {
n++
}
}
return n
}
// ciState fetches the merged CI state for sha; a 404 (head commit gone after a
// merge) means no CI, as for Gitea.
func (c *GitHubClient) ciState(repo, sha string) (string, error) {
if sha == "" {
return "", nil
}
var status struct {
State string `json:"state"`
TotalCount int `json:"total_count"`
}
if err := c.do("/repos/"+repo+"/commits/"+sha+"/status", &status); err != nil {
if IsNotFound(err) {
return "", nil
}
return "", err
}
// Only the first page of check runs is read; a head with more than 100 is not expected.
var checks struct {
CheckRuns []githubCheckRun `json:"check_runs"`
}
if err := c.do("/repos/"+repo+"/commits/"+sha+"/check-runs?per_page="+strconv.Itoa(githubPageSize), &checks); err != nil {
if IsNotFound(err) {
return "", nil
}
return "", err
}
return mergeGitHubCI(status.State, status.TotalCount, checks.CheckRuns), nil
}
// FetchState makes *GitHubClient a StateFetcher. The agent logins come from the
// client, so the Gitea agentLogin argument is ignored.
func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) {
repo := ref.RepoPath()
n := strconv.Itoa(ref.Number)
var pr githubPR
if err := c.do("/repos/"+repo+"/pulls/"+n, &pr); err != nil {
if IsNotFound(err) {
return PRState{}, fmt.Errorf("%w: %w", errPRGone, err)
}
return PRState{}, err
}
ci, err := c.ciState(repo, pr.Head.Sha)
if err != nil {
return PRState{}, err
}
comments := 0
for _, path := range []string{"/issues/" + n + "/comments", "/pulls/" + n + "/comments", "/pulls/" + n + "/reviews"} {
items, err := listAll[githubActivity](c, "/repos/"+repo+path)
if err != nil {
return PRState{}, err
}
comments += countNonAgentActivity(items, c.AgentLogins)
}
return PRState{
Ref: ref,
State: pr.State,
Merged: pr.Merged,
HeadSHA: pr.Head.Sha,
BaseSHA: pr.Base.Sha,
Mergeable: githubMergeability(pr.Mergeable),
MergeableState: pr.MergeableState,
CIStatus: ci,
NonAgentComments: comments,
Title: pr.Title,
URL: pr.HTMLURL,
}, nil
}
+377
View File
@@ -0,0 +1,377 @@
package agent
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestMergeGitHubCI(t *testing.T) {
run := func(status, conclusion string) githubCheckRun { return githubCheckRun{Status: status, Conclusion: conclusion} }
done := func(c string) githubCheckRun { return run("completed", c) }
tests := []struct {
name string
status string
count int
runs []githubCheckRun
want string
}{
{"nothing", "pending", 0, nil, ""},
{"zero statuses report pending but mean none", "pending", 0, []githubCheckRun{done("success")}, "success"},
{"status failure wins over green checks", "failure", 2, []githubCheckRun{done("success")}, "failure"},
{"status error", "error", 1, nil, "error"},
{"check failure wins over green status", "success", 1, []githubCheckRun{done("success"), done("failure")}, "failure"},
{"check failure wins over running checks", "pending", 1, []githubCheckRun{run("in_progress", ""), done("timed_out")}, "failure"},
{"running check keeps it pending", "success", 1, []githubCheckRun{run("queued", "")}, "pending"},
{"pending status keeps it pending", "pending", 1, []githubCheckRun{done("success")}, "pending"},
{"skipped and neutral are not failures", "", 0, []githubCheckRun{done("skipped"), done("neutral")}, "success"},
{"cancelled is a failure", "", 0, []githubCheckRun{done("cancelled")}, "failure"},
{"status only", "success", 3, nil, "success"},
}
for _, tt := range tests {
if got := mergeGitHubCI(tt.status, tt.count, tt.runs); got != tt.want {
t.Errorf("%s: mergeGitHubCI = %q, want %q", tt.name, got, tt.want)
}
}
}
func TestCountNonAgentActivity(t *testing.T) {
item := func(login, state string) githubActivity {
var a githubActivity
a.User.Login, a.State = login, state
return a
}
items := []githubActivity{
item("iuclabs-coder[bot]", ""),
item("IUCLabs-Reviewer[bot]", "COMMENTED"),
item("dependabot[bot]", ""),
item("alice", "CHANGES_REQUESTED"),
item("alice", "PENDING"),
item("bob", ""),
}
if n := countNonAgentActivity(items, DefaultGitHubAgentLogins); n != 2 {
t.Errorf("count = %d, want 2 (alice's review + bob; agents and drafts excluded)", n)
}
}
func TestGitHubAgentLoginsEnv(t *testing.T) {
t.Setenv("GITHUB_AGENT_LOGINS", "")
if got := GitHubAgentLogins(); len(got) != 4 {
t.Errorf("default = %v", got)
}
t.Setenv("GITHUB_AGENT_LOGINS", " a[bot], ,b ")
if got := GitHubAgentLogins(); strings.Join(got, "|") != "a[bot]|b" {
t.Errorf("env = %v", got)
}
}
// fakeGitHubPR serves one PR whose state tests mutate between polls.
type fakeGitHubPR struct {
mu sync.Mutex
pr string
status string
checks string
issue []string
review []string
reviews []string
authSeen []string
reject string // a token the server answers 401 for
rateLimit bool
}
func (f *fakeGitHubPR) set(fn func(*fakeGitHubPR)) {
f.mu.Lock()
defer f.mu.Unlock()
fn(f)
}
func activity(logins ...string) []string {
out := make([]string, len(logins))
for i, l := range logins {
state := ""
if strings.HasPrefix(l, "review:") {
l, state = strings.TrimPrefix(l, "review:"), "CHANGES_REQUESTED"
}
out[i] = fmt.Sprintf(`{"user":{"login":%q},"state":%q}`, l, state)
}
return out
}
func (f *fakeGitHubPR) serve(t *testing.T) *httptest.Server {
t.Helper()
page := func(w http.ResponseWriter, r *http.Request, items []string) {
p, _ := strconv.Atoi(r.URL.Query().Get("page"))
if r.URL.Query().Get("per_page") != "100" || p < 1 {
t.Errorf("%s: unpaged list request", r.URL)
}
lo, hi := min((p-1)*100, len(items)), min(p*100, len(items))
_, _ = w.Write([]byte("[" + strings.Join(items[lo:hi], ",") + "]"))
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
auth := r.Header.Get("Authorization")
f.authSeen = append(f.authSeen, auth)
if f.rateLimit {
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message":"API rate limit exceeded"}`))
return
}
if f.reject != "" && auth == "Bearer "+f.reject {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"Bad credentials"}`))
return
}
switch r.URL.Path {
case "/repos/IUCLabs/app/pulls/5":
_, _ = w.Write([]byte(f.pr))
case "/repos/IUCLabs/app/commits/aaa/status", "/repos/IUCLabs/app/commits/bbb/status":
_, _ = w.Write([]byte(f.status))
case "/repos/IUCLabs/app/commits/aaa/check-runs", "/repos/IUCLabs/app/commits/bbb/check-runs":
_, _ = w.Write([]byte(f.checks))
case "/repos/IUCLabs/app/issues/5/comments":
page(w, r, f.issue)
case "/repos/IUCLabs/app/pulls/5/comments":
page(w, r, f.review)
case "/repos/IUCLabs/app/pulls/5/reviews":
page(w, r, f.reviews)
default:
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"Not Found"}`))
}
}))
t.Cleanup(srv.Close)
return srv
}
func openPR(head string, mergeable string) string {
return `{"state":"open","title":"t","merged":false,"mergeable":` + mergeable +
`,"mergeable_state":"clean","html_url":"https://github.com/IUCLabs/app/pull/5","head":{"sha":"` + head + `"},"base":{"sha":"base1"}}`
}
var ghRef = PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 5}
func newFakeGitHubClient(srv *httptest.Server) *GitHubClient {
return &GitHubClient{APIURL: srv.URL, HTTP: srv.Client(), AgentLogins: DefaultGitHubAgentLogins}
}
func TestGitHubFetchState(t *testing.T) {
humans := make([]string, 0, 101)
for i := 0; i < 101; i++ {
humans = append(humans, "carol")
}
f := &fakeGitHubPR{
pr: openPR("aaa", "null"),
status: `{"state":"success","total_count":1}`,
checks: `{"check_runs":[{"status":"completed","conclusion":"failure"}]}`,
issue: activity(humans...),
review: activity("iuclabs-coder[bot]", "alice"),
reviews: activity("review:alice", "iuclabs-reviewer[bot]"),
}
st, err := newFakeGitHubClient(f.serve(t)).FetchState(ghRef, "unkin-agent")
if err != nil {
t.Fatal(err)
}
if st.State != "open" || st.HeadSHA != "aaa" || st.BaseSHA != "base1" || st.Mergeable != MergeUnknown || st.MergeableState != "clean" {
t.Errorf("state = %+v", st)
}
if st.CIStatus != "failure" {
t.Errorf("ci = %q, want failure from the check run", st.CIStatus)
}
if st.NonAgentComments != 103 {
t.Errorf("non-agent = %d, want 103 (101 paged issue comments + review comment + review)", st.NonAgentComments)
}
for _, a := range f.authSeen {
if a != "" {
t.Errorf("anonymous client sent Authorization %q", a)
}
}
b, _ := json.Marshal(st)
if !strings.Contains(string(b), `"Forge":"github"`) || !strings.Contains(string(b), `"mergeable":null`) {
t.Errorf("json = %s", b)
}
}
func TestGitHubFetchStateErrors(t *testing.T) {
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":0}`, checks: `{"check_runs":[]}`}
c := newFakeGitHubClient(f.serve(t))
gone := ghRef
gone.Number = 6
if _, err := c.FetchState(gone, ""); !IsPRGone(err) {
t.Errorf("missing PR err = %v, want PR gone", err)
}
f.set(func(f *fakeGitHubPR) { f.rateLimit = true })
_, err := c.FetchState(ghRef, "")
if err == nil || IsAuthError(err) || !strings.Contains(err.Error(), "rate limited") {
t.Errorf("rate limit err = %v, want a transient non-auth error", err)
}
f.set(func(f *fakeGitHubPR) { f.rateLimit = false })
c.Token = func() (string, error) { return "", errors.New("vault down") }
if _, err := c.FetchState(ghRef, ""); err == nil || !strings.Contains(err.Error(), "vault down") {
t.Errorf("token err = %v", err)
}
}
func TestGitHubAnonymousRejectionIsNoCredential(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"Requires authentication"}`))
}))
defer srv.Close()
_, err := newFakeGitHubClient(srv).FetchState(ghRef, "")
if !IsNoCredential(err) {
t.Errorf("err = %v, want ErrNoCredential", err)
}
if !strings.Contains(err.Error(), "github GET") {
t.Errorf("err = %v, want it to name github", err)
}
}
func TestGitHubReMintsRejectedToken(t *testing.T) {
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: `{"check_runs":[]}`, reject: "old"}
c := newFakeGitHubClient(f.serve(t))
current := "old"
refreshes := 0
c.Token = func() (string, error) { return current, nil }
c.Refresh = func() (string, error) { refreshes++; current = "new"; return current, nil }
if _, err := c.FetchState(ghRef, ""); err != nil {
t.Fatal(err)
}
if refreshes != 1 {
t.Errorf("refreshes = %d, want 1", refreshes)
}
if last := f.authSeen[len(f.authSeen)-1]; last != "Bearer new" {
t.Errorf("last auth = %q", last)
}
f.set(func(f *fakeGitHubPR) { f.reject = "new" })
c.Refresh = func() (string, error) { return "new", nil }
if _, err := c.FetchState(ghRef, ""); !IsAuthError(err) || IsNoCredential(err) {
t.Errorf("err = %v, want an auth error after the re-mint is rejected too", err)
}
}
func TestInstallationTokenReMintsNearExpiry(t *testing.T) {
var mints atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := mints.Add(1)
exp := time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339)
w.WriteHeader(http.StatusCreated)
_, _ = fmt.Fprintf(w, `{"token":"t%d","expires_at":%q}`, n, exp)
}))
defer srv.Close()
a := &GitHubApp{AppID: "1", InstallationID: "777", Key: testKey, APIURL: srv.URL, HTTP: srv.Client()}
for i := 1; i <= 2; i++ {
if tok, err := a.InstallationToken(); err != nil || tok != "t"+strconv.Itoa(i) {
t.Fatalf("call %d: token = %q, %v (a token inside the refresh margin must be re-minted)", i, tok, err)
}
}
if tok, err := a.RefreshInstallationToken(); err != nil || tok != "t3" {
t.Errorf("refresh = %q, %v", tok, err)
}
}
// runGitHubWatch drives Watch through steps (one per tick) and returns the
// result of the tick after the last step; it fails if the watch ends earlier.
func runGitHubWatch(t *testing.T, f *fakeGitHubPR, steps ...func(*fakeGitHubPR)) WatchResult {
t.Helper()
c := newFakeGitHubClient(f.serve(t))
ticks := make(chan time.Time)
type result struct {
res WatchResult
err error
}
done := make(chan result, 1)
baseline := make(chan struct{})
go func() {
res, err := Watch(c, []PRRef{ghRef}, "", ticks, func([]PRState) { close(baseline) }, nil)
done <- result{res, err}
}()
select {
case <-baseline:
case r := <-done:
t.Fatalf("watch ended at baseline: %+v, %v", r.res, r.err)
}
now := time.Now()
for i, step := range steps {
f.set(step)
now = now.Add(time.Minute)
select {
case ticks <- now:
case r := <-done:
t.Fatalf("step %d: watch ended early: %+v, %v", i, r.res, r.err)
}
}
close(ticks)
r := <-done
if r.err != nil {
t.Fatal(r.err)
}
return r.res
}
func pendingPR() *fakeGitHubPR {
return &fakeGitHubPR{
pr: openPR("aaa", "true"),
status: `{"state":"pending","total_count":1}`,
checks: `{"check_runs":[{"status":"in_progress"}]}`,
}
}
// The agents' own pushes and comments and CI going green are silent; a human
// changes-requested review alerts.
func TestWatchGitHubHumanReviewAlerts(t *testing.T) {
res := runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) {
f.pr = openPR("bbb", "null")
f.issue = activity("iuclabs-coder[bot]", "github-actions[bot]")
},
func(f *fakeGitHubPR) {
f.status = `{"state":"success","total_count":1}`
f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"}]}`
f.reviews = activity("iuclabs-reviewer[bot]")
},
)
if !res.TimedOut {
t.Fatalf("benign steps alerted: %+v", res)
}
res = runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) { f.reviews = activity("iuclabs-reviewer[bot]", "review:alice") },
)
if res.Reason != "new comment from a non-agent user" || res.Ref != ghRef {
t.Errorf("result = %+v, want the human review to alert", res)
}
}
func TestWatchGitHubCheckRunFailureAlerts(t *testing.T) {
res := runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) {
f.status = `{"state":"success","total_count":1}`
f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"},{"status":"completed","conclusion":"failure"}]}`
},
)
if res.Reason != "CI failed (failure)" {
t.Errorf("result = %+v, want a CI failure", res)
}
}
func TestWatchGitHubMergeAlerts(t *testing.T) {
res := runGitHubWatch(t, pendingPR(),
func(f *fakeGitHubPR) { f.pr = strings.Replace(openPR("aaa", "null"), `"merged":false`, `"merged":true`, 1) },
)
if res.Reason != "PR merged" {
t.Errorf("result = %+v, want merged", res)
}
}
+38 -2
View File
@@ -9,14 +9,26 @@ import (
// PRRef identifies a single pull request by repository and number.
type PRRef struct {
// Forge is ForgeGitHub for a GitHub PR; empty means Gitea.
Forge string `json:",omitempty"`
Owner string
Repo string
Number int
}
// String renders the ref in canonical owner/repo#N form.
// ForgeGitHub marks a PRRef that lives on GitHub.
const ForgeGitHub = "github"
const githubPRURLPrefix = "https://github.com/"
// String renders the ref in canonical owner/repo#N form, prefixed github: for
// a GitHub PR.
func (r PRRef) String() string {
return fmt.Sprintf("%s/%s#%d", r.Owner, r.Repo, r.Number)
s := fmt.Sprintf("%s/%s#%d", r.Owner, r.Repo, r.Number)
if r.Forge != "" {
return r.Forge + ":" + s
}
return s
}
// RepoPath returns the "owner/repo" portion used in Gitea API URLs.
@@ -49,6 +61,30 @@ func ParsePRRef(s string) (PRRef, error) {
return PRRef{Owner: owner, Repo: repo, Number: n}, nil
}
// ParseWatchRef parses a Gitea ref (see ParsePRRef) or a GitHub one:
// "github:owner/repo#N", "github:owner/repo:N" or
// "https://github.com/owner/repo/pull/N".
func ParseWatchRef(s string) (PRRef, error) {
s = strings.TrimSpace(s)
if rest, ok := strings.CutPrefix(s, githubPRURLPrefix); ok {
parts := strings.Split(strings.TrimSuffix(rest, "/"), "/")
if len(parts) != 4 || parts[2] != "pull" {
return PRRef{}, fmt.Errorf("invalid GitHub PR URL %q: expected %sowner/repo/pull/N", s, githubPRURLPrefix)
}
s = "github:" + parts[0] + "/" + parts[1] + "#" + parts[3]
}
rest, ok := strings.CutPrefix(s, "github:")
if !ok {
return ParsePRRef(s)
}
ref, err := ParsePRRef(rest)
if err != nil {
return PRRef{}, err
}
ref.Forge = ForgeGitHub
return ref, nil
}
// ParseDurationFlag parses a duration flag value, accepting either a Go
// duration string ("30s", "1h30m") or a bare integer read as seconds ("15").
// flag names the flag so the error says which value was rejected.
+33
View File
@@ -181,3 +181,36 @@ func TestRemoteHost(t *testing.T) {
}
}
}
func TestParseWatchRef(t *testing.T) {
tests := []struct {
in string
want PRRef
}{
{"unkin/repo#4", PRRef{Owner: "unkin", Repo: "repo", Number: 4}},
{"github:IUCLabs/app#12", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
{"github:IUCLabs/app:12", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
{" https://github.com/IUCLabs/app/pull/12 ", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
{"https://github.com/IUCLabs/app/pull/12/", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
}
for _, tt := range tests {
got, err := ParseWatchRef(tt.in)
if err != nil || got != tt.want {
t.Errorf("ParseWatchRef(%q) = %+v, %v; want %+v", tt.in, got, err, tt.want)
}
}
for _, bad := range []string{
"github:IUCLabs#1", "github:IUCLabs/app#0", "https://github.com/IUCLabs/app/issues/3",
"https://github.com/IUCLabs/app/pull/3/files", "https://github.com/IUCLabs/app/pull/x", "gitlab:o/r#1",
} {
if got, err := ParseWatchRef(bad); err == nil {
t.Errorf("ParseWatchRef(%q) = %+v, want error", bad, got)
}
}
if s := (PRRef{Forge: ForgeGitHub, Owner: "o", Repo: "r", Number: 3}).String(); s != "github:o/r#3" {
t.Errorf("String() = %q", s)
}
if _, err := ParsePRRef("github:o/r#3"); err == nil {
t.Error("ParsePRRef must not accept GitHub refs: Gitea-only tools use it")
}
}
+2 -1
View File
@@ -72,7 +72,8 @@ type PRState struct {
HeadSHA string `json:"head_sha"`
BaseSHA string `json:"base_sha"`
Mergeable Mergeability `json:"mergeable"`
CIStatus string `json:"ci_status"` // success / pending / failure / error / ""
MergeableState string `json:"mergeable_state,omitempty"` // GitHub only
CIStatus string `json:"ci_status"` // success / pending / failure / error / ""
NonAgentComments int `json:"non_agent_comments"`
Title string `json:"title"`
URL string `json:"url"`