Documentation
¶
Overview ¶
Package github talks to GitHub on the user's behalf.
The token is borrowed from the GitHub CLI (gh auth token) on every refresh and held only in memory. It never reaches a log line, an error message, or the database: the Token type prints as [redacted] in every format, and every error that leaves this package is scrubbed of the token text.
The inbox comes from one batched GraphQL request (three aliased searches plus the query's rate-limit cost); the REST rate-limit endpoint fills in the remaining budgets.
Index ¶
- Constants
- Variables
- func Redact(err error, tok Token) error
- type Avatar
- type ChangedFile
- type ChangedFiles
- type Checks
- type Client
- func (c *Client) FetchAvatar(ctx context.Context, rawURL string) (*Avatar, error)
- func (c *Client) FetchChangedFiles(ctx context.Context, tok Token, ref ItemRef, head string) (*ChangedFiles, error)
- func (c *Client) FetchDetails(ctx context.Context, tok Token, ids []string) (*Details, error)
- func (c *Client) FetchInbox(ctx context.Context, tok Token) (*Inbox, error)
- func (c *Client) FetchItem(ctx context.Context, tok Token, id string) (*ItemUpdate, error)
- func (c *Client) FetchItemStates(ctx context.Context, tok Token, refs []ItemRef) (map[ItemRef]ItemState, error)
- func (c *Client) FetchPullHead(ctx context.Context, tok Token, ref ItemRef) (*PullHead, error)
- func (c *Client) FetchRateLimits(ctx context.Context, tok Token) (*RateLimits, error)
- type Details
- type Finder
- type Inbox
- type Item
- type ItemDetails
- type ItemRef
- type ItemState
- type ItemUpdate
- type Label
- type MissingScopesError
- type PullHead
- type QueryRate
- type Rate
- type RateLimits
- type Repository
- type Reviews
- type Runner
- type ScopeWarning
- type SearchResult
- type StatusError
- type Token
- type TokenSource
- type Viewer
Constants ¶
const ( StateOpen = "OPEN" StateClosed = "CLOSED" StateMerged = "MERGED" )
An item's state, as GitHub reports it. MERGED is for pull requests only.
const (
// DefaultAvatarHost is GitHub's avatar host, the only host FetchAvatar downloads from.
DefaultAvatarHost = "avatars.githubusercontent.com"
)
const (
// DefaultBaseURL is GitHub's public API.
DefaultBaseURL = "https://api.github.com"
)
Variables ¶
var ( // ErrAvatarURL is returned for an avatar URL that is not https on the avatar host. ErrAvatarURL = errors.New("not a GitHub avatar URL") // ErrAvatarImage is returned when the download is not a PNG, JPEG, GIF, or WebP image. ErrAvatarImage = errors.New("the avatar is not a supported image") )
var ( // ErrGraphQL is returned when a GraphQL response carries errors. ErrGraphQL = errors.New("the GitHub GraphQL API returned errors") // ErrUnexpectedStatus matches a *StatusError with errors.Is. ErrUnexpectedStatus = errors.New("unexpected response status from the GitHub API") // ErrMalformedResponse is returned for a response body that can't be used. ErrMalformedResponse = errors.New("malformed response from the GitHub API") )
var ( // ErrGHNotFound is returned when the GitHub CLI is not installed or not on the search path. ErrGHNotFound = errors.New("the GitHub CLI (gh) was not found: install the GitHub CLI from https://cli.github.com, then run gh auth login") // ErrNotLoggedIn is returned when the GitHub CLI has no token for github.com. ErrNotLoggedIn = errors.New("the GitHub CLI is not logged in to github.com: run gh auth login") )
var ErrHeadMoved = errors.New("the pull request was pushed to while its files were read; try again")
ErrHeadMoved is returned when a pull request was pushed to each time its files were read, so no list can be tied to one commit.
var ErrInvalidItemRef = errors.New("invalid pull request or issue reference")
ErrInvalidItemRef is returned for an ItemRef whose number is not positive; it is never sent.
var ErrMissingScopes = errors.New("the GitHub token is missing required scopes")
ErrMissingScopes matches a MissingScopesError with errors.Is.
Functions ¶
Types ¶
type Avatar ¶
type Avatar struct {
// ContentType is the image's media type, sniffed from its bytes, e.g. "image/png".
ContentType string
// Data is the image itself.
Data []byte
}
Avatar is a downloaded profile picture.
type ChangedFile ¶
type ChangedFile struct {
// Path is the file's path after the change.
Path string
// PreviousPath is a renamed or copied file's path before the change, or "".
PreviousPath string
// Status is GitHub's word for the change: added, removed, modified, renamed, copied,
// changed, or unchanged.
Status string
}
ChangedFile is one file a pull request changes.
type ChangedFiles ¶
type ChangedFiles struct {
// Head is the head commit the list belongs to.
Head string
// Total is how many files the pull request changes, which can exceed len(Files).
Total int
// Files are the files GitHub listed: every one, or the first 3,000.
Files []ChangedFile
// Complete reports that Files holds every changed file.
Complete bool
}
ChangedFiles is a pull request's changed files at one head commit.
type Checks ¶
type Checks struct {
// State is GitHub's overall result: SUCCESS, FAILURE, ERROR, PENDING, or EXPECTED,
// and "" when the head commit has no checks.
State string
Passed int
Failed int
Pending int
Skipped int
}
Checks counts the head commit's check runs and commit statuses by outcome.
type Client ¶
type Client struct {
// BaseURL is the API root, without a trailing slash. Tests point it at a local server.
BaseURL string
// HTTP sends the requests.
HTTP *http.Client
// UserAgent identifies the app to GitHub.
UserAgent string
// AvatarHost is the only host FetchAvatar downloads from, as host or host:port. It
// defaults to DefaultAvatarHost; tests point it at a local server.
AvatarHost string
}
Client calls the GitHub REST and GraphQL APIs.
func NewClient ¶
NewClient returns a client for GitHub's public API that identifies itself with the app's slug and version.
func (*Client) FetchAvatar ¶
FetchAvatar downloads the profile picture at rawURL, a Viewer's AvatarURL. The URL must be https on the avatar host, and redirects may not leave that host. No token is sent, because avatars are public. The image type is sniffed from the bytes rather than taken from the response header, and only raster image types are accepted.
func (*Client) FetchChangedFiles ¶
func (c *Client) FetchChangedFiles(ctx context.Context, tok Token, ref ItemRef, head string) (*ChangedFiles, error)
FetchChangedFiles lists the files a pull request changes, with each renamed file's previous path, through the REST API: GitHub's GraphQL API does not report where a renamed file came from. The list is read between two readings of the head commit, so it belongs to one commit: when the head moved meanwhile, it is read again for the new head, and ErrHeadMoved is returned if the head moves again. head is the head commit already known, or "" to read it first.
It costs one REST request per 100 files, plus one or two for the head.
func (*Client) FetchDetails ¶
FetchDetails reads the details of the items with the given node IDs, in concurrent batches. GitHub's errors about single items it cannot resolve are not failures: those items are simply left out.
func (*Client) FetchInbox ¶
FetchInbox runs the batched inbox query: one POST to /graphql. The result includes the token's X-OAuth-Scopes header for CheckScopes.
func (*Client) FetchItem ¶
FetchItem reads one pull request or issue, by node ID, as of now. Unlike the inbox query's searches, it never waits on GitHub's index, so it sees a merge or a close at once.
func (*Client) FetchItemStates ¶
func (c *Client) FetchItemStates(ctx context.Context, tok Token, refs []ItemRef) (map[ItemRef]ItemState, error)
FetchItemStates reads the state of each pull request or issue in refs, as of now. A ref GitHub cannot resolve (a number that does not exist, a repository that is gone or that the token cannot see) is left out of the result. Any other error fails the whole call, so a passing problem never makes an item look done.
func (*Client) FetchPullHead ¶
FetchPullHead reads a pull request's head commit and size as of now, with one REST request.
func (*Client) FetchRateLimits ¶
FetchRateLimits reads the REST, GraphQL, and search budgets from GET /rate_limit, which does not count against them.
type Details ¶
type Details struct {
// Items maps each item's node ID to its details. An ID GitHub could not resolve, such
// as one deleted since the inbox query, is left out.
Items map[string]ItemDetails
// RateLimit is the GraphQL budget after the last request; its Cost is the sum of
// every request's cost.
RateLimit QueryRate
// Requests is how many requests were made: 0 when there were no IDs.
Requests int
}
Details is what FetchDetails learned.
type Inbox ¶
type Inbox struct {
// Viewer is the token's account.
Viewer Viewer
ReviewRequested SearchResult
Authored SearchResult
Assigned SearchResult
// RateLimit is the GraphQL budget after this query, including its cost.
RateLimit QueryRate
// OAuthScopes is the response's X-OAuth-Scopes header ("" when absent).
OAuthScopes string
}
Inbox is the decoded result of the batched inbox query.
type Item ¶
type Item struct {
IsPR bool
NodeID string
Number int
Title string
URL string
CreatedAt time.Time
UpdatedAt time.Time
// State is StateOpen, StateClosed, or StateMerged, and "" when GitHub did not say.
State string
// IsDraft and HeadRef are set for pull requests only.
IsDraft bool
HeadRef string
AuthorLogin string
// AuthorType is the author's GraphQL type: User for a person, Bot for a GitHub App
// or bot, or another actor type such as Mannequin.
AuthorType string
// AuthorAssociation is the author's relationship to the repository (OWNER, MEMBER,
// COLLABORATOR, CONTRIBUTOR, NONE, ...).
AuthorAssociation string
// IsCrossRepository reports a pull request opened from another repository (a fork).
IsCrossRepository bool
RepoOwner string
RepoName string
// Repo describes the item's repository.
Repo Repository
}
Item is one pull request or issue from a search.
type ItemDetails ¶
type ItemDetails struct {
Labels []Label
// Comments counts the conversation's comments; for a pull request it includes the
// review comments.
Comments int
Additions int
Deletions int
ChangedFiles int
Commits int
// HeadOID is the SHA of a pull request's head commit; it changes on every push.
HeadOID string
// Mergeable is MERGEABLE, CONFLICTING, or UNKNOWN while GitHub is still working it out.
Mergeable string
Checks Checks
Reviews Reviews
}
ItemDetails is what an inbox card shows about one pull request or issue. The pull request fields are zero for an issue.
type ItemRef ¶
ItemRef names a pull request or issue by its repository and number. GitHub's numbers are shared by a repository's pull requests and issues, so the number alone picks one.
type ItemState ¶
type ItemState struct {
// PullRequest reports a pull request; false is an issue.
PullRequest bool
Title string
URL string
// State is StateOpen, StateClosed, or StateMerged.
State string
// ClosedAt is when the item was merged or closed, or zero while it is open.
ClosedAt time.Time
// HeadOID is a pull request's head commit SHA; "" for an issue.
HeadOID string
}
ItemState is what GitHub says about a pull request or issue as of now.
type ItemUpdate ¶
type ItemUpdate struct {
// Found is false when GitHub could not resolve the ID, because the item was deleted
// or the token can no longer see it. Item and Details are zero then.
Found bool
Item Item
Details ItemDetails
// RateLimit is the GraphQL budget after the request, including its cost.
RateLimit QueryRate
}
ItemUpdate is what FetchItem learned about one item.
type Label ¶
type Label struct {
Name string
// Color is "#rrggbb" in lower case, or "" when GitHub's value is not a color.
Color string
}
Label is one label on an item.
type MissingScopesError ¶
type MissingScopesError struct {
Missing []string
}
MissingScopesError lists the required scopes the token lacks.
func (*MissingScopesError) Error ¶
func (e *MissingScopesError) Error() string
Error names the missing scopes and how to grant them.
func (*MissingScopesError) Is ¶
func (e *MissingScopesError) Is(target error) bool
Is reports whether target is ErrMissingScopes.
type PullHead ¶
type PullHead struct {
// Head is the head commit's SHA.
Head string
// ChangedFiles is how many files the pull request changes.
ChangedFiles int
// State is "open" or "closed".
State string
}
PullHead is where a pull request stands as of now.
type RateLimits ¶
RateLimits holds the budgets the rate gauge shows.
type Repository ¶
type Repository struct {
// NodeID is the repository's GraphQL ID, which survives a rename.
NodeID string
Description string
// Visibility is PUBLIC, PRIVATE, or INTERNAL.
Visibility string
IsArchived bool
// ArchivedAt is when the repository was archived; zero when it is not.
ArchivedAt time.Time
// IsDisabled and IsLocked report a repository that cannot be used: disabled by
// GitHub, or locked, for instance while it migrates (LockReason says why).
IsDisabled bool
IsLocked bool
LockReason string
// IsFork reports a fork, and Parent is the "owner/name" it was made from ("" when the
// viewer cannot see the parent).
IsFork bool
Parent string
// DefaultBranch is the default branch's name ("" for an empty repository).
DefaultBranch string
// ViewerPermission is the viewer's access: ADMIN, MAINTAIN, WRITE, TRIAGE, or READ.
ViewerPermission string
// ViewerMergeMethod is the merge method GitHub offers the viewer first: MERGE,
// SQUASH, or REBASE.
ViewerMergeMethod string
MergeCommitAllowed bool
SquashMergeAllowed bool
RebaseMergeAllowed bool
AutoMergeAllowed bool
DeleteBranchOnMerge bool
AllowUpdateBranch bool
// Language is the primary language's name, and LanguageColor its "#rrggbb" color in
// lower case; both "" when GitHub detected none.
Language string
LanguageColor string
// PushedAt is the last push to any branch; zero when unknown.
PushedAt time.Time
}
Repository is what the inbox query reads about an item's repository: its identity, its state, its merge settings, and the viewer's access to it.
type Reviews ¶
type Reviews struct {
// Decision is APPROVED, CHANGES_REQUESTED, or REVIEW_REQUIRED, and "" when the
// repository requires no review.
Decision string
// Reviewers is everyone asked to review or who has reviewed, the author excluded.
Reviewers int
// Reviewed is how many of them have reviewed and are not asked to review again.
Reviewed int
// Approvals and ChangesRequested count the reviewers whose latest review is one.
Approvals int
ChangesRequested int
}
Reviews counts who was asked to review a pull request and who has.
type Runner ¶
type Runner interface {
Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error)
}
Runner runs a program with arguments and returns what it wrote. Implementations run the argv directly, never through a shell.
type ScopeWarning ¶
type ScopeWarning string
ScopeWarning describes a scope check that passed without proof.
const ScopesUnverifiable ScopeWarning = "GitHub did not report this token's scopes " +
"(a fine-grained token?), so the repo and read:org scopes can't be verified; " +
"some items may be missing"
ScopesUnverifiable is the warning for a token that reports no scopes, such as a fine-grained token. Requests still go ahead; results may be incomplete.
func CheckScopes ¶
func CheckScopes(header string) (ScopeWarning, error)
CheckScopes checks a response's X-OAuth-Scopes header for the scopes the inbox needs. An empty header (a token that reports no scopes) returns ScopesUnverifiable and no error. A header without repo, or without any of read:org, write:org, or admin:org, returns a *MissingScopesError.
type SearchResult ¶
type SearchResult struct {
// IssueCount is GitHub's total match count, which can exceed len(Items).
IssueCount int
Items []Item
}
SearchResult is one aliased search: the total match count and the items returned.
type StatusError ¶
StatusError is a non-2xx response from the GitHub API.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
Error describes the status, GitHub's message, and a hint for a rejected token.
func (*StatusError) Is ¶
func (e *StatusError) Is(target error) bool
Is reports whether target is ErrUnexpectedStatus.
type Token ¶
type Token struct {
// contains filtered or unexported fields
}
Token is a GitHub API token. Its value is only reachable through Reveal; printing, logging, or encoding a Token always yields [redacted].
The value sits behind a pointer so that even reflection-based printing of a struct holding a Token in an unexported field shows an address, not the token.
func (Token) MarshalJSON ¶
MarshalJSON encodes the token as the string "[redacted]".
func (Token) MarshalText ¶
MarshalText encodes the token as [redacted].
type TokenSource ¶
type TokenSource struct {
// contains filtered or unexported fields
}
TokenSource borrows the GitHub CLI's token for github.com.
func NewTokenSource ¶
func NewTokenSource(runner Runner, finder Finder) *TokenSource
NewTokenSource returns a TokenSource that finds gh with finder and runs it with runner.
type Viewer ¶
type Viewer struct {
// Login is the account's username.
Login string
// Name is the profile's display name ("" when the profile sets none).
Name string
// URL is the account's profile page on GitHub.
URL string
// AvatarURL is the profile picture on GitHub's avatar host. FetchAvatar downloads it.
AvatarURL string
}
Viewer is the account a token belongs to.