Documentation
¶
Overview ¶
Package gitlab provides a GitLab API client for merge request lifecycle management.
The package handles:
- Creating and fetching merge requests with assignees, reviewers, and labels
- Waiting for CI/CD pipeline completion with real-time job-level visualization
- Approving and merging merge requests
- Label retrieval for interactive selection
Authentication requires a GITLAB_TOKEN environment variable containing a personal access token with api scope.
Usage:
client, err := gitlab.NewClient()
client.SetLogger(logger)
client.SetProjectFromURL("https://gitlab.com/org/repo.git")
labels, _ := client.ListLabels()
mr, _ := client.CreateMergeRequest("feature", "main", "Title", "Body", "user", "reviewer", nil, false)
Thread Safety: Client is not safe for concurrent use. The pipeline waiting methods use internal goroutines for parallel job fetching but the Client itself should be used from a single goroutine.
Index ¶
- Variables
- type APIClient
- type Client
- func (c *Client) ApproveMergeRequest(ctx context.Context, mrIID int64) error
- func (c *Client) CreateMergeRequest(ctx context.Context, ...) (*gitlab.MergeRequest, error)
- func (c *Client) GetMergeRequestByBranch(ctx context.Context, sourceBranch, targetBranch string) (*gitlab.MergeRequest, error)
- func (c *Client) GetMergeRequestsByBranch(ctx context.Context, sourceBranch string) ([]*gitlab.BasicMergeRequest, error)
- func (c *Client) ListLabels(ctx context.Context) ([]*Label, error)
- func (c *Client) MergeMergeRequest(ctx context.Context, mrIID int64, squash bool, commitTitle string) error
- func (c *Client) SetLogger(logger *bullets.Logger)
- func (c *Client) SetProjectFromURL(ctx context.Context, url string) error
- func (c *Client) WaitForPipeline(ctx context.Context, timeout time.Duration) (string, error)
- type DisplayRenderer
- type Job
- type Label
- type Option
Constants ¶
This section is empty.
Variables ¶
var ( // ErrTokenRequired is returned when GITLAB_TOKEN environment variable is missing. ErrTokenRequired = errTokenRequired // ErrInvalidURLFormat is returned when the GitLab URL format is invalid. ErrInvalidURLFormat = errInvalidURLFormat // ErrAssigneeNotFound is returned when the assignee user cannot be found. ErrAssigneeNotFound = errAssigneeNotFound // ErrReviewerNotFound is returned when the reviewer user cannot be found. ErrReviewerNotFound = errReviewerNotFound // ErrPipelineTimeout is returned when waiting for pipeline completion times out. ErrPipelineTimeout = errPipelineTimeout // ErrPipelineCanceled is returned when the caller's context is cancelled while // waiting, for example on interrupt. It is distinct from a timeout so callers can // tell a deliberate abort from an exhausted budget. ErrPipelineCanceled = errPipelineCanceled // ErrMRNotFound is returned when no merge request is found for the branch. ErrMRNotFound = errMRNotFound // ErrMRAlreadyExists is returned when a merge request already exists for the branch. ErrMRAlreadyExists = errMRAlreadyExists // ErrMRNotMergeable is returned when GitLab reports a state that waiting cannot // fix -- a conflict, an unresolved discussion, a draft. It names the state, so a // caller can say why the merge was refused instead of surfacing a bare 405. ErrMRNotMergeable = errMRNotMergeable // ErrMergeabilityTimeout is returned when GitLab never settled the merge request // into a mergeable state within the budget. The message carries the last state // seen, which is the only clue to why it stalled. ErrMergeabilityTimeout = errMergeabilityTimeout // ErrMergeabilityCanceled is returned when the caller's context is cancelled while // waiting for mergeability, for example on interrupt. It is distinct from a // timeout so callers can tell a deliberate abort from an exhausted budget. ErrMergeabilityCanceled = errMergeabilityCanceled )
Error definitions for GitLab API operations.
Functions ¶
This section is empty.
Types ¶
type APIClient ¶ added in v0.5.0
type APIClient interface {
// SetProjectFromURL configures the project from a git remote URL.
// Supports both HTTPS and SSH formats.
SetProjectFromURL(ctx context.Context, url string) error
// ListLabels returns all labels available in the project.
ListLabels(ctx context.Context) ([]*Label, error)
// CreateMergeRequest creates a new merge request with the specified parameters.
// Returns the created merge request or an error if creation fails.
CreateMergeRequest(
ctx context.Context,
sourceBranch, targetBranch, title, description, assignee, reviewer string,
labels []string, squash bool,
) (*gitlab.MergeRequest, error)
// GetMergeRequestByBranch fetches an existing merge request by source and target branches.
// Returns errMRNotFound if no matching merge request exists.
GetMergeRequestByBranch(ctx context.Context, sourceBranch, targetBranch string) (*gitlab.MergeRequest, error)
// WaitForPipeline waits for all pipelines to complete for the merge request.
// Returns the overall status (success, failed, etc.) or an error on timeout.
WaitForPipeline(ctx context.Context, timeout time.Duration) (string, error)
// ApproveMergeRequest approves a merge request.
// Returns an error if the approval fails.
ApproveMergeRequest(ctx context.Context, mrIID int64) error
// MergeMergeRequest merges a merge request with optional squash.
// Returns an error if the merge fails.
MergeMergeRequest(ctx context.Context, mrIID int64, squash bool, commitTitle string) error
// GetMergeRequestsByBranch returns all open merge requests for the given source branch.
GetMergeRequestsByBranch(ctx context.Context, sourceBranch string) ([]*gitlab.BasicMergeRequest, error)
}
APIClient defines the interface for GitLab API operations.
[platform.GitLabAdapter] holds a value of this type rather than the concrete Client, so an implementation can be substituted where the adapter is constructed. Tests use that seam two ways: with a fake from testing/mocks, or with a real Client pointed at an httptest server.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a GitLab API client wrapper that manages merge request lifecycle operations. It stores internal state (projectID, mrIID, mrSHA) that is set by methods like Client.SetProjectFromURL and Client.CreateMergeRequest.
Not safe for concurrent use.
func NewClient ¶
NewClient creates a new GitLab client authenticated via the GITLAB_TOKEN environment variable.
Returns ErrTokenRequired if GITLAB_TOKEN is not set. Returns a wrapped error if the underlying GitLab client creation fails.
func (*Client) ApproveMergeRequest ¶
ApproveMergeRequest approves a merge request by its internal ID.
Parameters:
- mrIID: the merge request internal ID (IID), not the global ID
func (*Client) CreateMergeRequest ¶
func (c *Client) CreateMergeRequest( ctx context.Context, sourceBranch, targetBranch, title, description, assignee, reviewer string, labels []string, squash bool, ) (*gitlab.MergeRequest, error)
CreateMergeRequest creates a new merge request with assignees, reviewers, and labels. The created MR automatically sets RemoveSourceBranch to true.
Parameters:
- sourceBranch: the feature branch name
- targetBranch: the target branch (e.g., "main")
- title: MR title (must not be empty)
- description: MR body/description
- assignee: GitLab username to assign
- reviewer: GitLab username to request review from
- labels: list of label names to apply (may be nil)
- squash: whether to squash commits on merge
Returns ErrMRAlreadyExists if an MR already exists for the same branches. Returns ErrAssigneeNotFound or ErrReviewerNotFound if users cannot be found. Stores the MR IID and SHA internally for use by Client.WaitForPipeline.
func (*Client) GetMergeRequestByBranch ¶
func (c *Client) GetMergeRequestByBranch( ctx context.Context, sourceBranch, targetBranch string, ) (*gitlab.MergeRequest, error)
GetMergeRequestByBranch fetches an existing open merge request by source and target branches. Only the first matching MR is returned. Stores the MR IID and SHA internally.
Returns ErrMRNotFound if no open MR matches the given branches.
func (*Client) GetMergeRequestsByBranch ¶
func (c *Client) GetMergeRequestsByBranch( ctx context.Context, sourceBranch string, ) ([]*gitlab.BasicMergeRequest, error)
GetMergeRequestsByBranch returns all open merge requests for the given source branch.
func (*Client) ListLabels ¶
ListLabels returns all labels for the project. [SetProjectFromURL] must be called before this method.
Returns an empty slice if no labels are configured.
func (*Client) MergeMergeRequest ¶
func (c *Client) MergeMergeRequest(ctx context.Context, mrIID int64, squash bool, commitTitle string) error
MergeMergeRequest merges a merge request with optional squash. The source branch is automatically removed after merge.
Parameters:
- mrIID: the merge request internal ID
- squash: if true, commits are squashed and commitTitle is used as squash commit message
- commitTitle: the merge/squash commit message
func (*Client) SetProjectFromURL ¶
SetProjectFromURL sets the project from a git remote URL. Supports both HTTPS and SSH URL formats:
- https://gitlab.com/group/project.git
- git@gitlab.com:group/project.git
The .git suffix should already be present; it is stripped internally.
Returns ErrInvalidURLFormat if the URL cannot be parsed. Returns a wrapped error if the project does not exist or the API call fails.
func (*Client) WaitForPipeline ¶
WaitForPipeline waits for all pipelines to complete for the merge request. It polls at 5-second intervals and displays real-time job-level progress with animated spinners. If no pipelines are configured, it returns "success" immediately.
Parameters:
- timeout: maximum wait duration (typically 1m to 8h)
Returns the overall pipeline status ("success", "failed", "canceled"). Returns ErrPipelineTimeout if the timeout is exceeded.
A merge 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(ctx context.Context, 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 Job ¶ added in v0.5.0
type Job struct {
ID int64 // Unique job ID
Name string // Job name as defined in .gitlab-ci.yml
Status string // Current job status
Stage string // Pipeline stage (e.g., "build", "test", "deploy")
CreatedAt time.Time // When the job was created
StartedAt *time.Time // When the job started running (nil if not started)
FinishedAt *time.Time // When the job finished (nil if still running)
Duration float64 // Job duration in seconds
WebURL string // Browser URL for the job
}
Job represents a GitLab pipeline job with detailed status information. Status values are: "created", "pending", "running", "success", "failed", "canceled", "skipped".
type Option ¶ added in v0.16.0
type Option func(*clientOptions)
Option configures NewClient.
func WithBaseURL ¶ added in v0.16.0
WithBaseURL points the client at a specific GitLab API endpoint instead of gitlab.com.
The SDK accepts a base URL only at construction and exposes no setter, so this is the sole way to redirect the client — which is what lets tests exercise the real client against an httptest server rather than a fake that echoes its own inputs.