Documentation
¶
Overview ¶
Package scm reaches a source-code host through one interface. GitHub and GitLab are the adapters so far.
Index ¶
- Constants
- Variables
- func AppJWT(ctx context.Context, signer Signer, appID string, now time.Time) (string, error)
- func Verify(secret, body []byte, header string) bool
- type AppTokens
- type Approval
- func ApprovalOf(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, ...) (Approval, error)
- func Approve(ctx context.Context, host Host, request ApprovalRequest, now time.Time) (Approval, error)
- func CountReview(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, ...) (Approval, error)
- type ApprovalRequest
- type ApprovalRules
- type CheckRun
- type CommentFinder
- type DeliveryStore
- type Event
- type ForkHeads
- type GitHub
- func (g *GitHub) BranchHead(ctx context.Context, branch string) (string, error)
- func (g *GitHub) BranchesAt(ctx context.Context, sha string) ([]string, error)
- func (g *GitHub) CanWrite(ctx context.Context, login string) (bool, error)
- func (g *GitHub) CheckRuns(ctx context.Context, sha, name string) ([]ListedCheck, error)
- func (g *GitHub) FirstCommit(ctx context.Context, path, ref string) (time.Time, error)
- func (g *GitHub) HasComment(ctx context.Context, pullRequest int, marker string) (bool, error)
- func (g *GitHub) OpenPullsFrom(ctx context.Context, owner, branch string) ([]OpenPull, error)
- func (g *GitHub) PostCheck(ctx context.Context, check CheckRun) (int64, error)
- func (g *GitHub) PullCommits(ctx context.Context, number int) ([]string, bool, error)
- func (g *GitHub) PullRequest(ctx context.Context, number int) (PullRequest, error)
- func (g *GitHub) ReadFile(ctx context.Context, path, ref string) ([]byte, error)
- func (g *GitHub) Reviews(ctx context.Context, number int) ([]Review, error)
- func (g *GitHub) UpdateCheck(ctx context.Context, id int64, check CheckRun) error
- func (g *GitHub) UpsertComment(ctx context.Context, pullRequest int, marker, body string) error
- func (g *GitHub) Visibility(ctx context.Context) (Visibility, error)
- type GitHubOptions
- type GitLab
- func (g *GitLab) BranchHead(ctx context.Context, branch string) (string, error)
- func (g *GitLab) PostCheck(context.Context, CheckRun) (int64, error)
- func (g *GitLab) ReadFile(ctx context.Context, path, ref string) ([]byte, error)
- func (g *GitLab) UpdateCheck(context.Context, int64, CheckRun) error
- func (g *GitLab) UpsertComment(ctx context.Context, mergeRequest int, marker, body string) error
- func (g *GitLab) Visibility(ctx context.Context) (Visibility, error)
- type GitLabOptions
- type History
- type Host
- type InstalledRepository
- type KMS
- type KMSError
- type KeyImport
- type LimitError
- type Limiter
- type ListedCheck
- type MemoryDeliveries
- type OpenPull
- type PullRequest
- type Queue
- type Reporter
- type Review
- type ReviewLister
- type Roles
- type Signer
- type StaticToken
- type StatusError
- type TokenSource
- type Visibility
- type Webhook
Constants ¶
const ( ReviewApproved = "APPROVED" ReviewChangesRequested = "CHANGES_REQUESTED" ReviewCommented = "COMMENTED" ReviewDismissed = "DISMISSED" ReviewPending = "PENDING" )
The review states a host lists. A webhook writes them in lower case.
const ( EventPullRequest = "pull_request" EventCheckRun = "check_run" EventInstallation = "installation" EventInstallationRepositories = "installation_repositories" )
The events the App queues. Every other event is acknowledged and dropped.
const ( InstallationCreated = "created" InstallationDeleted = "deleted" InstallationSuspended = "suspend" InstallationUnsuspended = "unsuspend" RepositoriesAdded = "added" RepositoriesRemoved = "removed" )
The installation actions the App queues. Each changes what the App's installations table holds.
const ( // ReplayWindow is how far an event's signed instant may sit from now. ReplayWindow = 10 * time.Minute // DeliveryRetention is how long a delivery id stays claimed: GitHub's // redelivery window, "the past 3 days" on its redelivering-webhooks page // as read on 2026-11-09. It outlasts the replay window because a // check_run states no instant, so the claim is what refuses its replay. DeliveryRetention = 72 * time.Hour )
const (
// ApproveAction is the identifier of the check's approve button.
ApproveAction = "approve"
)
const (
// DefaultAPI is github.com's API root.
DefaultAPI = "https://api.github.com"
)
Variables ¶
var ( ErrAuthorApproval = errors.New("scm: the pull request's author cannot approve it") ErrNoWriteRole = errors.New("scm: the approver holds no write role") ErrStaleHead = errors.New("scm: the pull request's head has moved") ErrNotAnApproval = errors.New("scm: the event is not an approval") ErrNotApproved = errors.New("scm: the review does not approve the change") ErrNoApprover = errors.New("scm: the review names no signed-in approver") ErrBotApproval = errors.New("scm: an App's account cannot approve") ErrOffHead = errors.New("scm: the review is not on the pull request's head") ErrExpiredReview = errors.New("scm: the review is older than an approval lasts") ErrNoApproval = errors.New("scm: no review approves the pull request's head") )
The refusals an approval can answer.
var ErrIgnoredEvent = errors.New("scm: event not processed")
ErrIgnoredEvent reports an event the App does not process.
var ErrNoCheck = errors.New("scm: this host takes no check from this token")
ErrNoCheck reports a host where the adapter posts no check.
var ErrNoCommit = errors.New("scm: no commit on the ref touched the path")
ErrNoCommit reports a ref where no commit touched the path asked about.
var ErrNotFound = errors.New("scm: not found")
ErrNotFound reports a file or an object the host does not have.
Functions ¶
Types ¶
type AppTokens ¶
type AppTokens struct {
API string
AppID string
Installation int64
Signer Signer
Now func() time.Time
// Client is as in GitHubOptions.
Client *http.Client
// contains filtered or unexported fields
}
AppTokens mints installation tokens with the App's minimum permissions and holds each until it nears its expiry.
type Approval ¶
type Approval struct {
PullRequest int
Approver string
HeadSHA string
At time.Time
// ReviewID names the review that approved, 0 for the App's button.
ReviewID int64
}
Approval records who approved which commit, and when. A failed check that an approval binds concludes neutral and names the approver.
func ApprovalOf ¶
func ApprovalOf(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, reviews []Review, now time.Time) (Approval, error)
ApprovalOf finds the newest review that approves the pull request's head and passes every rule. Each reviewer's own latest approval, request for changes or dismissal is their standing: a later comment leaves it as it was. With no approval, the error says why the newest approval was refused.
func Approve ¶
func Approve(ctx context.Context, host Host, request ApprovalRequest, now time.Time) (Approval, error)
Approve verifies one approval against the host. Any error refuses it.
func CountReview ¶
func CountReview(ctx context.Context, roles Roles, rules ApprovalRules, pull PullRequest, review Review, now time.Time) (Approval, error)
CountReview holds one review to every rule. pull is the pull request as the host answers now, so a review of a commit the head has since left never counts. The write role is asked last, because it costs a request.
type ApprovalRequest ¶
type ApprovalRequest struct {
PullRequest int
Approver string
HeadSHA string
// AllowAuthor lets a pull request's author approve it. It is off by default.
AllowAuthor bool
}
ApprovalRequest is one press of the approve action.
func RequestFrom ¶
func RequestFrom(event Event) (ApprovalRequest, error)
RequestFrom reads an approval out of a queued event.
type ApprovalRules ¶
ApprovalRules are what a repository asks of an approval: whether the author may approve, and how long an approval lasts.
type CheckRun ¶
type CheckRun struct {
Name string
HeadSHA string
Conclusion string
Title string
Summary string
Text string
Completed time.Time
}
CheckRun is one completed check.
type CommentFinder ¶
type CommentFinder interface {
// HasComment reports whether the token's own account wrote a comment on
// the pull request that opens with marker.
HasComment(ctx context.Context, pullRequest int, marker string) (bool, error)
}
CommentFinder finds a sticky comment without writing one.
type DeliveryStore ¶
type DeliveryStore interface {
// Claim reports true the first time an id is seen.
Claim(ctx context.Context, delivery string, now time.Time) (bool, error)
// Release forgets an id whose event could not be queued, so a redelivery
// is processed.
Release(ctx context.Context, delivery string) error
}
DeliveryStore gives each delivery id one claim.
type Event ¶
type Event struct {
Delivery string
Name string
Action string
Installation int64
Repository string
Sender string
PullRequest int
HeadSHA string
RequestedAction string
// BaseBranch is the base branch of the pull request a check_run names,
// empty when the payload states none in its format.
BaseBranch string
// Account is the login of the account an installation event's
// installation belongs to.
Account string
// Added and Removed are the repositories an installation event gives the
// installation and takes from it. A created installation lists its
// repositories in Added.
Added, Removed []InstalledRepository
// At is the instant the signed payload states for this event. It is zero
// for a check_run, whose payload holds no instant of the click.
At time.Time
}
Event is the part of a webhook the App acts on. Every string passed a check against its own format, because the rest of the App treats them as safe.
type ForkHeads ¶
type ForkHeads interface {
// OpenPullsFrom lists this repository's open pull requests whose head is
// branch in a repository owner holds.
OpenPullsFrom(ctx context.Context, owner, branch string) ([]OpenPull, error)
// BranchesAt lists this repository's branches whose head is the commit.
BranchesAt(ctx context.Context, sha string) ([]string, error)
}
ForkHeads is what a fork's follow-up asks before it posts on a commit.
type GitHub ¶
type GitHub struct {
// contains filtered or unexported fields
}
GitHub is the Host for one repository.
func NewGitHub ¶
func NewGitHub(options GitHubOptions) (*GitHub, error)
NewGitHub returns the adapter. The token never travels over plain HTTP, except to a loopback address.
func (*GitHub) BranchHead ¶
BranchHead reads the commit at the head of a branch through the git refs API. The answer must name the branch's own ref, so a prefix never matches.
func (*GitHub) BranchesAt ¶
BranchesAt lists this repository's branches whose head is the commit.
func (*GitHub) CheckRuns ¶
CheckRuns lists the commit's completed check runs named name, every attempt included, that GitHub Actions or this token's own App posted.
func (*GitHub) FirstCommit ¶
FirstCommit returns the committer date of the oldest commit on ref that touched path. The commits API lists the newest first, so it pages to the end. A ref where no commit touched path is ErrNoCommit.
func (*GitHub) HasComment ¶
HasComment reports whether the token's own account wrote a comment that opens with marker, as UpsertComment finds one. It writes nothing.
func (*GitHub) OpenPullsFrom ¶
OpenPullsFrom lists the open pull requests whose head is branch in a repository owner holds. It asks by branch, not by commit: GitHub's list of a commit's pull requests leaves out a fork's.
func (*GitHub) PostCheck ¶
PostCheck creates the check run and returns its id. Only a GitHub App can create one, and the answer names that App, so the adapter takes the App's account as the token's own from then on.
func (*GitHub) PullCommits ¶
PullCommits pages through the pull request's commits, oldest first. GitHub lists 250 at most, and a list that reaches 250 is capped.
func (*GitHub) PullRequest ¶
PullRequest reads the head and the author.
func (*GitHub) Reviews ¶
Reviews pages through the pull request's reviews in the order GitHub lists them. A review whose account was deleted names no reviewer, and a pending review states no time.
func (*GitHub) UpdateCheck ¶
UpdateCheck rewrites the output of a check run this token created. The conclusion stays as it was posted.
func (*GitHub) UpsertComment ¶
UpsertComment edits the sticky comment in place. Only a comment the token's own account wrote qualifies, so neither a person nor another App that writes the marker into its own comment can have it rewritten.
func (*GitHub) Visibility ¶
func (g *GitHub) Visibility(ctx context.Context) (Visibility, error)
Visibility asks the host, and an answer that omits the field is an error.
type GitHubOptions ¶
type GitHubOptions struct {
// API is the API root, DefaultAPI when empty.
API string
// Repository is owner/name.
Repository string
Tokens TokenSource
// Client makes the requests, under this package's timeout and redirect
// rule. Required, so that a service can pass one bound by its allowlist.
Client *http.Client
// Limits and Installation apply the App's write limits. A token from CI
// has neither.
Limits *Limiter
Installation int64
}
GitHubOptions configures a GitHub adapter.
type GitLab ¶
type GitLab struct {
// contains filtered or unexported fields
}
GitLab is the Reporter for one project. It reaches GitLab's REST API v4, and it has run against a stub built from GitLab's documentation and on a self-managed GitLab CE 19.5.1 (e2e/gitlab), not on gitlab.com.
func NewGitLab ¶
func NewGitLab(options GitLabOptions) (*GitLab, error)
NewGitLab returns the adapter. The token never travels over plain HTTP, except to a loopback address.
func (*GitLab) BranchHead ¶
BranchHead reads the commit at the head of a branch through the repository branches API.
func (*GitLab) PostCheck ¶
PostCheck posts nothing. A commit status needs the Developer role and a note needs less, so the note's token cannot set one, and a status has no neutral state to state.
func (*GitLab) UpdateCheck ¶
UpdateCheck sends nothing, because PostCheck creates no check.
func (*GitLab) UpsertComment ¶
UpsertComment edits the sticky note in place. Only a note this token's own user wrote qualifies, because a note's author carries no bot field. A failed search posts nothing, so a merge request never holds a second note.
func (*GitLab) Visibility ¶
func (g *GitLab) Visibility(ctx context.Context) (Visibility, error)
Visibility asks the host. An answer outside GitLab's three values is an error, and internal counts as private.
type GitLabOptions ¶
type GitLabOptions struct {
// API is the instance's REST root, CI_API_V4_URL in a job. It has no
// default, so a self-managed instance's token never reaches gitlab.com.
API string
// Project is the project's numeric id.
Project string
Tokens TokenSource
// Client is as in GitHubOptions.
Client *http.Client
}
GitLabOptions configures a GitLab adapter.
type History ¶
type History interface {
// PullCommits lists the pull request's commits, oldest first. Capped says
// the list reached the most the host lists, so later commits can be
// missing from it.
PullCommits(ctx context.Context, number int) (commits []string, capped bool, err error)
// CheckRuns lists the commit's completed check runs named name that
// GitHub Actions or the App this token belongs to posted. No other App's
// check run is listed, whatever its name.
CheckRuns(ctx context.Context, sha, name string) ([]ListedCheck, error)
}
History reads what earlier reports posted on a pull request.
type Host ¶
type Host interface {
Reporter
PullRequest(ctx context.Context, number int) (PullRequest, error)
// CanWrite reports whether login holds a write role on the repository.
CanWrite(ctx context.Context, login string) (bool, error)
}
Host is one repository a person can approve a change on.
type InstalledRepository ¶
InstalledRepository is one repository an installation reaches: its id and owner/name.
type KMS ¶
type KMS struct {
// contains filtered or unexported fields
}
KMS calls AWS KMS in one region with the credentials it was given. Its errors name the call and AWS's error type, never a key, a token or a signature.
func KMSFromEnvironment ¶
func KMSFromEnvironment(getenv func(string) string, keyID string, client *http.Client, now func() time.Time) (*KMS, error)
KMSFromEnvironment reads AWS's credentials, region and endpoint from the environment's variables. A key ARN names its region, which then needs no variable. The client is required, as GitHubOptions.Client is.
func (*KMS) PrepareImport ¶
PrepareImport asks KMS for the wrapping key and import token of keyID, for the RSA_AES_KEY_WRAP_SHA_256 algorithm, the one KMS takes for an RSA private key.
type KMSError ¶
type KMSError struct {
Action string
Status int
// Type is AWS's error type, such as AccessDeniedException.
Type string
}
KMSError is an answer of KMS other than 200.
type KeyImport ¶
type KeyImport struct {
// contains filtered or unexported fields
}
KeyImport is one import into a KMS key created with origin EXTERNAL: its wrapping public key and import token, valid for 24 hours.
type LimitError ¶
LimitError says a request was held back, and for how long to wait.
func (*LimitError) Error ¶
func (e *LimitError) Error() string
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter holds GitHub's limits per installation: two token buckets for content writes, and a ceiling on requests in flight.
func NewLimiter ¶
NewLimiter returns a Limiter reading the given clock.
type ListedCheck ¶
ListedCheck is one completed check run as a commit's list gives it.
type MemoryDeliveries ¶
type MemoryDeliveries struct {
// contains filtered or unexported fields
}
MemoryDeliveries is a DeliveryStore for one process. Only verified deliveries reach it, and it holds each for DeliveryRetention.
func NewMemoryDeliveries ¶
func NewMemoryDeliveries() *MemoryDeliveries
NewMemoryDeliveries returns an empty store.
type OpenPull ¶
type OpenPull struct {
Number int
HeadSHA string
// HeadRepository is owner/name, empty when the host no longer has it.
HeadRepository string
}
OpenPull is one open pull request as the host lists it.
type PullRequest ¶
PullRequest is what an approval needs to know about a pull request.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue carries events from the handler to the workers.
type Reporter ¶
type Reporter interface {
// PostCheck returns the check's id. A host without one answers ErrNoCheck.
PostCheck(ctx context.Context, check CheckRun) (int64, error)
// UpdateCheck replaces the output of check run id with check's title,
// summary and text. A host without checks answers ErrNoCheck.
UpdateCheck(ctx context.Context, id int64, check CheckRun) error
// UpsertComment edits the comment that opens with marker and that the
// token's own account wrote, or creates it when there is none.
UpsertComment(ctx context.Context, pullRequest int, marker, body string) error
// ReadFile reads a file at a ref. A missing file is ErrNotFound.
ReadFile(ctx context.Context, path, ref string) ([]byte, error)
Visibility(ctx context.Context) (Visibility, error)
}
Reporter is what a report needs from one repository on one source-code host.
type Review ¶
type Review struct {
ID int64
Reviewer string
// State is one of the Review states, in upper case.
State string
CommitID string
SubmittedAt time.Time
}
Review is one pull request review as the host lists it.
type ReviewLister ¶
ReviewLister lists a pull request's reviews.
type Signer ¶
Signer signs a SHA-256 digest with RSASSA-PKCS1-v1_5. The production signer is a KMS call, so the private key never reaches this process.
type StatusError ¶
StatusError is an answer the host refused. It never carries the body, which is the host's text and can echo the request.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
func (*StatusError) Is ¶
func (e *StatusError) Is(target error) bool
Is makes a 404 match ErrNotFound.
type TokenSource ¶
TokenSource supplies the bearer token of each request.
type Visibility ¶
type Visibility int
Visibility is who can read a repository.
const ( Private Visibility = iota Public )
A repository is public or it is not. Internal counts as private.