github

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package github provides a client for interacting with the GitHub API.

Package github provides a client for interacting with the GitHub API.

Package github provides a client for interacting with the GitHub API.

Package github provides a client for interacting with the GitHub API.

Package github provides a client for interacting with the GitHub API.

Index

Constants

View Source
const (
	// MaxGitHubConcurrency limits the number of concurrent requests to GitHub
	// to avoid triggering secondary rate limits.
	MaxGitHubConcurrency = 10
)

Variables

View Source
var (
	// ErrAutoMergeNotEnabled is returned when auto-merge is not enabled for the repository.
	ErrAutoMergeNotEnabled = errors.New("auto-merge is not enabled for this repository")
	// ErrPRCleanStatus is returned when a PR is already in a clean/mergeable status.
	ErrPRCleanStatus = errors.New("PR is already in clean status")
	// ErrPRAlreadyMerged is returned when a PR was merged while waiting.
	ErrPRAlreadyMerged = errors.New("PR was merged while waiting")
)
View Source
var ErrRepoAccessDenied = errors.New("github: repository not found or access denied")

ErrRepoAccessDenied is returned by CheckRepoAccess when the authenticated user cannot see the repository. GitHub deliberately returns 404 (not 403) for private repos a token can't read, so "not found" and "no access" are indistinguishable and collapse into this one error.

ValidMergeMethods lists every accepted merge method value.

Functions

func BatchGetPRContentGraphQL added in v0.19.1

func BatchGetPRContentGraphQL(ctx context.Context, runner GitCommandRunner, repo Repo, prNumbers []int) (map[int]PRContent, error)

BatchGetPRContentGraphQL fetches the current title and body for multiple PR numbers in a single GraphQL query, replacing one REST GetPullRequest call per PR. PRs absent from the response (e.g. not found) are omitted from the map.

func BatchGetPRMergeableStates

func BatchGetPRMergeableStates(ctx context.Context, runner GitCommandRunner, prNodeIDs []string) (map[string]*PRMergeableState, error)

BatchGetPRMergeableStates checks mergeable state for multiple PRs in a single GraphQL query. Returns a map from node ID to PRMergeableState. If a PR fails to fetch, it won't be in the map.

func BatchGetPRNodeIDsGraphQL added in v0.19.2

func BatchGetPRNodeIDsGraphQL(ctx context.Context, runner GitCommandRunner, repo Repo, prNumbers []int) (map[int]string, error)

BatchGetPRNodeIDsGraphQL fetches PR node IDs for multiple PR numbers using a single GraphQL query, replacing one REST GetPullRequest call per number. Numbers with no matching PR are simply absent from the returned map.

func BatchGetPRStateBodyGraphQL added in v0.19.2

func BatchGetPRStateBodyGraphQL(ctx context.Context, runner GitCommandRunner, repo Repo, prNumbers []int) (map[int]PRStateBody, error)

BatchGetPRStateBodyGraphQL fetches the state and body for multiple PR numbers in a single GraphQL query, replacing one REST GetPullRequest call per number. Numbers with no matching PR are absent from the returned map.

func BatchGetPRTitlesGraphQL

func BatchGetPRTitlesGraphQL(ctx context.Context, runner GitCommandRunner, repo Repo, prNumbers []int) (map[int]string, error)

BatchGetPRTitlesGraphQL fetches PR titles for multiple PR numbers using a single GraphQL query.

func CreatePullRequest

func CreatePullRequest(ctx context.Context, client *github.Client, repo Repo, opts CreatePROptions) ([]string, *github.PullRequest, error)

CreatePullRequest creates a new pull request. Returns warnings (non-fatal issues like failed label/assignee additions) and error, matching the same contract as UpdatePullRequest.

func DisableAutoMerge

func DisableAutoMerge(ctx context.Context, runner GitCommandRunner, prNodeID string) error

DisableAutoMerge disables GitHub's auto-merge feature on a PR.

func EnableAutoMerge

func EnableAutoMerge(ctx context.Context, runner GitCommandRunner, prNodeID string, opts EnableAutoMergeOptions) error

EnableAutoMerge enables GitHub's auto-merge feature on a PR. This requires the repository to have auto-merge enabled in settings.

func GetGitHubClient

func GetGitHubClient(ctx context.Context, runner GitCommandRunner) (*github.Client, string, string, error)

GetGitHubClient creates a GitHub client with authentication

func GetPullRequestByBranch

func GetPullRequestByBranch(ctx context.Context, client *github.Client, repo Repo, branchName string) (*github.PullRequest, error)

GetPullRequestByBranch gets a pull request for a branch

func MergePullRequest

func MergePullRequest(ctx context.Context, client *github.Client, repo Repo, branchName string, opts MergePROptions) error

MergePullRequest merges a pull request using the GitHub API. If opts.CommitBody is set, it is used as an additional commit message body for merge/squash strategies.

func ParseReviewers

func ParseReviewers(reviewersStr string) ([]string, []string)

ParseReviewers parses a comma-separated string of reviewers Returns individual reviewers and team reviewers Team reviewers can be specified as "org/team" or just "team"

func SyncPrInfo

func SyncPrInfo(ctx context.Context, runner GitCommandRunner, branchNames []string, repo Repo, onUpdate func(string, *PullRequestInfo)) error

SyncPrInfo syncs PR information for branches from GitHub. It fetches every branch's PR in a single GraphQL query rather than one REST call per branch.

func UpdatePullRequest

func UpdatePullRequest(ctx context.Context, client *github.Client, runner GitCommandRunner, repo Repo, prNumber int, opts UpdatePROptions) ([]string, error)

UpdatePullRequest updates an existing pull request Returns warnings (non-fatal issues like failed label/assignee additions) and error

func WaitForPRMerge

func WaitForPRMerge(ctx context.Context, runner GitCommandRunner, prNodeID string, timeout time.Duration, pollInterval time.Duration) error

WaitForPRMerge polls until a PR is merged or times out. Returns nil if the PR is merged, error otherwise.

Types

type AppTokenProvider added in v0.20.0

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

AppTokenProvider mints GitHub App installation access tokens for repositories. Installation tokens are durable — the underlying transport refreshes them before expiry — so background jobs (the repo sync loop) can authenticate git fetches with no user present. The App must be installed on the repo's owner.

func NewAppTokenProvider added in v0.20.0

func NewAppTokenProvider(appID int64, privateKeyPEM []byte) (*AppTokenProvider, error)

NewAppTokenProvider builds a provider from a GitHub App ID and its PEM-encoded private key (PKCS#1 or PKCS#8).

func (*AppTokenProvider) InstallationToken added in v0.20.0

func (p *AppTokenProvider) InstallationToken(ctx context.Context, owner, name string) (string, error)

InstallationToken returns a fresh installation access token scoped to the owner of owner/name. The installation ID is resolved once per owner and cached; the token itself is minted and refreshed by the underlying transport.

type AutoMergeStatus

type AutoMergeStatus struct {
	Enabled     bool
	EnabledAt   string
	EnabledBy   string
	MergeMethod string
}

AutoMergeStatus represents the state of GitHub's auto-merge feature on a PR

func GetAutoMergeStatus

func GetAutoMergeStatus(ctx context.Context, runner GitCommandRunner, prNodeID string) (*AutoMergeStatus, error)

GetAutoMergeStatus checks if auto-merge is enabled on a PR and returns its status.

type CheckConclusion added in v0.22.0

type CheckConclusion string

CheckConclusion is a GitHub check-run conclusion.

const (
	CheckConclusionSuccess        CheckConclusion = "SUCCESS"
	CheckConclusionFailure        CheckConclusion = "FAILURE"
	CheckConclusionNeutral        CheckConclusion = "NEUTRAL"
	CheckConclusionSkipped        CheckConclusion = "SKIPPED"
	CheckConclusionCanceled       CheckConclusion = "CANCELED"
	CheckConclusionTimedOut       CheckConclusion = "TIMED_OUT"
	CheckConclusionActionRequired CheckConclusion = "ACTION_REQUIRED"
)

type CheckDetail

type CheckDetail struct {
	Name       string
	Status     CheckRunStatus
	Conclusion CheckConclusion
	StartedAt  time.Time
	FinishedAt time.Time
}

CheckDetail represents the status of an individual CI check

type CheckRunStatus added in v0.22.0

type CheckRunStatus string

CheckRunStatus is a GitHub check-run status.

const (
	CheckRunStatusQueued     CheckRunStatus = "QUEUED"
	CheckRunStatusInProgress CheckRunStatus = "IN_PROGRESS"
	CheckRunStatusCompleted  CheckRunStatus = "COMPLETED"
)

type CheckStatus

type CheckStatus struct {
	Passing        bool
	Pending        bool
	Checks         []CheckDetail
	ReviewDecision ReviewDecision // empty if none
	Author         string         // GitHub username of PR author
	State          git.PRState    // empty if unknown
}

CheckStatus represents the combined status of all CI checks for a PR

func (*CheckStatus) HasFailingChecks

func (s *CheckStatus) HasFailingChecks() bool

HasFailingChecks returns true if any CI checks are failing

func (*CheckStatus) HasPendingChecks

func (s *CheckStatus) HasPendingChecks() bool

HasPendingChecks returns true if any CI checks are pending

func (*CheckStatus) IsApproved

func (s *CheckStatus) IsApproved() bool

IsApproved returns true if the review decision indicates approval

func (*CheckStatus) IsReady

func (s *CheckStatus) IsReady() bool

IsReady returns true if all checks pass and the PR is approved

type ChecksByBranch added in v0.22.0

type ChecksByBranch map[string]*CheckStatus

ChecksByBranch maps branch names to their PR check status. Branches without a PR (or whose status could not be fetched) are absent.

func BatchGetPRChecksStatusGraphQL

func BatchGetPRChecksStatusGraphQL(ctx context.Context, runner GitCommandRunner, repo Repo, branchNames []string) (ChecksByBranch, error)

BatchGetPRChecksStatusGraphQL returns the check status for multiple branches using a single GraphQL query. This function fetches both CI check status and PR review decisions in a single request for efficiency.

func (ChecksByBranch) Get added in v0.22.0

func (c ChecksByBranch) Get(branch string) *CheckStatus

Get returns the check status for a branch, or nil if unknown. Safe to call on a nil map.

type Client

type Client interface {
	// CreatePullRequest creates a new pull request
	CreatePullRequest(ctx context.Context, opts CreatePROptions) (*PullRequestInfo, error)

	// UpdatePullRequest updates an existing pull request
	// Returns warnings (non-fatal issues like failed label/assignee additions) and error
	UpdatePullRequest(ctx context.Context, prNumber int, opts UpdatePROptions) (warnings []string, err error)

	// GetPullRequestByBranch gets a pull request for a branch
	GetPullRequestByBranch(ctx context.Context, branchName string) (*PullRequestInfo, error)

	// GetPullRequest gets a pull request by number
	GetPullRequest(ctx context.Context, prNumber int) (*PullRequestInfo, error)

	// MergePullRequest merges a pull request using the specified merge method
	MergePullRequest(ctx context.Context, branchName string, opts MergePROptions) error

	// GetAllowedMergeMethods returns the allowed merge methods for the repository
	GetAllowedMergeMethods(ctx context.Context) (*MergeMethodSettings, error)

	// GetPRChecksStatus returns the check status for a single branch
	GetPRChecksStatus(ctx context.Context, branchName string) (*CheckStatus, error)

	// BatchGetPRChecksStatus returns the check status for multiple branches
	BatchGetPRChecksStatus(ctx context.Context, branchNames []string) (ChecksByBranch, error)

	// BatchGetPRTitles returns titles for multiple PRs by number
	BatchGetPRTitles(ctx context.Context, prNumbers []int) (map[int]string, error)

	// Repo returns the repository the client is bound to
	Repo() Repo

	// ClosePullRequest closes a pull request
	ClosePullRequest(ctx context.Context, prNumber int) error

	// Comment methods for navigation location support
	// CreatePRComment creates a new comment on a pull request
	CreatePRComment(ctx context.Context, prNumber int, body string) (int64, error)

	// UpdatePRComment updates an existing pull request comment
	UpdatePRComment(ctx context.Context, commentID int64, body string) error

	// DeletePRComment deletes a pull request comment
	DeletePRComment(ctx context.Context, commentID int64) error

	// ListPRComments lists all comments on a pull request
	ListPRComments(ctx context.Context, prNumber int) ([]PRComment, error)

	// GetCurrentUser returns the authenticated GitHub username
	GetCurrentUser(ctx context.Context) (string, error)
}

Client is an interface for GitHub API interactions

type CreatePROptions

type CreatePROptions struct {
	Title         string
	Body          string
	Head          string
	Base          string
	Draft         bool
	Reviewers     []string
	TeamReviewers []string
	Labels        []string
	Assignees     []string
}

CreatePROptions contains options for creating a pull request

type EnableAutoMergeOptions

type EnableAutoMergeOptions struct {
	MergeMethod MergeMethod
	CommitBody  string // optional — omit for default GitHub behavior
}

EnableAutoMergeOptions contains options for enabling auto-merge on a PR.

type GitCommandRunner added in v0.19.1

type GitCommandRunner interface {
	GetConfig(key string) (string, error)
	RunGHCommandWithContext(ctx context.Context, args ...string) (string, error)
}

GitCommandRunner is the minimal git surface the GitHub integration needs: it reads git config (to resolve the host and token) and executes gh CLI commands. The full git.Runner satisfies it, so callers pass their existing runner; the GitHub package depends only on these two methods rather than the whole git surface.

type MergeMethod

type MergeMethod string

MergeMethod represents a GitHub PR merge method

const (
	// MergeMethodMerge creates a merge commit
	MergeMethodMerge MergeMethod = "merge"
	// MergeMethodSquash squashes commits before merging
	MergeMethodSquash MergeMethod = "squash"
	// MergeMethodRebase rebases commits onto base branch
	MergeMethodRebase MergeMethod = "rebase"
)

func (MergeMethod) Valid added in v0.22.0

func (m MergeMethod) Valid() bool

Valid reports whether m is one of the accepted merge methods.

type MergeMethodSettings

type MergeMethodSettings struct {
	AllowMergeCommit bool
	AllowSquashMerge bool
	AllowRebaseMerge bool
}

MergeMethodSettings contains the allowed merge methods for a repository

type MergePROptions

type MergePROptions struct {
	Method     MergeMethod
	CommitBody string // Optional commit body for merge/squash commit message.
}

MergePROptions configures how a pull request should be merged.

type PRComment

type PRComment struct {
	ID   int64
	Body string
}

PRComment represents a comment on a pull request

type PRContent added in v0.19.1

type PRContent struct {
	Title string
	Body  string
}

PRContent is the current title and body of a pull request, fetched in bulk.

type PRMergeableState

type PRMergeableState struct {
	Mergeable      bool   // True if PR can be merged without conflicts
	MergeStateText string // mergeStateStatus value: CLEAN, DIRTY, BLOCKED, UNKNOWN, etc.
	State          git.PRState
}

PRMergeableState represents the mergeable state of a PR

func GetPRMergeableState

func GetPRMergeableState(ctx context.Context, runner GitCommandRunner, prNodeID string) (*PRMergeableState, error)

GetPRMergeableState checks if a PR has merge conflicts.

func WaitForMergeable

func WaitForMergeable(ctx context.Context, runner GitCommandRunner, prNodeID string, timeout time.Duration, pollInterval time.Duration) (*PRMergeableState, error)

WaitForMergeable polls until a PR's mergeStateStatus becomes CLEAN or HAS_HOOKS (ready to merge). Returns the final PRMergeableState when ready. Returns ErrPRAlreadyMerged if the PR is merged during polling. Returns an error if the PR is CLOSED, DIRTY (conflicts), times out, or the context is canceled.

type PRStateBody added in v0.19.2

type PRStateBody struct {
	State git.PRState
	Body  string
}

PRStateBody holds the subset of pull-request fields needed to append a consolidation footer and decide whether a PR still needs closing.

type PullRequestInfo

type PullRequestInfo struct {
	Number  int
	NodeID  string
	HTMLURL string
	Title   string
	Body    string
	State   git.PRState
	Draft   bool
	Base    string
	Head    string
	// Warnings contains non-fatal issues that occurred during PR creation/update
	// (e.g., failed to add labels or assignees)
	Warnings []string
}

PullRequestInfo contains information about a pull request This is a simplified struct to avoid coupling to go-github library

func ToPullRequestInfo

func ToPullRequestInfo(pr *github.PullRequest) *PullRequestInfo

ToPullRequestInfo converts a github.PullRequest to PullRequestInfo

type Repo added in v0.22.0

type Repo struct {
	Owner string
	Name  string
}

Repo identifies a GitHub repository by owner and name.

func (Repo) String added in v0.22.0

func (r Repo) String() string

String returns the "owner/name" form.

type RepoAccess added in v0.20.0

type RepoAccess struct {
	Owner         string
	Name          string
	DefaultBranch string
	CloneURL      string
	Private       bool
	CanPush       bool
}

RepoAccess describes a user's access to a GitHub repository — enough for the onboarding flow to decide whether to proceed and how to clone it. Because the lookup is authenticated with a specific user's token, CanPush reflects that user's permission level, not the server's.

func CheckRepoAccess added in v0.20.0

func CheckRepoAccess(ctx context.Context, token, owner, name string) (*RepoAccess, error)

CheckRepoAccess verifies that token grants access to owner/name on github.com and returns the repository's canonical coordinates. A nil error means the authenticated user can at least read the repo; ErrRepoAccessDenied means the repo is missing or invisible to that token. Other errors are transport-level.

type RepoInfo

type RepoInfo struct {
	Hostname string
	Owner    string
	Repo     string
}

RepoInfo contains parsed information from a git remote URL

func ParseGitHubRemoteURL

func ParseGitHubRemoteURL(remoteURL string) (*RepoInfo, error)

ParseGitHubRemoteURL parses a git remote URL and extracts hostname, owner, and repo Supports both github.com and GitHub Enterprise URLs Examples:

type ReviewDecision added in v0.22.0

type ReviewDecision string

ReviewDecision is a GitHub PR review decision.

const (
	ReviewDecisionApproved         ReviewDecision = "APPROVED"
	ReviewDecisionChangesRequested ReviewDecision = "CHANGES_REQUESTED"
	ReviewDecisionReviewRequired   ReviewDecision = "REVIEW_REQUIRED"
)

type StackitGitHubClient

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

StackitGitHubClient implements Client using the real GitHub API

func NewGitHubClient

func NewGitHubClient(ctx context.Context, runner GitCommandRunner) (*StackitGitHubClient, error)

NewGitHubClient creates a new RealGitHubClient

func (*StackitGitHubClient) BatchGetPRChecksStatus

func (c *StackitGitHubClient) BatchGetPRChecksStatus(ctx context.Context, branchNames []string) (ChecksByBranch, error)

BatchGetPRChecksStatus returns the check status for multiple branches

func (*StackitGitHubClient) BatchGetPRTitles

func (c *StackitGitHubClient) BatchGetPRTitles(ctx context.Context, prNumbers []int) (map[int]string, error)

BatchGetPRTitles returns titles for multiple PRs by number

func (*StackitGitHubClient) ClosePullRequest

func (c *StackitGitHubClient) ClosePullRequest(ctx context.Context, prNumber int) error

ClosePullRequest closes a pull request

func (*StackitGitHubClient) CreatePRComment

func (c *StackitGitHubClient) CreatePRComment(ctx context.Context, prNumber int, body string) (int64, error)

CreatePRComment creates a new comment on a pull request

func (*StackitGitHubClient) CreatePullRequest

func (c *StackitGitHubClient) CreatePullRequest(ctx context.Context, opts CreatePROptions) (*PullRequestInfo, error)

CreatePullRequest creates a new pull request

func (*StackitGitHubClient) DeletePRComment

func (c *StackitGitHubClient) DeletePRComment(ctx context.Context, commentID int64) error

DeletePRComment deletes a pull request comment

func (*StackitGitHubClient) GetAllowedMergeMethods

func (c *StackitGitHubClient) GetAllowedMergeMethods(ctx context.Context) (*MergeMethodSettings, error)

GetAllowedMergeMethods returns the allowed merge methods for the repository

func (*StackitGitHubClient) GetCurrentUser

func (c *StackitGitHubClient) GetCurrentUser(ctx context.Context) (string, error)

GetCurrentUser returns the authenticated GitHub username

func (*StackitGitHubClient) GetPRChecksStatus

func (c *StackitGitHubClient) GetPRChecksStatus(ctx context.Context, branchName string) (*CheckStatus, error)

GetPRChecksStatus returns the check status for a single branch

func (*StackitGitHubClient) GetPullRequest

func (c *StackitGitHubClient) GetPullRequest(ctx context.Context, prNumber int) (*PullRequestInfo, error)

GetPullRequest gets a pull request by number

func (*StackitGitHubClient) GetPullRequestByBranch

func (c *StackitGitHubClient) GetPullRequestByBranch(ctx context.Context, branchName string) (*PullRequestInfo, error)

GetPullRequestByBranch gets a pull request for a branch

func (*StackitGitHubClient) ListPRComments

func (c *StackitGitHubClient) ListPRComments(ctx context.Context, prNumber int) ([]PRComment, error)

ListPRComments lists all comments on a pull request with pagination

func (*StackitGitHubClient) MergePullRequest

func (c *StackitGitHubClient) MergePullRequest(ctx context.Context, branchName string, opts MergePROptions) error

MergePullRequest merges a pull request using the specified merge method

func (*StackitGitHubClient) Repo added in v0.22.0

func (c *StackitGitHubClient) Repo() Repo

Repo returns the repository the client is bound to

func (*StackitGitHubClient) UpdatePRComment

func (c *StackitGitHubClient) UpdatePRComment(ctx context.Context, commentID int64, body string) error

UpdatePRComment updates an existing pull request comment

func (*StackitGitHubClient) UpdatePullRequest

func (c *StackitGitHubClient) UpdatePullRequest(ctx context.Context, prNumber int, opts UpdatePROptions) ([]string, error)

UpdatePullRequest updates an existing pull request

type UpdatePROptions

type UpdatePROptions struct {
	Title           *string
	Body            *string
	Base            *string
	Draft           *bool
	Reviewers       []string
	TeamReviewers   []string
	Labels          []string
	Assignees       []string
	MergeWhenReady  *bool
	RerequestReview bool
}

UpdatePROptions contains options for updating a pull request

Jump to

Keyboard shortcuts

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