github

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package github provides a GitHub API client for pull request lifecycle management.

The package handles:

  • Creating and fetching pull requests with assignees, reviewers, and labels
  • Waiting for GitHub Actions workflow completion with real-time job-level visualization
  • Merging pull requests (merge, squash, or rebase strategies)
  • Deleting remote branches after merge
  • Label retrieval for interactive selection

Authentication requires a GITHUB_TOKEN environment variable containing a personal access token with repo scope.

Usage:

client, err := github.NewClient()
client.SetLogger(logger)
client.SetRepositoryFromURL("https://github.com/owner/repo.git")
labels, _ := client.ListLabels()
pr, _ := client.CreatePullRequest("feature", "main", "Title", "Body", []string{"user"}, []string{"reviewer"}, nil)

Thread Safety: Client is not safe for concurrent use. The workflow waiting methods use internal goroutines but the Client itself should be used from a single goroutine.

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrTokenRequired is returned when GITHUB_TOKEN environment variable is missing.
	ErrTokenRequired = errTokenRequired
	// ErrInvalidURLFormat is returned when the GitHub URL format is invalid.
	ErrInvalidURLFormat = errInvalidURLFormat
	// ErrWorkflowTimeout is returned when waiting for workflow completion times out.
	ErrWorkflowTimeout = errWorkflowTimeout
	// ErrPRNotFound is returned when no pull request is found for the branch.
	ErrPRNotFound = errPRNotFound
	// ErrPRAlreadyExists is returned when a pull request already exists for the branch.
	ErrPRAlreadyExists = errPRAlreadyExists
)

Error definitions for GitHub API operations.

Functions

func GetMergeMethod added in v0.4.0

func GetMergeMethod(squash bool) string

GetMergeMethod returns the appropriate merge method string for the GitHub API. Returns "squash" if squash is true, otherwise "merge".

Types

type APIClient added in v0.5.0

type APIClient interface {
	// SetRepositoryFromURL configures the repository from a git remote URL.
	// Supports both HTTPS and SSH formats.
	SetRepositoryFromURL(url string) error

	// ListLabels returns all labels available in the repository.
	ListLabels() ([]*Label, error)

	// CreatePullRequest creates a new pull request with the specified parameters.
	// Returns the created pull request or an error if creation fails.
	CreatePullRequest(
		head, base, title, body string,
		assignees, reviewers, labels []string,
	) (*github.PullRequest, error)

	// GetPullRequestByBranch fetches an existing pull request by head and base branches.
	// Returns errPRNotFound if no matching pull request exists.
	GetPullRequestByBranch(head, base string) (*github.PullRequest, error)

	// WaitForWorkflows waits for all workflow runs to complete for the pull request.
	// Returns the overall conclusion (success, failure, etc.) or an error on timeout.
	WaitForWorkflows(timeout time.Duration) (string, error)

	// MergePullRequest merges a pull request using the specified merge method.
	// mergeMethod can be "merge", "squash", or "rebase".
	// commitTitle is used as the merge commit message.
	MergePullRequest(prNumber int, mergeMethod, commitTitle string) error

	// GetPullRequestsByHead returns all open pull requests for the given head branch.
	GetPullRequestsByHead(head string) ([]*github.PullRequest, error)

	// DeleteBranch deletes a branch from the remote repository.
	DeleteBranch(branch string) error
}

APIClient defines the interface for GitHub API operations. This interface enables dependency injection and facilitates black box testing by allowing mock implementations to replace the actual GitHub API client.

type Client

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

Client represents a GitHub API client wrapper that manages pull request lifecycle operations. It stores internal state (owner, repo, prNumber, prSHA) that is set by methods like Client.SetRepositoryFromURL and Client.CreatePullRequest.

Not safe for concurrent use.

func NewClient

func NewClient() (*Client, error)

NewClient creates a new GitHub client authenticated via the GITHUB_TOKEN environment variable.

Returns ErrTokenRequired if GITHUB_TOKEN is not set.

func (*Client) CreatePullRequest

func (c *Client) CreatePullRequest(
	head, base, title, body string,
	assignees, reviewers, labels []string,
) (*github.PullRequest, error)

CreatePullRequest creates a new pull request with assignees, reviewers, and labels. Reviewers that match the PR author are automatically filtered out.

Parameters:

  • head: the source branch name
  • base: the target branch (e.g., "main")
  • title: PR title (must not be empty)
  • body: PR description
  • assignees: GitHub usernames to assign (may be nil)
  • reviewers: GitHub usernames to request review from (may be nil)
  • labels: label names to apply (may be nil)

Returns ErrPRAlreadyExists if a PR already exists for the same branches. Stores the PR number and SHA internally for use by Client.WaitForWorkflows.

func (*Client) DeleteBranch

func (c *Client) DeleteBranch(branch string) error

DeleteBranch deletes a branch from the remote repository via the GitHub Git Refs API.

Parameters:

  • branch: the branch name to delete (without "refs/heads/" prefix)

func (*Client) GetPullRequestByBranch

func (c *Client) GetPullRequestByBranch(head, base string) (*github.PullRequest, error)

GetPullRequestByBranch fetches an existing open pull request by head and base branches. Only the first matching PR is returned. Stores the PR number and SHA internally.

Returns ErrPRNotFound if no open PR matches the given branches.

func (*Client) GetPullRequestsByHead

func (c *Client) GetPullRequestsByHead(head string) ([]*github.PullRequest, error)

GetPullRequestsByHead returns all open pull requests for the given head branch.

func (*Client) ListLabels

func (c *Client) ListLabels() ([]*Label, error)

ListLabels returns all labels for the repository. Client.SetRepositoryFromURL must be called before this method.

Returns an empty slice if no labels are configured.

func (*Client) MergePullRequest

func (c *Client) MergePullRequest(prNumber int, mergeMethod, commitTitle string) error

MergePullRequest merges a pull request using the specified merge method.

Parameters:

  • prNumber: the pull request number
  • mergeMethod: one of "merge", "squash", or "rebase" (see GetMergeMethod)
  • commitTitle: used as the merge commit message

func (*Client) SetLogger

func (c *Client) SetLogger(logger *bullets.Logger)

SetLogger sets the logger for the GitHub client.

func (*Client) SetRepositoryFromURL

func (c *Client) SetRepositoryFromURL(url string) error

SetRepositoryFromURL sets the repository from a git remote URL. Supports both HTTPS and SSH URL formats:

Returns ErrInvalidURLFormat if the URL cannot be parsed into owner/repo. Returns a wrapped error if the repository does not exist or the API call fails.

func (*Client) WaitForWorkflows

func (c *Client) WaitForWorkflows(timeout time.Duration) (string, error)

WaitForWorkflows waits for all GitHub Actions workflow runs to complete for the pull request. It polls at 5-second intervals and displays real-time job-level progress with animated spinners. If no workflows are configured, it returns "success" immediately.

Parameters:

  • timeout: maximum wait duration (typically 1m to 8h)

Returns the overall conclusion ("success", "failure", "cancelled", etc.). Returns ErrWorkflowTimeout if the timeout is exceeded.

A pull request must have been created or fetched before calling this method.

type DisplayRenderer added in v0.5.0

type DisplayRenderer interface {
	// Info logs an informational message.
	Info(message string)

	// Debug logs a debug message.
	Debug(message string)

	// Error logs an error message.
	Error(message string)

	// Success logs a success message.
	Success(message string)

	// InfoHandle creates an updatable handle for an info message.
	// The handle can be updated with new content or converted to success/error.
	InfoHandle(message string) *bullets.BulletHandle

	// SpinnerCircle creates an animated spinner with the given message.
	// Returns a Spinner that can be stopped with Success(), Error(), or Replace().
	SpinnerCircle(message string) *bullets.Spinner

	// IncreasePadding increases the indentation level for nested output.
	IncreasePadding()

	// DecreasePadding decreases the indentation level for nested output.
	DecreasePadding()
}

DisplayRenderer defines the interface for UI rendering operations. This interface abstracts the bullets.Logger and bullets.UpdatableLogger functionality to enable testing of display logic without actual terminal output.

type JobInfo added in v0.5.0

type JobInfo struct {
	ID          int64      // Unique job ID
	Name        string     // Job name as defined in workflow YAML
	Status      string     // Current job status
	Conclusion  string     // Final conclusion (empty until completed)
	StartedAt   *time.Time // When the job started (nil if queued)
	CompletedAt *time.Time // When the job finished (nil if still running)
	HTMLURL     string     // Browser URL for the job
}

JobInfo represents a GitHub workflow job with detailed status information. Status values are: "queued", "in_progress", "completed". Conclusion values (only set when completed): "success", "failure", "cancelled", "skipped", "neutral".

type Label

type Label struct {
	Name string
}

Label represents a GitHub label.

type StateTracker added in v0.5.0

type StateTracker interface {
	// contains filtered or unexported methods
}

StateTracker defines the interface for thread-safe job/check state management. This interface abstracts the checkTracker functionality to enable testing of state transitions and display handle management without real API calls.

Jump to

Keyboard shortcuts

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