Help us shape the future of Go! Take the 2026 Go Developer Survey

github

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: May 18, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultMaxRetries is the default maximum number of retry attempts
	DefaultMaxRetries = 3

	// DefaultBaseDelay is the default base delay for exponential backoff
	DefaultBaseDelay = 1 * time.Second

	// DefaultMaxDelay is the default maximum delay between retries
	DefaultMaxDelay = 30 * time.Second

	// DefaultTimeout is the default request timeout
	DefaultTimeout = 30 * time.Second

	// DefaultCacheTTL is the default cache time-to-live
	DefaultCacheTTL = 5 * time.Minute
)

Default configuration values

Variables

View Source
var ErrBranchProtectionPermissionDenied = errors.New("insufficient permissions to read branch protection rules")

Functions

func DetectBaseChanged

func DetectBaseChanged(existingPR *PullRequest, detectedBase string) bool

DetectBaseChanged checks if the base branch of an existing PR differs from the detected base Returns true if the base has changed and needs updating

func DetectRebase

func DetectRebase(existingPR *PullRequest, currentBaseSHA string) bool

DetectRebase checks if the base commit SHA has changed, indicating a rebase occurred This is different from DetectBaseChanged which only checks branch names Returns true if the base SHA differs, suggesting a rebase on the same branch

func DetectReviewerConflicts

func DetectReviewerConflicts(currentReviewers []string, parentPR *PullRequest) []string

DetectReviewerConflicts checks for potential reviewer assignment conflicts in stacked PRs Returns warnings about reviewers assigned to multiple levels of the stack

func FormatReviewerAssignment

func FormatReviewerAssignment(assignment *ReviewerAssignment, parentPR *PullRequest, inherited bool) string

FormatReviewerAssignment formats assigned reviewers for display

func FormatStackingMetadata

func FormatStackingMetadata(parentPR *PullRequest) string

FormatStackingMetadata formats the stacking information to be added to PR body Shows parent PR reference and stacking context

func GenerateCacheKey

func GenerateCacheKey(method, path string, params map[string]string) string

GenerateCacheKey creates a cache key from request parameters

func IsAuthenticationError

func IsAuthenticationError(err error) bool

IsAuthenticationError checks if an error is an AuthenticationError

func IsAuthorizationError

func IsAuthorizationError(err error) bool

IsAuthorizationError checks if an error is an AuthorizationError

func IsCircularDependencyError

func IsCircularDependencyError(err error) bool

IsCircularDependencyError checks if an error is a CircularDependencyError

func IsInvalidBaseError

func IsInvalidBaseError(err error) bool

IsInvalidBaseError checks if an error is an InvalidBaseError

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error is a NotFoundError

func IsParentPRConflictError

func IsParentPRConflictError(err error) bool

IsParentPRConflictError checks if an error is a ParentPRConflictError

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError checks if an error is a RateLimitError

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError checks if an error is retryable This checks for both explicit RetryableError and RateLimitError types

func IsStackingError

func IsStackingError(err error) bool

IsStackingError checks if an error is a StackingError

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a ValidationError

func ParseErrorResponse

func ParseErrorResponse(errResp *ErrorResponse) error

ParseErrorResponse converts a GitHub API ErrorResponse to an appropriate error type

func RetryWithBackoff

func RetryWithBackoff(ctx context.Context, policy *RetryPolicy, fn RetryFunc) (*http.Response, error)

RetryWithBackoff retries a function with exponential backoff It returns the last response and error encountered

func ShouldRetry

func ShouldRetry(resp *http.Response, err error) bool

ShouldRetry determines if an HTTP response should be retried

Types

type AssignReviewersRequest

type AssignReviewersRequest struct {
	Reviewers     []string `json:"reviewers,omitempty"`      // Individual user logins
	TeamReviewers []string `json:"team_reviewers,omitempty"` // Team slugs (without org prefix)
}

AssignReviewersRequest represents the payload for requesting reviewers

type AuthenticationError

type AuthenticationError struct {
	Message string
	Err     error
}

AuthenticationError represents an authentication failure (401)

func NewAuthenticationError

func NewAuthenticationError(message string, err error) *AuthenticationError

NewAuthenticationError creates a new AuthenticationError

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

type AuthorizationError

type AuthorizationError struct {
	Message  string
	Resource string // The resource that was denied
	Err      error
}

AuthorizationError represents an authorization failure (403)

func NewAuthorizationError

func NewAuthorizationError(message string, resource string, err error) *AuthorizationError

NewAuthorizationError creates a new AuthorizationError

func (*AuthorizationError) Error

func (e *AuthorizationError) Error() string

func (*AuthorizationError) Unwrap

func (e *AuthorizationError) Unwrap() error

type Cache

type Cache interface {
	// Get retrieves a cached value by key
	Get(key string) (value interface{}, found bool)

	// Set stores a value in the cache with a TTL
	Set(key string, value interface{}, ttl time.Duration)

	// Delete removes a value from the cache
	Delete(key string)

	// Clear removes all values from the cache
	Clear()

	// GetETag retrieves the ETag for a cached key
	GetETag(key string) (etag string, found bool)

	// SetWithETag stores a value with its ETag
	SetWithETag(key string, value interface{}, etag string, ttl time.Duration)

	// Stats returns cache statistics
	Stats() CacheStats
}

Cache defines the interface for caching GitHub API responses

type CacheStats

type CacheStats struct {
	Hits      int64   // Number of cache hits
	Misses    int64   // Number of cache misses
	Evictions int64   // Number of evictions due to TTL expiration
	Size      int     // Current number of entries
	HitRate   float64 // Hit rate percentage (hits / (hits + misses))
}

CacheStats holds statistics about cache performance

type CircuitBreaker

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

CircuitBreaker tracks failures and can temporarily stop requests

func NewCircuitBreaker

func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow checks if a request should be allowed through

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current state of the circuit breaker

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker

const (
	// CircuitClosed means requests are allowed
	CircuitClosed CircuitState = iota
	// CircuitOpen means requests are blocked
	CircuitOpen
	// CircuitHalfOpen means testing if service recovered
	CircuitHalfOpen
)

type CircularDependencyError

type CircularDependencyError struct {
	Message       string
	Branches      []string // The branches forming the circular dependency
	CurrentPR     int      // Current PR number
	ConflictingPR int      // PR number that creates the circular dependency
	Err           error
}

CircularDependencyError represents a circular dependency in stacked PRs

func NewCircularDependencyError

func NewCircularDependencyError(message string, branches []string, currentPR, conflictingPR int, err error) *CircularDependencyError

NewCircularDependencyError creates a new CircularDependencyError

func (*CircularDependencyError) Error

func (e *CircularDependencyError) Error() string

func (*CircularDependencyError) Unwrap

func (e *CircularDependencyError) Unwrap() error

type Client

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

Client is a wrapper around go-gh's REST and GraphQL clients with enhanced features

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient creates a new GitHub client with the specified options It automatically detects the current repository context and sets up authentication

func (*Client) AssignReviewers

func (c *Client) AssignReviewers(
	ctx context.Context,
	owner, repo string,
	number int,
	users, teams []string,
) error

AssignReviewers assigns reviewers to a pull request via GitHub API POST /repos/{owner}/{repo}/pulls/{number}/requested_reviewers

func (*Client) AssignReviewersForCurrentRepo

func (c *Client) AssignReviewersForCurrentRepo(
	ctx context.Context,
	number int,
	users, teams []string,
) error

AssignReviewersForCurrentRepo assigns reviewers to a PR in the current repository

func (*Client) CacheStats

func (c *Client) CacheStats() CacheStats

CacheStats returns statistics about the cache

func (*Client) CheckDraftTransition

func (c *Client) CheckDraftTransition(
	ctx context.Context,
	owner, repo string,
	pr *PullRequest,
) (*DraftTransitionResult, error)

CheckDraftTransition determines if a PR can safely transition from draft to ready Takes into account dependent PRs that might be affected by the state change

func (*Client) CheckDraftTransitionForCurrentRepo

func (c *Client) CheckDraftTransitionForCurrentRepo(
	ctx context.Context,
	pr *PullRequest,
) (*DraftTransitionResult, error)

CheckDraftTransitionForCurrentRepo checks draft transition for a PR in the current repository

func (*Client) ClearCache

func (c *Client) ClearCache()

ClearCache clears all cached entries

func (*Client) Close

func (c *Client) Close() error

Close stops the client and cleans up resources Should be called when the client is no longer needed

func (*Client) ConvertPRToDraft

func (c *Client) ConvertPRToDraft(ctx context.Context, owner, repo string, pr *PullRequest) (*PullRequest, error)

ConvertPRToDraft converts a ready pull request to draft status This uses the GitHub GraphQL API since there's no REST endpoint for this Requires the PR to have a NodeID populated

func (*Client) ConvertPRToDraftForCurrentRepo

func (c *Client) ConvertPRToDraftForCurrentRepo(ctx context.Context, pr *PullRequest) (*PullRequest, error)

ConvertPRToDraftForCurrentRepo converts a ready PR to draft in the current repository

func (*Client) CreatePullRequest

func (c *Client) CreatePullRequest(
	ctx context.Context,
	owner, repo string,
	title, head, base, body string,
	draft bool,
	parentPR *PullRequest,
) (*PullRequest, error)

CreatePullRequest creates a new pull request in the specified repository It handles stacking by accepting dynamic base branch and formatting stacking metadata

func (*Client) CreatePullRequestForCurrentRepo

func (c *Client) CreatePullRequestForCurrentRepo(
	ctx context.Context,
	title, head, base, body string,
	draft bool,
	parentPR *PullRequest,
) (*PullRequest, error)

CreatePullRequestForCurrentRepo creates a PR in the current repository context

func (*Client) CurrentUser

func (c *Client) CurrentUser(ctx context.Context) (*User, error)

CurrentUser retrieves information about the authenticated user

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body interface{}, response interface{}) error

Do executes an HTTP request with retry logic, caching, and ETag support

func (*Client) DoGraphQL

func (c *Client) DoGraphQL(ctx context.Context, query string, variables map[string]interface{}, response interface{}) error

DoGraphQL executes a GraphQL query with retry logic

func (*Client) EnrichPullRequest

func (c *Client) EnrichPullRequest(ctx context.Context, owner, repo string, pr *PullRequest) error

EnrichPullRequest fetches and adds additional metadata to a pull request This includes reviews, checks, and requested reviewers

func (*Client) EnrichPullRequests

func (c *Client) EnrichPullRequests(ctx context.Context, owner, repo string, prs []*PullRequest) error

EnrichPullRequests enriches multiple pull requests with metadata in parallel

func (*Client) FindDependentPRs

func (c *Client) FindDependentPRs(ctx context.Context, owner, repo, baseBranch string) ([]*PullRequest, error)

FindDependentPRs finds all pull requests that target the given branch as their base These are "child" PRs in a stacked PR workflow - PRs that depend on the given branch

func (*Client) FindDependentPRsForCurrentBranch

func (c *Client) FindDependentPRsForCurrentBranch(ctx context.Context, branchName string) ([]*PullRequest, error)

FindDependentPRsForCurrentBranch finds dependent PRs for the current repository's branch

func (*Client) FindExistingPR

func (c *Client) FindExistingPR(ctx context.Context, owner, repo, branchName string) (*PullRequest, error)

FindExistingPR finds an existing pull request for the given branch Returns the PR if found, nil if not found, or error if there was an API issue

func (*Client) FindExistingPRForCurrentBranch

func (c *Client) FindExistingPRForCurrentBranch(ctx context.Context, branchName string) (*PullRequest, error)

FindExistingPRForCurrentBranch finds an existing PR for the current repository's branch

func (*Client) GetCurrentRepositoryPullRequests

func (c *Client) GetCurrentRepositoryPullRequests(ctx context.Context, opts *PullRequestListOptions) ([]*PullRequest, error)

GetCurrentRepositoryPullRequests fetches PRs for the current repository context

func (*Client) GetCurrentRepositoryPullRequestsWithPagination

func (c *Client) GetCurrentRepositoryPullRequestsWithPagination(ctx context.Context, opts *PullRequestListOptions) ([]*PullRequest, error)

GetCurrentRepositoryPullRequestsWithPagination fetches all PRs for the current repository

func (*Client) GetCurrentUser

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

GetCurrentUser returns the login name of the authenticated user

func (*Client) GetPullRequestChecks

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

GetPullRequestChecks fetches check runs for a specific pull request's head commit

func (*Client) GetPullRequestRequestedReviewers

func (c *Client) GetPullRequestRequestedReviewers(ctx context.Context, owner, repo string, number int) ([]PRReviewer, error)

GetPullRequestRequestedReviewers fetches requested reviewers for a specific pull request

func (*Client) GetPullRequestReviews

func (c *Client) GetPullRequestReviews(ctx context.Context, owner, repo string, number int) ([]PRReview, error)

GetPullRequestReviews fetches reviews for a specific pull request

func (*Client) GetPullRequests

func (c *Client) GetPullRequests(ctx context.Context, owner, repo string, opts *PullRequestListOptions) ([]*PullRequest, error)

GetPullRequests fetches pull requests from the specified repository It handles pagination, rate limiting, and retries automatically

func (*Client) GetPullRequestsRaw

func (c *Client) GetPullRequestsRaw(ctx context.Context, owner, repo string, opts *PullRequestListOptions) ([]*PullRequest, *http.Response, error)

GetPullRequestsRaw fetches pull requests and returns the raw HTTP response This is useful for accessing pagination headers and other metadata

func (*Client) GetPullRequestsWithPagination

func (c *Client) GetPullRequestsWithPagination(ctx context.Context, owner, repo string, opts *PullRequestListOptions) ([]*PullRequest, error)

GetPullRequestsWithPagination fetches all pull requests across multiple pages It automatically handles pagination by following the Link header

func (*Client) GetRequiredStatusChecks added in v0.0.6

func (c *Client) GetRequiredStatusChecks(ctx context.Context, owner, repo, branch string) ([]RequiredCheck, error)

GetRequiredStatusChecks returns the required status checks for the given branch. Returns an empty list if the branch has no protection rules or the caller lacks admin permissions.

func (*Client) GetRequiredStatusChecksForCurrentRepo added in v0.0.6

func (c *Client) GetRequiredStatusChecksForCurrentRepo(ctx context.Context, branch string) ([]RequiredCheck, error)

GetRequiredStatusChecksForCurrentRepo returns required status checks for a branch in the current repo.

func (*Client) GraphQL

func (c *Client) GraphQL() *api.GraphQLClient

GraphQL returns the underlying GraphQL client

func (*Client) HandleStackedPRUpdate

func (c *Client) HandleStackedPRUpdate(
	ctx context.Context,
	existingPR *PullRequest,
	detectedBase string,
	currentBaseSHA string,
	promptUser bool,
) (*StackedPRUpdateResult, error)

HandleStackedPRUpdate orchestrates the complete workflow for updating stacked PR bases It detects base changes, optionally prompts user, updates PR base, and displays results Returns StackedPRUpdateResult with details of what was updated

func (*Client) InvalidateCacheKey

func (c *Client) InvalidateCacheKey(key string)

InvalidateCacheKey removes a specific key from the cache

func (*Client) MarkPRReadyForReview

func (c *Client) MarkPRReadyForReview(ctx context.Context, owner, repo string, pr *PullRequest) (*PullRequest, error)

MarkPRReadyForReview marks a draft pull request as ready for review This uses the GitHub GraphQL API since there's no REST endpoint for this Requires the PR to have a NodeID populated

func (*Client) MarkPRReadyForReviewForCurrentRepo

func (c *Client) MarkPRReadyForReviewForCurrentRepo(ctx context.Context, pr *PullRequest) (*PullRequest, error)

MarkPRReadyForReviewForCurrentRepo marks a draft PR as ready in the current repository

func (*Client) MergePullRequest added in v0.0.6

func (c *Client) MergePullRequest(ctx context.Context, owner, repo string, number int, opts *MergeOptions) (*MergeResult, error)

MergePullRequest merges a pull request via the GitHub API. PUT /repos/{owner}/{repo}/pulls/{number}/merge

func (*Client) MergePullRequestForCurrentRepo added in v0.0.6

func (c *Client) MergePullRequestForCurrentRepo(ctx context.Context, number int, opts *MergeOptions) (*MergeResult, error)

MergePullRequestForCurrentRepo merges a PR in the current repository context

func (*Client) REST

func (c *Client) REST() *api.RESTClient

REST returns the underlying REST client

func (*Client) Repository

func (c *Client) Repository() *Repository

Repository returns the current repository context

func (*Client) UpdatePRBase

func (c *Client) UpdatePRBase(ctx context.Context, owner, repo string, number int, newBase string) error

UpdatePRBase updates the base branch of an existing pull request This is useful for stacked PRs when the parent branch changes

func (*Client) UpdatePRBaseForCurrentRepo

func (c *Client) UpdatePRBaseForCurrentRepo(ctx context.Context, number int, newBase string) error

UpdatePRBaseForCurrentRepo updates the base branch for a PR in the current repository

func (*Client) UpdatePullRequest

func (c *Client) UpdatePullRequest(
	ctx context.Context,
	owner, repo string,
	number int,
	title, body string,
	draft *bool,
	parentPR *PullRequest,
) (*PullRequest, error)

UpdatePullRequest updates an existing pull request with stacking awareness Handles updating title, body, state, base branch, and draft status

func (*Client) UpdatePullRequestForCurrentRepo

func (c *Client) UpdatePullRequestForCurrentRepo(
	ctx context.Context,
	number int,
	title, body string,
	draft *bool,
	parentPR *PullRequest,
) (*PullRequest, error)

UpdatePullRequestForCurrentRepo updates a PR in the current repository context

func (*Client) VerifyAuthentication

func (c *Client) VerifyAuthentication(ctx context.Context) error

VerifyAuthentication checks if the client is properly authenticated by attempting to retrieve the current user's information

type ClientOption

type ClientOption func(*Client) error

ClientOption is a functional option for configuring the Client

func WithBaseDelay

func WithBaseDelay(delay time.Duration) ClientOption

WithBaseDelay sets the base delay for exponential backoff

func WithCache

func WithCache(cache Cache) ClientOption

WithCache sets a custom cache implementation

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) ClientOption

WithCacheTTL sets the cache time-to-live duration

func WithConfig

func WithConfig(config *Config) ClientOption

WithConfig sets the entire configuration

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client

func WithMaxDelay

func WithMaxDelay(delay time.Duration) ClientOption

WithMaxDelay sets the maximum delay between retries

func WithMaxRetries

func WithMaxRetries(maxRetries int) ClientOption

WithMaxRetries sets the maximum number of retry attempts

func WithRepository

func WithRepository(owner, name string) ClientOption

WithRepository sets the repository context manually

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the request timeout

func WithoutCache

func WithoutCache() ClientOption

WithoutCache disables response caching

type Config

type Config struct {
	// MaxRetries is the maximum number of retry attempts for transient failures
	MaxRetries int

	// BaseDelay is the base delay for exponential backoff
	BaseDelay time.Duration

	// MaxDelay is the maximum delay between retries
	MaxDelay time.Duration

	// Timeout is the request timeout duration
	Timeout time.Duration

	// CacheTTL is the cache time-to-live duration
	CacheTTL time.Duration

	// EnableCache enables response caching
	EnableCache bool

	// HTTPClient is the underlying HTTP client (optional)
	HTTPClient *http.Client
}

Config holds configuration options for the GitHub client

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default values

type CreatePRRequest

type CreatePRRequest struct {
	Title               string `json:"title"`
	Head                string `json:"head"`            // branch name (source)
	Base                string `json:"base"`            // base branch (target)
	Body                string `json:"body"`            // PR description
	Draft               bool   `json:"draft,omitempty"` // optional draft state
	MaintainerCanModify bool   `json:"maintainer_can_modify,omitempty"`
}

CreatePRRequest represents the payload for creating a pull request

type DraftTransitionResult

type DraftTransitionResult struct {
	CanTransition     bool     // Whether the PR can safely transition to ready
	BlockingReasons   []string // Reasons preventing transition
	DependentPRsOpen  bool     // Whether there are dependent PRs still open
	DependentPRsDraft bool     // Whether dependent PRs are in draft state
	DependentPRCount  int      // Number of dependent PRs found
}

DraftTransitionResult represents the result of checking if a PR can transition from draft

type ErrorResponse

type ErrorResponse struct {
	Message          string       `json:"message"`
	DocumentationURL string       `json:"documentation_url,omitempty"`
	Errors           []FieldError `json:"errors,omitempty"`
	StatusCode       int          `json:"-"` // HTTP status code (not in JSON)
}

ErrorResponse represents GitHub's error response format This matches the structure of GitHub API error responses

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

type FieldError

type FieldError struct {
	Field   string // The field that failed validation
	Code    string // Error code (e.g., "missing", "invalid", "already_exists")
	Message string // Human-readable error message
}

FieldError represents a validation error for a specific field

type GitHubClient

type GitHubClient interface {
	// REST returns the underlying REST client
	REST() *api.RESTClient

	// GraphQL returns the underlying GraphQL client
	GraphQL() *api.GraphQLClient

	// Repository returns the current repository context
	Repository() *Repository

	// Do executes an HTTP request with retry logic and caching
	Do(ctx context.Context, method, path string, body interface{}, response interface{}) error

	// DoGraphQL executes a GraphQL query
	DoGraphQL(ctx context.Context, query string, variables map[string]interface{}, response interface{}) error
}

GitHubClient defines the interface for GitHub API operations This interface allows for easy mocking in tests

type InvalidBaseError

type InvalidBaseError struct {
	Message    string
	BaseBranch string   // The invalid base branch
	ValidBases []string // List of valid base branches (if available)
	Err        error
}

InvalidBaseError represents an invalid base branch error in stacked PRs

func NewInvalidBaseError

func NewInvalidBaseError(message string, baseBranch string, validBases []string, err error) *InvalidBaseError

NewInvalidBaseError creates a new InvalidBaseError

func (*InvalidBaseError) Error

func (e *InvalidBaseError) Error() string

func (*InvalidBaseError) Unwrap

func (e *InvalidBaseError) Unwrap() error

type MemoryCache

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

MemoryCache is a thread-safe in-memory cache with TTL and ETag support

func NewMemoryCache

func NewMemoryCache(cleanupInterval time.Duration) *MemoryCache

NewMemoryCache creates a new in-memory cache with automatic cleanup

func (*MemoryCache) Clear

func (m *MemoryCache) Clear()

Clear removes all values from the cache

func (*MemoryCache) Delete

func (m *MemoryCache) Delete(key string)

Delete removes a value from the cache

func (*MemoryCache) Get

func (m *MemoryCache) Get(key string) (interface{}, bool)

Get retrieves a cached value by key

func (*MemoryCache) GetETag

func (m *MemoryCache) GetETag(key string) (string, bool)

GetETag retrieves the ETag for a cached key

func (*MemoryCache) Set

func (m *MemoryCache) Set(key string, value interface{}, ttl time.Duration)

Set stores a value in the cache with a TTL

func (*MemoryCache) SetWithETag

func (m *MemoryCache) SetWithETag(key string, value interface{}, etag string, ttl time.Duration)

SetWithETag stores a value with its ETag

func (*MemoryCache) Stats

func (m *MemoryCache) Stats() CacheStats

Stats returns cache statistics

func (*MemoryCache) Stop

func (m *MemoryCache) Stop()

Stop stops the background cleanup goroutine Should be called when the cache is no longer needed

type MergeConflictError added in v0.0.6

type MergeConflictError struct {
	Err error
}

MergeConflictError indicates the PR has merge conflicts

func (*MergeConflictError) Error added in v0.0.6

func (e *MergeConflictError) Error() string

func (*MergeConflictError) Unwrap added in v0.0.6

func (e *MergeConflictError) Unwrap() error

type MergeMethodNotAllowedError added in v0.0.6

type MergeMethodNotAllowedError struct {
	Method string
	Err    error
}

MergeMethodNotAllowedError indicates the merge method is not permitted by repo settings

func (*MergeMethodNotAllowedError) Error added in v0.0.6

func (*MergeMethodNotAllowedError) Unwrap added in v0.0.6

func (e *MergeMethodNotAllowedError) Unwrap() error

type MergeOptions added in v0.0.6

type MergeOptions struct {
	Method          string // "squash" or "rebase"
	CommitTitle     string // squash only: merge commit title
	CommitMessage   string // squash only: merge commit body
	ExpectedHeadSHA string // reject merge if PR head has moved
}

MergeOptions contains options for merging a pull request

type MergeResult added in v0.0.6

type MergeResult struct {
	Merged  bool   `json:"merged"`
	SHA     string `json:"sha"`
	Message string `json:"message"`
}

MergeResult represents the result of a merge operation

type NoOpCache

type NoOpCache struct{}

NoOpCache is a cache implementation that does nothing Used when caching is disabled

func (*NoOpCache) Clear

func (n *NoOpCache) Clear()

Clear does nothing

func (*NoOpCache) Delete

func (n *NoOpCache) Delete(key string)

Delete does nothing

func (*NoOpCache) Get

func (n *NoOpCache) Get(key string) (interface{}, bool)

Get always returns not found

func (*NoOpCache) GetETag

func (n *NoOpCache) GetETag(key string) (string, bool)

GetETag always returns empty string and false

func (*NoOpCache) Set

func (n *NoOpCache) Set(key string, value interface{}, ttl time.Duration)

Set does nothing

func (*NoOpCache) SetWithETag

func (n *NoOpCache) SetWithETag(key string, value interface{}, etag string, ttl time.Duration)

SetWithETag does nothing

func (*NoOpCache) Stats

func (n *NoOpCache) Stats() CacheStats

Stats returns empty statistics

type NotFoundError

type NotFoundError struct {
	Message  string
	Resource string // The resource that was not found
	Err      error
}

NotFoundError represents a resource not found error (404)

func NewNotFoundError

func NewNotFoundError(message string, resource string, err error) *NotFoundError

NewNotFoundError creates a new NotFoundError

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type NotMergeableError added in v0.0.6

type NotMergeableError struct {
	Reason string
	Err    error
}

NotMergeableError indicates the PR cannot be merged (e.g., branch protection)

func (*NotMergeableError) Error added in v0.0.6

func (e *NotMergeableError) Error() string

func (*NotMergeableError) Unwrap added in v0.0.6

func (e *NotMergeableError) Unwrap() error

type PRBranch

type PRBranch struct {
	Ref  string       `json:"ref"`  // branch name
	SHA  string       `json:"sha"`  // commit SHA
	Repo PRRepository `json:"repo"` // repository info
}

PRBranch represents a branch in a pull request (head or base)

type PRCheck

type PRCheck struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Status      string    `json:"status"`     // queued, in_progress, completed
	Conclusion  string    `json:"conclusion"` // success, failure, neutral, cancelled, skipped, timed_out, action_required
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at,omitempty"`
	App         *struct {
		ID int `json:"id"`
	} `json:"app,omitempty"`
}

PRCheck represents a check run status

type PRRepository

type PRRepository struct {
	Name     string `json:"name"`
	FullName string `json:"full_name"` // owner/name format
	Owner    PRUser `json:"owner"`
}

PRRepository represents minimal repository information

type PRReview

type PRReview struct {
	ID          int       `json:"id"`
	User        PRUser    `json:"user"`
	State       string    `json:"state"` // APPROVED, CHANGES_REQUESTED, COMMENTED, DISMISSED, PENDING
	SubmittedAt time.Time `json:"submitted_at"`
}

PRReview represents a pull request review

type PRReviewer

type PRReviewer struct {
	Login string `json:"login"`
	Type  string `json:"type"` // User or Team
}

PRReviewer represents a requested reviewer

type PRStatus

type PRStatus struct {
	ReviewStatus string // approved, changes_requested, review_required, commented, pending
	CheckStatus  string // success, failure, pending, in_progress, neutral
}

PRStatus represents the aggregated status of a pull request

func DeterminePRStatus

func DeterminePRStatus(reviews []PRReview, checks []PRCheck) PRStatus

DeterminePRStatus analyzes reviews and checks to determine overall PR status

type PRUser

type PRUser struct {
	Login string `json:"login"`
	Name  string `json:"name,omitempty"`
	Email string `json:"email,omitempty"`
}

PRUser represents a user associated with a pull request

type ParentPRConflictError

type ParentPRConflictError struct {
	Message     string
	ParentPR    int    // Parent PR number
	ParentState string // Parent PR state (closed, merged, etc.)
	Reason      string // Reason for the conflict
	Err         error
}

ParentPRConflictError represents a conflict with the parent PR in stacked workflow

func NewParentPRConflictError

func NewParentPRConflictError(message string, parentPR int, parentState, reason string, err error) *ParentPRConflictError

NewParentPRConflictError creates a new ParentPRConflictError

func (*ParentPRConflictError) Error

func (e *ParentPRConflictError) Error() string

func (*ParentPRConflictError) Unwrap

func (e *ParentPRConflictError) Unwrap() error

type PullRequest

type PullRequest struct {
	Number    int       `json:"number"`
	NodeID    string    `json:"node_id"` // GraphQL global node ID
	Title     string    `json:"title"`
	Body      string    `json:"body"`
	State     string    `json:"state"` // open, closed
	Draft     bool      `json:"draft"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	User      PRUser    `json:"user"`
	Head      PRBranch  `json:"head"`
	Base      PRBranch  `json:"base"`
	HTMLURL   string    `json:"html_url"`

	// Additional fields populated by separate API calls
	Reviews   []PRReview   `json:"-"` // Not included in list PR response
	Checks    []PRCheck    `json:"-"` // Not included in list PR response
	Reviewers []PRReviewer `json:"-"` // Not included in list PR response
}

PullRequest represents a GitHub pull request with all relevant information

type PullRequestListOptions

type PullRequestListOptions struct {
	State     string // open, closed, all (default: open)
	Sort      string // created, updated, popularity, long-running (default: created)
	Direction string // asc, desc (default: desc)
	PerPage   int    // Results per page (default: 30, max: 100)
	Page      int    // Page number (default: 1)
}

PullRequestListOptions contains options for listing pull requests

func DefaultPullRequestListOptions

func DefaultPullRequestListOptions() *PullRequestListOptions

DefaultPullRequestListOptions returns options with sensible defaults

type RateLimitError

type RateLimitError struct {
	Message   string
	Limit     int
	Remaining int
	ResetAt   int64 // Unix timestamp
	Err       error
}

RateLimitError represents a rate limit error (429)

func NewRateLimitError

func NewRateLimitError(message string, limit, remaining int, resetAt int64, err error) *RateLimitError

NewRateLimitError creates a new RateLimitError

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

func (*RateLimitError) IsRetryable

func (e *RateLimitError) IsRetryable() bool

IsRetryable returns true since rate limit errors are transient

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type RateLimitInfo

type RateLimitInfo struct {
	Limit     int       // Maximum number of requests per hour
	Remaining int       // Number of requests remaining in the current window
	Reset     time.Time // Time when the rate limit resets
}

RateLimitInfo contains information about GitHub API rate limits

func ParseRateLimitHeaders

func ParseRateLimitHeaders(headers http.Header) *RateLimitInfo

ParseRateLimitHeaders extracts rate limit information from HTTP response headers GitHub returns X-RateLimit-* headers with rate limit information

func (*RateLimitInfo) IsRateLimited

func (r *RateLimitInfo) IsRateLimited() bool

IsRateLimited checks if the rate limit has been exceeded

func (*RateLimitInfo) String

func (r *RateLimitInfo) String() string

String returns a string representation of the rate limit info

func (*RateLimitInfo) TimeUntilReset

func (r *RateLimitInfo) TimeUntilReset() time.Duration

TimeUntilReset returns the duration until the rate limit resets

type Repository

type Repository struct {
	Owner string
	Name  string
}

Repository represents a GitHub repository context

func (*Repository) String

func (r *Repository) String() string

String returns the repository in "owner/name" format

type RequiredCheck added in v0.0.6

type RequiredCheck struct {
	Context string
	AppID   *int
}

RequiredCheck represents a required status check from branch protection rules.

type RetryFunc

type RetryFunc func() (*http.Response, error)

RetryFunc is a function that can be retried

type RetryPolicy

type RetryPolicy struct {
	MaxRetries int
	BaseDelay  time.Duration
	MaxDelay   time.Duration
}

RetryPolicy defines the retry behavior

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy returns a retry policy with sensible defaults

type RetryableError

type RetryableError struct {
	Message string
	Err     error
}

RetryableError represents an error that can be retried

func NewRetryableError

func NewRetryableError(message string, err error) *RetryableError

NewRetryableError creates a new RetryableError

func (*RetryableError) Error

func (e *RetryableError) Error() string

func (*RetryableError) IsRetryable

func (e *RetryableError) IsRetryable() bool

IsRetryable returns true

func (*RetryableError) Unwrap

func (e *RetryableError) Unwrap() error

type ReviewerAssignment

type ReviewerAssignment struct {
	Users []string // Individual GitHub usernames (without @ prefix)
	Teams []string // Team slugs in org/team format (without @ prefix)
}

ReviewerAssignment represents parsed reviewers separated by type

func GetStackAwareReviewers

func GetStackAwareReviewers(opts *StackAwareReviewerOptions) *ReviewerAssignment

GetStackAwareReviewers returns reviewers considering stacking context Handles reviewer inheritance, deduplication, and conflict detection

func ParseReviewers

func ParseReviewers(reviewers []string) *ReviewerAssignment

ParseReviewers parses a list of @usernames and @org/team into separate lists Removes the @ prefix and separates individual users from team reviewers

type StackAwareReviewerOptions

type StackAwareReviewerOptions struct {
	CurrentReviewers []string     // Reviewers from template for current PR
	ParentPR         *PullRequest // Parent PR in stack (if any)
	CurrentUser      string       // Current user to filter out
	InheritParent    bool         // Whether to inherit parent PR reviewers
	DeduplicateStack bool         // Whether to deduplicate across stack
}

StackAwareReviewerOptions contains options for stack-aware reviewer suggestions

type StackedPRUpdateResult

type StackedPRUpdateResult struct {
	UpdatedBase    bool   // Whether the base was actually updated
	OldBase        string // Previous base branch name
	NewBase        string // New base branch name
	RebaseDetected bool   // Whether a rebase was detected
	Error          error  // Any error that occurred
}

StackedPRUpdateResult represents the result of a stacked PR update operation

type StackingError

type StackingError struct {
	Message       string
	CurrentBranch string                 // Current branch name
	BaseBranch    string                 // Base branch name
	Operation     string                 // Operation being performed (create, update, etc.)
	Context       map[string]interface{} // Additional context
	Err           error
}

StackingError represents a general stacking-related error

func NewStackingError

func NewStackingError(message string, currentBranch, baseBranch, operation string, err error) *StackingError

NewStackingError creates a new StackingError

func (*StackingError) Error

func (e *StackingError) Error() string

func (*StackingError) Unwrap

func (e *StackingError) Unwrap() error

func (*StackingError) WithContext

func (e *StackingError) WithContext(key string, value interface{}) *StackingError

WithContext adds context to a StackingError

type UpdatePRRequest

type UpdatePRRequest struct {
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
	State string `json:"state,omitempty"` // open, closed
	Base  string `json:"base,omitempty"`  // base branch
	Draft *bool  `json:"draft,omitempty"` // pointer to allow nil (no change) vs false (ready for review)
}

UpdatePRRequest represents the payload for updating a pull request

type User

type User struct {
	Login string
	Name  string
	Email string
}

User represents a GitHub user

type ValidationError

type ValidationError struct {
	Message string
	Errors  []FieldError // Field-specific validation errors
	Err     error
}

ValidationError represents a validation error (422)

func NewValidationError

func NewValidationError(message string, errors []FieldError, err error) *ValidationError

NewValidationError creates a new ValidationError

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Jump to

Keyboard shortcuts

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