Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cb54c67be1 | |||
| 85c80493ac | |||
| 7b9511500b | |||
| 08340cce22 | |||
| 6261b8e8d3 | |||
| 05c665857d | |||
| 2332cf4b5f | |||
| c4471975a3 | |||
| 161a33c2ed | |||
| 2faf4eff59 | |||
| 6c6044c6a0 |
@@ -13,7 +13,7 @@ like repospawner can run these tools as itself.
|
|||||||
as Ben" attribution problem). Subcommands: `pr create`, `pr comment`,
|
as Ben" attribution problem). Subcommands: `pr create`, `pr comment`,
|
||||||
`pr edit`, `issue create`, `issue comment`, `issue edit`, `issue close`,
|
`pr edit`, `issue create`, `issue comment`, `issue edit`, `issue close`,
|
||||||
`issue reopen`, `whoami`.
|
`issue reopen`, `whoami`.
|
||||||
- **`watchpr`** — poll one or more PRs and exit when a tracked PR changes
|
- **`watchpr`** — poll one or more Gitea or GitHub PRs and exit when a tracked PR changes
|
||||||
meaningfully: it merges/closes, gets a new non-agent comment, its CI fails,
|
meaningfully: it merges/closes, gets a new non-agent comment, its CI fails,
|
||||||
or it loses mergeability. Benign transitions (CI pending→success, the agent's
|
or it loses mergeability. Benign transitions (CI pending→success, the agent's
|
||||||
own comments) are ignored.
|
own comments) are ignored.
|
||||||
@@ -29,7 +29,7 @@ like repospawner can run these tools as itself.
|
|||||||
Vault, so it does not touch `internal/agent`.
|
Vault, so it does not touch `internal/agent`.
|
||||||
- **`agentgh`** — `gh`/git against GitHub as an iuclabs GitHub App (`--app
|
- **`agentgh`** — `gh`/git against GitHub as an iuclabs GitHub App (`--app
|
||||||
coder|reviewer`), via an installation token minted from Vault-held app creds.
|
coder|reviewer`), via an installation token minted from Vault-held app creds.
|
||||||
Subcommands: `token`, `credential`, `whoami`, `gh`.
|
Subcommands: `token`, `credential`, `whoami`, `gh`, `clone`, `setup`.
|
||||||
|
|
||||||
All tools are separate `main` packages under `cmd/` and share the
|
All tools are separate `main` packages under `cmd/` and share the
|
||||||
`internal/agent` package (Vault AppRole login, Gitea REST client, PR-ref
|
`internal/agent` package (Vault AppRole login, Gitea REST client, PR-ref
|
||||||
@@ -39,13 +39,13 @@ parsing, watch-state comparison, git worktree helpers).
|
|||||||
|
|
||||||
```
|
```
|
||||||
cmd/agentpr/main.go # agentpr CLI (pr + issue create/comment/edit, issue close/reopen, whoami)
|
cmd/agentpr/main.go # agentpr CLI (pr + issue create/comment/edit, issue close/reopen, whoami)
|
||||||
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
|
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit; routes refs to Gitea/GitHub)
|
||||||
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
||||||
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
||||||
cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
|
cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
|
||||||
cmd/agentreview/main.go # agentreview serve (webhook HMAC, event filter, semaphore + per-PR dedupe)
|
cmd/agentreview/main.go # agentreview serve (webhook HMAC, event filter, semaphore + per-PR dedupe)
|
||||||
cmd/agentreview/review.go # review flow (diff, shallow clone, claude argv/env, post review)
|
cmd/agentreview/review.go # review flow (diff, shallow clone, claude argv/env, post review)
|
||||||
cmd/agentgh/main.go # agentgh CLI (token / credential / whoami / gh, persistent --app)
|
cmd/agentgh/main.go # agentgh CLI (token / credential / whoami / gh / clone / setup, persistent --app)
|
||||||
internal/agent/ # shared plumbing:
|
internal/agent/ # shared plumbing:
|
||||||
token.go # env config + in-process Gitea-token cache
|
token.go # env config + in-process Gitea-token cache
|
||||||
vault.go # AppRole login + read the gitea creds path
|
vault.go # AppRole login + read the gitea creds path
|
||||||
@@ -58,6 +58,7 @@ internal/agent/ # shared plumbing:
|
|||||||
seedoutpost.go # seed-outpost flow (Authentik token -> Vault KV)
|
seedoutpost.go # seed-outpost flow (Authentik token -> Vault KV)
|
||||||
seedoauth.go # seed-oauth flow (oauth2-proxy credential set in Vault KV)
|
seedoauth.go # seed-oauth flow (oauth2-proxy credential set in Vault KV)
|
||||||
github.go # GitHub App: KV creds, RS256 JWT (stdlib), installation token, bot identity
|
github.go # GitHub App: KV creds, RS256 JWT (stdlib), installation token, bot identity
|
||||||
|
githubpr.go # GitHub PR state for watchpr (status + check-runs merge, comment filter)
|
||||||
go.mod # module git.unkin.net/unkin/agent-tools
|
go.mod # module git.unkin.net/unkin/agent-tools
|
||||||
Makefile # build / test / lint / completions / rpm / version-bump
|
Makefile # build / test / lint / completions / rpm / version-bump
|
||||||
packaging/nfpm.yaml # nfpm spec (envsubst-templated) for the RPM (all binaries)
|
packaging/nfpm.yaml # nfpm spec (envsubst-templated) for the RPM (all binaries)
|
||||||
@@ -94,7 +95,8 @@ Config via env (all have defaults):
|
|||||||
| `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) |
|
| `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) |
|
||||||
| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as (`coder`/`reviewer`; `--app` wins) |
|
| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as (`coder`/`reviewer`; `--app` wins) |
|
||||||
| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/<app>` | KV-v2 path (mount first) of the app creds |
|
| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/<app>` | KV-v2 path (mount first) of the app creds |
|
||||||
| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base for `agentgh` (https, or http on loopback) |
|
| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base for `agentgh`/`watchpr` (https, or http on loopback) |
|
||||||
|
| `GITHUB_AGENT_LOGINS` | the four iuclabs/actions/dependabot bots | comma-separated GitHub logins whose activity watchpr ignores |
|
||||||
|
|
||||||
### agentws git auth (ephemeral credential helper)
|
### agentws git auth (ephemeral credential helper)
|
||||||
|
|
||||||
@@ -203,6 +205,14 @@ from `GET /users/<slug>[bot]` (installation token). `agentgh gh` runs `gh` via
|
|||||||
`os/exec` with `GH_TOKEN` and `GH_HOST=github.com` set in the child env (other
|
`os/exec` with `GH_TOKEN` and `GH_HOST=github.com` set in the child env (other
|
||||||
GitHub token/host vars stripped), and propagates its exit code (128+signal); `DisableFlagParsing` plus
|
GitHub token/host vars stripped), and propagates its exit code (128+signal); `DisableFlagParsing` plus
|
||||||
`TraverseChildren` lets `--app` precede `gh` while gh's flags pass untouched.
|
`TraverseChildren` lets `--app` precede `gh` while gh's flags pass untouched.
|
||||||
|
`setup`/`clone` write repo-local config only (after `rev-parse --git-dir`): an
|
||||||
|
explicit pushurl, an identity `url.<origin>.insteadOf <origin>` rule (git uses
|
||||||
|
the longest matching prefix, so it beats any inherited `insteadOf`/`pushInsteadOf`
|
||||||
|
for github.com), an empty `credential.https://github.com.helper` reset followed by
|
||||||
|
`!agentgh --app '<app>' credential` (helpers run in config-file order and the empty
|
||||||
|
value clears the whole inherited list; the bare name is used when PATH resolves
|
||||||
|
to the running binary, else its shell-quoted absolute path), and the bot identity
|
||||||
|
from `Identity()`. `clone` passes the same reset and rewrite via `-c`.
|
||||||
|
|
||||||
## Gotchas
|
## Gotchas
|
||||||
|
|
||||||
@@ -299,6 +309,16 @@ GitHub token/host vars stripped), and propagates its exit code (128+signal); `Di
|
|||||||
a merge to the base branch moves `base.sha` under every open PR — but that
|
a merge to the base branch moves `base.sha` under every open PR — but that
|
||||||
move only arms; the two minutes it then has to outlast are the recompute the
|
move only arms; the two minutes it then has to outlast are the recompute the
|
||||||
move started, not the falses before it.
|
move started, not the falses before it.
|
||||||
|
- GitHub refs (`github:owner/repo#N`, `https://github.com/owner/repo/pull/N`)
|
||||||
|
carry `PRRef.Forge`; `ParseWatchRef` accepts them, `ParsePRRef` does not, so
|
||||||
|
Gitea-only tools never see one. watchpr builds a client only for the forges its
|
||||||
|
refs name, polls GitHub as the `reviewer` app (anonymous on a failed mint), and
|
||||||
|
re-mints the installation token within 5m of `expires_at` and on a rejected
|
||||||
|
credential (401, or a 403 naming the token).
|
||||||
|
GitHub's `mergeable` is null while computing (→ unknown), so the Gitea
|
||||||
|
debounce applies unchanged. A rate-limited 403/429 pauses until
|
||||||
|
Retry-After/X-RateLimit-Reset, capped at 15m, never counts towards the failure
|
||||||
|
limit, and is never an `APIError`, so it cannot end a watch as an auth failure.
|
||||||
- CI "combined status" comes from `/commits/{sha}/status`; an empty head SHA
|
- CI "combined status" comes from `/commits/{sha}/status`; an empty head SHA
|
||||||
yields an empty state without an API call.
|
yields an empty state without an API call.
|
||||||
- Gitea backs every PR with an issue of the same number and serves comments from
|
- Gitea backs every PR with an issue of the same number and serves comments from
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ different agent identity.
|
|||||||
|
|
||||||
- **`agentpr`** — create and edit pull requests and issues, close and reopen
|
- **`agentpr`** — create and edit pull requests and issues, close and reopen
|
||||||
issues, and post comments on either, as the agent user.
|
issues, and post comments on either, as the agent user.
|
||||||
- **`watchpr`** — poll one or more PRs and exit when one changes in a way worth
|
- **`watchpr`** — poll one or more Gitea or GitHub PRs and exit when one
|
||||||
acting on.
|
changes in a way worth acting on.
|
||||||
- **`agentws`** — manage per-branch git worktrees for `unkin-agent`, cloning
|
- **`agentws`** — manage per-branch git worktrees for `unkin-agent`, cloning
|
||||||
into Ben's source checkout and isolating agent work under the XDG cache.
|
into Ben's source checkout and isolating agent work under the XDG cache.
|
||||||
- **`agentvault`** — run deterministic Vault flows in one invocation, so agents
|
- **`agentvault`** — run deterministic Vault flows in one invocation, so agents
|
||||||
@@ -41,7 +41,8 @@ Everything is configured by environment variables, all with defaults:
|
|||||||
| `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) |
|
| `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) |
|
||||||
| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as: `coder` or `reviewer` (`--app` wins) |
|
| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as: `coder` or `reviewer` (`--app` wins) |
|
||||||
| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/<app>` | KV-v2 path of the app creds (wins over the app name) |
|
| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/<app>` | KV-v2 path of the app creds (wins over the app name) |
|
||||||
| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base (`agentgh`; https only) |
|
| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base (`agentgh`, `watchpr`; https only) |
|
||||||
|
| `GITHUB_AGENT_LOGINS` | `iuclabs-coder[bot],iuclabs-reviewer[bot],github-actions[bot],dependabot[bot]` | comma-separated GitHub logins whose comments and reviews `watchpr` ignores |
|
||||||
|
|
||||||
## agentpr
|
## agentpr
|
||||||
|
|
||||||
@@ -142,8 +143,33 @@ watchpr --once --json unkin/argocd-apps#42
|
|||||||
|
|
||||||
# Orchestrators: run inside a background command (2h hard cap) and restart on exit 3
|
# Orchestrators: run inside a background command (2h hard cap) and restart on exit 3
|
||||||
watchpr --max-wait 110m unkin/argocd-apps#42
|
watchpr --max-wait 110m unkin/argocd-apps#42
|
||||||
|
|
||||||
|
# GitHub PRs, mixed freely with Gitea ones
|
||||||
|
watchpr unkin/argocd-apps#42 github:IUCLabs/app#7 https://github.com/IUCLabs/app/pull/8
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### GitHub refs
|
||||||
|
|
||||||
|
`github:owner/repo#N`, `github:owner/repo:N` and
|
||||||
|
`https://github.com/owner/repo/pull/N` name a GitHub PR; unprefixed refs stay
|
||||||
|
Gitea. GitHub is polled as the `reviewer` app (the same Vault creds as
|
||||||
|
`agentgh`); its installation token is re-minted before it expires and again if
|
||||||
|
GitHub rejects it. If no token can be minted, `watchpr` warns and polls
|
||||||
|
anonymously, which works for public repos only: GitHub hides a private repo
|
||||||
|
behind a 404 (reported as `PR no longer visible`), and the anonymous limit is
|
||||||
|
60 requests/hour. A poll costs 6 requests per PR (more for lists past 100
|
||||||
|
entries), CI included. When GitHub rate-limits, `watchpr` warns
|
||||||
|
and pauses that PR (or the baseline) until the `Retry-After` /
|
||||||
|
`X-RateLimit-Reset` time, capped at 15m; the pause never counts towards the
|
||||||
|
consecutive-failure limit. CI combines the commit status
|
||||||
|
API with the check-runs API, and any failing status or check run (`failure`,
|
||||||
|
`timed_out`, `cancelled`, `action_required`, `startup_failure`) counts as a
|
||||||
|
failure. Issue comments, review comments and reviews (including changes
|
||||||
|
requested) all count as comments, except those from `GITHUB_AGENT_LOGINS`.
|
||||||
|
GitHub reports `mergeable: null` while it computes mergeability; that reads as
|
||||||
|
unknown, and `mergeable_state` is shown alongside. Alerts, exits, `--once`,
|
||||||
|
`--json` and `--max-wait` behave exactly as for Gitea.
|
||||||
|
|
||||||
On a meaningful change `watchpr` prints the reason and the PR's current state,
|
On a meaningful change `watchpr` prints the reason and the PR's current state,
|
||||||
then exits 0. Use `--json` for machine-readable output.
|
then exits 0. Use `--json` for machine-readable output.
|
||||||
|
|
||||||
@@ -156,7 +182,7 @@ safe to restart.
|
|||||||
### Exit behaviour
|
### Exit behaviour
|
||||||
|
|
||||||
A watcher that sees nothing must not look healthy, so every terminal failure
|
A watcher that sees nothing must not look healthy, so every terminal failure
|
||||||
exits non-zero naming its cause:
|
exits non-zero naming its cause. Messages name the forge that failed (`gitea` or `github`).
|
||||||
|
|
||||||
| Cause | Message |
|
| Cause | Message |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -169,8 +195,9 @@ Gitea tokens expire in ~1h, far shorter than a watch, so a rejected token is
|
|||||||
re-minted once and the request replayed; only a failure that survives that
|
re-minted once and the request replayed; only a failure that survives that
|
||||||
re-mint ends the watch. Anonymous polling of a public repo is unaffected — with
|
re-mint ends the watch. Anonymous polling of a public repo is unaffected — with
|
||||||
no token there is nothing to reject and Vault is never reached for one.
|
no token there is nothing to reject and Vault is never reached for one.
|
||||||
Transient failures (5xx, network errors, rate limiting) are warned about and
|
Transient failures (5xx, network errors) are warned about and retried, and
|
||||||
retried, and give up after 20 consecutive failures of the same PR.
|
give up after 20 consecutive failures of the same PR. GitHub rate limits pause
|
||||||
|
instead (see GitHub refs) and never count towards that limit.
|
||||||
|
|
||||||
## agentws
|
## agentws
|
||||||
|
|
||||||
@@ -449,10 +476,18 @@ agentgh token # print a fresh installation token
|
|||||||
agentgh gh pr list --repo iuclabs/x # run gh with GH_TOKEN set in its env only
|
agentgh gh pr list --repo iuclabs/x # run gh with GH_TOKEN set in its env only
|
||||||
agentgh --app reviewer gh pr view 1 # act as iuclabs-reviewer (or AGENTGH_APP=reviewer)
|
agentgh --app reviewer gh pr view 1 # act as iuclabs-reviewer (or AGENTGH_APP=reviewer)
|
||||||
|
|
||||||
# git over https as the app
|
agentgh clone iuclabs/x [dir] [--branch b] # clone over https, then setup
|
||||||
git config credential.https://github.com.helper '!agentgh credential'
|
agentgh setup [dir] # make an existing https clone push as the app
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`setup` (and `clone`) pin `remote.origin.pushurl` to the https origin URL so a
|
||||||
|
global `pushInsteadOf` cannot rewrite pushes to SSH, reset the inherited
|
||||||
|
`credential.https://github.com.helper` chain (e.g. `gh auth git-credential`) to
|
||||||
|
just `agentgh --app <app> credential`, and set `user.name`/`user.email` to the
|
||||||
|
app bot's noreply identity. All writes go to the repo's local config. Check with
|
||||||
|
`printf 'protocol=https\nhost=github.com\n\n' | git credential fill`
|
||||||
|
(`username=x-access-token`).
|
||||||
|
|
||||||
`--app` (`coder`|`reviewer`, env `AGENTGH_APP`, default `coder`) selects the app
|
`--app` (`coder`|`reviewer`, env `AGENTGH_APP`, default `coder`) selects the app
|
||||||
for every subcommand; `AGENTGH_KV_PATH` overrides the KV path outright.
|
for every subcommand; `AGENTGH_KV_PATH` overrides the KV path outright.
|
||||||
`credential get` answers only for `https://github.com` (`username=x-access-token`);
|
`credential get` answers only for `https://github.com` (`username=x-access-token`);
|
||||||
|
|||||||
+143
-1
@@ -6,6 +6,8 @@
|
|||||||
// agentgh credential get # git credential helper for github.com
|
// agentgh credential get # git credential helper for github.com
|
||||||
// agentgh whoami # bot login + commit email
|
// agentgh whoami # bot login + commit email
|
||||||
// agentgh gh <args...> # run gh with GH_TOKEN set
|
// agentgh gh <args...> # run gh with GH_TOKEN set
|
||||||
|
// agentgh clone <owner/repo> [dir] # clone + setup
|
||||||
|
// agentgh setup [dir] # make an existing clone push as the app
|
||||||
// agentgh --app reviewer <cmd> # act as another app (env AGENTGH_APP)
|
// agentgh --app reviewer <cmd> # act as another app (env AGENTGH_APP)
|
||||||
package main
|
package main
|
||||||
|
|
||||||
@@ -64,10 +66,32 @@ func newRootCmd() *cobra.Command {
|
|||||||
root.SetVersionTemplate("{{.Version}}\n")
|
root.SetVersionTemplate("{{.Version}}\n")
|
||||||
root.PersistentFlags().StringVar(&app, "app", defaultApp(), "GitHub App to act as: "+strings.Join(agent.GitHubApps, "|")+" (env AGENTGH_APP)")
|
root.PersistentFlags().StringVar(&app, "app", defaultApp(), "GitHub App to act as: "+strings.Join(agent.GitHubApps, "|")+" (env AGENTGH_APP)")
|
||||||
load := func() (*agent.GitHubApp, error) { return agent.GitHubAppFor(app) }
|
load := func() (*agent.GitHubApp, error) { return agent.GitHubAppFor(app) }
|
||||||
root.AddCommand(newTokenCmd(load), newCredentialCmd(load), newWhoamiCmd(load), newGHCmd(load), newVersionCmd())
|
helper := func() (string, error) { return credentialHelper(app) }
|
||||||
|
root.AddCommand(newTokenCmd(load), newCredentialCmd(load), newWhoamiCmd(load), newGHCmd(load),
|
||||||
|
newCloneCmd(load, helper), newSetupCmd(load, helper), newVersionCmd())
|
||||||
return root
|
return root
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// credentialHelper bakes the bare name when PATH resolves to this binary, so a
|
||||||
|
// temp or versioned executable path never lands in .git/config.
|
||||||
|
func credentialHelper(app string) (string, error) {
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
bin := shellQuote(exe)
|
||||||
|
if p, err := exec.LookPath("agentgh"); err == nil {
|
||||||
|
a, errA := os.Stat(p)
|
||||||
|
b, errB := os.Stat(exe)
|
||||||
|
if errA == nil && errB == nil && os.SameFile(a, b) {
|
||||||
|
bin = "agentgh"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "!" + bin + " --app " + shellQuote(app) + " credential", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
|
||||||
|
|
||||||
type loader func() (*agent.GitHubApp, error)
|
type loader func() (*agent.GitHubApp, error)
|
||||||
|
|
||||||
func token(load loader) (string, error) {
|
func token(load loader) (string, error) {
|
||||||
@@ -203,6 +227,124 @@ func runGH(args []string, tok string, stdin io.Reader, stdout, stderr io.Writer)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const helperKey = "credential.https://" + githubHost + ".helper"
|
||||||
|
|
||||||
|
// gitAuth resets inherited github.com helpers (e.g. a global `gh auth
|
||||||
|
// git-credential`) so only helper answers.
|
||||||
|
func gitAuth(helper string) []string {
|
||||||
|
return []string{"-c", helperKey + "=", "-c", helperKey + "=" + helper}
|
||||||
|
}
|
||||||
|
|
||||||
|
// identityRewrite is the longest possible insteadOf match for u, so it beats any
|
||||||
|
// inherited insteadOf/pushInsteadOf prefix rule for github.com.
|
||||||
|
func identityRewrite(u string) (key, val string) { return "url." + u + ".insteadOf", u }
|
||||||
|
|
||||||
|
// configure pins origin's pushurl and fetch/push URLs, replaces the inherited
|
||||||
|
// helper chain with helper and sets the commit identity.
|
||||||
|
func configure(dir, helper, name, email string) error {
|
||||||
|
if _, err := agent.Git(dir, "rev-parse", "--git-dir"); err != nil {
|
||||||
|
return fmt.Errorf("%s is not a git repository: %w", dir, err)
|
||||||
|
}
|
||||||
|
u, err := agent.Git(dir, "config", "--get", "remote.origin.url")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(u, "https://"+githubHost+"/") {
|
||||||
|
return fmt.Errorf("origin %q is not an https://%s/ URL", u, githubHost)
|
||||||
|
}
|
||||||
|
rk, rv := identityRewrite(u)
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"remote", "set-url", "--push", "origin", u},
|
||||||
|
{"config", "--local", rk, rv},
|
||||||
|
{"config", "--local", "--replace-all", helperKey, ""},
|
||||||
|
{"config", "--local", "--add", helperKey, helper},
|
||||||
|
{"config", "--local", "user.name", name},
|
||||||
|
{"config", "--local", "user.email", email},
|
||||||
|
} {
|
||||||
|
if _, err := agent.Git(dir, args...); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type helperFunc func() (string, error)
|
||||||
|
|
||||||
|
func identityAndHelper(load loader, helper helperFunc) (name, email, h string, err error) {
|
||||||
|
if h, err = helper(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a, err := load()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name, email, err = a.Identity()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSetupCmd(load loader, helper helperFunc) *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "setup [dir]",
|
||||||
|
Short: "Make an existing github.com clone push as the app",
|
||||||
|
Args: cobra.MaximumNArgs(1),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
dir := "."
|
||||||
|
if len(args) == 1 {
|
||||||
|
dir = args[0]
|
||||||
|
}
|
||||||
|
name, email, h, err := identityAndHelper(load, helper)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := configure(dir, h, name, email); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: pushing as %s\n", dir, name)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCloneCmd(load loader, helper helperFunc) *cobra.Command {
|
||||||
|
var branch string
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "clone <owner/repo> [dir]",
|
||||||
|
Short: "Clone a github.com repo over https and set it up to push as the app",
|
||||||
|
Args: cobra.RangeArgs(1, 2),
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
owner, repo, err := agent.ParseRepo(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dir := repo
|
||||||
|
if len(args) == 2 {
|
||||||
|
dir = args[1]
|
||||||
|
}
|
||||||
|
name, email, h, err := identityAndHelper(load, helper)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
u := "https://" + githubHost + "/" + owner + "/" + repo + ".git"
|
||||||
|
rk, rv := identityRewrite(u)
|
||||||
|
gitArgs := append(gitAuth(h), "-c", rk+"="+rv, "clone")
|
||||||
|
if branch != "" {
|
||||||
|
gitArgs = append(gitArgs, "--branch", branch)
|
||||||
|
}
|
||||||
|
gitArgs = append(gitArgs, "--", u, dir)
|
||||||
|
if _, err := agent.Git("", gitArgs...); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := configure(dir, h, name, email); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: pushing as %s\n", dir, name)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cmd.Flags().StringVar(&branch, "branch", "", "branch to check out")
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
func newVersionCmd() *cobra.Command {
|
func newVersionCmd() *cobra.Command {
|
||||||
return &cobra.Command{
|
return &cobra.Command{
|
||||||
Use: "version",
|
Use: "version",
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -79,6 +80,14 @@ func fakeStack(t *testing.T) {
|
|||||||
}}})
|
}}})
|
||||||
}))
|
}))
|
||||||
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch {
|
||||||
|
case r.URL.Path == "/app":
|
||||||
|
_, _ = w.Write([]byte(`{"slug":"iuclabs-coder"}`))
|
||||||
|
return
|
||||||
|
case strings.HasPrefix(r.URL.Path, "/users/"):
|
||||||
|
_, _ = w.Write([]byte(`{"id":42}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
inst := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/app/installations/"), "/access_tokens")
|
inst := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/app/installations/"), "/access_tokens")
|
||||||
w.WriteHeader(http.StatusCreated)
|
w.WriteHeader(http.StatusCreated)
|
||||||
_, _ = w.Write([]byte(`{"token":"ghs_inst` + inst + `"}`))
|
_, _ = w.Write([]byte(`{"token":"ghs_inst` + inst + `"}`))
|
||||||
@@ -172,3 +181,127 @@ func TestRunGHSignalExitCode(t *testing.T) {
|
|||||||
t.Errorf("err = %v, want exit code 143", err)
|
t.Errorf("err = %v, want exit code 143", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func git(t *testing.T, dir string, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
out, err := agent.Git(dir, args...)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// hijackedGlobal points git at a global config carrying the ways a user's
|
||||||
|
// config steals github.com pushes: SSH pushInsteadOf and a URL-scoped helper.
|
||||||
|
func hijackedGlobal(t *testing.T, extra string) {
|
||||||
|
t.Helper()
|
||||||
|
cfg := filepath.Join(t.TempDir(), "gitconfig")
|
||||||
|
body := "[url \"git@github.com:\"]\n\tpushInsteadOf = https://github.com/\n" +
|
||||||
|
"[credential \"https://github.com\"]\n\thelper = \"!f() { echo username=neoloc; echo password=hijack; }; f\"\n" +
|
||||||
|
"[credential]\n\thelper = \"!f() { echo username=generic; echo password=hijack; }; f\"\n" + extra
|
||||||
|
if err := os.WriteFile(cfg, []byte(body), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("GIT_CONFIG_GLOBAL", cfg)
|
||||||
|
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureBeatsGlobalHijacks(t *testing.T) {
|
||||||
|
hijackedGlobal(t, "[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n")
|
||||||
|
dir := t.TempDir()
|
||||||
|
git(t, dir, "init", "-q")
|
||||||
|
git(t, dir, "remote", "add", "origin", "https://github.com/o/r.git")
|
||||||
|
if got := git(t, dir, "remote", "get-url", "origin"); got != "git@github.com:o/r.git" {
|
||||||
|
t.Fatalf("precondition: insteadOf not active, url %q", got)
|
||||||
|
}
|
||||||
|
helper := filepath.Join(t.TempDir(), "helper")
|
||||||
|
if err := os.WriteFile(helper, []byte("#!/bin/sh\necho username=x-access-token\necho password=app\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if err := configure(dir, helper, "iuclabs-coder[bot]", "42+iuclabs-coder[bot]@users.noreply.github.com"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{{"remote", "get-url", "origin"}, {"remote", "get-url", "--push", "origin"}} {
|
||||||
|
if got := git(t, dir, args...); got != "https://github.com/o/r.git" {
|
||||||
|
t.Errorf("%v = %q", args, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := exec.Command("git", "credential", "fill")
|
||||||
|
c.Dir = dir
|
||||||
|
c.Stdin = strings.NewReader("protocol=https\nhost=github.com\n\n")
|
||||||
|
out, err := c.Output()
|
||||||
|
if err != nil || !strings.Contains(string(out), "username=x-access-token\npassword=app\n") {
|
||||||
|
t.Errorf("credential fill = %q %v", out, err)
|
||||||
|
}
|
||||||
|
if got := git(t, dir, "config", "user.email"); got != "42+iuclabs-coder[bot]@users.noreply.github.com" {
|
||||||
|
t.Errorf("user.email = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureRejectsNonRepo(t *testing.T) {
|
||||||
|
hijackedGlobal(t, "")
|
||||||
|
t.Setenv("GIT_CEILING_DIRECTORIES", os.TempDir())
|
||||||
|
if err := configure(t.TempDir(), "h", "n", "e"); err == nil || !strings.Contains(err.Error(), "not a git repository") {
|
||||||
|
t.Errorf("err = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCredentialHelper(t *testing.T) {
|
||||||
|
exe, _ := os.Executable()
|
||||||
|
t.Setenv("PATH", t.TempDir())
|
||||||
|
if got, _ := credentialHelper("it's"); got != "!"+shellQuote(exe)+` --app 'it'\''s' credential` {
|
||||||
|
t.Errorf("off PATH: %q", got)
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.Symlink(exe, filepath.Join(dir, "agentgh")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", dir)
|
||||||
|
if got, _ := credentialHelper("coder"); got != "!agentgh --app 'coder' credential" {
|
||||||
|
t.Errorf("on PATH: %q", got)
|
||||||
|
}
|
||||||
|
out, err := exec.Command("/bin/sh", "-c", "printf %s "+shellQuote("a b'c\"$d")).Output()
|
||||||
|
if err != nil || string(out) != "a b'c\"$d" {
|
||||||
|
t.Errorf("shellQuote round-trip = %q %v", out, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureRejectsNonHTTPSOrigin(t *testing.T) {
|
||||||
|
hijackedGlobal(t, "")
|
||||||
|
dir := t.TempDir()
|
||||||
|
git(t, dir, "init", "-q")
|
||||||
|
git(t, dir, "remote", "add", "origin", "git@github.com:o/r.git")
|
||||||
|
if err := configure(dir, "h", "n", "e"); err == nil {
|
||||||
|
t.Error("ssh origin accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCloneCommand(t *testing.T) {
|
||||||
|
fakeStack(t)
|
||||||
|
src := t.TempDir()
|
||||||
|
git(t, src, "init", "-q", "-b", "main")
|
||||||
|
git(t, src, "-c", "user.name=x", "-c", "user.email=x@x", "commit", "-q", "--allow-empty", "-m", "init")
|
||||||
|
git(t, src, "branch", "feat")
|
||||||
|
hijackedGlobal(t, "[url \""+src+"\"]\n\tinsteadOf = https://github.com/o/r.git\n[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n")
|
||||||
|
dst := filepath.Join(t.TempDir(), "r")
|
||||||
|
out, err := run(t, "", "--app", "reviewer", "clone", "o/r", dst, "--branch", "feat")
|
||||||
|
if err != nil || !strings.Contains(out, "pushing as iuclabs-coder[bot]") {
|
||||||
|
t.Fatalf("clone: %q %v", out, err)
|
||||||
|
}
|
||||||
|
if got := git(t, dst, "rev-parse", "--abbrev-ref", "HEAD"); got != "feat" {
|
||||||
|
t.Errorf("branch = %q", got)
|
||||||
|
}
|
||||||
|
if got := git(t, dst, "config", "remote.origin.pushurl"); got != "https://github.com/o/r.git" {
|
||||||
|
t.Errorf("pushurl = %q", got)
|
||||||
|
}
|
||||||
|
exe, _ := os.Executable()
|
||||||
|
got := git(t, dst, "config", "--local", "--get-all", "--null", helperKey)
|
||||||
|
if got != "\x00!"+shellQuote(exe)+" --app 'reviewer' credential\x00" {
|
||||||
|
t.Errorf("helper chain = %q", got)
|
||||||
|
}
|
||||||
|
if _, err := run(t, "", "clone", "not-a-repo"); err == nil {
|
||||||
|
t.Error("bad repo accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+88
-15
@@ -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
|
// 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
|
// new comment from someone other than the agent, its CI fails, or it loses
|
||||||
// mergeability after the baseline. Benign transitions (CI pending→success, the
|
// mergeability after the baseline. Benign transitions (CI pending→success, the
|
||||||
@@ -16,6 +16,7 @@
|
|||||||
// minutes old.
|
// minutes old.
|
||||||
//
|
//
|
||||||
// watchpr owner/repo#12 owner/repo:15
|
// 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 --once --json owner/repo#12
|
||||||
// watchpr --interval 30s owner/repo#12
|
// watchpr --interval 30s owner/repo#12
|
||||||
// watchpr --interval 30 owner/repo#12
|
// watchpr --interval 30 owner/repo#12
|
||||||
@@ -69,12 +70,18 @@ func newRootCmd() *cobra.Command {
|
|||||||
var once, jsonMode bool
|
var once, jsonMode bool
|
||||||
|
|
||||||
root := &cobra.Command{
|
root := &cobra.Command{
|
||||||
Use: "watchpr [flags] owner/repo#N [owner/repo#N ...]",
|
Use: "watchpr [flags] REF [REF ...]",
|
||||||
Short: "Poll Gitea PRs and exit when one changes meaningfully.",
|
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" +
|
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" +
|
"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" +
|
"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" +
|
"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.",
|
"change (current states are printed), 1 on any error.",
|
||||||
Version: version,
|
Version: version,
|
||||||
@@ -97,13 +104,16 @@ func newRootCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
refs := make([]agent.PRRef, 0, len(args))
|
refs := make([]agent.PRRef, 0, len(args))
|
||||||
for _, a := range args {
|
for _, a := range args {
|
||||||
ref, err := agent.ParsePRRef(a)
|
ref, err := agent.ParseWatchRef(a)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
refs = append(refs, ref)
|
refs = append(refs, ref)
|
||||||
}
|
}
|
||||||
c := clientFor(jsonMode)
|
c, err := fetcherFor(refs, jsonMode)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if once {
|
if once {
|
||||||
return runOnce(c, refs, jsonMode)
|
return runOnce(c, refs, jsonMode)
|
||||||
}
|
}
|
||||||
@@ -131,6 +141,38 @@ func newRootCmd() *cobra.Command {
|
|||||||
return root
|
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,
|
// 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
|
// so an unavailable token is a warning, not a failure; a poll that is actually
|
||||||
// rejected re-mints then.
|
// rejected re-mints then.
|
||||||
@@ -143,6 +185,28 @@ func clientFor(jsonMode bool) *agent.GiteaClient {
|
|||||||
return agent.NewGiteaClient(token)
|
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
|
// 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,
|
// 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
|
// 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.
|
// 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()
|
login := agent.AgentLogin()
|
||||||
states := make([]agent.PRState, 0, len(refs))
|
states := make([]agent.PRState, 0, len(refs))
|
||||||
for _, ref := range refs {
|
for _, ref := range refs {
|
||||||
st, err := agent.FetchState(c, ref, login)
|
st, err := c.FetchState(ref, login)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return describeFailure(err)
|
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
|
// runWatch establishes a baseline then polls until a tracked PR changes
|
||||||
// meaningfully, at which point it reports the change and returns.
|
// 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()
|
login := agent.AgentLogin()
|
||||||
|
|
||||||
ticker := time.NewTicker(interval)
|
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
|
// outlived its Vault lease are three different problems and only the last is
|
||||||
// fixed by a fresh token.
|
// fixed by a fresh token.
|
||||||
func describeFailure(err error) error {
|
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 {
|
switch {
|
||||||
case agent.IsNoCredential(err):
|
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):
|
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):
|
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):
|
case agent.IsPRGone(err):
|
||||||
return fmt.Errorf("PR no longer visible (repo deleted, renamed, or made private), aborted: %w", 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 {
|
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",
|
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)
|
shortSHA(st.HeadSHA), shortSHA(st.BaseSHA), st.NonAgentComments)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,9 +420,9 @@ func suppressedAtBaseline(st agent.PRState) string {
|
|||||||
var conds []string
|
var conds []string
|
||||||
switch st.Mergeable {
|
switch st.Mergeable {
|
||||||
case agent.MergeNo:
|
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:
|
case agent.MergeUnknown:
|
||||||
conds = append(conds, "mergeability unknown (the conflict rule is disarmed until Gitea reports mergeable or the commits move)")
|
conds = append(conds, "mergeability unknown (the conflict rule is disarmed until the forge reports mergeable or the commits move)")
|
||||||
}
|
}
|
||||||
if st.CIStatus == "failure" || st.CIStatus == "error" {
|
if st.CIStatus == "failure" || st.CIStatus == "error" {
|
||||||
conds = append(conds, "CI already "+st.CIStatus)
|
conds = append(conds, "CI already "+st.CIStatus)
|
||||||
|
|||||||
@@ -404,3 +404,69 @@ func TestReportTimeout(t *testing.T) {
|
|||||||
t.Errorf("json output = %q (err %v)", buf.String(), err)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -53,6 +53,9 @@ func runGit(dir string, args ...string) (string, error) {
|
|||||||
return strings.TrimSpace(stdout.String()), nil
|
return strings.TrimSpace(stdout.String()), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Git runs git with args in dir and returns trimmed stdout.
|
||||||
|
func Git(dir string, args ...string) (string, error) { return runGit(dir, args...) }
|
||||||
|
|
||||||
// GitClone clones url into dir. Any globalArgs (e.g. "-c",
|
// GitClone clones url into dir. Any globalArgs (e.g. "-c",
|
||||||
// "credential.helper=...") are passed before the clone subcommand so auth can be
|
// "credential.helper=...") are passed before the clone subcommand so auth can be
|
||||||
// supplied without persisting it in the resulting checkout's config.
|
// supplied without persisting it in the resulting checkout's config.
|
||||||
|
|||||||
+12
-2
@@ -14,6 +14,8 @@ import (
|
|||||||
// so callers can react to specific failures (e.g. tolerate a 404 for a commit
|
// 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.
|
// whose branch was deleted after a merge) instead of parsing error strings.
|
||||||
type APIError struct {
|
type APIError struct {
|
||||||
|
// Service names the forge that answered; empty means Gitea.
|
||||||
|
Service string
|
||||||
Method string
|
Method string
|
||||||
Path string
|
Path string
|
||||||
StatusCode int
|
StatusCode int
|
||||||
@@ -21,7 +23,15 @@ type APIError struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (e *APIError) Error() string {
|
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
|
// 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.
|
// 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
|
// 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.
|
// 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.
|
// IsNoCredential reports whether err is an auth failure on an anonymous request.
|
||||||
func IsNoCredential(err error) bool {
|
func IsNoCredential(err error) bool {
|
||||||
|
|||||||
@@ -81,10 +81,15 @@ type GitHubApp struct {
|
|||||||
APIURL string
|
APIURL string
|
||||||
HTTP *http.Client
|
HTTP *http.Client
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
token string
|
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
|
// ParseRSAPrivateKey decodes a PEM RSA key in PKCS#1 or PKCS#8 form. Errors
|
||||||
// never include key material.
|
// never include key material.
|
||||||
func ParseRSAPrivateKey(pemData string) (*rsa.PrivateKey, error) {
|
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
|
// 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) {
|
func (a *GitHubApp) InstallationToken() (string, error) {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
if a.token != "" {
|
if a.token != "" && time.Now().Before(a.expires.Add(-tokenRefreshMargin)) {
|
||||||
return a.token, nil
|
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())
|
jwt, err := a.JWT(time.Now())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
var out struct {
|
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"
|
path := "/app/installations/" + url.PathEscape(a.InstallationID) + "/access_tokens"
|
||||||
if err := a.do(http.MethodPost, path, jwt, &out); err != nil {
|
if err := a.do(http.MethodPost, path, jwt, &out); err != nil {
|
||||||
@@ -176,7 +193,10 @@ func (a *GitHubApp) InstallationToken() (string, error) {
|
|||||||
if out.Token == "" {
|
if out.Token == "" {
|
||||||
return "", fmt.Errorf("github token mint for installation %s: no token in response", a.InstallationID)
|
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
|
return a.token, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,351 @@
|
|||||||
|
package agent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxRateLimitWait caps how long a watch pauses for one rate limit.
|
||||||
|
const maxRateLimitWait = 15 * time.Minute
|
||||||
|
|
||||||
|
// RateLimitError is a GitHub 403/429 rate limit, which clears at Reset.
|
||||||
|
type RateLimitError struct {
|
||||||
|
Path string
|
||||||
|
Status int
|
||||||
|
Reset time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *RateLimitError) Error() string {
|
||||||
|
return fmt.Sprintf("github GET %s: rate limited (HTTP %d) until %s", e.Path, e.Status, e.Reset.Format(time.RFC3339))
|
||||||
|
}
|
||||||
|
|
||||||
|
// rateLimitReset reads Retry-After (seconds), then X-RateLimit-Reset (epoch
|
||||||
|
// seconds), falling back to a minute from now.
|
||||||
|
func rateLimitReset(h http.Header, now time.Time) time.Time {
|
||||||
|
if s, err := strconv.Atoi(h.Get("Retry-After")); err == nil {
|
||||||
|
return now.Add(time.Duration(s) * time.Second)
|
||||||
|
}
|
||||||
|
if s, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil {
|
||||||
|
return time.Unix(s, 0)
|
||||||
|
}
|
||||||
|
return now.Add(time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitWait reports whether err is a rate limit and how long from now to
|
||||||
|
// wait it out, between a second and maxRateLimitWait.
|
||||||
|
func RateLimitWait(err error, now time.Time) (time.Duration, bool) {
|
||||||
|
var rl *RateLimitError
|
||||||
|
if !errors.As(err, &rl) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return min(max(rl.Reset.Sub(now), time.Second), maxRateLimitWait), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 &RateLimitError{Path: path, Status: resp.StatusCode, Reset: rateLimitReset(resp.Header, time.Now())}
|
||||||
|
}
|
||||||
|
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; a non-empty key names the
|
||||||
|
// field holding the list when each page is wrapped in an object.
|
||||||
|
func listAll[T any](c *GitHubClient, path, key string) ([]T, error) {
|
||||||
|
var all []T
|
||||||
|
for page := 1; ; page++ {
|
||||||
|
var items []T
|
||||||
|
pagePath := path + "?per_page=" + strconv.Itoa(githubPageSize) + "&page=" + strconv.Itoa(page)
|
||||||
|
if key == "" {
|
||||||
|
if err := c.do(pagePath, &items); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var wrapped map[string]json.RawMessage
|
||||||
|
if err := c.do(pagePath, &wrapped); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if raw, ok := wrapped[key]; ok {
|
||||||
|
if err := json.Unmarshal(raw, &items); err != nil {
|
||||||
|
return nil, fmt.Errorf("github GET %s: decoding %s: %w", pagePath, key, 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
|
||||||
|
}
|
||||||
|
checks, err := listAll[githubCheckRun](c, "/repos/"+repo+"/commits/"+sha+"/check-runs", "check_runs")
|
||||||
|
if err != nil {
|
||||||
|
if IsNotFound(err) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return mergeGitHubCI(status.State, status.TotalCount, checks), 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
|
||||||
|
}
|
||||||
@@ -0,0 +1,508 @@
|
|||||||
|
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()
|
||||||
|
slice := func(r *http.Request, items []string) 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))
|
||||||
|
return "[" + strings.Join(items[lo:hi], ",") + "]"
|
||||||
|
}
|
||||||
|
page := func(w http.ResponseWriter, r *http.Request, items []string) {
|
||||||
|
_, _ = w.Write([]byte(slice(r, items)))
|
||||||
|
}
|
||||||
|
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.Header().Set("Retry-After", "120")
|
||||||
|
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(`{"check_runs":` + slice(r, 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: []string{`{"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: []string{}}
|
||||||
|
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 d, ok := RateLimitWait(err, time.Now()); !ok || IsAuthError(err) || d < 110*time.Second || d > 120*time.Second {
|
||||||
|
t.Errorf("rate limit err = %v (wait %v), want a ~120s rate limit that is not an auth error", err, d)
|
||||||
|
}
|
||||||
|
|
||||||
|
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: []string{}, 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:
|
||||||
|
// The previous step's poll may already see the last step's state.
|
||||||
|
if i < len(steps)-1 || r.err != nil {
|
||||||
|
t.Fatalf("step %d: watch ended early: %+v, %v", i, r.res, r.err)
|
||||||
|
}
|
||||||
|
return r.res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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: []string{`{"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 = []string{`{"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 = []string{`{"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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRateLimitWait(t *testing.T) {
|
||||||
|
now := time.Unix(1_000_000, 0)
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
header http.Header
|
||||||
|
want time.Duration
|
||||||
|
}{
|
||||||
|
{"retry-after", http.Header{"Retry-After": {"30"}, "X-Ratelimit-Reset": {"1000600"}}, 30 * time.Second},
|
||||||
|
{"reset epoch", http.Header{"X-Ratelimit-Reset": {"1000600"}}, 10 * time.Minute},
|
||||||
|
{"capped", http.Header{"X-Ratelimit-Reset": {"1003600"}}, maxRateLimitWait},
|
||||||
|
{"already reset", http.Header{"X-Ratelimit-Reset": {"999000"}}, time.Second},
|
||||||
|
{"no header", http.Header{}, time.Minute},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
err := fmt.Errorf("wrapped: %w", &RateLimitError{Reset: rateLimitReset(tt.header, now)})
|
||||||
|
if d, ok := RateLimitWait(err, now); !ok || d != tt.want {
|
||||||
|
t.Errorf("%s: wait = %v, %v; want %v", tt.name, d, ok, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := RateLimitWait(errors.New("boom"), now); ok {
|
||||||
|
t.Error("a plain error is not a rate limit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A re-run that fails on the same head after reporting success still alerts.
|
||||||
|
func TestWatchGitHubSameHeadSuccessToFailureAlerts(t *testing.T) {
|
||||||
|
res := runGitHubWatch(t, pendingPR(),
|
||||||
|
func(f *fakeGitHubPR) {
|
||||||
|
f.status = `{"state":"success","total_count":1}`
|
||||||
|
f.checks = []string{`{"status":"completed","conclusion":"success"}`}
|
||||||
|
},
|
||||||
|
// Sending this step's tick proves the success poll has finished.
|
||||||
|
func(*fakeGitHubPR) {},
|
||||||
|
func(f *fakeGitHubPR) {
|
||||||
|
f.checks = []string{`{"status":"completed","conclusion":"success"}`, `{"status":"completed","conclusion":"failure"}`}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if res.Reason != "CI failed (failure)" {
|
||||||
|
t.Errorf("result = %+v, want the late failure to alert", res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A failing check run past the first page of 100 still fails CI.
|
||||||
|
func TestGitHubCheckRunsPaginated(t *testing.T) {
|
||||||
|
checks := make([]string, 0, 101)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
checks = append(checks, `{"status":"completed","conclusion":"success"}`)
|
||||||
|
}
|
||||||
|
checks = append(checks, `{"status":"completed","conclusion":"failure"}`)
|
||||||
|
f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: checks}
|
||||||
|
st, err := newFakeGitHubClient(f.serve(t)).FetchState(ghRef, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.CIStatus != "failure" {
|
||||||
|
t.Errorf("ci = %q, want failure from page 2", st.CIStatus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rate limit pauses the baseline and the polls until it resets and never
|
||||||
|
// counts towards MaxPollFailures.
|
||||||
|
func TestWatchGitHubRidesOutRateLimit(t *testing.T) {
|
||||||
|
f := pendingPR()
|
||||||
|
f.rateLimit = true
|
||||||
|
c := newFakeGitHubClient(f.serve(t))
|
||||||
|
ticks := make(chan time.Time)
|
||||||
|
baseline := make(chan struct{})
|
||||||
|
var warnings int
|
||||||
|
done := make(chan error, 1)
|
||||||
|
var res WatchResult
|
||||||
|
go func() {
|
||||||
|
var err error
|
||||||
|
res, err = Watch(c, []PRRef{ghRef}, "", ticks, func([]PRState) { close(baseline) }, func(PRRef, error) { warnings++ })
|
||||||
|
done <- err
|
||||||
|
}()
|
||||||
|
now := time.Now()
|
||||||
|
tick := func(d time.Duration) {
|
||||||
|
t.Helper()
|
||||||
|
now = now.Add(d)
|
||||||
|
select {
|
||||||
|
case ticks <- now:
|
||||||
|
case err := <-done:
|
||||||
|
t.Fatalf("watch ended early: %+v, %v", res, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tick(time.Minute)
|
||||||
|
f.set(func(f *fakeGitHubPR) { f.rateLimit = false })
|
||||||
|
tick(2 * time.Minute)
|
||||||
|
select {
|
||||||
|
case <-baseline:
|
||||||
|
case err := <-done:
|
||||||
|
t.Fatalf("watch ended at baseline: %+v, %v", res, err)
|
||||||
|
}
|
||||||
|
// Ticks run a day behind the fake's reset, so every pause is the 15m cap.
|
||||||
|
// The 1m tick inside each pause is skipped, and its send completing proves
|
||||||
|
// the previous poll is done before the fake changes.
|
||||||
|
now = now.Add(-24 * time.Hour)
|
||||||
|
f.set(func(f *fakeGitHubPR) { f.rateLimit = true })
|
||||||
|
for i := 0; i < 2*MaxPollFailures; i++ {
|
||||||
|
tick(15 * time.Minute)
|
||||||
|
tick(time.Minute)
|
||||||
|
}
|
||||||
|
f.set(func(f *fakeGitHubPR) {
|
||||||
|
f.rateLimit = false
|
||||||
|
f.pr = strings.Replace(f.pr, `"merged":false`, `"merged":true`, 1)
|
||||||
|
})
|
||||||
|
tick(15 * time.Minute)
|
||||||
|
close(ticks)
|
||||||
|
if err := <-done; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if res.Reason != "PR merged" {
|
||||||
|
t.Errorf("result = %+v, want merged", res)
|
||||||
|
}
|
||||||
|
if warnings != 1+2*MaxPollFailures {
|
||||||
|
t.Errorf("warnings = %d, want one per rate-limited fetch (%d)", warnings, 1+2*MaxPollFailures)
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
-2
@@ -9,14 +9,26 @@ import (
|
|||||||
|
|
||||||
// PRRef identifies a single pull request by repository and number.
|
// PRRef identifies a single pull request by repository and number.
|
||||||
type PRRef struct {
|
type PRRef struct {
|
||||||
|
// Forge is ForgeGitHub for a GitHub PR; empty means Gitea.
|
||||||
|
Forge string `json:",omitempty"`
|
||||||
Owner string
|
Owner string
|
||||||
Repo string
|
Repo string
|
||||||
Number int
|
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 {
|
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.
|
// RepoPath returns the "owner/repo" portion used in Gitea API URLs.
|
||||||
@@ -49,6 +61,33 @@ func ParsePRRef(s string) (PRRef, error) {
|
|||||||
return PRRef{Owner: owner, Repo: repo, Number: n}, nil
|
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", where a trailing path ("/files"),
|
||||||
|
// query or fragment on the URL is ignored.
|
||||||
|
func ParseWatchRef(s string) (PRRef, error) {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if rest, ok := strings.CutPrefix(s, githubPRURLPrefix); ok {
|
||||||
|
rest, _, _ = strings.Cut(rest, "#")
|
||||||
|
rest, _, _ = strings.Cut(rest, "?")
|
||||||
|
parts := strings.Split(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
|
// ParseDurationFlag parses a duration flag value, accepting either a Go
|
||||||
// duration string ("30s", "1h30m") or a bare integer read as seconds ("15").
|
// duration string ("30s", "1h30m") or a bare integer read as seconds ("15").
|
||||||
// flag names the flag so the error says which value was rejected.
|
// flag names the flag so the error says which value was rejected.
|
||||||
|
|||||||
@@ -181,3 +181,40 @@ 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}},
|
||||||
|
{"https://github.com/IUCLabs/app/pull/12/files", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
|
||||||
|
{"https://github.com/IUCLabs/app/pull/12#issuecomment-1", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
|
||||||
|
{"https://github.com/IUCLabs/app/pull/12?x=y", PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 12}},
|
||||||
|
{"https://github.com/IUCLabs/app/pull/12/files?w=1#diff-a/b", 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/x", "https://github.com/IUCLabs/app/pull/x/files", "https://github.com/IUCLabs/app/pull", "https://github.com/IUCLabs/app/pull?x=1", "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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+35
-2
@@ -72,7 +72,8 @@ type PRState struct {
|
|||||||
HeadSHA string `json:"head_sha"`
|
HeadSHA string `json:"head_sha"`
|
||||||
BaseSHA string `json:"base_sha"`
|
BaseSHA string `json:"base_sha"`
|
||||||
Mergeable Mergeability `json:"mergeable"`
|
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"`
|
NonAgentComments int `json:"non_agent_comments"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
@@ -276,15 +277,35 @@ const MaxPollFailures = 20
|
|||||||
// failure surviving a token re-mint, a 404 from the PR lookup itself (the repo
|
// failure surviving a token re-mint, a 404 from the PR lookup itself (the repo
|
||||||
// is gone, renamed, or no longer visible), and MaxPollFailures consecutive
|
// is gone, renamed, or no longer visible), and MaxPollFailures consecutive
|
||||||
// failures of one PR all abort, because a watcher that sees nothing must not
|
// failures of one PR all abort, because a watcher that sees nothing must not
|
||||||
// look healthy.
|
// look healthy. A GitHub rate limit is none of these: the baseline fetch or the
|
||||||
|
// PR's polls pause until it resets (see RateLimitWait), handing it to onError,
|
||||||
|
// and the pause never counts towards MaxPollFailures.
|
||||||
// onBaseline, if set, receives every captured baseline once, before the first
|
// onBaseline, if set, receives every captured baseline once, before the first
|
||||||
// tick, so a caller can show what state the watch started from.
|
// tick, so a caller can show what state the watch started from.
|
||||||
// A closed ticks channel ends the watch with a TimedOut result.
|
// A closed ticks channel ends the watch with a TimedOut result.
|
||||||
func Watch(f StateFetcher, refs []PRRef, agentLogin string, ticks <-chan time.Time, onBaseline func([]PRState), onError func(PRRef, error)) (WatchResult, error) {
|
func Watch(f StateFetcher, refs []PRRef, agentLogin string, ticks <-chan time.Time, onBaseline func([]PRState), onError func(PRRef, error)) (WatchResult, error) {
|
||||||
watches := make(map[string]*prWatch, len(refs))
|
watches := make(map[string]*prWatch, len(refs))
|
||||||
baselines := make([]PRState, 0, len(refs))
|
baselines := make([]PRState, 0, len(refs))
|
||||||
|
clock := time.Now()
|
||||||
for _, ref := range refs {
|
for _, ref := range refs {
|
||||||
st, err := f.FetchState(ref, agentLogin)
|
st, err := f.FetchState(ref, agentLogin)
|
||||||
|
for {
|
||||||
|
d, limited := RateLimitWait(err, clock)
|
||||||
|
if !limited {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if onError != nil {
|
||||||
|
onError(ref, err)
|
||||||
|
}
|
||||||
|
for until := clock.Add(d); clock.Before(until); {
|
||||||
|
t, ok := <-ticks
|
||||||
|
if !ok {
|
||||||
|
return WatchResult{TimedOut: true, States: baselines}, nil
|
||||||
|
}
|
||||||
|
clock = t
|
||||||
|
}
|
||||||
|
st, err = f.FetchState(ref, agentLogin)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return WatchResult{}, err
|
return WatchResult{}, err
|
||||||
}
|
}
|
||||||
@@ -299,13 +320,25 @@ func Watch(f StateFetcher, refs []PRRef, agentLogin string, ticks <-chan time.Ti
|
|||||||
}
|
}
|
||||||
latest := append([]PRState(nil), baselines...)
|
latest := append([]PRState(nil), baselines...)
|
||||||
fails := make(map[string]int, len(refs))
|
fails := make(map[string]int, len(refs))
|
||||||
|
pausedUntil := make(map[string]time.Time, len(refs))
|
||||||
// The tick carries the time it fired, which is the clock the conflict
|
// The tick carries the time it fired, which is the clock the conflict
|
||||||
// window is measured on.
|
// window is measured on.
|
||||||
for now := range ticks {
|
for now := range ticks {
|
||||||
for i, ref := range refs {
|
for i, ref := range refs {
|
||||||
key := ref.String()
|
key := ref.String()
|
||||||
|
if now.Before(pausedUntil[key]) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
cur, err := f.FetchState(ref, agentLogin)
|
cur, err := f.FetchState(ref, agentLogin)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if d, limited := RateLimitWait(err, now); limited {
|
||||||
|
pausedUntil[key] = now.Add(d)
|
||||||
|
watches[key].missed()
|
||||||
|
if onError != nil {
|
||||||
|
onError(ref, err)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
if IsAuthError(err) || IsPRGone(err) {
|
if IsAuthError(err) || IsPRGone(err) {
|
||||||
return WatchResult{}, fmt.Errorf("polling %s: %w", key, err)
|
return WatchResult{}, fmt.Errorf("polling %s: %w", key, err)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user