gitlab

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: 12 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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
	// 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
)

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(url string) error

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

	// CreateMergeRequest creates a new merge request with the specified parameters.
	// Returns the created merge request or an error if creation fails.
	CreateMergeRequest(
		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(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(timeout time.Duration) (string, error)

	// ApproveMergeRequest approves a merge request.
	// Returns an error if the approval fails.
	ApproveMergeRequest(mrIID int64) error

	// MergeMergeRequest merges a merge request with optional squash.
	// Returns an error if the merge fails.
	MergeMergeRequest(mrIID int64, squash bool, commitTitle string) error

	// GetMergeRequestsByBranch returns all open merge requests for the given source branch.
	GetMergeRequestsByBranch(sourceBranch string) ([]*gitlab.BasicMergeRequest, error)
}

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

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

func NewClient() (*Client, error)

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

func (c *Client) ApproveMergeRequest(mrIID int64) error

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(
	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(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(sourceBranch string) ([]*gitlab.BasicMergeRequest, error)

GetMergeRequestsByBranch returns all open merge requests for the given source branch.

func (*Client) ListLabels

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

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(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) SetLogger

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

SetLogger sets the logger for the GitLab client.

func (*Client) SetProjectFromURL

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

SetProjectFromURL sets the project from a git remote URL. Supports both HTTPS and SSH URL formats:

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

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

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(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 Label

type Label struct {
	Name string
}

Label represents a GitLab label.

type StateTracker added in v0.5.0

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

StateTracker defines the interface for thread-safe job state management. This interface abstracts the jobTracker 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