provider

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	CheckPass      = "pass"
	CheckFail      = "fail"
	CheckPending   = "pending" // queued or running
	CheckSkipped   = "skipped" // also neutral results and manual GitLab jobs
	CheckCancelled = "cancelled"
	ChecksNone     = "none" // no checks reported
)

Check states, the same for all providers. A PR's overall checks state is CheckPass, CheckFail, CheckPending or ChecksNone.

View Source
const (
	ReviewApproved         = "approved"
	ReviewChangesRequested = "changes_requested"
	ReviewCommented        = "commented"
	ReviewPending          = "pending" // asked to review, no verdict (yet)
)

Reviewer states.

View Source
const (
	DecisionApproved         = "approved"
	DecisionChangesRequested = "changes_requested"
	DecisionReviewRequired   = "review_required" // the provider requires (more) approvals
)

Review decisions; "" means no verdict.

View Source
const (
	BlockerNotOpen            = "not_open"
	BlockerDraft              = "draft"
	BlockerConflicts          = "conflicts"
	BlockerBehind             = "behind" // the base branch must be merged in first
	BlockerChecksFailed       = "checks_failed"
	BlockerChecksPending      = "checks_pending"
	BlockerChangesRequested   = "changes_requested"
	BlockerApprovalRequired   = "approval_required"
	BlockerUnresolvedComments = "unresolved_comments"
	BlockerOpenTasks          = "open_tasks"
	BlockerBlocked            = "blocked" // by other provider rules, see ProviderStatus
)

Merge blockers, in the order they are reported.

View Source
const (
	StateOpen   = "open"
	StateClosed = "closed" // closed without merging
	StateMerged = "merged"
)

PR states, the same for all providers.

Variables

This section is empty.

Functions

func CurrentBranch

func CurrentBranch(nfo *Info) (string, error)

CurrentBranch returns the current branch name of the repository detected from Info.

func DefaultBranchBitbucket

func DefaultBranchBitbucket(ctx context.Context, bb *bitbucketAPIClient, nfo *Info) (string, error)

DefaultBranchBitbucket returns the main branch of a Bitbucket Cloud repository.

func DefaultBranchGitHub

func DefaultBranchGitHub(ctx context.Context, gh *githublib.Client, nfo *Info) (string, error)

DefaultBranchGitHub returns the default branch for a GitHub repository.

func DefaultBranchGitLab

func DefaultBranchGitLab(ctx context.Context, gl *gitlab.Client, nfo *Info) (string, error)

DefaultBranchGitLab returns the default branch for a GitLab project.

func FindRepoRoot

func FindRepoRoot(path string) (root, gitdir, wt string, err error)

FindRepoRoot returns the absolute path to the root of the repository and git related dir locations: - wt: if "" => the git checkout at root is not a worktree or path to git worktree folder - gitdir: absolute path to root of git repository dir ($root/.git if not in worktree)

func IsAuthError

func IsAuthError(err error) bool

IsAuthError reports whether err is caused by missing credentials or by credentials the provider rejected (HTTP 401).

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a provider API "404 Not Found" response, e.g. for a non-existent PR, comment or task.

func IsUnsupported

func IsUnsupported(err error) bool

IsUnsupported reports whether err is an UnsupportedError.

func LastCommitTitle

func LastCommitTitle(nfo *Info) (string, error)

LastCommitTitle returns the first line of the last commit message on HEAD.

func LocalBranchDelete

func LocalBranchDelete(repo *git.Repository, name string, force bool) error

LocalBranchDelete deletes a local branch reference. It refuses to delete the currently checked out branch. The force flag is currently ignored for safety (git also refuses deletion of the current branch).

func LocalBranchRename

func LocalBranchRename(repo *git.Repository, oldName, newName string) error

LocalBranchRename renames a local branch reference and updates HEAD if needed.

func ResolvePRTitle

func ResolvePRTitle(inTitle string, nfo *Info) (string, error)

ResolvePRTitle ensures a non-empty title, using last commit subject when missing.

Types

type AddCommentOptions

type AddCommentOptions struct {
	Path string `json:"path"`
	Line int    `json:"line"`
	Body string `json:"body"`
}

AddCommentOptions holds parameters for adding an inline PR comment.

type AddTaskOptions

type AddTaskOptions struct {
	Body string `json:"body"`
	// CommentID attaches the task to an existing comment (optional).
	CommentID int `json:"comment_id,omitempty"`
	// Pending creates the task as part of the caller's unsubmitted review.
	Pending bool `json:"pending,omitempty"`
}

AddTaskOptions holds parameters for creating a PR task.

type AuthError

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

AuthError reports missing credentials.

func (*AuthError) Error

func (e *AuthError) Error() string

type BranchDeleteOptions

type BranchDeleteOptions struct {
	Force bool
}

type BranchInfo

type BranchInfo struct {
	Name       string    `json:"name"`
	CommitDate time.Time `json:"commit_date"`
	Author     string    `json:"author"`
}

type BranchListOptions

type BranchListOptions struct {
	Pattern string
	Sort    string // name|date|author
	Author  string // case-insensitive substring match on author
	Since   string // human duration like 72h, 10d, 3w
}

type BranchRenameOptions

type BranchRenameOptions struct {
	// NoUpdatePRs leaves open PRs targeting the branch alone.
	NoUpdatePRs bool
	// Force renames even if open GitLab MRs use the branch as source, which
	// GitLab cannot change: those MRs lose their source branch.
	Force bool
}

type Check

type Check struct {
	Name string `json:"name"`
	// Group is the GitLab pipeline stage.
	Group string `json:"group,omitempty"`
	// State is CheckPass, CheckFail, CheckPending, CheckSkipped or
	// CheckCancelled.
	State string `json:"state"`
	// ProviderState is the provider's own status, lowercased, e.g. GitHub
	// "timed_out" or GitLab "manual".
	ProviderState string `json:"provider_state"`
	// Optional is set for checks allowed to fail (GitLab allow_failure);
	// their failure does not fail the PR's checks.
	Optional    bool      `json:"optional,omitempty"`
	Description string    `json:"description,omitempty"`
	URL         string    `json:"url,omitempty"`
	StartedAt   time.Time `json:"started_at,omitzero"`
	CompletedAt time.Time `json:"completed_at,omitzero"`
}

Check is one CI result of a PR: a GitHub check run or commit status, a GitLab pipeline job, or a Bitbucket build status.

type ChecksReport

type ChecksReport struct {
	PR     int    `json:"pr"`
	Commit string `json:"commit,omitempty"`
	// State is CheckFail if a non-optional check failed or was cancelled,
	// else CheckPending while any check is pending, else CheckPass;
	// ChecksNone without checks.
	State string `json:"state"`
	// URL is the GitLab pipeline.
	URL    string  `json:"url,omitempty"`
	Checks []Check `json:"checks"`
}

ChecksReport lists the checks of a PR's head commit.

func (*ChecksReport) Pending

func (r *ChecksReport) Pending() int

Pending returns the number of pending checks.

type CloseOptions

type CloseOptions struct {
	// DeleteBranch deletes the source branch after closing, in the
	// repository it lives in, which may be a fork.
	DeleteBranch bool
}

CloseOptions controls PrClose.

type CommentCounts

type CommentCounts struct {
	Total int `json:"total"`
	// Unresolved counts unresolved threads that can be resolved.
	Unresolved int `json:"unresolved"`
}

CommentCounts counts the comments of a PR, as listed by `pr comments`.

type CreateOptions

type CreateOptions struct {
	Title string
	Body  string
	Base  string // target branch
	Head  string // source branch
	Draft bool
	// SquashByDefault indicates the PR/MR should default to squashing commits when merged
	// (provider support varies; ignored where unsupported)
	SquashByDefault  bool
	DeleteAfterMerge bool
}

CreateOptions controls PR/MR creation.

type Info

type Info struct {
	LocalRepo

	Provider Provider // enum: github|gitlab|bitbucket|unknown
	Variant  string   // cloud|self-hosted|unknown
	Evidence string   // method used (e.g. config, api_v4_version, headers, url-heuristic)
	HTTPBase string   // web root (configured, or the http(s) base used for probing), if any
	APIBase  string   // configured API root (api_url), if any

	// HostConfig is the [hosts] entry of Host, if any.
	HostConfig *config.HostConfig

	Host   string // e.g. github.com
	Owner  string // e.g. user or project
	Repo   string // repository name without .git
	Remote string // remote name used (e.g. origin)
	URL    string // original remote URL used

	Config *config.Config // user configuration (may be nil)
}

Info contains parsed repository and provider details inferred from git remotes.

func DetectFromRepo

func DetectFromRepo(ctx context.Context, localRepo *LocalRepo, cfg *config.Config) (*Info, error)

DetectFromRepo infers provider and repo info for an already detected local repository by inspecting remotes (preferring origin, then upstream, then first). It also performs light network probing (like the Python reference) to identify self-hosted services. Canceling ctx stops probing.

func (*Info) WebRoot

func (nfo *Info) WebRoot() string

WebRoot returns the web root of the repository's host without trailing slash, e.g. https://github.com or https://example.com/gitlab.

type InvalidArgumentError

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

InvalidArgumentError reports a caller error detected before contacting the provider (e.g. an empty body or unknown filter value).

func (*InvalidArgumentError) Error

func (e *InvalidArgumentError) Error() string

type ListOptions

type ListOptions struct {
	State    string // open (default), closed (without merging), merged or all
	Author   string
	Assignee string
	Base     string
	Head     string
	Limit    int
}

ListOptions are filters for PR list queries.

type LocalRepo

type LocalRepo struct {
	Root     string          // absolute repository root directory (worktree), respects -C
	GitDir   string          // absolute path to /../.git dir (resolved .git file if inside worktree)
	Worktree string          // absolute path to /../.git/worktrees/<name>
	GitRepo  *git.Repository // handle to git repository instance or nil if not available
}

func FindLocalRepo

func FindLocalRepo(path string) (*LocalRepo, error)

type MergeOptions

type MergeOptions struct {
	// Method is merge, squash or rebase; empty uses the provider's or
	// repository's default. GitLab does not support rebase.
	Method string
	// DeleteBranch deletes (true) or keeps (false) the source branch; nil
	// leaves it to the PR's or repository's setting.
	DeleteBranch *bool
}

MergeOptions controls how a PR/MR is merged.

type MergeStatus

type MergeStatus struct {
	// Mergeable is the provider's verdict: GitHub mergeable_state, GitLab
	// detailed_merge_status. It is nil while the provider is still checking,
	// and always on Bitbucket, which does not report one.
	Mergeable *bool `json:"mergeable"`
	// ProviderStatus is the provider's raw merge status.
	ProviderStatus string `json:"provider_status,omitempty"`
	// Blockers lists what stands between the PR and merging, whether or
	// not the provider enforces it (e.g. unresolved comments).
	Blockers []string `json:"blockers"`
	// contains filtered or unexported fields
}

MergeStatus tells whether a PR can be merged.

type NotFoundError

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

NotFoundError reports an object that gr looked up itself and did not find.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type PRComment

type PRComment struct {
	ID        int       `json:"id"`
	Author    string    `json:"author"`
	Body      string    `json:"body"`
	CreatedAt time.Time `json:"created_at"`
	// Resolvable is set on thread roots that can be resolved; Resolved
	// then tells whether the thread is.
	Resolvable bool `json:"resolvable"`
	Resolved   bool `json:"resolved"`
	// Optional location for inline comments (when available)
	Path string `json:"path,omitempty"`
	Line int    `json:"line,omitempty"`
	URL  string `json:"url,omitempty"`
	// ParentID is set for replies.
	ParentID int `json:"parent_id,omitempty"`
}

PRComment represents a single review comment on a PR/MR.

type PRDetails

type PRDetails struct {
	Number int    `json:"number"`
	Title  string `json:"title"`
	Body   string `json:"body"`
	Author string `json:"author"`
	// State is StateOpen, StateClosed or StateMerged.
	State string `json:"state"`
	// ProviderState is the provider's own state, lowercased, e.g. GitLab
	// "opened"/"locked" or Bitbucket "declined"/"superseded".
	ProviderState string    `json:"provider_state"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	Merged        bool      `json:"merged"`
	Draft         bool      `json:"draft"`
	Base          string    `json:"base"`
	Head          string    `json:"head"`
	// HeadSHA is the head commit (abbreviated on Bitbucket).
	HeadSHA string `json:"head_sha,omitempty"`
	URL     string `json:"url"`
}

PRDetails is a provider-agnostic view of a single PR/MR.

func (*PRDetails) Summary

func (d *PRDetails) Summary() PullRequest

Summary returns the list representation of a PR.

type PRStatus

type PRStatus struct {
	PRDetails
	// Reviews, Checks and Comments are nil if they could not be fetched;
	// Warnings then says why.
	Reviews  *Reviews       `json:"reviews"`
	Checks   *ChecksReport  `json:"checks"`
	Comments *CommentCounts `json:"comments"`
	// Tasks is set on Bitbucket only.
	Tasks    *TaskCounts `json:"tasks,omitempty"`
	Merge    MergeStatus `json:"merge"`
	Warnings []string    `json:"warnings,omitempty"`
}

PRStatus is a PR with everything that decides whether it can be merged: reviews, checks, open discussions and the provider's merge verdict.

type PRTask

type PRTask struct {
	ID         int       `json:"id"`
	Body       string    `json:"body"`
	Resolved   bool      `json:"resolved"`
	Pending    bool      `json:"pending"`
	Creator    string    `json:"creator"`
	CreatedAt  time.Time `json:"created_at"`
	ResolvedBy string    `json:"resolved_by,omitempty"`
	ResolvedAt time.Time `json:"resolved_at,omitzero"`
	// CommentID is set when the task is attached to a PR comment.
	CommentID int    `json:"comment_id,omitempty"`
	URL       string `json:"url,omitempty"`
}

PRTask is a pull request task (Bitbucket's checklist items shown on a PR).

type Provider

type Provider int

Provider represents a supported git hosting provider.

const (
	ProviderUnknown Provider = iota
	ProviderGitHub
	ProviderGitLab
	ProviderBitbucket
)

func ParseProvider

func ParseProvider(name string) (Provider, bool)

ParseProvider parses a provider name as used in the configuration.

func (Provider) BranchDelete

func (p Provider) BranchDelete(ctx context.Context, nfo *Info, name string, opts BranchDeleteOptions) error

BranchDelete deletes a remote branch across providers. It prevents deleting the default branch unless Force is true (where detectable).

func (Provider) BranchListRemote

func (p Provider) BranchListRemote(ctx context.Context, nfo *Info, opts BranchListOptions) ([]BranchInfo, error)

BranchListRemote lists remote branches using provider APIs.

func (Provider) BranchRename

func (p Provider) BranchRename(ctx context.Context, nfo *Info, oldName, newName string, opts BranchRenameOptions) error

BranchRename renames a remote branch across providers.

func (Provider) BranchWebURL

func (p Provider) BranchWebURL(nfo *Info, branch string) (string, error)

BranchWebURL constructs a web URL for viewing a branch for the given repo info. It supports GitHub, GitLab, and Bitbucket Cloud. For self-hosted instances, it uses Info.HTTPBase if available; otherwise it falls back to https://<host>.

func (Provider) PrAddComment

func (p Provider) PrAddComment(ctx context.Context, nfo *Info, number int, opts AddCommentOptions) (*PRComment, error)

PrAddComment adds an inline review comment to a PR.

func (Provider) PrAddTask

func (p Provider) PrAddTask(ctx context.Context, nfo *Info, number int, opts AddTaskOptions) (*PRTask, error)

PrAddTask creates a task on a PR.

func (Provider) PrChecks

func (p Provider) PrChecks(ctx context.Context, nfo *Info, number int) (*ChecksReport, error)

PrChecks returns the CI checks of a PR's head commit.

func (Provider) PrClose

func (p Provider) PrClose(ctx context.Context, nfo *Info, number int, opts CloseOptions) (*PRDetails, error)

PrClose closes a pull/merge request without merging. If closing succeeded but deleting the source branch failed, PrClose returns the closed PR together with an error.

func (Provider) PrComments

func (p Provider) PrComments(ctx context.Context, nfo *Info, number int) ([]PRComment, error)

PrComments lists review comments for a PR number on GitLab or Bitbucket.

func (Provider) PrCreate

func (p Provider) PrCreate(ctx context.Context, nfo *Info, in CreateOptions) (*PRDetails, error)

PrCreate creates a pull/merge request on the detected provider.

func (Provider) PrList

func (p Provider) PrList(ctx context.Context, nfo *Info, opts ListOptions) ([]PullRequest, error)

PrList lists pull/merge requests for a detected provider.

func (Provider) PrMerge

func (p Provider) PrMerge(ctx context.Context, nfo *Info, number int, opts MergeOptions) (*PRDetails, error)

PrMerge merges a pull/merge request across supported providers. If the merge succeeded but deleting the source branch failed, PrMerge returns the merged PR together with an error.

func (Provider) PrReplyComment

func (p Provider) PrReplyComment(ctx context.Context, nfo *Info, number, commentID int, body string) (*PRComment, error)

PrReplyComment posts a reply to an existing PR comment and returns the reply.

func (Provider) PrResolveComment

func (p Provider) PrResolveComment(ctx context.Context, nfo *Info, number, commentID int) error

PrResolveComment marks a PR comment as resolved.

func (Provider) PrSetTaskResolved

func (p Provider) PrSetTaskResolved(ctx context.Context, nfo *Info, number, taskID int, resolved bool) (*PRTask, error)

PrSetTaskResolved resolves (or reopens) a PR task.

func (Provider) PrStatus

func (p Provider) PrStatus(ctx context.Context, nfo *Info, number int) (*PRStatus, error)

PrStatus fetches a PR together with its reviews, checks and comment counts. Parts that cannot be fetched (e.g. for lack of token permissions) are left nil and reported in Warnings.

func (Provider) PrTasks

func (p Provider) PrTasks(ctx context.Context, nfo *Info, number int, opts TaskListOptions) ([]PRTask, error)

PrTasks lists tasks of a PR.

func (Provider) PrView

func (p Provider) PrView(ctx context.Context, nfo *Info, number int) (*PRDetails, error)

PrView retrieves details for a single pull/merge request.

func (Provider) String

func (p Provider) String() string

type PullRequest

type PullRequest struct {
	Number        int       `json:"number"`
	Title         string    `json:"title"`
	Author        string    `json:"author"`
	State         string    `json:"state"`
	ProviderState string    `json:"provider_state"`
	Draft         bool      `json:"draft"`
	Base          string    `json:"base"`
	Head          string    `json:"head"`
	CreatedAt     time.Time `json:"created_at"`
	URL           string    `json:"url"`
}

PullRequest is a provider-agnostic PR representation for listings. State and ProviderState are as in PRDetails.

type Reviewer

type Reviewer struct {
	Login string `json:"login"`
	// State is ReviewApproved, ReviewChangesRequested, ReviewCommented or
	// ReviewPending.
	State string `json:"state"`
	// Requested is set for requested (assigned) reviewers.
	Requested bool `json:"requested"`
}

Reviewer is a user (or GitHub team) who reviewed or was asked to.

type Reviews

type Reviews struct {
	// Decision is the provider's review verdict where it reports one
	// (GitHub reviewDecision, GitLab approval rules); otherwise
	// DecisionChangesRequested if anyone requested changes, else
	// DecisionApproved if anyone approved, else "".
	Decision  string `json:"decision"`
	Approvals int    `json:"approvals"`
	// ApprovalsRequired is the number of approvals GitLab's approval rules
	// require; 0 if none or unknown.
	ApprovalsRequired int        `json:"approvals_required,omitempty"`
	Reviewers         []Reviewer `json:"reviewers"`
}

Reviews summarizes the reviews of a PR.

type TaskCounts

type TaskCounts struct {
	Open     int `json:"open"`
	Resolved int `json:"resolved"`
}

TaskCounts counts the tasks of a Bitbucket PR.

type TaskListOptions

type TaskListOptions struct {
	State string
}

TaskListOptions filters PR tasks. State is one of open, resolved or all.

type UnsupportedError

type UnsupportedError struct {
	Op       string // e.g. "PR tasks"
	Provider Provider
}

UnsupportedError reports an operation that a provider does not offer, such as tasks outside Bitbucket.

func (*UnsupportedError) Error

func (e *UnsupportedError) Error() string

Jump to

Keyboard shortcuts

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