ghclient

package
v0.14.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

View Source
var ErrDeleteUnauthorized = errors.New("credential not authorized to delete issues")

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

func IsNotFound(err error) bool

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

func RepoMatches(entries []string, repo Repo) bool

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

func ValidateProxy(rawURL string) error

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 NewApp

func NewApp(cfg AppConfig) (*App, error)

NewApp builds an App from cfg, parsing and validating the private key.

func (*App) Deliveries added in v0.5.4

func (a *App) Deliveries(ctx context.Context, visit func(Delivery) bool) (complete bool, err error)

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

func (a *App) Installation(ctx context.Context, repo Repo) (*Client, error)

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

func (a *App) Installations(ctx context.Context) ([]*Client, error)

Installations returns one client per installation of the App: the fan-out for cross-repository sweeps like the reconcile searches.

func (*App) Redeliver added in v0.5.4

func (a *App) Redeliver(ctx context.Context, deliveryID int64) error

Redeliver asks GitHub to redeliver one App webhook delivery attempt.

func (*App) ScopedToken

func (a *App) ScopedToken(ctx context.Context, repo Repo, perms TokenPerms) (string, time.Time, error)

ScopedToken mints a short-lived installation token restricted to the single repository and permissions given, returning the token and its expiry.

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, so 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

func NewToken(token, baseURL string, opts ...Option) (*Client, error)

NewToken returns a Client authenticated with a personal access token, the dev-mode fallback. baseURL "" means api.github.com.

func (*Client) AddLabels

func (c *Client) AddLabels(ctx context.Context, repo Repo, number int, add []string) error

AddLabels adds labels to the issue, creating any that do not exist.

func (*Client) Assign

func (c *Client) Assign(ctx context.Context, repo Repo, number int, logins []string) error

Assign adds assignees to the issue.

func (*Client) Close

func (c *Client) Close(ctx context.Context, repo Repo, number int) error

Close closes the issue.

func (*Client) Comment

func (c *Client) Comment(ctx context.Context, repo Repo, number int, body string) error

Comment adds a comment to the issue.

func (*Client) Create

func (c *Client) Create(ctx context.Context, repo Repo, req IssueRequest) (*Issue, error)

Create opens a new issue.

func (*Client) CreatePR

func (c *Client) CreatePR(ctx context.Context, repo Repo, req PRRequest) (*PR, error)

CreatePR opens a pull request.

func (*Client) DefaultBranch

func (c *Client) DefaultBranch(ctx context.Context, repo Repo) (string, error)

DefaultBranch returns the repository's default branch name.

func (*Client) DeleteIssue added in v0.5.7

func (c *Client) DeleteIssue(ctx context.Context, repo Repo, number int) error

DeleteIssue permanently deletes an issue. The REST API cannot delete issues; 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) EditBody

func (c *Client) EditBody(ctx context.Context, repo Repo, number int, body string) error

EditBody replaces the issue body.

func (*Client) EditComment added in v0.5.3

func (c *Client) EditComment(ctx context.Context, repo Repo, commentID int64, body string) error

EditComment replaces the body of an existing issue comment.

func (*Client) FindPRByHead added in v0.4.0

func (c *Client) FindPRByHead(ctx context.Context, repo Repo, branch string) (*PR, error)

FindPRByHead returns the open pull request whose head is branch, or nil. It is the idempotency check before creating a remediation PR (a crash between push and status write must not open a duplicate).

func (*Client) GetAlert

func (c *Client) GetAlert(ctx context.Context, repo Repo, number int) (*Alert, error)

GetAlert fetches one code-scanning alert.

func (*Client) GetIssue added in v0.4.0

func (c *Client) GetIssue(ctx context.Context, repo Repo, number int) (*Issue, error)

GetIssue fetches one issue: the projection reconciler's current-state read before diffing labels and body.

func (*Client) HeadSHA added in v0.3.0

func (c *Client) HeadSHA(ctx context.Context, repo Repo, branch string) (string, error)

HeadSHA resolves the current commit SHA of refs/heads/<branch>.

func (*Client) InstallationRepos added in v0.10.0

func (c *Client) InstallationRepos(ctx context.Context) (repos []Repo, complete bool, err error)

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

func (c *Client) ListComments(ctx context.Context, repo Repo, number int) ([]*Comment, error)

ListComments returns every comment on the issue, following pagination.

func (*Client) ListOpen

func (c *Client) ListOpen(ctx context.Context, repo Repo, labels []string) ([]*Issue, error)

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

func (c *Client) OpenAlert(ctx context.Context, repo Repo, number int) error

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."), so the state is read rather than inferred from the error.

func (*Client) PushBranch added in v0.3.0

func (c *Client) PushBranch(ctx context.Context, repo Repo, req BranchPush) (string, error)

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. It returns the pushed commit's SHA.

func (*Client) RemoveLabel

func (c *Client) RemoveLabel(ctx context.Context, repo Repo, number int, name string) error

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

func (c *Client) SearchIssues(ctx context.Context, query string) ([]*Issue, error)

SearchIssues runs an issue search query and returns every matching issue, following pagination.

func (*Client) Tarball added in v0.4.0

func (c *Client) Tarball(ctx context.Context, repo Repo, ref string) (io.ReadCloser, error)

Tarball streams the repository's tarball archive at ref (a SHA, branch, or tag). The caller must Close the reader. The archive is the tree only (no .git), which is what the artifact server serves; agents synthesize their local git state from it.

type Comment

type Comment struct {
	ID                int64
	Body              string
	UserLogin         string
	AuthorAssociation string
}

Comment is one issue comment.

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

type IssueRequest struct {
	Title  string
	Body   string
	Labels []string
}

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 Option added in v0.11.2

type Option func(*settings)

Option adjusts how a Client is built.

func WithProxy added in v0.11.2

func WithProxy(rawURL string) Option

WithProxy routes all of the client's traffic through the HTTP/HTTPS forward proxy at rawURL, overriding the process proxy environment. Empty is a no-op (the environment applies).

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 PR

type PR struct {
	Number  int
	HTMLURL string
}

PR is a freshly created pull request.

type PRRequest

type PRRequest struct {
	Title string
	Head  string
	Base  string
	Body  string
}

PRRequest is the payload for creating a pull request.

type Repo

type Repo struct {
	Owner string
	Name  string
}

Repo identifies a GitHub repository.

func (Repo) String

func (r Repo) String() string

String renders the repository as "owner/name".

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL