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

pr

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package pr provides pull request operations for GitHub and GitLab.

Core types:

  • Provider: Interface for creating and managing pull requests
  • Options: Configuration for creating a pull request
  • PullRequest: Represents a created pull request with URL and number
  • Builder: Fluent builder for constructing PR descriptions

Implementations:

  • GitHubProvider: GitHub PR provider using go-github
  • GitLabProvider: GitLab MR provider using go-gitlab

Example usage:

provider, _ := pr.NewGitHubProvider(token, "owner", "repo")
pull, err := provider.CreatePR(ctx, pr.Options{
    Title: "Add feature",
    Body:  "Description",
    Base:  "main",
    Head:  "feature/my-branch",
})

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoProvider indicates no PR provider is configured.
	ErrNoProvider = errors.New("no PR provider configured")

	// ErrUnknownProvider indicates the git remote uses an unknown provider.
	ErrUnknownProvider = errors.New("unknown git provider")

	// ErrExists indicates a PR already exists for the branch.
	ErrExists = errors.New("pull request already exists for this branch")

	// ErrNotFound indicates the PR does not exist.
	ErrNotFound = errors.New("pull request not found")

	// ErrClosed indicates the PR is closed.
	ErrClosed = errors.New("pull request is closed")

	// ErrMerged indicates the PR is already merged.
	ErrMerged = errors.New("pull request is already merged")

	// ErrBranchNotPushed indicates the branch has not been pushed to remote.
	ErrBranchNotPushed = errors.New("branch not pushed to remote")

	// ErrNoChanges indicates there are no changes between branches.
	ErrNoChanges = errors.New("no changes between branches")

	// ErrMergeConflict indicates a merge conflict occurred.
	ErrMergeConflict = errors.New("merge conflict")
)

PR provider errors

Functions

func ContextWithProvider

func ContextWithProvider(ctx context.Context, p Provider) context.Context

ContextWithProvider adds a PR Provider to a context.Context. Use ProviderFromContext to retrieve it.

Example:

provider, _ := pr.ProviderFromEnv(remoteURL)
ctx := pr.ContextWithProvider(context.Background(), provider)
// Pass ctx to functions that need PR access

func DetectProvider

func DetectProvider(remoteURL string) (string, error)

DetectProvider attempts to detect the PR provider from a remote URL.

func ParseRepoFromURL

func ParseRepoFromURL(remoteURL string) (owner, repo string, err error)

ParseRepoFromURL extracts owner and repo from a git remote URL.

Types

type Builder

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

Builder helps construct PR options using a fluent interface.

func NewBuilder

func NewBuilder(title string) *Builder

NewBuilder creates a new PR builder with the given title.

func (*Builder) AsDraft

func (b *Builder) AsDraft() *Builder

AsDraft creates as a draft PR.

func (*Builder) Build

func (b *Builder) Build() Options

Build returns the constructed PR options.

func (*Builder) WithAssignees

func (b *Builder) WithAssignees(assignees ...string) *Builder

WithAssignees adds assignees.

func (*Builder) WithBase

func (b *Builder) WithBase(base string) *Builder

WithBase sets the target branch.

func (*Builder) WithBody

func (b *Builder) WithBody(body string) *Builder

WithBody sets the PR body.

func (*Builder) WithHead

func (b *Builder) WithHead(head string) *Builder

WithHead sets the source branch.

func (*Builder) WithLabels

func (b *Builder) WithLabels(labels ...string) *Builder

WithLabels adds labels.

func (*Builder) WithMetadata

func (b *Builder) WithMetadata(key, value string) *Builder

WithMetadata adds custom metadata.

func (*Builder) WithMilestone

func (b *Builder) WithMilestone(milestone string) *Builder

WithMilestone sets the milestone.

func (*Builder) WithReviewers

func (b *Builder) WithReviewers(reviewers ...string) *Builder

WithReviewers adds reviewers.

func (*Builder) WithSummary

func (b *Builder) WithSummary(summary string, changes []string, testPlan string) *Builder

WithSummary creates a formatted body with summary, changes, and test plan.

func (*Builder) WithTicket

func (b *Builder) WithTicket(ticketID string) *Builder

WithTicket adds a ticket reference to the title. Example: "Add feature" -> "[TK-421] Add feature"

type Filter

type Filter struct {
	State     State    // Filter by state (empty = all)
	Base      string   // Filter by base branch
	Head      string   // Filter by head branch
	Author    string   // Filter by author username
	Labels    []string // Filter by labels (all must match)
	Sort      string   // Sort field (created, updated)
	Direction string   // Sort direction (asc, desc)
	Limit     int      // Maximum number to return (0 = default)
}

Filter configures pull request listing.

type GitHubProvider

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

GitHubProvider implements Provider for GitHub repositories.

func NewGitHubProvider

func NewGitHubProvider(token, owner, repo string) (*GitHubProvider, error)

NewGitHubProvider creates a new GitHub provider. token is a personal access token or GitHub App token. owner and repo identify the repository (e.g., "anthropic", "devflow").

func NewGitHubProviderFromURL

func NewGitHubProviderFromURL(token, remoteURL string) (*GitHubProvider, error)

NewGitHubProviderFromURL creates a GitHub provider from a remote URL. Example: "https://github.com/randalmurphal/devflow.git"

func (*GitHubProvider) AddComment

func (p *GitHubProvider) AddComment(ctx context.Context, id int, body string) error

AddComment adds a comment to a pull request.

func (*GitHubProvider) CreatePR

func (p *GitHubProvider) CreatePR(ctx context.Context, opts Options) (*PullRequest, error)

CreatePR creates a new pull request.

func (*GitHubProvider) GetPR

func (p *GitHubProvider) GetPR(ctx context.Context, id int) (*PullRequest, error)

GetPR retrieves a pull request by number.

func (*GitHubProvider) ListPRs

func (p *GitHubProvider) ListPRs(ctx context.Context, filter Filter) ([]*PullRequest, error)

ListPRs lists pull requests matching the filter.

func (*GitHubProvider) MergePR

func (p *GitHubProvider) MergePR(ctx context.Context, id int, opts MergeOptions) error

MergePR merges a pull request.

func (*GitHubProvider) RequestReview

func (p *GitHubProvider) RequestReview(ctx context.Context, id int, reviewers []string) error

RequestReview requests review from the specified users.

func (*GitHubProvider) UpdatePR

func (p *GitHubProvider) UpdatePR(ctx context.Context, id int, opts UpdateOptions) (*PullRequest, error)

UpdatePR updates an existing pull request.

type GitLabProvider

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

GitLabProvider implements Provider for GitLab repositories.

func NewGitLabProvider

func NewGitLabProvider(token, baseURL, projectID string) (*GitLabProvider, error)

NewGitLabProvider creates a new GitLab provider. token is a personal access token. baseURL is the GitLab instance URL (empty for gitlab.com). projectID can be numeric ID or "namespace/project" path.

func NewGitLabProviderFromURL

func NewGitLabProviderFromURL(token, remoteURL string) (*GitLabProvider, error)

NewGitLabProviderFromURL creates a GitLab provider from a remote URL. Example: "https://gitlab.com/namespace/project.git"

func (*GitLabProvider) AddComment

func (p *GitLabProvider) AddComment(ctx context.Context, id int, body string) error

AddComment adds a note to a merge request.

func (*GitLabProvider) CreatePR

func (p *GitLabProvider) CreatePR(ctx context.Context, opts Options) (*PullRequest, error)

CreatePR creates a new merge request.

func (*GitLabProvider) GetPR

func (p *GitLabProvider) GetPR(ctx context.Context, id int) (*PullRequest, error)

GetPR retrieves a merge request by IID.

func (*GitLabProvider) ListPRs

func (p *GitLabProvider) ListPRs(ctx context.Context, filter Filter) ([]*PullRequest, error)

ListPRs lists merge requests matching the filter.

func (*GitLabProvider) MergePR

func (p *GitLabProvider) MergePR(ctx context.Context, id int, opts MergeOptions) error

MergePR merges a merge request.

func (*GitLabProvider) RequestReview

func (p *GitLabProvider) RequestReview(ctx context.Context, id int, reviewers []string) error

RequestReview requests review from the specified users. Note: GitLab uses reviewer IDs, so usernames should be numeric IDs.

func (*GitLabProvider) UpdatePR

func (p *GitLabProvider) UpdatePR(ctx context.Context, id int, opts UpdateOptions) (*PullRequest, error)

UpdatePR updates an existing merge request.

type MergeMethod

type MergeMethod string

MergeMethod specifies how to merge a pull request.

const (
	MergeMethodMerge  MergeMethod = "merge"
	MergeMethodSquash MergeMethod = "squash"
	MergeMethodRebase MergeMethod = "rebase"
)

type MergeOptions

type MergeOptions struct {
	Method        MergeMethod // Merge method (merge, squash, rebase)
	CommitTitle   string      // Custom commit title (for squash/merge)
	CommitMessage string      // Custom commit message (for squash/merge)
	SHA           string      // Expected HEAD SHA (for optimistic locking)
	DeleteBranch  bool        // Delete source branch after merge
}

MergeOptions configures pull request merging.

type MockProvider

type MockProvider struct {
	CreatePRFunc      func(ctx context.Context, opts Options) (*PullRequest, error)
	GetPRFunc         func(ctx context.Context, id int) (*PullRequest, error)
	UpdatePRFunc      func(ctx context.Context, id int, opts UpdateOptions) (*PullRequest, error)
	MergePRFunc       func(ctx context.Context, id int, opts MergeOptions) error
	AddCommentFunc    func(ctx context.Context, id int, body string) error
	RequestReviewFunc func(ctx context.Context, id int, reviewers []string) error
	ListPRsFunc       func(ctx context.Context, filter Filter) ([]*PullRequest, error)
}

MockProvider is a mock implementation of Provider for testing.

func (*MockProvider) AddComment

func (m *MockProvider) AddComment(ctx context.Context, id int, body string) error

AddComment implements Provider.

func (*MockProvider) CreatePR

func (m *MockProvider) CreatePR(ctx context.Context, opts Options) (*PullRequest, error)

CreatePR implements Provider.

func (*MockProvider) GetPR

func (m *MockProvider) GetPR(ctx context.Context, id int) (*PullRequest, error)

GetPR implements Provider.

func (*MockProvider) ListPRs

func (m *MockProvider) ListPRs(ctx context.Context, filter Filter) ([]*PullRequest, error)

ListPRs implements Provider.

func (*MockProvider) MergePR

func (m *MockProvider) MergePR(ctx context.Context, id int, opts MergeOptions) error

MergePR implements Provider.

func (*MockProvider) RequestReview

func (m *MockProvider) RequestReview(ctx context.Context, id int, reviewers []string) error

RequestReview implements Provider.

func (*MockProvider) UpdatePR

func (m *MockProvider) UpdatePR(ctx context.Context, id int, opts UpdateOptions) (*PullRequest, error)

UpdatePR implements Provider.

type Options

type Options struct {
	Title     string            // PR title (required)
	Body      string            // PR description (markdown)
	Base      string            // Target branch (default: "main")
	Head      string            // Source branch (auto-detected if empty)
	Labels    []string          // Labels to apply
	Reviewers []string          // Reviewer usernames
	Assignees []string          // Assignee usernames
	Draft     bool              // Create as draft
	Milestone string            // Milestone name or ID
	Metadata  map[string]string // Additional metadata
}

Options configures pull request creation.

type Provider

type Provider interface {
	// CreatePR creates a new pull request.
	CreatePR(ctx context.Context, opts Options) (*PullRequest, error)

	// GetPR retrieves a pull request by ID.
	GetPR(ctx context.Context, id int) (*PullRequest, error)

	// UpdatePR updates an existing pull request.
	UpdatePR(ctx context.Context, id int, opts UpdateOptions) (*PullRequest, error)

	// MergePR merges a pull request.
	MergePR(ctx context.Context, id int, opts MergeOptions) error

	// AddComment adds a comment to a pull request.
	AddComment(ctx context.Context, id int, body string) error

	// RequestReview requests review from the specified users.
	RequestReview(ctx context.Context, id int, reviewers []string) error

	// ListPRs lists pull requests matching the filter.
	ListPRs(ctx context.Context, filter Filter) ([]*PullRequest, error)
}

Provider is the interface for creating and managing pull requests. Implementations exist for GitHub and GitLab.

func MustProviderFromContext

func MustProviderFromContext(ctx context.Context) Provider

MustProviderFromContext retrieves a PR Provider or panics. Use in code where provider is required and missing is a programming error.

func MustProviderFromEnv

func MustProviderFromEnv(remoteURL string) Provider

MustProviderFromEnv creates a provider or panics. Use when the provider is required and missing is a programming error.

func ProviderFromContext

func ProviderFromContext(ctx context.Context) Provider

ProviderFromContext retrieves a PR Provider from a context.Context. Returns nil if no Provider is present.

Example:

func createPR(ctx context.Context, title string) (*PullRequest, error) {
    provider := pr.ProviderFromContext(ctx)
    if provider == nil {
        return nil, ErrNoProvider
    }
    return provider.CreatePR(ctx, Options{Title: title})
}

func ProviderFromEnv

func ProviderFromEnv(remoteURL string) (Provider, error)

ProviderFromEnv creates a provider based on remote URL and environment. Automatically detects GitHub vs GitLab and uses appropriate token env var.

Environment variables checked:

  • GITHUB_TOKEN for GitHub
  • GITLAB_TOKEN for GitLab
  • GIT_TOKEN as fallback for either

Example:

remoteURL, _ := gitCtx.GetRemoteURL("origin")
provider, err := pr.ProviderFromEnv(remoteURL)
if err != nil {
    log.Fatal(err)
}
pr, _ := provider.CreatePR(ctx, opts)

func ProviderFromEnvWithToken

func ProviderFromEnvWithToken(remoteURL, token string) (Provider, error)

ProviderFromEnvWithToken creates a provider with an explicit token. Use this when you have the token from configuration rather than environment.

Example:

token := config.GetGitToken()
provider, err := pr.ProviderFromEnvWithToken(remoteURL, token)

type PullRequest

type PullRequest struct {
	ID           int        // PR number/ID
	URL          string     // Web URL
	HTMLURL      string     // Full HTML URL
	Title        string     // PR title
	Body         string     // PR description
	State        State      // Current state
	Draft        bool       // Whether it's a draft
	Head         string     // Source branch
	Base         string     // Target branch
	CreatedAt    time.Time  // Creation time
	UpdatedAt    time.Time  // Last update time
	MergedAt     *time.Time // Merge time (nil if not merged)
	MergedBy     string     // Username who merged
	Commits      int        // Number of commits
	Additions    int        // Lines added
	Deletions    int        // Lines deleted
	ChangedFiles int        // Number of files changed
	Labels       []string   // Applied labels
	Reviewers    []string   // Requested reviewers
	Assignees    []string   // Assigned users
}

PullRequest represents a created pull request.

type State

type State string

State represents the state of a pull request.

const (
	StateOpen   State = "open"
	StateClosed State = "closed"
	StateMerged State = "merged"
)

type UpdateOptions

type UpdateOptions struct {
	Title     *string  // New title (nil = no change)
	Body      *string  // New body (nil = no change)
	Base      *string  // New base branch (nil = no change)
	Labels    []string // Labels to set (replaces existing)
	Assignees []string // Assignees to set (replaces existing)
	Draft     *bool    // Draft status (nil = no change)
}

UpdateOptions configures pull request updates.

Jump to

Keyboard shortcuts

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