github

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 35 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 github talks to GitHub on the user's behalf.

The token is borrowed from the GitHub CLI (gh auth token) and kept in memory only. A TokenSource hands the same token to every caller for up to ten minutes, so a refresh does not wait for gh each time, and callers that ask at once share one gh run. It asks gh again sooner when:

  • GitHub refuses the token (HTTP 401, Bad credentials): WithToken forgets it and retries the request once with a fresh one, so a token revoked or replaced by gh auth login is picked up at once;
  • gh's account changes: gh rewrites its hosts file on gh auth switch, login, and logout, and a token borrowed before that is dropped;
  • the app quits: Clear forgets the token.

The token 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

View Source
const (
	StateOpen   = "OPEN"
	StateClosed = "CLOSED"
	StateMerged = "MERGED"
)

An item's state, as GitHub reports it. MERGED is for pull requests only.

View Source
const (
	TimelineComment           = "IssueComment"
	TimelineCrossReferenced   = "CrossReferencedEvent"
	TimelineConnected         = "ConnectedEvent"
	TimelineDisconnected      = "DisconnectedEvent"
	TimelineClosed            = "ClosedEvent"
	TimelineReopened          = "ReopenedEvent"
	TimelineAssigned          = "AssignedEvent"
	TimelineUnassigned        = "UnassignedEvent"
	TimelineLabeled           = "LabeledEvent"
	TimelineUnlabeled         = "UnlabeledEvent"
	TimelineRenamed           = "RenamedTitleEvent"
	TimelineMarkedAsDuplicate = "MarkedAsDuplicateEvent"

	TimelineReview           = "PullRequestReview"
	TimelineMerged           = "MergedEvent"
	TimelineForcePushed      = "HeadRefForcePushedEvent"
	TimelineReviewRequested  = "ReviewRequestedEvent"
	TimelineReadyForReview   = "ReadyForReviewEvent"
	TimelineConvertedToDraft = "ConvertToDraftEvent"
)

The timeline items the sheets read, by GitHub's type names: both sheets' first, then those only a pull request's timeline has.

View Source
const (
	ReviewStateApproved         = "APPROVED"
	ReviewStateChangesRequested = "CHANGES_REQUESTED"
	ReviewStateCommented        = "COMMENTED"
	ReviewStateDismissed        = "DISMISSED"
	ReviewStatePending          = "PENDING"
)

A review's state, as GitHub's PullRequestReviewState says.

View Source
const (
	StateReasonCompleted  = "COMPLETED"
	StateReasonNotPlanned = "NOT_PLANNED"
	StateReasonDuplicate  = "DUPLICATE"
	StateReasonReopened   = "REOPENED"
)

Why an issue is closed, or was reopened, as GitHub's stateReason says.

View Source
const (
	IssueReasonCompleted  = "completed"
	IssueReasonNotPlanned = "not_planned"
)

Why the issue sheet closes an issue, as GitHub's REST API takes it. A close as a duplicate names its duplicate, which the sheet doesn't offer.

View Source
const (
	// MaxThreadPages is the most pages of notifications the app reads: 1,000 threads.
	MaxThreadPages = 20

	// ThreadsPerPage is the most threads GitHub lists on a page, which the listing asks
	// for.
	ThreadsPerPage = 50
)
View Source
const (
	// MergeStateClean can be merged now.
	MergeStateClean = "CLEAN"

	// MergeStateHasHooks can be merged now, and the repository runs pre-receive hooks.
	MergeStateHasHooks = "HAS_HOOKS"

	// MergeStateUnstable can be merged, though checks that are not required failed.
	MergeStateUnstable = "UNSTABLE"

	// MergeStateBlocked waits on a requirement: a review, a required check, or a rule.
	MergeStateBlocked = "BLOCKED"

	// MergeStateBehind is behind its base branch, which the repository requires it not be.
	MergeStateBehind = "BEHIND"

	// MergeStateDirty has conflicts with its base branch.
	MergeStateDirty = "DIRTY"

	// MergeStateUnknown is still being worked out by GitHub.
	MergeStateUnknown = "UNKNOWN"
)

A pull request's merge state, as GitHub's mergeStateStatus reports it.

View Source
const (
	CheckKindRun    = "run"
	CheckKindStatus = "status"
)

Check kinds: a GitHub Actions or app check run, or a commit status.

View Source
const (
	CheckPassed  = "passed"
	CheckFailed  = "failed"
	CheckPending = "pending"
	CheckSkipped = "skipped"
)

Where a check is counted.

View Source
const (
	ResourceGraphQL = "graphql"
	ResourceCore    = "core"
	ResourceSearch  = "search"
)

Budgets GitHub names in a reading's Resource.

View Source
const (
	ReviewApprove        = "APPROVE"
	ReviewRequestChanges = "REQUEST_CHANGES"
	ReviewComment        = "COMMENT"
)

Review events a submitted review can carry.

View Source
const (
	MergeMethodMerge  = "MERGE"
	MergeMethodSquash = "SQUASH"
	MergeMethodRebase = "REBASE"
)

Merge methods, as GitHub's GraphQL API and viewerDefaultMergeMethod name them.

View Source
const (
	SideLeft  = "LEFT"
	SideRight = "RIGHT"
)

Sides of a diff a line comment can be on.

View Source
const (
	// DefaultAvatarHost is GitHub's avatar host, the only host FetchAvatar downloads from.
	DefaultAvatarHost = "avatars.githubusercontent.com"
)
View Source
const (
	// DefaultBaseURL is GitHub's public API.
	DefaultBaseURL = "https://api.github.com"
)
View Source
const ItemsMax = 100

ItemsMax is the most items FetchItems reads in one request: GitHub's own limit on the IDs one nodes lookup takes.

View Source
const LoginAvatarSize = 40

LoginAvatarSize is the size, in pixels, FetchLoginAvatar asks for: a picture shown 20 points square, on a display of two pixels to the point.

View Source
const MaxReviewRequests = 50

MaxReviewRequests is the most review requests a read of a pull request's details lists (the fragment's reviewRequests(first: 50)): a read that lists this many may have left some out, so it can't tell who else the pull request asks.

View Source
const SuiteAwaitsApproval = "ACTION_REQUIRED"

SuiteAwaitsApproval is the conclusion of a suite whose run waits for a maintainer's approval, as a fork's first workflow runs do.

View Source
const TokenTTL = 10 * time.Minute

TokenTTL is how long a TokenSource keeps handing out the token it borrowed before it asks gh again.

Variables

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

	// ErrResponseTooLarge is returned, with ErrMalformedResponse, for a response larger
	// than the client reads, so a read that can ask for less, as the issue sheet's can,
	// asks again.
	ErrResponseTooLarge = errors.New("the GitHub API response is too large")
)
View Source
var (
	// ErrDownloadURL is returned for a download URL, or a redirect, that isn't https on
	// one of the download hosts.
	ErrDownloadURL = errors.New("not a GitHub release download")

	// ErrDownloadTooLarge is returned when a download passes the size it was allowed.
	ErrDownloadTooLarge = errors.New("the download is larger than allowed")

	// ErrDownloadStalled is returned when a download sends nothing for too long.
	ErrDownloadStalled = errors.New("the download stalled")
)
View Source
var (
	// ErrEditIgnored is returned when GitHub accepted an edit but left the item as it was,
	// as it does for a change the token's account may not make.
	ErrEditIgnored = errors.New("GitHub did not make the change")

	// ErrInvalidLogin is returned for an edit about a login GitHub could not have issued.
	ErrInvalidLogin = errors.New("invalid GitHub login")

	// ErrPushedSince is returned when a pull request was pushed to after the head commit an
	// edit was pinned to: GitHub refused the edit, and nothing changed.
	ErrPushedSince = errors.New("the pull request was pushed to since it was read")

	// ErrMergeableNow is returned when GitHub refuses to turn on auto-merge because the pull
	// request can be merged right now.
	ErrMergeableNow = errors.New("the pull request can be merged now")

	// ErrNotMergeable matches a *NotMergeableError with errors.Is.
	ErrNotMergeable = errors.New("GitHub won't merge the pull request yet")

	// ErrOwnPull is returned for an approval or a request for changes on the user's own pull
	// request, which GitHub refuses.
	ErrOwnPull = errors.New("GitHub refuses a review of your own pull request")

	// ErrPendingReview is returned when the user already has a pending review on the pull
	// request, started on GitHub and not submitted, which blocks another.
	ErrPendingReview = errors.New("you have a pending review on the pull request")

	// ErrLineNotInDiff is returned when GitHub refuses a line comment on a line its diff does
	// not show.
	ErrLineNotInDiff = errors.New("a line comment is not on a line of the diff")
)
View Source
var (
	// ErrIssueGone is returned for a read of an earlier page of an issue GitHub can no
	// longer find: it was deleted, or the token can no longer see it.
	ErrIssueGone = errors.New("GitHub can't find the issue")

	// ErrPullGone is returned for a read of an earlier page of a pull request GitHub can no
	// longer find.
	ErrPullGone = errors.New("GitHub can't find the pull request")

	// ErrInvalidCursor is returned for a timeline cursor GitHub could not have given: an
	// empty one, or one longer than its cursors run.
	ErrInvalidCursor = errors.New("invalid timeline cursor")
)
View Source
var (
	// ErrThreadNotFound is returned when GitHub answers a write to a notification thread
	// 404 Not Found, as for a thread that is already done or isn't the user's.
	ErrThreadNotFound = errors.New("GitHub found no such notification thread")

	// ErrInvalidThreadPage is returned for a page of notifications past MaxThreadPages.
	ErrInvalidThreadPage = errors.New("the app reads no such page of notifications")

	// ErrInvalidCommentURL is returned for a comment's URL that isn't the API's URL of an
	// issue's or a pull request's comment; nothing is sent.
	ErrInvalidCommentURL = errors.New("not the URL of a comment on GitHub's API")
)
View Source
var (
	// ErrInvalidProgressRequest is returned for a ProgressRequest without a repository, a
	// tag, or a commit's full SHA; it is never sent.
	ErrInvalidProgressRequest = errors.New("invalid release progress request")

	// ErrRepositoryNotFound is returned when GitHub can't find the repository asked about,
	// or the token can't see it.
	ErrRepositoryNotFound = errors.New("GitHub couldn't find the repository")
)
View Source
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")
)
View Source
var ErrAvatarLogin = errors.New("not a login with a GitHub avatar")

ErrAvatarLogin is returned for a login FetchLoginAvatar won't ask the avatar host about: one that isn't a user's, such as a bot's.

View Source
var ErrChoreRefused = errors.New("the client sends no such chore")

ErrChoreRefused is returned for a chore the client never sends: a method but DELETE or PATCH, a thread ID that isn't positive, or a client with no ChoreGate.

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

View Source
var ErrInvalidCompareRequest = errors.New("invalid release comparison request")

ErrInvalidCompareRequest is returned for a CompareRequest without a tag or a branch; it is never sent.

View Source
var ErrInvalidItemRef = errors.New("invalid pull request or issue reference")

ErrInvalidItemRef is returned for an item.Ref that names no pull request or issue; it is never sent.

View Source
var ErrInvalidLabel = errors.New("invalid label name")

ErrInvalidLabel is returned for a label name no label can have, before anything is sent.

View Source
var ErrInvalidWrite = errors.New("the change to GitHub is not valid")

ErrInvalidWrite is returned for a review, merge, or comment that cannot be sent as it stands; nothing is sent.

View Source
var ErrMissingScopes = errors.New("the GitHub token is missing required scopes")

ErrMissingScopes matches a MissingScopesError with errors.Is.

View Source
var ErrMutationAsQuery = errors.New("a GraphQL mutation can only be sent as an edit")

ErrMutationAsQuery is returned when a GraphQL mutation is sent as a query: a mutation changes GitHub, so it goes only through mutate, which the WriteGate paces.

View Source
var ErrNotModified = errors.New("not modified since the last answer")

ErrNotModified is returned for a GET sent with an earlier answer's ETag (withETag) that GitHub answered 304 Not Modified: what that GET would answer is as it was in the earlier answer, and the request cost nothing. The error do returns carries the 304's headers (notModifiedError).

View Source
var ErrStatusURL = errors.New("not a status page the app reads")

ErrStatusURL is returned for a status page host that isn't one of the client's status hosts, a path that isn't absolute and clean, or a redirect off the request's own host.

Functions

func CanTriage added in v0.2.0

func CanTriage(permission string) bool

CanTriage reports a repository permission, as GitHub's GraphQL API names it, that lets an account change an issue's labels and assignees: triage or more.

func CanWrite added in v0.2.0

func CanWrite(permission string) bool

CanWrite reports that permission, the viewer's access to a repository as GitHub names it (Repo.ViewerPermission), is write access or more: ADMIN, MAINTAIN, or WRITE.

func DefaultDownloadHosts added in v0.2.0

func DefaultDownloadHosts() []string

DefaultDownloadHosts returns the hosts a release download may come from: github.com, whose download links redirect to GitHub's release asset host, and the older asset host.

func DefaultStatusHosts added in v0.2.0

func DefaultStatusHosts() []string

DefaultStatusHosts returns the status pages FetchStatus may read from: GitHub's, Claude's, and OpenAI's. Each gets only the request for its summary: no token, and nothing of the user's.

func GHHostsFile added in v0.2.0

func GHHostsFile(home string) string

GHHostsFile returns where the GitHub CLI records its signed-in accounts, as gh finds it: hosts.yml in GH_CONFIG_DIR when that is set, else in XDG_CONFIG_HOME/gh, else in home/.config/gh, which gh uses on macOS too.

func IsBadCredentials added in v0.2.0

func IsBadCredentials(err error) bool

IsBadCredentials reports whether err is GitHub refusing the token itself: HTTP 401, or a Bad credentials message.

func Mergeable added in v0.2.0

func Mergeable(status string) bool

Mergeable reports whether a merge state lets a merge through now without bypassing anything: CLEAN or HAS_HOOKS. UNSTABLE merges too, but only after the user accepts the failing checks, which the caller decides.

func MergedKey added in v0.2.0

func MergedKey(r repo.Name, branch string) string

MergedKey is the key FetchMergedPullRequests answers a repository's branch under.

func NotificationsRefused added in v0.2.0

func NotificationsRefused(err error) bool

NotificationsRefused reports whether err is GitHub refusing the token the notifications listing itself, as it does a fine-grained token: 404, or 403 that is neither a rate limit (rateLimited) nor carries a Retry-After. A rate limit says to wait, not that the token can't read them; a 401 is the token itself, which WithToken borrows again.

func RateLimited added in v0.2.0

func RateLimited(err error) bool

RateLimited reports whether err is GitHub refusing a request for its rate limits (429, or 403 saying so), or asking the app to wait before the next (Retry-After), rather than refusing the request itself: a caller sending many reads stops at the first.

func Redact

func Redact(err error, tok Token) error

Redact returns err with every occurrence of the token's text replaced by [redacted]. errors.Is and errors.As still see the original chain, but the unredacted message is not reachable through errors.Unwrap. A nil error or an empty token returns err unchanged.

func WithToken added in v0.2.0

func WithToken[T any](ctx context.Context, tokens Tokens, call func(Token) (T, error)) (T, error)

WithToken runs call with a token from tokens. When GitHub refuses that token as bad credentials, which it does once the token is revoked or replaced, WithToken forgets it and runs call once more with a fresh one.

Types

type Assignable added in v0.2.0

type Assignable struct {
	Login string
	Name  string
}

Assignable is someone an issue can be assigned to: their login, and their name, or "".

type AutoMerge added in v0.2.0

type AutoMerge struct {
	// Method is the merge method it will use: MERGE, SQUASH, or REBASE; "" when auto-merge
	// is off.
	Method string

	// EnabledAt is when it was turned on, and EnabledBy who turned it on ("" when the
	// read does not say).
	EnabledAt time.Time
	EnabledBy string
}

AutoMerge is a pull request's auto-merge: GitHub merges it once its requirements are met.

func (AutoMerge) On added in v0.2.0

func (a AutoMerge) On() bool

On reports whether auto-merge is on.

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.

func (*Avatar) DataURL

func (a *Avatar) DataURL() string

DataURL returns the image as a data: URL, which the UI can show without a network request of its own.

type BranchQuery added in v0.2.0

type BranchQuery struct {
	Repo     repo.Name
	Branches []string
}

BranchQuery asks which of a repository's branch names were the head branch of a pull request that merged.

type BranchUpdate added in v0.2.0

type BranchUpdate struct {
	Message string
}

BranchUpdate is GitHub's answer to a branch update, which it makes in the background.

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 Check added in v0.2.0

type Check struct {
	// Kind is CheckKindRun or CheckKindStatus.
	Kind string

	// Name is the check run's name, or the status's context.
	Name string

	// Workflow is the GitHub Actions workflow a check run belongs to, or "".
	Workflow string

	// State is a check run's conclusion once it completed, or else its status (QUEUED,
	// IN_PROGRESS, ...); a status's state (SUCCESS, FAILURE, ERROR, PENDING, EXPECTED).
	State string

	// Outcome is where the check is counted: CheckPassed, CheckFailed, CheckPending, or
	// CheckSkipped.
	Outcome string

	// URL is the check's page, "" when it has none.
	URL string

	// Required reports a check the base branch requires; false off a pull request, where
	// GitHub isn't asked.
	Required bool
}

Check is one check run or commit status on a commit: a pull request's head, or the newest commit of a repository's default branch (ReleaseStatus.HeadCheckList).

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

	// Awaiting counts the head commit's GitHub Actions runs held until a maintainer approves
	// them, as a fork's runs are: suites that ended ACTION_REQUIRED with a workflow run.
	// GitHub counts none of them in State or the other counts, which can read SUCCESS while
	// they wait.
	Awaiting int
}

Checks counts the head commit's check runs and commit statuses by outcome.

type ChoreGate added in v0.2.0

type ChoreGate interface {
	// AllowChore asks to send one chore now, spending from the budget resource names
	// (ResourceCore). It counts the chore and returns nil when it may go, or returns an
	// error that says why not and when to try again.
	AllowChore(resource string) error

	// HoldWrites hears that GitHub asked the app to send no more writes for wait, which
	// holds the edits too.
	HoldWrites(wait time.Duration)
}

ChoreGate paces the chore lane's notification writes (chore), apart from the edits the WriteGate paces. *budget.Tracker implements it. It must return promptly.

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

	// StatusHosts are the only hosts FetchStatus reads a status page from, as host or
	// host:port; a read may be redirected only on its own host. They default to
	// DefaultStatusHosts; tests point them at a local server.
	StatusHosts []string

	// DownloadHosts are the only hosts DownloadAsset downloads from, and may be redirected
	// to, as host or host:port. They default to DefaultDownloadHosts; tests point them at a
	// local server.
	DownloadHosts []string

	// Rates hears the budget reading every API response carries, and what its request
	// spent, so the app's view of the budgets follows every call it makes. Nil hears none.
	Rates RateObserver

	// Writes paces the edits the client sends GitHub (see edits.go). Nil lets every edit
	// go.
	Writes WriteGate

	// Chores paces the chore lane's notification writes, apart from the edits and more
	// slowly (see edits.go). Nil refuses every chore.
	Chores ChoreGate
	// contains filtered or unexported fields
}

Client calls the GitHub REST and GraphQL APIs.

func NewClient

func NewClient(version string) *Client

NewClient returns a client for GitHub's public API that identifies itself with the app's slug and version.

func (*Client) AddAssignees added in v0.2.0

func (c *Client) AddAssignees(ctx context.Context, tok Token, ref item.Ref, logins []string) (*Edited, error)

AddAssignees assigns logins to the issue ref, with one REST request (POST /repos/{owner}/{repo}/issues/{number}/assignees). GitHub answers with the issue; a login missing from its assignees is one GitHub didn't assign, as it does for someone who can't be instead of refusing, and ErrEditIgnored is returned naming them.

func (*Client) AddComment added in v0.2.0

func (c *Client) AddComment(ctx context.Context, tok Token, ref item.Ref, body string) (*Comment, error)

AddComment adds a comment to the conversation of the pull request or issue ref, with one REST request (POST /repos/{owner}/{repo}/issues/{number}/comments). The review sheet uses it only to ask Dependabot to rebase, and the issue sheet for the user's comment, whose refusals are worded as a comment's (commentError).

func (*Client) AddLabels added in v0.2.0

func (c *Client) AddLabels(ctx context.Context, tok Token, ref item.Ref, names []string) ([]Label, error)

AddLabels adds the labels named names to the issue ref, with one REST request (POST /repos/{owner}/{repo}/issues/{number}/labels), and returns its labels after the edit. A name missing from them is one GitHub didn't add, as it does for an account without triage access instead of refusing, and ErrEditIgnored is returned naming it.

func (*Client) ApproveWorkflowRun added in v0.2.0

func (c *Client) ApproveWorkflowRun(ctx context.Context, tok Token, name repo.Name, runID int64) error

ApproveWorkflowRun approves the GitHub Actions workflow run with ID runID in the repository name, which GitHub holds until a maintainer approves it, as it does a fork's, with one REST request (POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve). It takes write access to the repository. GitHub documents it for a public fork's first-time contributor, and may refuse a run its other approval settings hold, which is worded (approveError) with what GitHub says. A run takes no head: the caller approves only the runs it read on the head the user saw.

func (*Client) CloseIssue added in v0.2.0

func (c *Client) CloseIssue(ctx context.Context, tok Token, ref item.Ref, reason string) (*IssueClosed, error)

CloseIssue closes the issue ref as reason, IssueReasonCompleted or IssueReasonNotPlanned, with one REST request (PATCH /repos/{owner}/{repo}/issues/{number}), and returns what GitHub says it is closed as. One GitHub left open returns ErrEditIgnored, and a refusal is worded as a close (closeError). Any other reason, and a ref whose kind is not an issue, are refused before anything is sent: the same path closes a pull request, which only ClosePull does. GitHub takes nothing to pin a close to, so a caller reads the issue first (FetchIssueState) and closes only over what the user saw.

func (*Client) ClosePull added in v0.2.0

func (c *Client) ClosePull(ctx context.Context, tok Token, ref item.Ref) error

ClosePull closes the pull request ref without merging it, with one REST request (PATCH /repos/{owner}/{repo}/pulls/{number}). GitHub answers with the pull request; one it left open returns ErrEditIgnored, and a refusal is worded as a close (closeError), never as a merge or a push. GitHub takes no head to pin a close to, so a caller reads the head first (FetchMergeState) and closes only what the user saw.

func (*Client) DownloadAsset added in v0.2.0

func (c *Client) DownloadAsset(ctx context.Context, rawURL string, w io.Writer, maxBytes int64) (int64, error)

DownloadAsset streams the public release file at rawURL into w, and returns how many bytes it wrote. The URL must be https on one of the download hosts (DownloadHosts), and so must every redirect, at most five of them. No token is sent: the repositories are public, and the download hosts are not the API, so the budget isn't touched. A download longer than maxBytes fails with ErrDownloadTooLarge, and one that sends nothing for 30 seconds with ErrDownloadStalled; ctx bounds the whole of it. What was written before a failure stays written: the caller throws it away.

func (*Client) EnableAutoMerge added in v0.2.0

func (c *Client) EnableAutoMerge(
	ctx context.Context, tok Token, ref item.Ref, nodeID, method, expectedHead string,
) (*AutoMerge, error)

EnableAutoMerge turns on auto-merge for the pull request ref, with node ID nodeID, with method, if its head is still expectedHead, with one GraphQL mutation. GitHub refuses it for a pull request it could merge right now, which returns ErrMergeableNow, and for a head that moved, which returns ErrPushedSince.

func (*Client) FetchAssignable added in v0.2.0

func (c *Client) FetchAssignable(ctx context.Context, tok Token, id, query string) ([]Assignable, error)

FetchAssignable reads the people the issue with node ID id can be assigned to whose login or name matches query, the first twenty, with one GraphQL request of one point. An issue GitHub can no longer find returns ErrIssueGone.

func (*Client) FetchAvatar

func (c *Client) FetchAvatar(ctx context.Context, rawURL string) (*Avatar, error)

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 item.Ref, 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

func (c *Client) FetchDetails(ctx context.Context, tok Token, ids []string, opts DetailOptions) (*Details, error)

FetchDetails reads the details of the items with the given node IDs, in concurrent batches, with what opts adds. GitHub's errors about single items it cannot resolve are not failures: those items are simply left out.

func (*Client) FetchInbox

func (c *Client) FetchInbox(ctx context.Context, tok Token) (*Inbox, error)

FetchInbox runs the batched inbox query: one POST to /graphql. The result includes the token's X-OAuth-Scopes header for CheckScopes.

func (*Client) FetchIssueState added in v0.2.0

func (c *Client) FetchIssueState(ctx context.Context, tok Token, id string) (*IssueState, error)

FetchIssueState reads whether the issue with node ID id is still open, whether the viewer may close it, and its newest comments, as of now, with one GraphQL request of one point. A close reads it first.

func (*Client) FetchIssueView added in v0.2.0

func (c *Client) FetchIssueView(ctx context.Context, tok Token, id string, opts DetailOptions) (*IssueView, error)

FetchIssueView reads what the issue sheet shows about the issue with node ID id, as of now, with what opts adds to its card's details, with one GraphQL request. When GitHub refuses the projects opts asks for, for want of a scope, it reads it again without them, and when the answer is larger than the client reads, again with a smaller page of the timeline.

func (*Client) FetchItem

func (c *Client) FetchItem(ctx context.Context, tok Token, id string, opts DetailOptions) (*ItemUpdate, error)

FetchItem reads one pull request or issue, by node ID, as of now, with what opts adds to its details. 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 []item.Ref) (map[string]ItemState, error)

FetchItemStates reads the state of each pull request or issue in refs, as of now, keyed by each ref's Key, so a ref finds its answer whatever its casing. 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. A ref's Kind is not needed: the number alone picks the item. A ref that names no item fails the call before anything is sent.

func (*Client) FetchItems added in v0.2.0

func (c *Client) FetchItems(ctx context.Context, tok Token, ids []string, opts DetailOptions) (*ItemUpdates, error)

FetchItems reads several pull requests or issues, by node ID, as of now, with what opts adds to their details, in one request, as FetchItem reads one. It reads at most ItemsMax; the caller asks for no more.

func (*Client) FetchLatestComment added in v0.2.0

func (c *Client) FetchLatestComment(ctx context.Context, tok Token, rawURL string) (*CommentAuthor, error)

FetchLatestComment reads who wrote a comment, from its API URL as a notification gives it (Thread.LatestCommentURL), with one REST request. The URL must be the client's API root's scheme and host, with exactly the path /repos/{owner}/{name}/issues/comments/{id} or /repos/{owner}/{name}/pulls/comments/{id}; anything else, the subject's own URL included, is refused with ErrInvalidCommentURL before anything is sent. Only the path built again from what was checked is sent, never the URL as given.

func (*Client) FetchLatestReleases added in v0.2.0

func (c *Client) FetchLatestReleases(ctx context.Context, tok Token, repos []repo.Name) (map[string]LatestRelease, error)

FetchLatestReleases reads the latest release of each repository in one query, keyed by each repository's Key. A repository with no release, or one GitHub can't find, is left out; any other error fails the whole call. The query's cost (one point) is counted like every other's.

func (*Client) FetchLoginAvatar added in v0.2.0

func (c *Client) FetchLoginAvatar(ctx context.Context, login string) (*Avatar, error)

FetchLoginAvatar downloads the profile picture of the account with login, LoginAvatarSize pixels square, from the avatar host by the login alone, as FetchAvatar does: no API request, so no token and no point of the budget. GitHub answers a login it doesn't know with its default picture. A login only a user or an organization could have is asked about (validLogin): a bot's, which GitHub answers with a pattern made from its name rather than the app's picture, fails with ErrAvatarLogin.

func (*Client) FetchMergeState added in v0.2.0

func (c *Client) FetchMergeState(ctx context.Context, tok Token, id string) (*MergeState, error)

FetchMergeState reads the merge state of the pull request with node ID id, as of now, with one GraphQL request of one point. A merge reads it first, so it never merges what branch protection would block: GitHub's REST merge lets an admin through.

func (*Client) FetchMergedPullRequests added in v0.2.0

func (c *Client) FetchMergedPullRequests(ctx context.Context, tok Token, queries []BranchQuery) (map[string][]MergedPR, error)

FetchMergedPullRequests returns, under MergedKey, the merged pull requests whose head branch had each name asked about, newest first, at most five each. A name no merged pull request had is left out, and so is a repository GitHub cannot resolve; any other error fails the whole call, so a passing problem never makes a branch look merged. A name that is not valid UTF-8 is never asked about, so it is left out too: a query could only ask about it rewritten, and so about another branch.

func (*Client) FetchPullDiff added in v0.2.0

func (c *Client) FetchPullDiff(ctx context.Context, tok Token, ref item.Ref, head string) (*PullDiff, error)

FetchPullDiff lists the files a pull request changes with their diffs, as GitHub's REST API shows them, at one head commit: head, the head already known (read first when it is ""). Each listed file names the commit it was read at, so a list whose files all name head, and that holds every file, costs no second reading of the head; otherwise the head is read after the list, as FetchChangedFiles does, and a list read while the pull request was pushed to is read again for the new head. ErrHeadMoved is returned when the head moves again.

It costs one REST request per 100 files, and one more when the head must be read.

func (*Client) FetchPullHead

func (c *Client) FetchPullHead(ctx context.Context, tok Token, ref item.Ref) (*PullHead, error)

FetchPullHead reads a pull request's head commit and size as of now, with one REST request.

func (*Client) FetchPullReview added in v0.2.0

func (c *Client) FetchPullReview(ctx context.Context, tok Token, id string) (*PullReview, error)

FetchPullReview reads what the review sheet shows about the pull request with node ID id, as of now, with one GraphQL request, and again with a smaller page of its conversation when the answer is larger than the client reads.

func (*Client) FetchRateLimits

func (c *Client) FetchRateLimits(ctx context.Context, tok Token) (*RateLimits, error)

FetchRateLimits reads the REST, GraphQL, and search budgets from GET /rate_limit, which does not count against them.

func (*Client) FetchReleaseCompare added in v0.2.0

func (c *Client) FetchReleaseCompare(
	ctx context.Context, tok Token, reqs []CompareRequest, answered ReleaseAnswered,
) (map[string]ReleaseCompare, error)

FetchReleaseCompare reads, for each request, how far its branch is ahead of its tag, and the newest commits since the tag. It is the second round after FetchReleaseStatus, whose tags tell the caller which tag to compare with. The answers are keyed by each request's Repo.Key, so a repository is compared once: a later request for one already asked about is dropped. A repository, tag, or branch GitHub can't resolve, or a repository it won't show the token, is left out; any other error fails the whole call. A request without a tag or a branch fails the call before anything is sent. The batching, and answered, are FetchReleaseStatus's.

func (*Client) FetchReleaseProgress added in v0.2.0

func (c *Client) FetchReleaseProgress(ctx context.Context, tok Token, req ProgressRequest) (*ReleaseProgress, error)

FetchReleaseProgress reads how a release's workflow on GitHub goes, as of now: the release GitHub has for the tag, with one GraphQL query of one point, and, unless that release is published, the tag's own workflow runs, with one REST request (GET /repos/{owner}/{name}/actions/runs, by the push event, the tag as the run's branch, and the tag's commit), which P0 found names a tag push's runs exactly. The budget counts both, like every other request. A repository GitHub can't find fails with ErrRepositoryNotFound.

func (*Client) FetchReleaseStatus added in v0.2.0

func (c *Client) FetchReleaseStatus(
	ctx context.Context, tok Token, repos []repo.Name, answered ReleaseAnswered,
) (map[string]ReleaseStatus, error)

FetchReleaseStatus reads, for each repository, what a release needs to know before it compares anything: whether it is archived, the viewer's access, the default branch and its newest commit, and its newest tags. The answers are keyed by each repository's Key, and a repository named twice is asked about once. A repository GitHub can't resolve, or won't show the token, is left out; any other error fails the whole call. The repositories are asked about 15 to a query, at most four queries at a time, each costing one point, which the budget hears. answered, when set, hears each query GitHub answers (see ReleaseAnswered).

func (*Client) FetchRepoLabels added in v0.2.0

func (c *Client) FetchRepoLabels(ctx context.Context, tok Token, id string) (*RepoLabels, error)

FetchRepoLabels reads the labels of the repository of the issue with node ID id, the first hundred in name order, with one GraphQL request of one point. An issue GitHub can no longer find returns ErrIssueGone.

func (*Client) FetchRepoReleaseStatus added in v0.2.0

func (c *Client) FetchRepoReleaseStatus(ctx context.Context, tok Token, name repo.Name) (ReleaseStatus, bool, error)

FetchRepoReleaseStatus reads one repository's status as FetchReleaseStatus does, and with it each of its newest commit's check runs and commit statuses (HeadCheckList), in the same query, for the same one point, which the budget hears. ok is false when GitHub can't resolve the repository or won't show it to the token.

func (*Client) FetchSignIn added in v0.3.0

func (c *Client) FetchSignIn(ctx context.Context, tok Token) (SignIn, error)

FetchSignIn returns the account tok belongs to and the scopes the token reports, with the same one-point GraphQL query FetchViewer sends, so the setup can tell the user whether the GitHub CLI's sign-in gives the inbox what it needs.

func (*Client) FetchStatus added in v0.2.0

func (c *Client) FetchStatus(ctx context.Context, req StatusRequest) (StatusAnswer, error)

FetchStatus reads a status page's summary: one GET of req.Path from req.Host, which must be one of the client's status hosts. A status page isn't the API, so the read sends no token and spends no point of any budget. With an ETag it is conditional, and a 304 carries no body. Only https is spoken, redirects may not leave the request's host, and a summary larger than 1 MiB is refused. It only reads the bytes: what they say is the caller's to decode.

func (*Client) FetchTimeline added in v0.2.0

func (c *Client) FetchTimeline(ctx context.Context, tok Token, kind item.Kind, id, before string) (*TimelinePage, error)

FetchTimeline reads the page of the timeline of the issue or pull request (kind) with node ID id before the cursor before, with one GraphQL request. An issue GitHub can no longer find returns ErrIssueGone, and a pull request ErrPullGone.

func (*Client) FetchViewer added in v0.2.0

func (c *Client) FetchViewer(ctx context.Context, tok Token) (string, error)

FetchViewer returns the login of the account tok belongs to, with a one-point GraphQL query, so an edit can be checked against the account whose inbox the user sees.

func (*Client) ListThreads added in v0.2.0

func (c *Client) ListThreads(ctx context.Context, tok Token, q ThreadQuery) (*ThreadPage, error)

ListThreads reads one page of the user's notifications, as the web inbox shows them: read and unread, but not done, newest updated first. Its URL is always built from the same fixed parameters, and only the page changes; the next page's number is read from GitHub's Link header, which is never followed as given. Page 1 sent with the ETag of its last answer, which GitHub answers 304 Not Modified while page 1 is as it was, costs nothing; a 304 says nothing of the later pages (ThreadPage.NotModified).

func (*Client) MarkThreadDone added in v0.2.0

func (c *Client) MarkThreadDone(ctx context.Context, tok Token, id int64) error

MarkThreadDone marks the notification thread id done, which takes it out of the user's inbox on GitHub, with one REST request through the chore lane (DELETE /notifications/threads/{id}, which GitHub answers 204 No Content). A thread GitHub can't find is ErrThreadNotFound, which the caller may take as done already.

func (*Client) MarkThreadRead added in v0.2.0

func (c *Client) MarkThreadRead(ctx context.Context, tok Token, id int64) error

MarkThreadRead marks the notification thread id read, which leaves it in the user's inbox on GitHub, with one REST request through the chore lane (PATCH /notifications/threads/{id}, which GitHub answers 205 Reset Content). A thread GitHub can't find is ErrThreadNotFound.

func (*Client) MergePull added in v0.2.0

func (c *Client) MergePull(ctx context.Context, tok Token, ref item.Ref, in MergeInput) (*Merged, error)

MergePull merges the pull request ref, if its head is still in.SHA, with one REST request (PUT /repos/{owner}/{repo}/pulls/{number}/merge). A head that moved returns ErrPushedSince, and a pull request GitHub won't merge yet a *NotMergeableError.

For an admin, GitHub's REST merge goes through branch protection unasked, so a caller reads the merge state first (FetchMergeState) and merges only one that is mergeable.

func (*Client) ParseSubject added in v0.2.0

func (c *Client) ParseSubject(raw string) (item.Ref, bool)

ParseSubject reads a notification subject's API URL into the pull request or issue it names: the client's API root's scheme and host, and exactly the path /repos/{owner}/{name}/pulls/{number} or /repos/{owner}/{name}/issues/{number}, with a valid owner and name and a positive number written plainly. Anything else, "" (a null URL, as a check suite's) included, names no item: ok is false, and the Ref is zero, with Kind "".

func (*Client) RemoveAssignee added in v0.2.0

func (c *Client) RemoveAssignee(ctx context.Context, tok Token, ref item.Ref, login string) (*Edited, error)

RemoveAssignee takes login off the assignees of a pull request or issue, with one REST request (DELETE /repos/{owner}/{repo}/issues/{number}/assignees). GitHub answers with the item as it stands after the edit; when login is still one of its assignees, GitHub ignored the change, and ErrEditIgnored is returned.

func (*Client) RemoveLabel added in v0.2.0

func (c *Client) RemoveLabel(ctx context.Context, tok Token, ref item.Ref, name string) ([]Label, error)

RemoveLabel takes the label named name off the issue ref, with one REST request (DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name}), and returns the labels left, or none for a label the issue no longer has, which GitHub answers as not found. A name still among them is ErrEditIgnored.

func (*Client) RemoveReviewRequest added in v0.2.0

func (c *Client) RemoveReviewRequest(ctx context.Context, tok Token, ref item.Ref, login string) (*Edited, error)

RemoveReviewRequest takes login off the reviewers a pull request asks, with one REST request (DELETE /repos/{owner}/{repo}/pulls/{number}/requested_reviewers). GitHub answers with who the pull request still asks: when that is still login by name, GitHub ignored the change, and ErrEditIgnored is returned. A team login is in is not changed: GitHub takes a team's request off for every member or for none.

func (*Client) SubmitReview added in v0.2.0

func (c *Client) SubmitReview(ctx context.Context, tok Token, ref item.Ref, in ReviewInput) (*SubmittedReview, error)

SubmitReview submits a review of the pull request ref, pinned to in.CommitID, with one REST request (POST /repos/{owner}/{repo}/pulls/{number}/reviews). GitHub answers with the review; one left pending, which a review with an event never is, returns ErrEditIgnored.

func (*Client) UpdateBranch added in v0.2.0

func (c *Client) UpdateBranch(ctx context.Context, tok Token, ref item.Ref, expectedHead string) (*BranchUpdate, error)

UpdateBranch merges the base branch into the pull request ref's branch, if its head is still expectedHead, with one REST request (PUT /repos/{owner}/{repo}/pulls/{number}/update-branch). GitHub makes the update in the background.

type Comment added in v0.2.0

type Comment struct {
	ID        int64
	URL       string
	CreatedAt time.Time
}

Comment is a conversation comment as GitHub answered its creation.

type CommentAuthor added in v0.2.0

type CommentAuthor struct {
	// Login is the author's login, "" when GitHub names none, as for a deleted account.
	Login string

	// Type is the author's type, in GitHub's words: User, Bot, Organization, and others.
	Type string
}

CommentAuthor is who wrote a comment.

type CommentMark added in v0.2.0

type CommentMark struct {
	ID        string
	CreatedAt time.Time
	Author    string
	Mine      bool
}

CommentMark is a comment as a close checks it: its ID, when it was written, by whom, and whether by the viewer.

type CompareRequest added in v0.2.0

type CompareRequest struct {
	Repo repo.Name

	// Tag is the tag's name, as in v1.4.2.
	Tag string

	// Branch is the branch's name, as in master.
	Branch string
}

CompareRequest asks how far a repository's branch is ahead of one of its tags.

type DetailOptions added in v0.2.0

type DetailOptions struct {
	// Projects reads the projects each issue is in, with its status in each, which needs
	// the token's read:project scope. When GitHub refuses them for want of a scope, the
	// request is sent again without them, and the answer says so.
	Projects bool
}

DetailOptions choose what a details request reads beyond the fields it always reads.

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

	// ProjectsRefused reports that GitHub refused the projects for want of a scope, so
	// the details were read without them.
	ProjectsRefused bool
}

Details is what FetchDetails learned.

func (*Details) Add

func (d *Details) Add(other *Details)

Add merges other into d: its items, its requests, and its cost. The budget reading kept is the latest of the two (see QueryRate.Later).

type Edited added in v0.2.0

type Edited struct {
	// UpdatedAt is the item's last update on GitHub, the edit included.
	UpdatedAt time.Time

	// ReviewRequests is who a pull request still asks to review, after
	// RemoveReviewRequest. It is zero after RemoveAssignee.
	ReviewRequests ReviewRequests
}

Edited is a pull request or issue as GitHub answered an edit to it.

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 IssueClosed added in v0.2.0

type IssueClosed struct {
	// Reason is what GitHub says the issue is closed as, in its REST words
	// (IssueReasonCompleted, IssueReasonNotPlanned, or "duplicate"), or "" when it doesn't
	// say. It is the reason asked for, unless someone closed the issue first: GitHub
	// ignores a reason unless the close changes the issue's state.
	Reason string

	// ClosedBy is the login GitHub says closed the issue, "" when it doesn't say: the
	// viewer's, unless someone closed it first.
	ClosedBy string
}

IssueClosed is GitHub's answer to the close of an issue.

type IssueState added in v0.2.0

type IssueState struct {
	// Found is false when GitHub could not resolve the ID; the rest is zero then.
	Found bool

	// State is StateOpen or StateClosed, and StateReason why (see the StateReason values).
	State       string
	StateReason string

	// CanClose says whether GitHub lets the viewer close it.
	CanClose bool

	// Comments counts its comments, and Recent are the newest ten, oldest first.
	Comments int
	Recent   []CommentMark
}

IssueState is what FetchIssueState read about an issue, as of now.

type IssueType added in v0.2.0

type IssueType struct {
	Name        string
	Description string

	// Color is the type's color as "#rrggbb", or "" for one this build doesn't know.
	Color string
}

IssueType is an issue's type, such as Bug.

type IssueView added in v0.2.0

type IssueView struct {
	// Update is the item and its card's details, as FetchItem reads them. When
	// Update.Found is false, GitHub could not resolve the ID and the rest is zero.
	Update ItemUpdate

	// Body is the description, as markdown, and LastEditedAt when it was last edited;
	// zero when it never was.
	Body         string
	LastEditedAt time.Time

	// StateReason is why it is closed (StateReasonCompleted, StateReasonNotPlanned, or
	// StateReasonDuplicate), StateReasonReopened for one reopened, and "" for one never
	// closed. ClosedAt is when it was last closed; zero while it is open.
	StateReason string
	ClosedAt    time.Time

	// Locked reports a locked conversation, which only people with write access can comment
	// on, and LockReason why: OFF_TOPIC, TOO_HEATED, RESOLVED, SPAM, or "".
	Locked     bool
	LockReason string

	// What GitHub lets the viewer do now: close it, reopen it, and edit it (its labels and
	// assignees included); and whether the viewer opened it.
	ViewerCanClose  bool
	ViewerCanReopen bool
	ViewerCanUpdate bool
	ViewerDidAuthor bool

	// Type is the issue's type, zero when it has none.
	Type IssueType

	// Milestone is the issue's milestone, nil when it is in none.
	Milestone *Milestone

	// DuplicateOf is the issue it was closed as a duplicate of, and Parent the issue it is
	// a sub-issue of; nil for none, or one the viewer cannot see.
	DuplicateOf *ItemRef
	Parent      *ItemRef

	// Assignees and Participants are the first ten of each, and how many there are.
	Assignees    People
	Participants People

	// SubIssues are its first 25 sub-issues; Update.Details.SubIssues counts them all.
	SubIssues []ItemRef

	// Fixes are the first ten pull requests that close it once merged, closed ones
	// included, and FixCount how many there are that the viewer can see.
	Fixes    []LinkedPull
	FixCount int

	// Reactions counts the description's reactions, each kind with any.
	Reactions []Reaction

	// LatestComment is its newest comment, nil when it has none.
	LatestComment *CommentMark

	// Timeline is the newest page of its timeline.
	Timeline TimelinePage
}

IssueView is what FetchIssueView read about one issue.

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.

func (Item) Closed

func (i Item) Closed() bool

Closed reports an item closed or merged. An item whose state is unknown is not.

func (Item) Ref added in v0.2.0

func (i Item) Ref() item.Ref

Ref names the item: its repository, number, and kind.

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

	// ReviewRequests is who a pull request asks to review, as of the read, at most
	// MaxReviewRequests in all. For a pull request GitHub answered for, both lists are
	// never nil, empty when it asks no one; for an issue they are nil.
	ReviewRequests ReviewRequests

	// AutoMerge is a pull request's auto-merge, when someone turned it on; zero when it is
	// off, and for an issue.
	AutoMerge AutoMerge

	// Projects lists the open projects an issue is in, in GitHub's order, when they were
	// read (see DetailOptions). It is nil when they were not, when the issue is in none,
	// and for a pull request.
	Projects []ProjectItem

	// SubIssues counts an issue's sub-issues, and those closed as done. It is zero for a
	// pull request and for an issue without sub-issues.
	SubIssues SubIssues
}

ItemDetails is what an inbox card shows about one pull request or issue. The pull request fields are zero for an issue.

type ItemRef

type ItemRef struct {
	IsPR bool

	// Repo is its repository as "owner/name".
	Repo   string
	Number int
	Title  string
	URL    string

	// State is StateOpen, StateClosed, or StateMerged.
	State string

	// StateReason is a closed issue's reason (see the StateReason values), "" otherwise.
	StateReason string

	// IsDraft reports a draft pull request.
	IsDraft bool
}

ItemRef is a pull request or issue another names: a sub-issue, a parent, a duplicate, a fix, or the other side of a timeline event.

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

	// HeadRef is the name of a pull request's head branch, as in feature-x; "" for an
	// issue.
	HeadRef 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

	// ProjectsRefused reports that GitHub refused the projects for want of a scope, so
	// the item was read without them.
	ProjectsRefused bool
}

ItemUpdate is what FetchItem learned about one item.

type ItemUpdates added in v0.2.0

type ItemUpdates struct {
	// Items are the items GitHub answered for, by node ID, each Found. One it answered
	// with null for is left out, never read as gone: without each error's path, an item
	// deleted can't be told from a passing problem, and the next whole refresh tells.
	Items map[string]ItemUpdate

	// RateLimit is the GraphQL budget after the request, including its cost.
	RateLimit QueryRate

	// ProjectsRefused reports that GitHub refused the projects for want of a scope, so
	// the items were read without them.
	ProjectsRefused bool
}

ItemUpdates is what FetchItems learned about several items.

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 LatestRelease added in v0.2.0

type LatestRelease struct {
	// Tag is the release's tag, as in v1.29.5.
	Tag string

	// URL is the release's page on GitHub.
	URL string

	// PublishedAt is when the release was published.
	PublishedAt time.Time

	// Assets are the release's files.
	Assets []ReleaseAsset
}

LatestRelease is a repository's latest release as GitHub reports it: the newest one that is neither a draft nor a prerelease.

type LineComment added in v0.2.0

type LineComment struct {
	Path string

	// Line is the comment's last line, on Side (SideLeft or SideRight).
	Line int
	Side string

	// StartLine is a multi-line comment's first line, on StartSide; 0 for one line.
	StartLine int
	StartSide string

	Body string
}

LineComment is one line comment of a review.

type LinkedPull added in v0.2.0

type LinkedPull struct {
	Ref ItemRef

	// Base is the branch it merges into, and MergedAt when it merged; zero while it hasn't.
	Base     string
	MergedAt time.Time

	// ReviewDecision is APPROVED, CHANGES_REQUESTED, REVIEW_REQUIRED, or "".
	ReviewDecision string

	// Checks is its head commit's overall result: SUCCESS, FAILURE, ERROR, PENDING,
	// EXPECTED, or "" for none.
	Checks string
}

LinkedPull is a pull request that closes an issue once it merges: one whose description says so, or one someone linked to the issue by hand.

type MergeInput added in v0.2.0

type MergeInput struct {
	// SHA is the head commit the user saw; GitHub refuses the merge when the head moved.
	SHA string

	// Method is MergeMethodMerge, MergeMethodSquash, or MergeMethodRebase.
	Method string
}

MergeInput is a merge to make.

type MergeState added in v0.2.0

type MergeState struct {
	// Found is false when GitHub could not resolve the ID; the rest is zero then.
	Found bool

	// Status is one of the MergeState values.
	Status string

	// Head is the head commit's SHA.
	Head string

	// State is StateOpen, StateClosed, or StateMerged.
	State string

	IsDraft    bool
	MergeQueue bool
	AutoMerge  AutoMerge

	// CanBypass says whether GitHub lets the viewer merge past the branch's rules.
	CanBypass bool
}

MergeState is what FetchMergeState read about a pull request, as of now.

type Merged added in v0.2.0

type Merged struct {
	// SHA is the commit the merge made.
	SHA string
}

Merged is a merge as GitHub answered it.

type MergedPR added in v0.2.0

type MergedPR struct {
	Number   int
	Title    string
	URL      string
	MergedAt time.Time

	// HeadOID is the commit its head branch was at, which GitHub keeps as the pull
	// request's head.
	HeadOID string
}

MergedPR is a merged pull request, as the cleanup of merged branches shows it.

type Milestone added in v0.2.0

type Milestone struct {
	Title string
	URL   string

	// DueOn is the day it is due, at midnight UTC; zero when it has no due date.
	DueOn time.Time

	// State is OPEN or CLOSED.
	State string

	// Progress is how far along it is, as a percentage of its issues and pull requests
	// closed.
	Progress float64
}

Milestone is the milestone an issue is in.

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 NotMergeableError added in v0.2.0

type NotMergeableError struct {
	// Reason is GitHub's own words, as in "At least 1 approving review is required by
	// reviewers with write access."
	Reason string

	// MergeQueue reports a branch that merges only through its merge queue.
	MergeQueue bool
	// contains filtered or unexported fields
}

NotMergeableError is GitHub refusing a merge for what the pull request still needs: a required review or check, a conflict, or a merge queue. It matches ErrNotMergeable.

func (*NotMergeableError) Error added in v0.2.0

func (e *NotMergeableError) Error() string

Error says why GitHub won't merge.

func (*NotMergeableError) Is added in v0.2.0

func (e *NotMergeableError) Is(target error) bool

Is reports whether target is ErrNotMergeable.

func (*NotMergeableError) Unwrap added in v0.2.0

func (e *NotMergeableError) Unwrap() error

Unwrap returns GitHub's refusal, so its status stays readable.

type People added in v0.2.0

type People struct {
	Logins []string
	Total  int
}

People are the first few logins of an issue's assignees or participants, and how many there are in all.

type ProgressRequest added in v0.2.0

type ProgressRequest struct {
	Repo repo.Name

	// Tag is the release's tag, as in v1.4.3, and Commit the full SHA of the commit it
	// tags.
	Tag    string
	Commit string
}

ProgressRequest asks how a release's workflow goes.

type ProjectField added in v0.2.0

type ProjectField struct {
	// Name is the field's name, such as "Priority".
	Name string

	// Value is the value as the project shows it: an option's name, a number, text, a date
	// such as "Jun 27, 2026", or an iteration's title.
	Value string

	// Color is a single-select option's color as "#rrggbb", and "" for any other value.
	Color string
}

ProjectField is an issue's value in one of a project's fields.

type ProjectItem added in v0.2.0

type ProjectItem struct {
	// Title is the project's title, and URL its page on GitHub.
	Title string
	URL   string

	// Status is the issue's option in the project's Status field, "" when it has none.
	Status string

	// StatusColor is the status option's color as "#rrggbb", "" when it has none.
	StatusColor string

	// Fields are the issue's values in the project's other fields, such as Priority or
	// Size, in GitHub's order. Fields without a value, the Status field, and GitHub's
	// built-in fields are left out.
	Fields []ProjectField
}

ProjectItem is an issue's place in one GitHub project.

type ProjectScope added in v0.2.0

type ProjectScope int

ProjectScope is what a token's scopes say about reading GitHub Projects.

const (
	// ProjectScopeUnverified is a token that reports no scopes, such as a fine-grained
	// token: only asking GitHub tells whether it reads projects.
	ProjectScopeUnverified ProjectScope = iota

	// ProjectScopeGranted is a token with the read:project scope, or the project scope,
	// which includes it.
	ProjectScopeGranted

	// ProjectScopeMissing is a token that reports its scopes, neither of them among them.
	ProjectScopeMissing
)

func ProjectsScope added in v0.2.0

func ProjectsScope(header string) ProjectScope

ProjectsScope reads a response's X-OAuth-Scopes header for read access to GitHub Projects. An empty header is ProjectScopeUnverified.

type PullDiff added in v0.2.0

type PullDiff struct {
	// Head is the head commit the files belong 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 []PullFile

	// Complete reports that Files holds every changed file.
	Complete bool
}

PullDiff is a pull request's changed files, with their diffs, at one head commit.

type PullFile added in v0.2.0

type PullFile struct {
	// Path is the file's path after the change, and PreviousPath a renamed or copied
	// file's path before it, or "".
	Path         string
	PreviousPath string

	// Status is GitHub's word for the change, as ChangedFile's.
	Status string

	// BlobSHA is the file's blob as GitHub lists it.
	BlobSHA string

	// Patch is the file's diff as GitHub shows it, without the file headers. HasPatch is
	// false when GitHub shows none: for a binary file, and one too large to show.
	Patch    string
	HasPatch bool

	Additions int
	Deletions int
}

PullFile is one file a pull request changes, with its diff.

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 PullReview added in v0.2.0

type PullReview struct {
	// Update is the item and its card's details, as FetchItem reads them. When
	// Update.Found is false, GitHub could not resolve the ID and the rest is zero.
	Update ItemUpdate

	// Body is the description, as markdown, and LastEditedAt when it was last edited; zero
	// when it never was.
	Body         string
	LastEditedAt time.Time

	// Reactions counts the description's reactions, each kind with any.
	Reactions []Reaction

	// BaseRef is the branch the pull request merges into.
	BaseRef string

	// MergeState is one of the MergeState values.
	MergeState string

	// MergeQueue reports a base branch that merges only through its merge queue.
	MergeQueue bool

	// ViewerDidAuthor reports the viewer's own pull request.
	ViewerDidAuthor bool

	// ViewerCanUpdateBranch and ViewerCanEnableAutoMerge say whether the viewer may bring
	// the branch up to date with its base, and turn on auto-merge, as GitHub judges it now.
	ViewerCanUpdateBranch    bool
	ViewerCanEnableAutoMerge bool

	// ViewerCanBypass says whether GitHub lets the viewer merge past the branch's rules, as
	// a repository admin can, without waiting for what they require.
	ViewerCanBypass bool

	// ViewerCanClose says whether GitHub lets the viewer close the pull request (its
	// Closable viewerCanClose).
	ViewerCanClose bool

	// ViewerReview is the viewer's own latest review: its state and the commit it was left
	// on; zero when the viewer has not reviewed.
	ViewerReview ReviewMark

	// PendingReviews counts the viewer's reviews started on GitHub and not submitted.
	PendingReviews int

	// AutoMerge is the pull request's auto-merge, zero when it is off.
	AutoMerge AutoMerge

	// Reviews are each reviewer's latest review, in GitHub's order.
	Reviews []Review

	// Checks are the head commit's checks and statuses, the first 100.
	Checks []Check

	// Unrun are the head commit's check suites, of its first 50, that ended without any
	// check among Checks and without passing: a fork's workflow runs waiting for a
	// maintainer's approval, and runs that failed to start. GitHub counts them in the merge
	// state (UNSTABLE) though no check shows them.
	Unrun []UnrunSuite

	// Closes are the first ten issues the pull request closes once it merges, the ones its
	// description names and the ones linked to it by hand, and CloseCount how many there are
	// that the viewer can see.
	Closes     []ItemRef
	CloseCount int

	// Timeline is the newest page of its conversation.
	Timeline TimelinePage
}

PullReview is what FetchPullReview read about one pull request.

type QueryRate

type QueryRate struct {
	Cost      int
	Limit     int
	Remaining int
	Used      int
	ResetAt   time.Time
}

QueryRate is the GraphQL budget reported by the query itself.

func (QueryRate) Later added in v0.2.0

func (r QueryRate) Later(o QueryRate) bool

Later reports whether r was read after o: in a later window, or in the same window with more used (or, used alike, less left), since used only grows within a window. Requests sent side by side answer in any order, so the last to answer is not always the latest reading.

type Rate

type Rate struct {
	Limit     int
	Used      int
	Remaining int
	ResetAt   time.Time
}

Rate is one API budget.

type RateLimits

type RateLimits struct {
	Core    Rate
	GraphQL Rate
	Search  Rate
}

RateLimits holds the budgets the rate gauge shows.

type RateObserver added in v0.2.0

type RateObserver interface {
	ObserveRate(reading RateReading, spent int)
}

RateObserver hears every budget reading the client's responses carry, with what the request spent from that budget: a GraphQL query's reported cost, one for a REST call, and nothing for GET /rate_limit, which is free. It must return promptly; requests sent side by side call it concurrently.

type RateReading added in v0.2.0

type RateReading struct {
	// Resource names the budget: ResourceGraphQL, ResourceCore, ResourceSearch, or
	// another GitHub keeps.
	Resource string

	Limit     int
	Remaining int
	Used      int

	// ResetAt is when the budget refills in full.
	ResetAt time.Time
}

RateReading is one budget as GitHub reported it with a response.

type Reaction added in v0.2.0

type Reaction struct {
	// Content is GitHub's name for the reaction: THUMBS_UP, THUMBS_DOWN, LAUGH, HOORAY,
	// CONFUSED, HEART, ROCKET, or EYES.
	Content string
	Count   int
}

Reaction counts one kind of reaction.

type ReleaseAnswered added in v0.2.0

type ReleaseAnswered func(n int)

ReleaseAnswered hears a release query's progress: once for each batch GitHub answered, with how many of the call's repositories or requests it held, so a caller can count them off against all it asked about. It is called from the batches' own goroutines, perhaps at once, and must return promptly. A nil ReleaseAnswered hears nothing.

type ReleaseAsset added in v0.2.0

type ReleaseAsset struct {
	// Name is the file's name, as in mage-x_1.29.5_darwin_arm64.tar.gz.
	Name string

	// URL is where it downloads from.
	URL string

	// Size is its size in bytes.
	Size int64

	// Digest is GitHub's digest of it, as in sha256:<hex>, or "" when GitHub has none.
	Digest string
}

ReleaseAsset is one file of a release.

type ReleaseCommit added in v0.2.0

type ReleaseCommit struct {
	// OID is the commit's SHA.
	OID string

	// Headline is the first line of its message.
	Headline string

	// CommittedAt is when it was committed, in UTC.
	CommittedAt time.Time
}

ReleaseCommit is a commit as a release lists it.

type ReleaseCompare added in v0.2.0

type ReleaseCompare struct {
	// AheadBy is how many commits the branch has that the tag does not.
	AheadBy int

	// TotalCommits is how many commits the comparison holds, which can exceed len(Commits).
	TotalCommits int

	// Commits are the newest of those commits, at most 10, as GitHub lists them. Never nil.
	Commits []ReleaseCommit
}

ReleaseCompare is how far a branch is ahead of a tag.

type ReleaseProgress added in v0.2.0

type ReleaseProgress struct {
	// Release is the release GitHub has for the tag, or nil while it has none, as before
	// the workflow drafts it.
	Release *TagRelease

	// Runs are the tag's own workflow runs: those a push of the tag started at its commit,
	// newest first. They are left unread, and empty, once the release is published. Never
	// nil.
	Runs []WorkflowRun
}

ReleaseProgress is how a release's workflow on GitHub goes, as of now.

func (ReleaseProgress) Published added in v0.2.0

func (p ReleaseProgress) Published() bool

Published reports the release published: GitHub has it, it isn't a draft, and it has a time it was published.

type ReleaseStatus added in v0.2.0

type ReleaseStatus struct {
	// Archived reports an archived repository, which takes no pushes.
	Archived bool

	// ViewerPermission is the viewer's access: ADMIN, MAINTAIN, WRITE, TRIAGE, or READ ("" when
	// GitHub did not say).
	ViewerPermission string

	// DefaultBranch is the default branch's name ("" for an empty repository).
	DefaultBranch string

	// Head is the default branch's newest commit; zero for an empty repository.
	Head ReleaseCommit

	// HeadChecks is the rollup state of Head's checks and statuses: SUCCESS, PENDING,
	// FAILURE, ERROR, or EXPECTED, and "" when it has none.
	HeadChecks string

	// HeadCheckList is each of Head's check runs and commit statuses, at most 100, which
	// only FetchRepoReleaseStatus reads; FetchReleaseStatus leaves it nil.
	HeadCheckList []Check

	// Tags are the repository's newest tags by commit date, newest first, at most 20. Never
	// nil.
	Tags []ReleaseTag
}

ReleaseStatus is what GitHub says about a repository a release is made from.

type ReleaseTag added in v0.2.0

type ReleaseTag struct {
	// Name is the tag's name, as in v1.4.2.
	Name string

	// OID is the object the tag points at: the commit for a lightweight tag, the tag object
	// for an annotated one.
	OID string

	// CommitOID is the commit the tag marks: OID for a lightweight tag, and what the tag
	// object points at for an annotated one. It is "" when that is not a commit.
	CommitOID string
}

ReleaseTag is one of a repository's tags.

type RepoLabel added in v0.2.0

type RepoLabel struct {
	Name        string
	Color       string
	Description string
}

RepoLabel is one of a repository's labels: its name, its color as "#rrggbb" or "", and what it says it is for.

type RepoLabels added in v0.2.0

type RepoLabels struct {
	Labels []RepoLabel
	Total  int
}

RepoLabels are the labels of an issue's repository, the first hundred in name order, and how many it has.

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 Review added in v0.2.0

type Review struct {
	Author string
	State  string
	URL    string
	Commit string

	// SubmittedAt is zero for a review not submitted.
	SubmittedAt time.Time
}

Review is one reviewer's latest review; its text is in the conversation (Timeline).

type ReviewInput added in v0.2.0

type ReviewInput struct {
	// Event is ReviewApprove, ReviewRequestChanges, or ReviewComment.
	Event string

	// Body is the review's text; it may be empty for an approval.
	Body string

	// CommitID is the head commit the user reviewed, which the review is pinned to.
	CommitID string

	// Comments are the review's line comments.
	Comments []LineComment
}

ReviewInput is a review to submit.

type ReviewLineComment added in v0.2.0

type ReviewLineComment struct {
	ID        string
	URL       string
	CreatedAt time.Time
	Body      string

	// Path is the file it is on, and Line the line it ends on, StartLine the one it starts
	// on for one over several lines (else 0), as the diff it was left on numbers them when
	// it is Outdated: the lines it was on have changed since.
	Path      string
	Line      int
	StartLine int
	Outdated  bool

	// DiffHunk is the diff hunk it was left on, up to its line, as GitHub gives it.
	DiffHunk string
}

ReviewLineComment is one of a review's line comments.

type ReviewMark added in v0.2.0

type ReviewMark struct {
	// State is APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED, or PENDING; "" for none.
	State string

	// Commit is the head commit the review was left on.
	Commit string
}

ReviewMark is a review's state and the commit it was left on.

type ReviewRequests added in v0.2.0

type ReviewRequests struct {
	// Users are the logins of the people and bots asked, in GitHub's order.
	Users []string

	// Teams are the slugs of the teams asked, in GitHub's order.
	Teams []string
}

ReviewRequests is who a pull request asks to review.

func (ReviewRequests) Asks added in v0.2.0

func (r ReviewRequests) Asks(login string) bool

Asks reports whether the pull request asks login to review by name, ignoring case. A team the login belongs to does not count.

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 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 SignIn added in v0.3.0

type SignIn struct {
	// Login, Name, and URL are the account's login, its display name ("" when it has
	// none), and its profile page.
	Login string
	Name  string
	URL   string

	// Scopes is the token's X-OAuth-Scopes header, which CheckScopes and ProjectsScope
	// read: "" for a token that reports none, such as a fine-grained one.
	Scopes string
}

SignIn is the account a token belongs to, as the setup shows it, and the scopes the token reports.

type StatusAnswer added in v0.2.0

type StatusAnswer struct {
	// Body is the summary as the page sent it, nil when NotModified.
	Body []byte

	// ETag is the answer's ETag, or "" when it sent none. A 304 carries the request's
	// ETag on, unless it sends another.
	ETag string

	// NotModified reports that the page answered 304: the summary is the one the
	// request's ETag names.
	NotModified bool
}

StatusAnswer is a status page's answer.

type StatusError

type StatusError struct {
	StatusCode int
	Message    string

	// RetryAfter is how long GitHub asked the app to wait before trying again (its
	// Retry-After header), or 0 when it did not say.
	RetryAfter time.Duration
}

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 StatusRequest added in v0.2.0

type StatusRequest struct {
	// Host is the page's host, one of the client's status hosts (StatusHosts).
	Host string

	// Path is the summary's path on the host, absolute and clean, e.g.
	// /api/v2/summary.json.
	Path string

	// ETag is the ETag of the last answer, sent as If-None-Match, or "" for none.
	ETag string
}

StatusRequest asks for a status page's summary.

type SubIssues added in v0.2.0

type SubIssues struct {
	Total int

	// Completed is how many are closed as done; never more than Total.
	Completed int
}

SubIssues counts an issue's sub-issues.

type SubmittedReview added in v0.2.0

type SubmittedReview struct {
	ID int64

	// State is APPROVED, CHANGES_REQUESTED, or COMMENTED.
	State string

	URL      string
	CommitID string

	// SubmittedAt is when GitHub recorded it.
	SubmittedAt time.Time
}

SubmittedReview is a review as GitHub answered its submission.

type TagRelease added in v0.2.0

type TagRelease struct {
	// URL is its page on GitHub.
	URL string

	// Draft reports a draft, which no one but the repository's writers sees.
	Draft bool

	// PublishedAt is when it was published, or zero while it isn't.
	PublishedAt time.Time
}

TagRelease is the release GitHub has for a tag.

type Thread added in v0.2.0

type Thread struct {
	// ID is GitHub's ID of the thread, always positive.
	ID int64

	// Unread reports a thread the user hasn't read.
	Unread bool

	// Reason is why the user was notified, in GitHub's words: review_requested, mention,
	// author, assign, subscribed, ci_activity, and others.
	Reason string

	// UpdatedAt is when the thread last changed, and LastReadAt when the user last read
	// it, zero when never.
	UpdatedAt  time.Time
	LastReadAt time.Time

	// SubjectType is what the thread is about, in GitHub's words: PullRequest, Issue,
	// Release, CheckSuite, Discussion, Commit, and others.
	SubjectType string

	// Title is the subject's title.
	Title string

	// Repo is the thread's repository; zero when GitHub named none that could be one.
	Repo repo.Name

	// Ref is the pull request or issue the subject's API URL names (ParseSubject); zero,
	// with Kind "", for any other subject. A web link to it is built from the Ref, never
	// rewritten from the API's URL.
	Ref item.Ref

	// LatestCommentURL is the subject's latest comment's API URL as GitHub gave it, which
	// is often the subject's own URL (after a merge or a close), or "" when GitHub gave
	// none. FetchLatestComment reads a comment's author from it.
	LatestCommentURL string
}

Thread is one notification thread: GitHub's notice about one subject, such as a pull request or an issue.

type ThreadPage added in v0.2.0

type ThreadPage struct {
	// Threads are the page's threads, but those dropped. Empty when NotModified.
	Threads []Thread

	// Dropped counts the page's threads that were left out, as one whose ID isn't a
	// positive number, or that couldn't be read at all.
	Dropped int

	// NotModified reports that GitHub answered 304 Not Modified to the ETag sent: page 1
	// is as it was in the answer that carried it, and the read cost nothing. It says
	// nothing of the later pages: a thread read or marked done there doesn't change page
	// 1, so the caller catches those only by a walk of every page.
	NotModified bool

	// ETag is page 1's ETag, for the next read of page 1: the answer's, or the one sent
	// when a 304 carried none. It is "" on every later page, which is never sent with one.
	ETag string

	// PollInterval is how long GitHub asks the app to wait before it reads the
	// notifications again (X-Poll-Interval), or 0 when it did not say.
	PollInterval time.Duration

	// NextPage is the page after this one, or 0 when there is none, or it would be past
	// MaxThreadPages.
	NextPage int

	// Capped reports that GitHub lists a page after this one, past MaxThreadPages, which
	// the app reads no further: the threads past it are left out. NextPage is then 0.
	Capped bool
}

ThreadPage is one page of the user's notifications, newest updated first.

type ThreadQuery added in v0.2.0

type ThreadQuery struct {
	// Page is the page to read, from 1 (0 reads page 1) to MaxThreadPages.
	Page int

	// ETag is the ETag the last answer for page 1 carried, which page 1 is sent with; ""
	// sends none. A later page is never sent with one.
	ETag string
}

ThreadQuery asks for one page of the user's notifications.

type TimelineItem added in v0.2.0

type TimelineItem struct {
	Type      string
	ID        string
	CreatedAt time.Time

	// Actor is who wrote the comment or made the event, "" when GitHub doesn't say, as for
	// a deleted account, and ActorType its GraphQL type: User, Bot, or another.
	Actor     string
	ActorType string

	// A comment's or a review's text, page, its author's relationship to the repository,
	// when it was last edited (zero when never), and whether the viewer wrote it. A merge's
	// page is its URL too.
	Body        string
	URL         string
	Association string
	EditedAt    time.Time
	Mine        bool

	// Minimized reports a comment someone folded away, and MinimizedReason why, as an
	// upper-case word: ABUSE, OFF_TOPIC, OUTDATED, RESOLVED, DUPLICATE, SPAM, or "".
	Minimized       bool
	MinimizedReason string

	// Ref is the other item an event names: the pull request or issue that mentioned this
	// one, the other side of a connection, the pull request or issue that closed it, or the
	// issue it was marked a duplicate of.
	Ref *ItemRef

	// WillClose reports a mention that closes this issue once it merges, and CrossRepo one
	// from another repository.
	WillClose bool
	CrossRepo bool

	// Commit is the short SHA of the commit that closed it, whose page URL holds, or of a
	// merge's commit; and DuplicateOf the issue a close as a duplicate names.
	Commit      string
	DuplicateOf *ItemRef

	// StateReason is a close's or a reopen's reason (see the StateReason values).
	StateReason string

	// Label is a label added or taken off, and Assignee who was assigned or unassigned.
	Label    *Label
	Assignee string

	// PreviousTitle and CurrentTitle are a rename's titles.
	PreviousTitle string
	CurrentTitle  string

	// ReviewState is a review's state (see the ReviewState values), and Outdated reports one
	// left on an earlier commit than the pull request's head as of the read. LineComments are
	// its first line comments, and LineCommentCount how many it has in all.
	ReviewState      string
	Outdated         bool
	LineComments     []ReviewLineComment
	LineCommentCount int

	// Reviewer is whom a review was requested of: a user's login, or a team as "org/team".
	Reviewer string

	// Branch is the branch a merge went into.
	Branch string

	// BeforeCommit and AfterCommit are a force push's short SHAs, before and after it.
	BeforeCommit string
	AfterCommit  string
}

TimelineItem is one comment, review, or event of an issue's or a pull request's timeline. Which fields are set depends on its Type, one of the Timeline values.

type TimelinePage added in v0.2.0

type TimelinePage struct {
	Items []TimelineItem

	// HasEarlier reports items before the page, which Before, the page's cursor, reads.
	HasEarlier bool
	Before     string

	// Total counts every item of the types the sheet reads in the whole timeline; on an
	// earlier page of a pull request's, those up to the page's end.
	Total int

	// RateLimit is the GraphQL budget after the read that brought the page.
	RateLimit QueryRate
}

TimelinePage is one page of an issue's or a pull request's timeline, oldest first.

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 NewToken

func NewToken(value string) Token

NewToken wraps a raw token value.

func (Token) Format

func (Token) Format(f fmt.State, _ rune)

Format prints [redacted] for every verb and flag.

func (Token) GoString

func (Token) GoString() string

GoString returns [redacted], so %#v never shows the token.

func (Token) IsZero

func (t Token) IsZero() bool

IsZero reports whether the token is empty.

func (Token) LogValue

func (Token) LogValue() slog.Value

LogValue makes slog record [redacted] for a token.

func (Token) MarshalJSON

func (Token) MarshalJSON() ([]byte, error)

MarshalJSON encodes the token as the string "[redacted]".

func (Token) MarshalText

func (Token) MarshalText() ([]byte, error)

MarshalText encodes the token as [redacted].

func (Token) Reveal

func (t Token) Reveal() string

Reveal returns the raw token. Use it only to set the Authorization header.

func (Token) Same added in v0.2.0

func (t Token) Same(o Token) bool

Same reports whether t and o hold the same token, comparing in constant time. A zero token is the same as no other.

func (Token) String

func (Token) String() string

String returns [redacted].

type TokenOption added in v0.2.0

type TokenOption func(*TokenSource)

TokenOption configures a TokenSource.

func WithHostsFile added in v0.2.0

func WithHostsFile(path string) TokenOption

WithHostsFile sets the GitHub CLI's hosts file (see GHHostsFile), which gh rewrites when its account changes; a token borrowed before a change is not handed out again. Without it no file is watched, and only the TTL, Forget, and Clear drop the token.

func WithTokenClock added in v0.2.0

func WithTokenClock(c clock.Clock) TokenOption

WithTokenClock sets the clock that ages the token. Without it the system clock does.

type TokenSource

type TokenSource struct {
	// contains filtered or unexported fields
}

TokenSource borrows the GitHub CLI's token for github.com and keeps it in memory for TokenTTL. It is safe for concurrent use.

func NewTokenSource

func NewTokenSource(runner execpath.Runner, finder execpath.Finder, opts ...TokenOption) *TokenSource

NewTokenSource returns a TokenSource that finds gh with finder and runs it with runner.

func (*TokenSource) Clear added in v0.2.0

func (s *TokenSource) Clear()

Clear drops the token held, whatever it is, as the app does when it quits.

func (*TokenSource) Forget added in v0.2.0

func (s *TokenSource) Forget(tok Token)

Forget drops tok if it is the token held, so the next Token asks gh again. It leaves a token borrowed since in place, so callers refused with the same old token do not throw away the fresh one.

func (*TokenSource) Token

func (s *TokenSource) Token(ctx context.Context) (Token, error)

Token returns the token borrowed last while it is younger than TokenTTL and gh's account has not changed since; otherwise it runs gh auth token, once for every caller asking meanwhile, and keeps what gh prints. It returns ErrGHNotFound when gh is missing and ErrNotLoggedIn when gh has no token, each with a message for the user (see uierr.Message). The command's output is never included in an error.

type Tokens added in v0.2.0

type Tokens interface {
	Token(ctx context.Context) (Token, error)
	Forget(tok Token)
}

Tokens lends a token and takes back one GitHub refused. *TokenSource implements it.

type UnrunSuite added in v0.2.0

type UnrunSuite struct {
	// Name is the GitHub Actions workflow, or else the app, that ran it.
	Name string

	// Conclusion is ACTION_REQUIRED for a run waiting for approval, or how it otherwise
	// ended, a conclusion a check run with it fails on (checkRunOutcome), as FAILURE or
	// STARTUP_FAILURE.
	Conclusion string

	// RunID is the GitHub Actions workflow run's ID, which REST names it by (as
	// ApproveWorkflowRun does), and URL its page; 0 and "" for another app's suite.
	RunID int64
	URL   string
}

UnrunSuite is a check suite that ended without a check: what ran it, and how it ended.

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.

type ViewerCache added in v0.2.0

type ViewerCache struct {
	// contains filtered or unexported fields
}

ViewerCache remembers the account the last token it was told of belongs to, so its holder asks GitHub who the token is (FetchViewer) only for a token it hasn't seen. The token stays in memory, as the TokenSource keeps it, and is only compared (Token.Same). The zero value is ready, and it is safe for concurrent use.

func (*ViewerCache) Get added in v0.2.0

func (c *ViewerCache) Get(tok Token) (string, bool)

Get returns the account tok belongs to, if tok is the token remembered.

func (*ViewerCache) Remember added in v0.2.0

func (c *ViewerCache) Remember(tok Token, login string)

Remember records that tok belongs to the account login, in place of the one remembered. A zero token or an empty login is not remembered.

type WorkflowRun added in v0.2.0

type WorkflowRun struct {
	// Name is the workflow's name, as goreleaser.
	Name string

	// Status is where it is: queued, in_progress, completed, and the rest of GitHub's
	// states. Conclusion is how it ended (success, failure, and the rest), or "" until it
	// has.
	Status     string
	Conclusion string

	// URL is its page on GitHub.
	URL string
}

WorkflowRun is one workflow run.

func (WorkflowRun) Completed added in v0.2.0

func (r WorkflowRun) Completed() bool

Completed reports a run that has ended.

func (WorkflowRun) Failed added in v0.2.0

func (r WorkflowRun) Failed() bool

Failed reports a run that concluded in failure, timed out, or never started. One canceled isn't a failure: it may be run again.

type WriteGate added in v0.2.0

type WriteGate interface {
	// AllowWrite asks to send one edit now, spending from the budget resource names
	// (ResourceCore for a REST edit). It counts the edit and returns nil when it may go,
	// or returns an error that says why not and when to try again.
	AllowWrite(resource string) error

	// HoldWrites hears that GitHub asked the app to send no more edits for wait.
	HoldWrites(wait time.Duration)
}

WriteGate paces the edits the client sends GitHub. *budget.Tracker implements it. It must return promptly; edits sent side by side call it concurrently.

Jump to

Keyboard shortcuts

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