Documentation
¶
Index ¶
- Constants
- Variables
- func IsClientError(err error) bool
- func IsPermanentClientError(err error) bool
- func IsRateLimitError(err error) bool
- func IsServerError(err error) bool
- func NewArchiveDownloadHTTPClient() *http.Client
- func NewHTTPErrorResponseForTest(statusCode int, message string) error
- func RenderIssueBody(params IssueRenderParams) string
- func RenderIssueTitle(featureName string, trigger string) string
- type AppsClient
- type Client
- func (c *Client) CreateIssue(ctx context.Context, owner, repo string, req *github.IssueRequest) (*github.Issue, error)
- func (c *Client) DownloadFileFromRelease(ctx context.Context, owner, repo string, httpClient *http.Client, ...) (*ReleaseFile, error)
- func (c *Client) DownloadTarball(ctx context.Context, owner, repo, ref string) (io.ReadCloser, error)
- func (c *Client) GetBlobContent(ctx context.Context, owner, repo, sha string) ([]byte, error)
- func (c *Client) GetCommitTree(ctx context.Context, owner, repo, sha string) (*github.Tree, error)
- func (c *Client) ListAppInstallations(ctx context.Context, opts *github.ListOptions) ([]*github.Installation, error)
- func (c *Client) ListInstallationRepositories(ctx context.Context, opts *github.ListOptions) ([]*github.Repository, error)
- func (c *Client) WithArchiveHTTPClient(hc *http.Client) *Client
- type ClientOption
- type CollaboratorPermissionService
- type GitClient
- type GitHubPermissionChecker
- func NewGitHubPermissionChecker(reposClient CollaboratorPermissionService, usersClient UserLookupService) *GitHubPermissionChecker
- func NewGitHubPermissionCheckerWithBaseURL(baseURL *url.URL) *GitHubPermissionChecker
- func NewGitHubPermissionCheckerWithTokenProvider(tokenProvider *TokenProvider, baseURL *url.URL) *GitHubPermissionChecker
- type GitHubUser
- type InstallationTokenProvider
- type IssueOccurrence
- type IssueRenderParams
- type IssuesClient
- type ReleaseFile
- type ReleaseInfo
- type RepoClient
- type TokenCacher
- type TokenProvider
- type UserEmail
- type UserGitHubClient
- type UserLookupService
- type UsersClient
- type WebhookVerifier
Constants ¶
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 ¶
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") )
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") )
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") )
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") )
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") )
var ( // ErrClientNotConfigured is returned when the collaborator client is nil. ErrClientNotConfigured = errors.New("github collaborator client not configured") )
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.
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.
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 ¶
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 ¶
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 ¶
IsRateLimitError reports whether err represents a GitHub rate limit error, including primary rate limits (429), secondary/abuse rate limits (403), and ErrSecondaryRateLimit.
func IsServerError ¶
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 ¶
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 ¶
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 ¶
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 (*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 ¶
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 ¶
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.
type ClientOption ¶
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 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 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 ¶
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 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 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 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=...").