Documentation
¶
Overview ¶
Package ghclient is patchy's GitHub REST client: GitHub App and personal-access-token authentication, installation-scoped clients and short-lived scoped tokens, and a narrow, fake-able surface (IssueStore, AlertStore, RepoStore) over the handful of endpoints the controllers use. Consumers depend on the per-concern interfaces, never on go-github types, so tests fake them with a struct.
Every client shares a rate-limit-aware transport that waits out GitHub's advertised primary and secondary rate-limit delays before retrying, so callers never see a bare 403/429 that a short pause would have cured.
Index ¶
- Constants
- Variables
- func IsNotFound(err error) bool
- func RepoMatches(entries []string, repo Repo) bool
- func ValidateProxy(rawURL string) error
- type Alert
- type AlertStore
- type App
- func (a *App) Deliveries(ctx context.Context, visit func(Delivery) bool) (complete bool, err error)
- func (a *App) Installation(ctx context.Context, repo Repo) (*Client, error)
- func (a *App) InstallationAccounts(ctx context.Context) ([]InstallationAccount, error)
- func (a *App) Installations(ctx context.Context) ([]*Client, error)
- func (a *App) Redeliver(ctx context.Context, deliveryID int64) error
- func (a *App) ScopedToken(ctx context.Context, repo Repo, perms TokenPerms) (string, time.Time, error)
- type AppAlertEnumerator
- type AppConfig
- type BranchPush
- type Client
- func (c *Client) AddLabels(ctx context.Context, repo Repo, number int, add []string) error
- func (c *Client) Assign(ctx context.Context, repo Repo, number int, logins []string) error
- func (c *Client) Close(ctx context.Context, repo Repo, number int) error
- func (c *Client) Comment(ctx context.Context, repo Repo, number int, body string) error
- func (c *Client) Create(ctx context.Context, repo Repo, req IssueRequest) (*Issue, error)
- func (c *Client) CreatePR(ctx context.Context, repo Repo, req PRRequest) (*PR, error)
- func (c *Client) DefaultBranch(ctx context.Context, repo Repo) (string, error)
- func (c *Client) DeleteIssue(ctx context.Context, repo Repo, number int) error
- func (c *Client) DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
- func (c *Client) EditBody(ctx context.Context, repo Repo, number int, body string) error
- func (c *Client) EditComment(ctx context.Context, repo Repo, commentID int64, body string) error
- func (c *Client) FindPRByHead(ctx context.Context, repo Repo, branch string) (*PR, error)
- func (c *Client) GetAlert(ctx context.Context, repo Repo, number int) (*Alert, error)
- func (c *Client) GetIssue(ctx context.Context, repo Repo, number int) (*Issue, error)
- func (c *Client) HeadSHA(ctx context.Context, repo Repo, branch string) (string, error)
- func (c *Client) InstallationRepos(ctx context.Context) (repos []Repo, complete bool, err error)
- func (c *Client) ListComments(ctx context.Context, repo Repo, number int) ([]*Comment, error)
- func (c *Client) ListOpen(ctx context.Context, repo Repo, labels []string) ([]*Issue, error)
- func (c *Client) ListOrgAlerts(ctx context.Context, org string, yield func(Repo, *Alert) bool) (complete bool, err error)
- func (c *Client) ListRepoAlerts(ctx context.Context, repo Repo, yield func(*Alert) bool) (complete bool, err error)
- func (c *Client) OpenAlert(ctx context.Context, repo Repo, number int) error
- func (c *Client) PushBranch(ctx context.Context, repo Repo, req BranchPush) error
- func (c *Client) RemoveLabel(ctx context.Context, repo Repo, number int, name string) error
- func (c *Client) SearchIssues(ctx context.Context, query string) ([]*Issue, error)
- func (c *Client) Tarball(ctx context.Context, repo Repo, ref string) (io.ReadCloser, error)
- type Comment
- type CommitFile
- type Delivery
- type InstallationAccount
- type Issue
- type IssueRequest
- type IssueStore
- type Option
- type PATAlertEnumerator
- type PR
- type PRRequest
- type Repo
- type RepoStore
- type TokenPerms
Constants ¶
const DefaultMaxAlerts = 10000
DefaultMaxAlerts bounds one backfill enumeration (100 alerts per page, so ~100 API pages). An estate that exceeds it reports itself incomplete rather than paging through an unbounded alert inventory; the operator re-runs with a narrower repository prefix.
Variables ¶
ErrDeleteUnauthorized reports the credential cannot delete issues: GitHub restricts the deleteIssue mutation to admin-permission user tokens — App installation tokens and fine-grained PATs are always refused ("Viewer not authorized to delete"). Callers may fall back to closing the issue.
Functions ¶
func IsNotFound ¶ added in v0.4.0
IsNotFound reports whether err (anywhere in its chain) is a GitHub API 404 — the projected object no longer exists on the forge.
func RepoMatches ¶ added in v0.10.0
RepoMatches reports whether repo matches any filter entry: an entry is a prefix of "owner/name" — "owner/", "owner/name" (which also matches "owner/name-suffix"), or "owner/name-prefix-" — and a slash-less entry is normalized to an owner prefix, so "acme" cannot match "acmex/..". Matching is case-insensitive, as GitHub owner and repository names are. An empty filter matches everything.
func ValidateProxy ¶ added in v0.11.2
ValidateProxy checks rawURL is a usable proxy URL ("" is valid: no proxy).
Types ¶
type Alert ¶
type Alert struct {
Number int
RuleID string
RuleName string
RuleDescription string
RuleHelp string
Tags []string
Severity string
State string
HTMLURL string
Path string
StartLine int
EndLine int
Snippet string
MostRecentSHA string
}
Alert is patchy's view of a code-scanning alert: the rule, the severity (security_severity_level falling back to the rule severity), and the most recent instance's location, message snippet, and commit.
type AlertStore ¶
type AlertStore interface {
// GetAlert fetches one code-scanning alert.
GetAlert(ctx context.Context, repo Repo, number int) (*Alert, error)
// DismissAlert dismisses an alert; reason must be one of GitHub's
// "false positive", "won't fix", or "used in tests".
DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
}
AlertStore is the code-scanning surface.
type App ¶
type App struct {
// contains filtered or unexported fields
}
App mints installation-scoped clients and tokens for a GitHub App.
func (*App) Deliveries ¶ added in v0.5.4
Deliveries walks the App webhook's delivery log newest-first, calling visit for each attempt until visit returns false or the log is exhausted. complete is false when the page cap ended the walk instead.
func (*App) Installation ¶
Installation returns a Client authenticated as the installation covering repo. Both the repo → installation lookup and the per-installation client are cached, so repeated calls cost no API requests.
func (*App) InstallationAccounts ¶ added in v0.10.0
func (a *App) InstallationAccounts(ctx context.Context) ([]InstallationAccount, error)
InstallationAccounts returns one entry per installation of the App — the account-shaped fan-out for cross-estate walks like the alert backfill.
func (*App) Installations ¶
Installations returns one client per installation of the App — the fan-out for cross-repository sweeps like the reconcile searches.
type AppAlertEnumerator ¶ added in v0.10.0
type AppAlertEnumerator struct {
App *App
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
AppAlertEnumerator walks the open code-scanning alerts of every account the App is installed on, picking the walk whose cost matches the filter:
- an account none of the repos entries name is skipped outright;
- an account whose entries all carry a name segment ("owner/name", "owner/name-prefix-") is walked by enumerating its repository inventory and listing only matching repositories — cost scales with repository count, not the org's alert count;
- a bare "owner/" entry (or an empty filter) keeps the full walk: the single org-wide listing for an organization account, the installation-repository fan-out for a user account, which has no org-wide listing.
The per-repository filter here is also the caller's safety net in ghas; applying it at both levels keeps the enumerator free to choose the cheap walk without changing what comes out.
func (*AppAlertEnumerator) Enumerate ¶ added in v0.10.0
func (e *AppAlertEnumerator) Enumerate( ctx context.Context, repos []string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
Enumerate implements the backfill enumeration over the App's installations. complete is false when the alert budget, a repository page cap, or the caller's yield ended the walk before the estate was exhausted.
type AppConfig ¶
type AppConfig struct {
AppID int64
PrivateKey []byte // PEM-encoded RSA private key
BaseURL string // default https://api.github.com/ ; tests and GHES override
ProxyURL string // forward proxy for all the App's traffic; "" = environment
}
AppConfig configures GitHub App authentication.
type BranchPush ¶ added in v0.3.0
type BranchPush struct {
Branch string
BaseSHA string
Message string
Files []CommitFile
Deletes []string
}
BranchPush describes one commit to create on top of BaseSHA and the branch to point at it.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps the GitHub REST API with patchy's narrow, fake-able surface. Construct one with NewToken or App.Installation.
func NewToken ¶
NewToken returns a Client authenticated with a personal access token — the dev-mode fallback. baseURL "" means api.github.com.
func (*Client) DefaultBranch ¶
DefaultBranch returns the repository's default branch name.
func (*Client) DeleteIssue ¶ added in v0.5.7
DeleteIssue permanently deletes an issue. The REST API cannot delete issues at all — only the GraphQL deleteIssue mutation can, and it needs the issue's node ID, so this fetches the issue first. Deleting requires admin-level repository permission; it exists for the demo reset, which removes the tracking issues a replayed demo would otherwise duplicate. A missing issue is success: deletion is idempotent.
func (*Client) DismissAlert ¶
func (c *Client) DismissAlert(ctx context.Context, repo Repo, number int, reason, comment string) error
DismissAlert dismisses a code-scanning alert. reason must be one of GitHub's "false positive", "won't fix", or "used in tests".
func (*Client) EditComment ¶ added in v0.5.3
EditComment replaces the body of an existing issue comment.
func (*Client) FindPRByHead ¶ added in v0.4.0
FindPRByHead returns the open pull request whose head is branch, or nil — the idempotency check before creating a remediation PR (a crash between push and status write must not open a duplicate).
func (*Client) GetIssue ¶ added in v0.4.0
GetIssue fetches one issue — the projection reconciler's current-state read before diffing labels and body.
func (*Client) HeadSHA ¶ added in v0.3.0
HeadSHA resolves the current commit SHA of refs/heads/<branch>.
func (*Client) InstallationRepos ¶ added in v0.10.0
InstallationRepos lists the repositories the installation's token can see (GET /installation/repositories). complete is false when the page cap ended the walk before the inventory was exhausted.
func (*Client) ListComments ¶
ListComments returns every comment on the issue, following pagination.
func (*Client) ListOpen ¶
ListOpen returns every open issue in repo carrying all of labels, following pagination. Pull requests (which the issues API also returns) are skipped.
func (*Client) ListOrgAlerts ¶ added in v0.10.0
func (c *Client) ListOrgAlerts( ctx context.Context, org string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
ListOrgAlerts walks the organization's open code-scanning alerts, calling yield with each alert and the repository it was raised in, until yield returns false or the listing is exhausted. complete is false when yield ended the walk early.
func (*Client) ListRepoAlerts ¶ added in v0.10.0
func (c *Client) ListRepoAlerts( ctx context.Context, repo Repo, yield func(*Alert) bool, ) (complete bool, err error)
ListRepoAlerts walks one repository's open code-scanning alerts, calling yield until it returns false or the listing is exhausted. complete is false when yield ended the walk early.
func (*Client) OpenAlert ¶ added in v0.5.7
OpenAlert reopens a code-scanning alert (undoes a dismissal). Only a dismissed alert can be reopened, so the current state is read first and anything else is success: an alert that is already open, fixed, or gone with the repository that held it has no dismissal left to undo. Reopening is therefore convergent rather than authoritative — the retried cleanup of a repository that was deleted or recreated since the dismissal still succeeds. GitHub rejects every illegal transition with the same opaque 400 ("There was an issue creating the request. Please try again."), which is why the state is read rather than sniffed out of the error.
func (*Client) PushBranch ¶ added in v0.3.0
PushBranch creates one commit on top of req.BaseSHA carrying req's file changes and points refs/heads/<Branch> at it, force-updating an existing branch so a retried event re-applies cleanly. It is the git-less push: blob → tree → commit → ref through the Git Data API.
func (*Client) RemoveLabel ¶
RemoveLabel removes one label from the issue. A 404 — the label is already absent — is not an error, so removals are idempotent.
func (*Client) SearchIssues ¶
SearchIssues runs an issue search query and returns every matching issue, following pagination.
type CommitFile ¶ added in v0.3.0
type CommitFile struct {
Path string
// Mode is the git file mode: "100644", "100755", or "120000".
Mode string
// Content is the raw blob; for a symlink ("120000"), the link target.
Content []byte
}
CommitFile is one file created or modified by a BranchPush.
type Delivery ¶ added in v0.5.4
type Delivery struct {
ID int64
GUID string
DeliveredAt time.Time
// Redelivery marks a redelivered attempt.
Redelivery bool
// OK reports whether the receiver answered 2xx.
OK bool
Event string
}
Delivery is one attempt from the App webhook's delivery log. Attempts of the same logical delivery (the original and its redeliveries) share a GUID.
type InstallationAccount ¶ added in v0.10.0
type InstallationAccount struct {
// Client is authenticated as the installation.
Client *Client
// Account is the org or user login the App is installed on.
Account string
// Org reports an organization account; false is a user account, which
// has no org-wide listings.
Org bool
}
InstallationAccount is one account the App is installed on, with a client authenticated as that installation.
type Issue ¶
type Issue struct {
// Repo is the issue's repository, populated from the list/search
// response so cross-repository sweeps can act on their results.
Repo Repo
Number int
Title string
Body string
State string
Labels []string
Assignees []string
CreatedAt time.Time
}
Issue is patchy's thin view of a GitHub issue, decoupled from go-github.
type IssueRequest ¶
IssueRequest is the payload for creating an issue.
type IssueStore ¶
type IssueStore interface {
// ListOpen returns every open issue in repo carrying all of labels.
ListOpen(ctx context.Context, repo Repo, labels []string) ([]*Issue, error)
// Create opens a new issue.
Create(ctx context.Context, repo Repo, req IssueRequest) (*Issue, error)
// Comment adds a comment to the issue.
Comment(ctx context.Context, repo Repo, number int, body string) error
// ListComments returns every comment on the issue, oldest first.
ListComments(ctx context.Context, repo Repo, number int) ([]*Comment, error)
// EditBody replaces the issue body.
EditBody(ctx context.Context, repo Repo, number int, body string) error
// AddLabels adds labels to the issue, creating them as needed.
AddLabels(ctx context.Context, repo Repo, number int, add []string) error
// RemoveLabel removes one label; a label already absent is not an error.
RemoveLabel(ctx context.Context, repo Repo, number int, name string) error
// Assign adds assignees to the issue.
Assign(ctx context.Context, repo Repo, number int, logins []string) error
// Close closes the issue.
Close(ctx context.Context, repo Repo, number int) error
}
IssueStore is the issue surface the controllers use; *Client implements it, controller tests fake it.
type PATAlertEnumerator ¶ added in v0.10.0
type PATAlertEnumerator struct {
Client *Client
// MaxAlerts bounds the walk; <= 0 means DefaultMaxAlerts.
MaxAlerts int
}
PATAlertEnumerator walks the open code-scanning alerts of an explicit repository list with a PAT client. A PAT sees no installation inventory, so it cannot discover repositories: every entry must be an exact "owner/name" — a bare "owner/" prefix is an error, not an empty result.
func (*PATAlertEnumerator) Enumerate ¶ added in v0.10.0
func (e *PATAlertEnumerator) Enumerate( ctx context.Context, repos []string, yield func(Repo, *Alert) bool, ) (complete bool, err error)
Enumerate implements the backfill enumeration over the exact repositories named. complete is false when the alert budget (or the caller's yield) ended the walk early.
type RepoStore ¶
type RepoStore interface {
// DefaultBranch returns the repository's default branch name.
DefaultBranch(ctx context.Context, repo Repo) (string, error)
// HeadSHA resolves the current commit SHA of refs/heads/<branch>.
HeadSHA(ctx context.Context, repo Repo, branch string) (string, error)
// CreatePR opens a pull request.
CreatePR(ctx context.Context, repo Repo, req PRRequest) (*PR, error)
// SearchIssues runs an issue search query (cross-repo reconcile
// queries) and returns every matching issue.
SearchIssues(ctx context.Context, query string) ([]*Issue, error)
}
RepoStore is the repository/PR/search surface.
type TokenPerms ¶
type TokenPerms struct {
Contents string
}
TokenPerms is the permission set for a scoped token; string values are "read"/"write" per the GitHub API; empty means not requested.