gh

package
v0.0.0-...-7dfa3a9 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 24 Imported by: 3 modules, 6 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

Index

Constants

View Source
const (
	// MaxRenderedOccurrences caps the number of occurrences displayed in the issue body
	// to prevent exceeding GitHub's 65,536 character payload limit.
	MaxRenderedOccurrences = 25
	// MaxSnippetLength caps the length of individual comment snippets.
	MaxSnippetLength = 200
)

Variables

View Source
var (
	ErrRateLimit             = errors.New("rate limit hit")
	ErrAssetNotFound         = errors.New("asset not found")
	ErrUnableToDownloadAsset = errors.New("unable to download asset")
	ErrUnableToReadAsset     = errors.New("unable to download asset")
	ErrFatalError            = errors.New("fatal error using github")
)
View Source
var (
	// ErrSecondaryRateLimit is returned when GitHub signals a secondary rate limit (403 or 429).
	ErrSecondaryRateLimit = errors.New("github secondary rate limit exceeded")
	// ErrNilIssueRequest indicates a nil IssueRequest was provided.
	ErrNilIssueRequest = errors.New("nil issue request provided")
)
View Source
var (
	// ErrInvalidPrivateKey is returned when the PEM block cannot be parsed as an RSA private key.
	ErrInvalidPrivateKey = errors.New("invalid rsa private key")

	// ErrEmptyAppID is returned when app ID is empty.
	ErrEmptyAppID = errors.New("app id must not be empty")
)
View Source
var (
	// ErrEmptyInstallationID is returned when an installation ID is empty.
	ErrEmptyInstallationID = errors.New("installation id must not be empty")

	// ErrNilTokenCacher is returned when a nil TokenCacher is provided.
	ErrNilTokenCacher = errors.New("token cacher must not be nil")
)
View Source
var (
	// ErrBlobTooLarge indicates a file blob exceeds the maximum allowed size.
	ErrBlobTooLarge = errors.New("file blob exceeds maximum size of 1MB")
	// ErrNilTree indicates GitHub returned a nil tree object.
	ErrNilTree = errors.New("received nil tree from git API")
)
View Source
var (
	// ErrClientNotConfigured is returned when the collaborator client is nil.
	ErrClientNotConfigured = errors.New("github collaborator client not configured")
)
View Source
var ErrFieldUnexpectedlyNil = errors.New("expected field to be non-nil")

ErrFieldUnexpectedlyNil is returned when a field that is expected to be non-nil is found to be nil. A lot of GitHub API fields are pointers, so we need to check for nil values.

View Source
var ErrRedirectNotFollowed = errors.New("github redirect not followed")

ErrRedirectNotFollowed is returned when GitHub responds with a redirect that was not followed: the 301 limit (maxArchiveLinkRedirects) was exhausted, a redirect status other than 301 was returned (go-github only follows 301; e.g. 307/308), or the redirect had no usable Location. Callers should treat it as permanent (see IsPermanentClientError) rather than retrying the same message immediately; the repository is scanned again the next time vcs-sync publishes it.

View Source
var ErrRepositoryInstallationNotFound = errors.New("github app installation not found for repository")

ErrRepositoryInstallationNotFound indicates that the GitHub App is not installed on the specified repository.

Functions

func IsClientError

func IsClientError(err error) bool

IsClientError reports whether err represents an HTTP 4XX client error returned by the GitHub API. Common examples include 400 Bad Request, 401 Unauthorized, 403 Forbidden, and 404 Not Found.

func IsPermanentClientError

func IsPermanentClientError(err error) bool

IsPermanentClientError reports whether err represents an unretryable 4XX client error (e.g. 400 Bad Request, 401 Unauthorized, 404 Not Found, 422 Unprocessable Entity), explicitly excluding transient rate-limiting errors (429 / secondary rate limits). A redirect that could not be followed (ErrRedirectNotFollowed) is also permanent.

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError reports whether err represents a GitHub rate limit error, including primary rate limits (429), secondary/abuse rate limits (403), and ErrSecondaryRateLimit.

func IsServerError

func IsServerError(err error) bool

IsServerError reports whether err represents an HTTP 5XX server error returned by the GitHub API. Common examples include 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout.

func NewArchiveDownloadHTTPClient

func NewArchiveDownloadHTTPClient() *http.Client

NewArchiveDownloadHTTPClient returns an HTTP client for repository archive downloads.

Every download gets its own HTTP/1.1 connection, which is closed when the download ends. With the default client, HTTP/2 multiplexes all concurrent downloads onto one shared connection, and Go never replaces a connection that stays busy, so one slow connection can slow every download for hours. With one connection per download, a slow connection affects only that download.

The client has no overall timeout; callers bound each download with a context deadline.

func NewHTTPErrorResponseForTest

func NewHTTPErrorResponseForTest(statusCode int, message string) error

NewHTTPErrorResponseForTest constructs a *github.ErrorResponse with the given HTTP status code and message. Primarily used for testing error handling and classification across consumers of lib/gh without requiring them to directly import github.com/google/go-github.

func RenderIssueBody

func RenderIssueBody(params IssueRenderParams) string

RenderIssueBody generates markdown body for a GitHub notification issue.

func RenderIssueTitle

func RenderIssueTitle(featureName string, trigger string) string

RenderIssueTitle generates a descriptive issue title based on feature and trigger.

Types

type AppsClient

type AppsClient interface {
	ListRepos(ctx context.Context, opts *github.ListOptions) (*github.ListRepositories, *github.Response, error)
	ListInstallations(ctx context.Context, opts *github.ListOptions) ([]*github.Installation, *github.Response, error)
}

type Client

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

func NewClient

func NewClient(token string, opts ...ClientOption) *Client

NewClient creates a new Github Client. If the token is not empty, it will use it as the auth token to make calls.

func NewClientWithHTTPClient

func NewClientWithHTTPClient(httpClient *http.Client, token string, opts ...ClientOption) *Client

NewClientWithHTTPClient creates a new Github Client with a custom HTTP client.

func (*Client) CreateIssue

func (c *Client) CreateIssue(
	ctx context.Context,
	owner, repo string,
	req *github.IssueRequest,
) (*github.Issue, error)

CreateIssue creates a new issue in the target repository.

func (*Client) DownloadFileFromRelease

func (c *Client) DownloadFileFromRelease(
	ctx context.Context,
	owner, repo string,
	httpClient *http.Client,
	filePattern string) (*ReleaseFile, error)

func (*Client) DownloadTarball

func (c *Client) DownloadTarball(
	ctx context.Context,
	owner, repo, ref string,
) (io.ReadCloser, error)

DownloadTarball downloads a tarball archive stream (.tar.gz) for a repository at a given git ref. The caller is responsible for closing the returned ReadCloser.

func (*Client) GetBlobContent

func (c *Client) GetBlobContent(ctx context.Context, owner, repo, sha string) ([]byte, error)

GetBlobContent fetches raw content of a git blob by SHA, enforcing a 1MB limit. Note for callers: To prevent unnecessary network I/O and memory allocation, callers should pre-filter git tree entries by relevant file extension and size before requesting blob contents.

func (*Client) GetCommitTree

func (c *Client) GetCommitTree(ctx context.Context, owner, repo, sha string) (*github.Tree, error)

GetCommitTree fetches the full recursive git tree for a given commit SHA.

func (*Client) ListAppInstallations

func (c *Client) ListAppInstallations(
	ctx context.Context,
	opts *github.ListOptions,
) ([]*github.Installation, error)

ListAppInstallations returns all installations of the authenticated GitHub App.

func (*Client) ListInstallationRepositories

func (c *Client) ListInstallationRepositories(
	ctx context.Context,
	opts *github.ListOptions,
) ([]*github.Repository, error)

ListInstallationRepositories returns all repositories accessible to the installation.

func (*Client) WithArchiveHTTPClient

func (c *Client) WithArchiveHTTPClient(hc *http.Client) *Client

WithArchiveHTTPClient returns a copy of c that downloads repository archives (the codeload request in DownloadTarball) with hc. GitHub API calls keep using their existing client.

type ClientOption

type ClientOption func(*github.Client)

func WithBaseURL

func WithBaseURL(baseURL *url.URL) ClientOption

type CollaboratorPermissionService

type CollaboratorPermissionService interface {
	GetPermissionLevel(ctx context.Context, owner, repo, user string) (
		*github.RepositoryPermissionLevel, *github.Response, error)
}

CollaboratorPermissionService abstracts the GitHub API operation for getting collaborator permissions.

type GitClient

type GitClient interface {
	GetTree(ctx context.Context, owner, repo, sha string, recursive bool) (*github.Tree, *github.Response, error)
	GetBlobRaw(ctx context.Context, owner, repo, sha string) ([]byte, *github.Response, error)
}

type GitHubPermissionChecker

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

GitHubPermissionChecker verifies user permissions against GitHub repositories.

FUTURE: Consider caching (e.g., in Valkey) the numeric-to-login resolution and the repository admin permission result to reduce GitHub API quota usage and optimize response latency under high traffic.

func NewGitHubPermissionChecker

func NewGitHubPermissionChecker(
	reposClient CollaboratorPermissionService,
	usersClient UserLookupService,
) *GitHubPermissionChecker

NewGitHubPermissionChecker creates a new GitHubPermissionChecker with the provided services.

func NewGitHubPermissionCheckerWithBaseURL

func NewGitHubPermissionCheckerWithBaseURL(baseURL *url.URL) *GitHubPermissionChecker

NewGitHubPermissionCheckerWithBaseURL creates a GitHubPermissionChecker with an optional custom base URL.

func NewGitHubPermissionCheckerWithTokenProvider

func NewGitHubPermissionCheckerWithTokenProvider(
	tokenProvider *TokenProvider,
	baseURL *url.URL,
) *GitHubPermissionChecker

NewGitHubPermissionCheckerWithTokenProvider creates a GitHubPermissionChecker with an optional TokenProvider and custom base URL.

func (*GitHubPermissionChecker) HasRepositoryAdminAccess

func (c *GitHubPermissionChecker) HasRepositoryAdminAccess(
	ctx context.Context,
	owner, repo, githubUserID string,
) (bool, error)

HasRepositoryAdminAccess checks if the given user (identified by GitHub username or numeric user ID string) has admin access to owner/repo on GitHub.

type GitHubUser

type GitHubUser struct {
	ID       int64
	Username string
}

type InstallationTokenProvider

type InstallationTokenProvider interface {
	GetInstallationToken(ctx context.Context, installationID string) (string, error)
}

InstallationTokenProvider retrieves a valid installation access token for a GitHub App installation.

type IssueOccurrence

type IssueOccurrence struct {
	FilePath       string
	LineNumber     int64
	CommentSnippet string
}

IssueOccurrence represents a code location occurrence in a repository.

type IssueRenderParams

type IssueRenderParams struct {
	FeatureID          string
	FeatureName        string
	Trigger            string
	RepositoryFullName string
	CommitSHA          string
	Occurrences        []IssueOccurrence
	WebStatusURL       string
}

IssueRenderParams contains all parameters needed to render a GitHub issue notification.

type IssuesClient

type IssuesClient interface {
	Create(ctx context.Context, owner, repo string, issue *github.IssueRequest) (*github.Issue, *github.Response, error)
}

type ReleaseFile

type ReleaseFile struct {
	Contents io.ReadCloser
	Info     ReleaseInfo
}

ReleaseFile represents a file in a given Github release.

type ReleaseInfo

type ReleaseInfo struct {
	// If the tag is valid, the will be non null.
	Tag *string
}

type RepoClient

type RepoClient interface {
	GetLatestRelease(ctx context.Context, owner, repo string) (*github.RepositoryRelease, *github.Response, error)
	GetArchiveLink(
		ctx context.Context,
		owner, repo string,
		archiveformat github.ArchiveFormat,
		opts *github.RepositoryContentGetOptions,
		maxRedirects int,
	) (*url.URL, *github.Response, error)
}

type TokenCacher

type TokenCacher interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Cache(ctx context.Context, key string, in []byte) error
}

TokenCacher caches installation access tokens.

type TokenProvider

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

TokenProvider manages RS256 JWT minting and cached GitHub App installation access tokens.

func NewTokenProvider

func NewTokenProvider(appID string, privateKeyPEM []byte, cacher TokenCacher) (*TokenProvider, error)

NewTokenProvider returns a new TokenProvider configured with the given cacher and standard HTTP transport. Validates appID and parses privateKeyPEM at construction time to fail fast on invalid credentials.

func (*TokenProvider) GetAppToken

func (tp *TokenProvider) GetAppToken() (string, error)

GetAppToken mints a fresh RS256 JWT for GitHub App-level API operations.

func (*TokenProvider) GetInstallationToken

func (tp *TokenProvider) GetInstallationToken(ctx context.Context, installationID string) (string, error)

GetInstallationToken returns a valid GitHub App installation access token.

func (*TokenProvider) GetInstallationTokenForRepo

func (tp *TokenProvider) GetInstallationTokenForRepo(ctx context.Context, owner, repo string) (string, error)

GetInstallationTokenForRepo retrieves an installation access token for the given owner and repository. It looks up the repository's installation ID via the GitHub App API and returns an installation token.

type UserEmail

type UserEmail struct {
	Email    string
	Verified bool
}

type UserGitHubClient

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

UserGitHubClient is a client that receives a token from a user that has installed our GitHub App. It uses that token to make requests on behalf of that user to verify things about them. It is different from the regular Client which is used for internal operations.

func NewUserGitHubClient

func NewUserGitHubClient(token string, opts ...ClientOption) *UserGitHubClient

NewUserGitHubClient creates a new UserGitHubClient with the given token. Assumes that the token is not empty.

func (*UserGitHubClient) GetCurrentUser

func (c *UserGitHubClient) GetCurrentUser(ctx context.Context) (*GitHubUser, error)

func (*UserGitHubClient) ListEmails

func (c *UserGitHubClient) ListEmails(ctx context.Context) ([]*UserEmail, error)

type UserLookupService

type UserLookupService interface {
	GetByID(ctx context.Context, id int64) (*github.User, *github.Response, error)
}

UserLookupService abstracts looking up user details from GitHub.

type UsersClient

type UsersClient interface {
	ListEmails(ctx context.Context, opts *github.ListOptions) ([]*github.UserEmail, *github.Response, error)
	Get(ctx context.Context, user string) (*github.User, *github.Response, error)
}

type WebhookVerifier

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

WebhookVerifier validates incoming GitHub webhook signatures using HMAC SHA-256.

func NewWebhookVerifier

func NewWebhookVerifier(secret []byte) *WebhookVerifier

NewWebhookVerifier creates a new WebhookVerifier with the provided secret.

func (*WebhookVerifier) VerifySignature

func (v *WebhookVerifier) VerifySignature(payload []byte, headerSig string) error

VerifySignature verifies a GitHub HMAC SHA-256 webhook signature header (e.g. "sha256=...").

Jump to

Keyboard shortcuts

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