github

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package github adapts read-only GitHub APIs to product-owned values.

It contains credential resolution, typed error classification, per-attempt rate limiting, bounded retries, pagination metadata, and mapping from go-github types. Callers depend on the narrow Reader capabilities instead of importing SDK types into the application or domain layers.

Index

Constants

View Source
const (
	DefaultBaseURL           = "https://api.github.com/"
	DefaultUploadURL         = "https://uploads.github.com/"
	DefaultRequestsPerSecond = 10.0
	DefaultBurst             = 20
)
View Source
const DefaultEnvToken = "GITHUB_TOKEN"

DefaultEnvToken is the conventional environment variable name for a GitHub token.

View Source
const KeyringService = "gitcontribute"

KeyringService is the service name used for credentials owned by gitcontribute.

Variables

View Source
var ErrCircuitOpen = errors.New("circuit breaker is open")

ErrCircuitOpen is returned when the circuit breaker rejects a request.

View Source
var ErrNoToken = errors.New("no GitHub token available")

ErrNoToken indicates that a token source could not provide a token.

View Source
var ErrRequiredToken = errors.New("configured GitHub token unavailable")

ErrRequiredToken indicates that an explicitly configured authentication source did not provide a token.

Functions

func IsNoToken

func IsNoToken(err error) bool

IsNoToken reports whether err is the sentinel no-token value.

Types

type AccessDeniedError

type AccessDeniedError struct {
	StatusCode int
	Message    string
}

AccessDeniedError indicates that the current GitHub credentials cannot read a resource. It covers authenticated and unauthenticated denial responses.

func (*AccessDeniedError) Error

func (e *AccessDeniedError) Error() string

type AuthoredPullRequestSearchOptions added in v0.5.0

type AuthoredPullRequestSearchOptions struct {
	Login        string
	State        string
	UpdatedAfter time.Time
	PageOptions
}

AuthoredPullRequestSearchOptions selects one bounded authored-PR search page. UpdatedAfter is translated to GitHub Search's UTC date-granularity qualifier.

type AuthoredPullRequestSearchResult added in v0.5.0

type AuthoredPullRequestSearchResult struct {
	Total      int
	Incomplete bool
	Items      []Issue
	Page       PageInfo
	Rate       RateInfo
}

AuthoredPullRequestSearchResult preserves GitHub's pagination, rate, and incomplete-results signals alongside the converted pull-request markers.

type AuthoredPullRequestSearcher added in v0.5.0

type AuthoredPullRequestSearcher interface {
	SearchAuthoredPullRequests(context.Context, AuthoredPullRequestSearchOptions) (AuthoredPullRequestSearchResult, error)
}

AuthoredPullRequestSearcher discovers pull requests authored by one login.

type CircuitState

type CircuitState int

CircuitState represents the state of the circuit breaker.

const (
	CircuitClosed   CircuitState = iota // normal operation, requests pass through
	CircuitOpen                         // failing fast, no requests allowed
	CircuitHalfOpen                     // probing, single request allowed
)

type Client

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

Client wraps go-github behind a narrow, domain-neutral interface.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a GitHub read client.

func (*Client) GetAuthenticatedIdentity added in v0.5.0

func (c *Client) GetAuthenticatedIdentity(ctx context.Context) (Identity, RateInfo, error)

GetAuthenticatedIdentity resolves the user associated with the configured read credential.

func (*Client) GetIssue

func (c *Client) GetIssue(ctx context.Context, owner, name string, number int) (Issue, RateInfo, error)

GetIssue reads one issue or pull-request marker by number.

func (*Client) GetPullRequestDetails

func (c *Client) GetPullRequestDetails(ctx context.Context, owner, name string, number int) (PullRequestDetails, RateInfo, error)

GetPullRequestDetails reads pull-request metadata not present on issue list rows.

func (*Client) GetRepository

func (c *Client) GetRepository(ctx context.Context, owner, name string) (Repository, RateInfo, error)

GetRepository reads repository metadata and the response rate-limit state.

func (*Client) ListIssueComments

func (c *Client) ListIssueComments(ctx context.Context, owner, name string, issueNumber int, opts PageOptions) (ListResult[IssueComment], error)

ListIssueComments reads one page of issue comments for a thread.

func (*Client) ListIssues

func (c *Client) ListIssues(ctx context.Context, owner, name string, opts ListIssueOptions) (ListResult[Issue], error)

ListIssues reads one page of issues and pull-request markers for a repository.

func (*Client) ListPullRequestComments

func (c *Client) ListPullRequestComments(ctx context.Context, owner, name string, number int, opts PageOptions) (ListResult[ReviewComment], error)

ListPullRequestComments reads one page of pull-request review comments.

func (*Client) ListPullRequestReviews

func (c *Client) ListPullRequestReviews(ctx context.Context, owner, name string, number int, opts PageOptions) (ListResult[Review], error)

ListPullRequestReviews reads one page of pull-request reviews.

func (*Client) SearchAuthoredPullRequests added in v0.5.0

SearchAuthoredPullRequests searches one bounded page of PRs authored by a login and preserves GitHub's incomplete-results signal.

func (*Client) SearchRepositories

func (c *Client) SearchRepositories(ctx context.Context, opts RepositorySearchOptions) (RepositorySearchResult, error)

SearchRepositories reads one page from GitHub's repository Search API.

type CommandRunner

type CommandRunner interface {
	Run(ctx context.Context, name string, args ...string) (string, error)
}

CommandRunner abstracts process execution so that tests can inject behavior.

func DefaultCommandRunner

func DefaultCommandRunner() CommandRunner

DefaultCommandRunner returns the real command runner.

type Config

type Config struct {
	BaseURL           string
	UploadURL         string
	TokenSource       TokenSource
	HTTPClient        *http.Client
	Limiter           Limiter
	RequestsPerSecond float64
	Burst             int
	Retry             *RetryConfig
}

Config controls how the GitHub client is constructed.

type GoneError

type GoneError struct {
	Resource string
}

GoneError indicates that GitHub reports a resource as permanently removed.

func (*GoneError) Error

func (e *GoneError) Error() string

type Identity added in v0.5.0

type Identity struct {
	Login  string
	ID     int64
	NodeID string
}

Identity is the stable login and identifiers associated with the active GitHub read credential.

type IdentityReader added in v0.5.0

type IdentityReader interface {
	GetAuthenticatedIdentity(context.Context) (Identity, RateInfo, error)
}

IdentityReader resolves the authenticated GitHub account without granting any mutation capability.

type Issue

type Issue struct {
	RepositoryOwner   string
	RepositoryName    string
	ID                int64
	NodeID            string
	Number            int
	Kind              ThreadKind
	Title             string
	Body              string
	State             string
	StateReason       string
	Draft             bool
	Locked            bool
	Author            string
	AuthorAssociation string
	Labels            []string
	Assignees         []string
	Milestone         string
	CommentsCount     int
	CreatedAt         time.Time
	UpdatedAt         time.Time
	ClosedAt          *time.Time
	HTMLURL           string
	PullRequestURL    string
}

Issue is a domain-neutral view of an issue or pull-request marker from the issues list endpoint.

type IssueComment

type IssueComment struct {
	ID                int64
	NodeID            string
	Body              string
	Author            string
	AuthorAssociation string
	CreatedAt         time.Time
	UpdatedAt         time.Time
	HTMLURL           string
	IssueURL          string
}

IssueComment is a domain-neutral view of an issue comment.

type IssueGetter

type IssueGetter interface {
	GetIssue(ctx context.Context, owner, name string, number int) (Issue, RateInfo, error)
}

IssueGetter is the optional exact-thread capability used by bounded archive refreshes. Keeping it separate avoids forcing broad discovery readers to implement an operation they do not need.

type Limiter

type Limiter interface {
	WaitN(ctx context.Context, n int) error
}

Limiter paces outbound requests. It matches the subset of rate.Limiter used by the transport so tests can inject a no-op or fake implementation.

func NewRateLimiter

func NewRateLimiter(rps float64, burst int) Limiter

NewRateLimiter returns a token-bucket limiter suitable for production use.

type ListIssueOptions

type ListIssueOptions struct {
	State     string
	Sort      string
	Direction string
	Since     time.Time
	Labels    []string
	PageOptions
}

ListIssueOptions specifies filters and pagination for listing repository issues.

type ListResult

type ListResult[T any] struct {
	Items []T
	Page  PageInfo
	Rate  RateInfo
}

ListResult is the common wrapper for paginated list responses.

type NotFoundError

type NotFoundError struct {
	Resource string
}

NotFoundError indicates a requested GitHub resource was not found.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type PageInfo

type PageInfo struct {
	Page      int
	PerPage   int
	NextPage  int
	PrevPage  int
	FirstPage int
	LastPage  int
	HasNext   bool
	HasPrev   bool
	HasFirst  bool
	HasLast   bool
}

PageInfo carries response pagination metadata.

type PageOptions

type PageOptions struct {
	Page    int
	PerPage int
}

PageOptions specifies pagination parameters.

type PrimaryRateLimitError

type PrimaryRateLimitError struct {
	Rate       RateInfo
	RetryAfter time.Duration
	Message    string
}

PrimaryRateLimitError is returned when GitHub's primary rate limit has been exceeded.

func (*PrimaryRateLimitError) Error

func (e *PrimaryRateLimitError) Error() string

type PullRequestDetails

type PullRequestDetails struct {
	ID                int64
	NodeID            string
	Number            int
	State             string
	Title             string
	Body              string
	Draft             bool
	Locked            bool
	Author            string
	AuthorAssociation string
	Labels            []string
	Assignees         []string
	Milestone         string
	CreatedAt         time.Time
	UpdatedAt         time.Time
	ClosedAt          *time.Time
	MergedAt          *time.Time
	Merged            bool
	Mergeable         *bool
	MergeCommitSHA    string
	HeadRef           string
	HeadSHA           string
	BaseRef           string
	BaseSHA           string
	CommentsCount     int
	Commits           int
	Additions         int
	Deletions         int
	ChangedFiles      int
	HTMLURL           string
}

PullRequestDetails is the PR-specific metadata beyond the issue marker.

type RateInfo

type RateInfo struct {
	Limit     int
	Remaining int
	Used      int
	Reset     time.Time
	Resource  string
}

RateInfo carries rate-limit metadata from the response headers.

type RateLimitedTransport

type RateLimitedTransport struct {
	Base    http.RoundTripper
	Limiter Limiter
}

RateLimitedTransport wraps an underlying RoundTripper with request pacing. It does not log request contents or tokens.

func (*RateLimitedTransport) RoundTrip

func (t *RateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error)

type Reader

type Reader interface {
	GetRepository(ctx context.Context, owner, name string) (Repository, RateInfo, error)
	ListIssues(ctx context.Context, owner, name string, opts ListIssueOptions) (ListResult[Issue], error)
	ListIssueComments(ctx context.Context, owner, name string, issueNumber int, opts PageOptions) (ListResult[IssueComment], error)
	GetPullRequestDetails(ctx context.Context, owner, name string, number int) (PullRequestDetails, RateInfo, error)
	ListPullRequestReviews(ctx context.Context, owner, name string, number int, opts PageOptions) (ListResult[Review], error)
	ListPullRequestComments(ctx context.Context, owner, name string, number int, opts PageOptions) (ListResult[ReviewComment], error)
}

Reader is the product-owned read contract for GitHub.

type Repository

type Repository struct {
	ID            int64
	NodeID        string
	Owner         string
	Name          string
	FullName      string
	Description   string
	DefaultBranch string
	HTMLURL       string
	Private       bool
	Fork          bool
	Archived      bool
	IsTemplate    bool
	Stars         int
	Watchers      int
	Forks         int
	OpenIssues    int
	Language      string
	License       string
	Topics        []string
	CreatedAt     time.Time
	UpdatedAt     time.Time
	PushedAt      *time.Time
}

Repository is a domain-neutral view of a GitHub repository.

type RepositorySearchOptions

type RepositorySearchOptions struct {
	Query string
	Sort  string
	Order string
	PageOptions
}

RepositorySearchOptions controls one GitHub repository search page.

type RepositorySearchResult

type RepositorySearchResult struct {
	Total      int
	Incomplete bool
	Items      []Repository
	Page       PageInfo
	Rate       RateInfo
}

RepositorySearchResult preserves GitHub's truncation and pagination facts.

type RepositorySearcher

type RepositorySearcher interface {
	SearchRepositories(ctx context.Context, opts RepositorySearchOptions) (RepositorySearchResult, error)
}

RepositorySearcher is the optional GitHub Search capability used by broad discovery. Keeping it separate lets archive-only readers stay small.

type RetryConfig

type RetryConfig struct {
	MaxAttempts int
	BaseDelay   time.Duration
	MaxDelay    time.Duration
	Clock       func() time.Time
	Sleeper     func(context.Context, time.Duration) error
	OnAttempt   func(RetryObservation)
}

RetryConfig controls how the retry transport paces and observes retries.

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns a production retry policy.

type RetryObservation

type RetryObservation struct {
	Attempt    int
	StatusCode int
	RateLimit  RateInfo
	Delay      time.Duration
	APIVersion string
	SourceURL  string
}

RetryObservation reports the outcome and pacing of a single retry attempt.

type Review

type Review struct {
	ID                int64
	NodeID            string
	State             string
	Body              string
	Author            string
	AuthorAssociation string
	CommitID          string
	SubmittedAt       time.Time
	HTMLURL           string
	PullRequestURL    string
}

Review is a domain-neutral view of a pull request review.

type ReviewComment

type ReviewComment struct {
	ID                int64
	NodeID            string
	InReplyTo         int64
	Body              string
	Path              string
	DiffHunk          string
	Author            string
	AuthorAssociation string
	CommitID          string
	OriginalCommitID  string
	PullRequestURL    string
	HTMLURL           string
	CreatedAt         time.Time
	UpdatedAt         time.Time
	Line              int
	OriginalLine      int
	StartLine         int
	OriginalStartLine int
	Side              string
	StartSide         string
	Position          int
	OriginalPosition  int
	SubjectType       string
}

ReviewComment is a domain-neutral view of a pull request review comment.

type SecondaryRateLimitError

type SecondaryRateLimitError struct {
	RetryAfter time.Duration
	Message    string
}

SecondaryRateLimitError is returned when GitHub's secondary (abuse) rate limit has been exceeded.

func (*SecondaryRateLimitError) Error

func (e *SecondaryRateLimitError) Error() string

type ThreadKind

type ThreadKind string

ThreadKind classifies an issue-list entry.

const (
	ThreadKindIssue       ThreadKind = "issue"
	ThreadKindPullRequest ThreadKind = "pull_request"
)

type TokenSource

type TokenSource interface {
	Token(ctx context.Context) (string, error)
}

TokenSource resolves a GitHub authentication token.

func ChainTokenSource

func ChainTokenSource(sources ...TokenSource) TokenSource

ChainTokenSource tries each source in order and returns the first non-empty token. Sources that return ErrNoToken are skipped.

func EnvTokenSource

func EnvTokenSource(name string) TokenSource

EnvTokenSource resolves a token from an environment variable.

func GhCLITokenSource

func GhCLITokenSource(runner CommandRunner, args ...string) TokenSource

GhCLITokenSource resolves a token by running `gh auth token`. Optional args are passed through to `gh` (for example a `--hostname` flag).

func KeyringTokenSource

func KeyringTokenSource(account string) TokenSource

KeyringTokenSource resolves a token from the operating system credential store. account identifies the credential within the gitcontribute service.

func NewTokenSource

func NewTokenSource(explicit, envVar string, runner CommandRunner) TokenSource

NewTokenSource builds the standard resolution chain: explicit value, environment variable, then `gh auth token`.

func RequireToken

func RequireToken(source TokenSource) TokenSource

RequireToken prevents an explicitly configured source from silently falling back to anonymous GitHub access.

func StaticTokenSource

func StaticTokenSource(token string) TokenSource

StaticTokenSource returns the provided token if it is non-empty.

type TransientError

type TransientError struct {
	Cause error
}

TransientError wraps a potentially retryable error.

func (*TransientError) Error

func (e *TransientError) Error() string

func (*TransientError) Unwrap

func (e *TransientError) Unwrap() error

Jump to

Keyboard shortcuts

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