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
+87 -14
View File
@@ -1,4 +1,4 @@
// Command watchpr polls one or more Gitea pull requests and exits when a
// Command watchpr polls one or more Gitea or GitHub pull requests and exits when a
// tracked PR changes in a way worth alerting on: it merges or closes, gets a
// new comment from someone other than the agent, its CI fails, or it loses
// mergeability after the baseline. Benign transitions (CI pending→success, the
@@ -16,6 +16,7 @@
// minutes old.
//
// watchpr owner/repo#12 owner/repo:15
// watchpr owner/repo#12 github:IUCLabs/repo#3 https://github.com/IUCLabs/repo/pull/4
// watchpr --once --json owner/repo#12
// watchpr --interval 30s owner/repo#12
// watchpr --interval 30 owner/repo#12
@@ -69,12 +70,18 @@ func newRootCmd() *cobra.Command {
var once, jsonMode bool
root := &cobra.Command{
Use: "watchpr [flags] owner/repo#N [owner/repo#N ...]",
Short: "Poll Gitea PRs and exit when one changes meaningfully.",
Use: "watchpr [flags] REF [REF ...]",
Short: "Poll Gitea and GitHub PRs and exit when one changes meaningfully.",
Long: "watchpr polls each PR every --interval and exits (reporting what changed)\n" +
"when a PR merges/closes, gets a new non-agent comment, its CI fails, or it\n" +
"loses mergeability after the baseline. Conditions already true at the\n" +
"baseline are printed, not alerted on. Refs take owner/repo#N or owner/repo:N.\n\n" +
"baseline are printed, not alerted on.\n\n" +
"Refs (Gitea and GitHub may be mixed):\n" +
" owner/repo#N, owner/repo:N Gitea PR\n" +
" github:owner/repo#N, github:owner/repo:N GitHub PR\n" +
" https://github.com/owner/repo/pull/N GitHub PR\n" +
"GitHub is polled as the iuclabs reviewer app (anonymously if minting fails);\n" +
"activity by GITHUB_AGENT_LOGINS (comma-separated) is ignored.\n\n" +
"Exit status: 0 on a change (or --once), 3 when --max-wait elapses with no\n" +
"change (current states are printed), 1 on any error.",
Version: version,
@@ -97,13 +104,16 @@ func newRootCmd() *cobra.Command {
}
refs := make([]agent.PRRef, 0, len(args))
for _, a := range args {
ref, err := agent.ParsePRRef(a)
ref, err := agent.ParseWatchRef(a)
if err != nil {
return err
}
refs = append(refs, ref)
}
c := clientFor(jsonMode)
c, err := fetcherFor(refs, jsonMode)
if err != nil {
return err
}
if once {
return runOnce(c, refs, jsonMode)
}
@@ -131,6 +141,38 @@ func newRootCmd() *cobra.Command {
return root
}
// fetcher routes each ref to the client for its forge.
type fetcher struct {
gitea agent.StateFetcher
github agent.StateFetcher
}
func (f fetcher) FetchState(ref agent.PRRef, agentLogin string) (agent.PRState, error) {
if ref.Forge == agent.ForgeGitHub {
return f.github.FetchState(ref, agentLogin)
}
return f.gitea.FetchState(ref, agentLogin)
}
// fetcherFor builds a client only for the forges the refs name, so a
// Gitea-only watch never touches GitHub creds and vice versa.
func fetcherFor(refs []agent.PRRef, jsonMode bool) (fetcher, error) {
var f fetcher
for _, ref := range refs {
switch {
case ref.Forge == agent.ForgeGitHub && f.github == nil:
c, err := githubClientFor(jsonMode)
if err != nil {
return f, err
}
f.github = c
case ref.Forge == "" && f.gitea == nil:
f.gitea = clientFor(jsonMode)
}
}
return f, nil
}
// clientFor builds the Gitea client. Watching public repos works anonymously,
// so an unavailable token is a warning, not a failure; a poll that is actually
// rejected re-mints then.
@@ -143,6 +185,28 @@ func clientFor(jsonMode bool) *agent.GiteaClient {
return agent.NewGiteaClient(token)
}
// githubApp is the app watchpr polls GitHub as; read-only polling needs no more.
const githubApp = "reviewer"
// githubClientFor builds the GitHub client as the reviewer app, falling back to
// anonymous (public repos only) when no token can be minted.
func githubClientFor(jsonMode bool) (*agent.GitHubClient, error) {
c, err := agent.NewGitHubClient(agent.GitHubAgentLogins())
if err != nil {
return nil, err
}
app, err := agent.GitHubAppFor(githubApp)
if err == nil {
_, err = app.InstallationToken()
}
if err != nil {
warn(os.Stderr, jsonMode, "no GitHub token (%v); polling anonymously", err)
return c, nil
}
c.UseApp(app)
return c, nil
}
// warnRecord is the --json form of a warning. Under --json every notice watchpr
// itself writes to stderr -- warnings and the baseline -- is an NDJSON record,
// so a caller parsing them line by line never has to guess which shape a line
@@ -164,11 +228,11 @@ func warn(w io.Writer, jsonMode bool, format string, args ...any) {
}
// runOnce fetches and prints the current state of each PR, then exits 0.
func runOnce(c *agent.GiteaClient, refs []agent.PRRef, jsonMode bool) error {
func runOnce(c agent.StateFetcher, refs []agent.PRRef, jsonMode bool) error {
login := agent.AgentLogin()
states := make([]agent.PRState, 0, len(refs))
for _, ref := range refs {
st, err := agent.FetchState(c, ref, login)
st, err := c.FetchState(ref, login)
if err != nil {
return describeFailure(err)
}
@@ -185,7 +249,7 @@ func runOnce(c *agent.GiteaClient, refs []agent.PRRef, jsonMode bool) error {
// runWatch establishes a baseline then polls until a tracked PR changes
// meaningfully, at which point it reports the change and returns.
func runWatch(c *agent.GiteaClient, refs []agent.PRRef, interval, maxWait time.Duration, jsonMode bool) error {
func runWatch(c agent.StateFetcher, refs []agent.PRRef, interval, maxWait time.Duration, jsonMode bool) error {
login := agent.AgentLogin()
ticker := time.NewTicker(interval)
@@ -294,13 +358,18 @@ func emitBaselines(w io.Writer, states []agent.PRState, interval time.Duration,
// outlived its Vault lease are three different problems and only the last is
// fixed by a fresh token.
func describeFailure(err error) error {
forge, who := "gitea", agent.AgentLogin()
var apiErr *agent.APIError
if errors.As(err, &apiErr) && apiErr.ServiceName() != "gitea" {
forge, who = apiErr.ServiceName(), "the "+githubApp+" app"
}
switch {
case agent.IsNoCredential(err):
return fmt.Errorf("gitea requires authentication and no token could be minted, aborted: %w", err)
return fmt.Errorf("%s requires authentication and no token could be minted, aborted: %w", forge, err)
case agent.IsPermissionDenied(err):
return fmt.Errorf("gitea denied access to %s (a fresh token will not help), aborted: %w", agent.AgentLogin(), err)
return fmt.Errorf("%s denied access to %s (a fresh token will not help), aborted: %w", forge, who, err)
case agent.IsAuthError(err):
return fmt.Errorf("gitea rejected the token and re-minting did not recover it, aborted: %w", err)
return fmt.Errorf("%s rejected the token and re-minting did not recover it, aborted: %w", forge, err)
case agent.IsPRGone(err):
return fmt.Errorf("PR no longer visible (repo deleted, renamed, or made private), aborted: %w", err)
}
@@ -326,8 +395,12 @@ func printState(st agent.PRState) {
}
func stateLine(st agent.PRState) string {
mergeable := st.Mergeable.String()
if st.MergeableState != "" {
mergeable += "(" + st.MergeableState + ")"
}
return fmt.Sprintf("%s state=%s merged=%t mergeable=%s ci=%s head=%s base=%s comments(non-agent)=%d",
st.Ref.String(), st.State, st.Merged, st.Mergeable, ciOrNone(st.CIStatus),
st.Ref.String(), st.State, st.Merged, mergeable, ciOrNone(st.CIStatus),
shortSHA(st.HeadSHA), shortSHA(st.BaseSHA), st.NonAgentComments)
}
@@ -347,7 +420,7 @@ func suppressedAtBaseline(st agent.PRState) string {
var conds []string
switch st.Mergeable {
case agent.MergeNo:
conds = append(conds, "already non-mergeable (a real conflict, or Gitea still recomputing)")
conds = append(conds, "already non-mergeable (a real conflict, or the forge still recomputing)")
case agent.MergeUnknown:
conds = append(conds, "mergeability unknown (the conflict rule is disarmed until Gitea reports mergeable or the commits move)")
}
+66
View File
@@ -404,3 +404,69 @@ func TestReportTimeout(t *testing.T) {
t.Errorf("json output = %q (err %v)", buf.String(), err)
}
}
// One invocation may mix Gitea and GitHub refs; each is polled on its own forge,
// and GitHub falls back to anonymous when no app token can be minted.
func TestOnceMixesGiteaAndGitHubRefs(t *testing.T) {
vault := failingVault(t)
giteaHits := 0
gitea := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
giteaHits++
switch r.URL.Path {
case "/api/v1/repos/unkin/repo/pulls/7":
_, _ = io.WriteString(w, `{"number":7,"state":"open","mergeable":true,"head":{"sha":"cafebabe"}}`)
case "/api/v1/repos/unkin/repo/commits/cafebabe/status":
_, _ = io.WriteString(w, `{"state":"success"}`)
default:
_, _ = io.WriteString(w, `[]`)
}
}))
defer gitea.Close()
var githubPaths []string
github := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
githubPaths = append(githubPaths, r.URL.Path)
if r.Header.Get("Authorization") != "" {
t.Errorf("anonymous fallback sent Authorization to %s", r.URL.Path)
}
switch r.URL.Path {
case "/repos/IUCLabs/app/pulls/3", "/repos/IUCLabs/app/pulls/4":
_, _ = io.WriteString(w, `{"state":"open","mergeable":true,"head":{"sha":"abc"},"base":{"sha":"def"}}`)
case "/repos/IUCLabs/app/commits/abc/status":
_, _ = io.WriteString(w, `{"state":"pending","total_count":0}`)
case "/repos/IUCLabs/app/commits/abc/check-runs":
_, _ = io.WriteString(w, `{"check_runs":[]}`)
default:
_, _ = io.WriteString(w, `[]`)
}
}))
defer github.Close()
t.Setenv("VAULT_ADDR", vault.URL)
t.Setenv("GITEA_URL", gitea.URL)
t.Setenv("GITHUB_API_URL", github.URL)
t.Setenv("AGENTGH_KV_PATH", "")
cmd := newRootCmd()
cmd.SetArgs([]string{"--once", "unkin/repo#7", "github:IUCLabs/app#3", "https://github.com/IUCLabs/app/pull/4"})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
if err := cmd.Execute(); err != nil {
t.Fatalf("mixed --once: %v", err)
}
if giteaHits != 3 {
t.Errorf("gitea requests = %d, want 3 (one PR)", giteaHits)
}
if len(githubPaths) != 12 {
t.Errorf("github requests = %v, want 6 per PR", githubPaths)
}
}
func TestDescribeFailureNamesGitHub(t *testing.T) {
forbidden := &agent.APIError{Service: "github", Method: "GET", Path: "/p", StatusCode: 403, Body: `{"message":"Resource not accessible by integration"}`}
got := describeFailure(forbidden).Error()
if !strings.HasPrefix(got, "github denied access to the reviewer app") {
t.Errorf("describeFailure = %q", got)
}
}