github

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 18 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) on every refresh and held only in memory. It never reaches a log line, an error message, or the database: the Token type prints as [redacted] in every format, and every error that leaves this package is scrubbed of the token text.

The inbox comes from one batched GraphQL request (three aliased searches plus the query's rate-limit cost); the REST rate-limit endpoint fills in the remaining budgets.

Index

Constants

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 (
	// 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"
)

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")
)
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 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 ErrInvalidItemRef = errors.New("invalid pull request or issue reference")

ErrInvalidItemRef is returned for an ItemRef whose number is not positive; it is never sent.

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

ErrMissingScopes matches a MissingScopesError with errors.Is.

Functions

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.

Types

type Avatar

type Avatar struct {
	// ContentType is the image's media type, sniffed from its bytes, e.g. "image/png".
	ContentType string

	// Data is the image itself.
	Data []byte
}

Avatar is a downloaded profile picture.

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 ChangedFile

type ChangedFile struct {
	// Path is the file's path after the change.
	Path string

	// PreviousPath is a renamed or copied file's path before the change, or "".
	PreviousPath string

	// Status is GitHub's word for the change: added, removed, modified, renamed, copied,
	// changed, or unchanged.
	Status string
}

ChangedFile is one file a pull request changes.

type ChangedFiles

type ChangedFiles struct {
	// Head is the head commit the list belongs to.
	Head string

	// Total is how many files the pull request changes, which can exceed len(Files).
	Total int

	// Files are the files GitHub listed: every one, or the first 3,000.
	Files []ChangedFile

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

ChangedFiles is a pull request's changed files at one head commit.

type Checks

type Checks struct {
	// State is GitHub's overall result: SUCCESS, FAILURE, ERROR, PENDING, or EXPECTED,
	// and "" when the head commit has no checks.
	State string

	Passed  int
	Failed  int
	Pending int
	Skipped int
}

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

type Client

type Client struct {
	// BaseURL is the API root, without a trailing slash. Tests point it at a local server.
	BaseURL string

	// HTTP sends the requests.
	HTTP *http.Client

	// UserAgent identifies the app to GitHub.
	UserAgent string

	// AvatarHost is the only host FetchAvatar downloads from, as host or host:port. It
	// defaults to DefaultAvatarHost; tests point it at a local server.
	AvatarHost string
}

Client calls the GitHub REST and GraphQL APIs.

func NewClient

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) 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 ItemRef, head string) (*ChangedFiles, error)

FetchChangedFiles lists the files a pull request changes, with each renamed file's previous path, through the REST API: GitHub's GraphQL API does not report where a renamed file came from. The list is read between two readings of the head commit, so it belongs to one commit: when the head moved meanwhile, it is read again for the new head, and ErrHeadMoved is returned if the head moves again. head is the head commit already known, or "" to read it first.

It costs one REST request per 100 files, plus one or two for the head.

func (*Client) FetchDetails

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

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

func (*Client) FetchInbox

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) FetchItem

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

FetchItem reads one pull request or issue, by node ID, as of now. Unlike the inbox query's searches, it never waits on GitHub's index, so it sees a merge or a close at once.

func (*Client) FetchItemStates

func (c *Client) FetchItemStates(ctx context.Context, tok Token, refs []ItemRef) (map[ItemRef]ItemState, error)

FetchItemStates reads the state of each pull request or issue in refs, as of now. A ref GitHub cannot resolve (a number that does not exist, a repository that is gone or that the token cannot see) is left out of the result. Any other error fails the whole call, so a passing problem never makes an item look done.

func (*Client) FetchPullHead

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

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

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.

type Details

type Details struct {
	// Items maps each item's node ID to its details. An ID GitHub could not resolve, such
	// as one deleted since the inbox query, is left out.
	Items map[string]ItemDetails

	// RateLimit is the GraphQL budget after the last request; its Cost is the sum of
	// every request's cost.
	RateLimit QueryRate

	// Requests is how many requests were made: 0 when there were no IDs.
	Requests int
}

Details is what FetchDetails learned.

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 one with the least remaining, the latest of requests that ran side by side.

type Finder

type Finder interface {
	Find(name string) (string, error)
}

Finder resolves a program name to the absolute path of an executable.

type Inbox

type Inbox struct {
	// Viewer is the token's account.
	Viewer Viewer

	ReviewRequested SearchResult
	Authored        SearchResult
	Assigned        SearchResult

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

	// OAuthScopes is the response's X-OAuth-Scopes header ("" when absent).
	OAuthScopes string
}

Inbox is the decoded result of the batched inbox query.

type Item

type Item struct {
	IsPR      bool
	NodeID    string
	Number    int
	Title     string
	URL       string
	CreatedAt time.Time
	UpdatedAt time.Time

	// State is StateOpen, StateClosed, or StateMerged, and "" when GitHub did not say.
	State string

	// IsDraft and HeadRef are set for pull requests only.
	IsDraft bool
	HeadRef string

	AuthorLogin string

	// AuthorType is the author's GraphQL type: User for a person, Bot for a GitHub App
	// or bot, or another actor type such as Mannequin.
	AuthorType string

	// AuthorAssociation is the author's relationship to the repository (OWNER, MEMBER,
	// COLLABORATOR, CONTRIBUTOR, NONE, ...).
	AuthorAssociation string

	// IsCrossRepository reports a pull request opened from another repository (a fork).
	IsCrossRepository bool

	RepoOwner string
	RepoName  string

	// Repo describes the item's repository.
	Repo Repository
}

Item is one pull request or issue from a search.

func (Item) Closed

func (i Item) Closed() bool

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

type ItemDetails

type ItemDetails struct {
	Labels []Label

	// Comments counts the conversation's comments; for a pull request it includes the
	// review comments.
	Comments int

	Additions    int
	Deletions    int
	ChangedFiles int
	Commits      int

	// HeadOID is the SHA of a pull request's head commit; it changes on every push.
	HeadOID string

	// Mergeable is MERGEABLE, CONFLICTING, or UNKNOWN while GitHub is still working it out.
	Mergeable string

	Checks  Checks
	Reviews Reviews
}

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

type ItemRef

type ItemRef struct {
	Owner  string
	Name   string
	Number int
}

ItemRef names a pull request or issue by its repository and number. GitHub's numbers are shared by a repository's pull requests and issues, so the number alone picks one.

func (ItemRef) String

func (r ItemRef) String() string

String names the pull request as owner/name#number.

type ItemState

type ItemState struct {
	// PullRequest reports a pull request; false is an issue.
	PullRequest bool

	Title string
	URL   string

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

	// ClosedAt is when the item was merged or closed, or zero while it is open.
	ClosedAt time.Time

	// HeadOID is a pull request's head commit SHA; "" for an issue.
	HeadOID string
}

ItemState is what GitHub says about a pull request or issue as of now.

type ItemUpdate

type ItemUpdate struct {
	// Found is false when GitHub could not resolve the ID, because the item was deleted
	// or the token can no longer see it. Item and Details are zero then.
	Found bool

	Item    Item
	Details ItemDetails

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

ItemUpdate is what FetchItem learned about one item.

type Label

type Label struct {
	Name string

	// Color is "#rrggbb" in lower case, or "" when GitHub's value is not a color.
	Color string
}

Label is one label on an item.

type MissingScopesError

type MissingScopesError struct {
	Missing []string
}

MissingScopesError lists the required scopes the token lacks.

func (*MissingScopesError) Error

func (e *MissingScopesError) Error() string

Error names the missing scopes and how to grant them.

func (*MissingScopesError) Is

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

Is reports whether target is ErrMissingScopes.

type PullHead

type PullHead struct {
	// Head is the head commit's SHA.
	Head string

	// ChangedFiles is how many files the pull request changes.
	ChangedFiles int

	// State is "open" or "closed".
	State string
}

PullHead is where a pull request stands as of now.

type 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.

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 Repository

type Repository struct {
	// NodeID is the repository's GraphQL ID, which survives a rename.
	NodeID string

	Description string

	// Visibility is PUBLIC, PRIVATE, or INTERNAL.
	Visibility string

	IsArchived bool

	// ArchivedAt is when the repository was archived; zero when it is not.
	ArchivedAt time.Time

	// IsDisabled and IsLocked report a repository that cannot be used: disabled by
	// GitHub, or locked, for instance while it migrates (LockReason says why).
	IsDisabled bool
	IsLocked   bool
	LockReason string

	// IsFork reports a fork, and Parent is the "owner/name" it was made from ("" when the
	// viewer cannot see the parent).
	IsFork bool
	Parent string

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

	// ViewerPermission is the viewer's access: ADMIN, MAINTAIN, WRITE, TRIAGE, or READ.
	ViewerPermission string

	// ViewerMergeMethod is the merge method GitHub offers the viewer first: MERGE,
	// SQUASH, or REBASE.
	ViewerMergeMethod string

	MergeCommitAllowed  bool
	SquashMergeAllowed  bool
	RebaseMergeAllowed  bool
	AutoMergeAllowed    bool
	DeleteBranchOnMerge bool
	AllowUpdateBranch   bool

	// Language is the primary language's name, and LanguageColor its "#rrggbb" color in
	// lower case; both "" when GitHub detected none.
	Language      string
	LanguageColor string

	// PushedAt is the last push to any branch; zero when unknown.
	PushedAt time.Time
}

Repository is what the inbox query reads about an item's repository: its identity, its state, its merge settings, and the viewer's access to it.

type Reviews

type Reviews struct {
	// Decision is APPROVED, CHANGES_REQUESTED, or REVIEW_REQUIRED, and "" when the
	// repository requires no review.
	Decision string

	// Reviewers is everyone asked to review or who has reviewed, the author excluded.
	Reviewers int

	// Reviewed is how many of them have reviewed and are not asked to review again.
	Reviewed int

	// Approvals and ChangesRequested count the reviewers whose latest review is one.
	Approvals        int
	ChangesRequested int
}

Reviews counts who was asked to review a pull request and who has.

type Runner

type Runner interface {
	Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error)
}

Runner runs a program with arguments and returns what it wrote. Implementations run the argv directly, never through a shell.

type ScopeWarning

type ScopeWarning string

ScopeWarning describes a scope check that passed without proof.

const ScopesUnverifiable ScopeWarning = "GitHub did not report this token's scopes " +
	"(a fine-grained token?), so the repo and read:org scopes can't be verified; " +
	"some items may be missing"

ScopesUnverifiable is the warning for a token that reports no scopes, such as a fine-grained token. Requests still go ahead; results may be incomplete.

func CheckScopes

func CheckScopes(header string) (ScopeWarning, error)

CheckScopes checks a response's X-OAuth-Scopes header for the scopes the inbox needs. An empty header (a token that reports no scopes) returns ScopesUnverifiable and no error. A header without repo, or without any of read:org, write:org, or admin:org, returns a *MissingScopesError.

type SearchResult

type SearchResult struct {
	// IssueCount is GitHub's total match count, which can exceed len(Items).
	IssueCount int
	Items      []Item
}

SearchResult is one aliased search: the total match count and the items returned.

type StatusError

type StatusError struct {
	StatusCode int
	Message    string
}

StatusError is a non-2xx response from the GitHub API.

func (*StatusError) Error

func (e *StatusError) Error() string

Error describes the status, GitHub's message, and a hint for a rejected token.

func (*StatusError) Is

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

Is reports whether target is ErrUnexpectedStatus.

type Token

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

Token is a GitHub API token. Its value is only reachable through Reveal; printing, logging, or encoding a Token always yields [redacted].

The value sits behind a pointer so that even reflection-based printing of a struct holding a Token in an unexported field shows an address, not the token.

func 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) String

func (Token) String() string

String returns [redacted].

type TokenSource

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

TokenSource borrows the GitHub CLI's token for github.com.

func NewTokenSource

func NewTokenSource(runner Runner, finder Finder) *TokenSource

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

func (*TokenSource) Token

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

Token runs gh auth token and returns the token it prints. It returns ErrGHNotFound when gh is missing and ErrNotLoggedIn when gh has no token. The command's output is never included in an error.

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.

Jump to

Keyboard shortcuts

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