gitlab

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package gitlab provides client and data types for the GitLab REST API.

Package gitlab provides client and data types for the GitLab REST API.

Package gitlab provides client and data types for the GitLab REST API.

This package handles all interactions with GitLab's issue tracking system, including fetching, creating, and updating issues. It provides bidirectional mapping between GitLab's data model and Beads' internal types.

Index

Constants

View Source
const (
	// DefaultAPIEndpoint is the GitLab API v4 endpoint suffix.
	DefaultAPIEndpoint = "/api/v4"

	// DefaultTimeout is the default HTTP request timeout.
	DefaultTimeout = 30 * time.Second

	// MaxRetries is the maximum number of retries for rate-limited requests.
	MaxRetries = 3

	// RetryDelay is the base delay between retries (exponential backoff).
	RetryDelay = time.Second

	// MaxPageSize is the maximum number of issues to fetch per page.
	MaxPageSize = 100

	// MaxPages is the maximum number of pages to fetch before stopping.
	// This prevents infinite loops from malformed X-Next-Page headers.
	MaxPages = 1000
)

API configuration constants.

Variables

View Source
var PriorityMapping = map[string]int{
	"critical": 0,
	"high":     1,
	"medium":   2,
	"low":      3,
	"none":     4,
}

PriorityMapping maps priority label values to beads priority (0-4). This is the single source of truth for priority mappings. Exported so DefaultMappingConfig in mapping.go can use it.

View Source
var StatusMapping = map[string]string{
	"open":        "open",
	"in_progress": "in_progress",
	"blocked":     "blocked",
	"deferred":    "deferred",
	"closed":      "closed",
}

StatusMapping maps status label values to beads status strings. This is the single source of truth for status mappings. Exported so DefaultMappingConfig in mapping.go can use it.

Functions

func BeadsIssueToGitLabFields

func BeadsIssueToGitLabFields(issue *types.Issue, config *MappingConfig) map[string]interface{}

BeadsIssueToGitLabFields converts a beads Issue to GitLab API update fields.

Types

type Client

type Client struct {
	Token      string       // GitLab personal access token or OAuth token
	BaseURL    string       // GitLab instance URL (e.g., "https://gitlab.com/api/v4")
	ProjectID  string       // Project ID or URL-encoded path (e.g., "group/project")
	GroupID    string       // Optional group ID or path for group-level issue fetching
	HTTPClient *http.Client // Optional custom HTTP client
	// contains filtered or unexported fields
}

Client provides methods to interact with the GitLab REST API.

func NewClient

func NewClient(token, baseURL, projectID string) *Client

NewClient creates a new GitLab client with the given token, base URL, and project ID.

func (*Client) CreateIssue

func (c *Client) CreateIssue(ctx context.Context, title, description string, labels []string) (*Issue, error)

CreateIssue creates a new issue in GitLab.

func (c *Client) CreateIssueLink(ctx context.Context, sourceIID, targetIID int, linkType string) (*IssueLink, error)

CreateIssueLink creates a link between two issues in the SAME project. Cross-project links are not supported by this function; attempting to link issues from different projects will result in an error from the GitLab API. linkType can be: "relates_to", "blocks", or "is_blocked_by".

func (*Client) CreateMilestone added in v1.0.0

func (c *Client) CreateMilestone(ctx context.Context, title, description string) (*Milestone, error)

CreateMilestone creates a new milestone in GitLab.

func (*Client) CreateTaskWorkItem added in v1.0.0

func (c *Client) CreateTaskWorkItem(ctx context.Context, projectPath, title, description, parentGID string) (*WorkItem, error)

CreateTaskWorkItem creates a Task-type work item via GraphQL, optionally with a parent. parentGID is the global ID of the parent work item (e.g., "gid://gitlab/WorkItem/456"). If parentGID is empty, creates a standalone task.

func (*Client) FetchIssueByIID

func (c *Client) FetchIssueByIID(ctx context.Context, iid int) (*Issue, error)

FetchIssueByIID retrieves a single issue by its project-scoped IID.

func (*Client) FetchIssues

func (c *Client) FetchIssues(ctx context.Context, state string, filters ...*IssueFilter) ([]Issue, error)

FetchIssues retrieves issues from GitLab with optional filtering by state and IssueFilter. state can be: "opened", "closed", or "all".

func (*Client) FetchIssuesSince

func (c *Client) FetchIssuesSince(ctx context.Context, state string, since time.Time, filters ...*IssueFilter) ([]Issue, error)

FetchIssuesSince retrieves issues from GitLab that have been updated since the given time. This enables incremental sync by only fetching issues modified after the last sync.

func (*Client) FetchMilestoneByIID added in v1.0.0

func (c *Client) FetchMilestoneByIID(ctx context.Context, iid int) (*Milestone, error)

FetchMilestoneByIID retrieves a single milestone by its project-scoped IID. Returns nil if no milestone matches the given IID.

func (*Client) FetchMilestones added in v1.0.0

func (c *Client) FetchMilestones(ctx context.Context, state string) ([]Milestone, error)

FetchMilestones retrieves milestones from the project with optional state filter. state can be: "active", "closed", or "" (all).

func (c *Client) GetIssueLinks(ctx context.Context, iid int) ([]IssueLink, error)

GetIssueLinks retrieves issue links for the specified issue IID.

func (*Client) GetWorkItemGID added in v1.0.0

func (c *Client) GetWorkItemGID(ctx context.Context, projectPath string, iid int) (string, error)

GetWorkItemGID looks up the global ID of a work item by its project-scoped IID.

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context) ([]Project, error)

ListProjects retrieves projects accessible to the authenticated user.

func (*Client) UpdateIssue

func (c *Client) UpdateIssue(ctx context.Context, iid int, updates map[string]interface{}) (*Issue, error)

UpdateIssue updates an existing issue in GitLab.

func (*Client) UpdateMilestone added in v1.0.0

func (c *Client) UpdateMilestone(ctx context.Context, milestoneID int, updates map[string]interface{}) (*Milestone, error)

UpdateMilestone updates an existing milestone in GitLab.

func (*Client) WithEndpoint

func (c *Client) WithEndpoint(endpoint string) *Client

WithEndpoint returns a new client configured to use a custom API endpoint. This is useful for testing with mock servers or self-hosted GitLab instances.

func (*Client) WithGroupID added in v0.63.0

func (c *Client) WithGroupID(groupID string) *Client

WithGroupID returns a new client configured to fetch issues at the group level. When GroupID is set, FetchIssues and FetchIssuesSince use /groups/:id/issues instead of /projects/:id/issues. Issue creation still uses the project endpoint.

func (*Client) WithHTTPClient

func (c *Client) WithHTTPClient(httpClient *http.Client) *Client

WithHTTPClient returns a new client configured to use the specified HTTP client. This is useful for testing or customizing timeouts and transport settings.

type Conflict

type Conflict struct {
	IssueID           string    // Beads issue ID
	LocalUpdated      time.Time // When the local version was last modified
	GitLabUpdated     time.Time // When the GitLab version was last modified
	GitLabExternalRef string    // URL to the GitLab issue
	GitLabIID         int       // GitLab issue IID (project-scoped)
	GitLabID          int       // GitLab's global issue ID
}

Conflict represents a conflict between local and GitLab versions. A conflict occurs when both the local and GitLab versions have been modified since the last sync.

type DependencyInfo

type DependencyInfo struct {
	FromGitLabIID int    // GitLab IID of the dependent issue
	ToGitLabIID   int    // GitLab IID of the dependency target
	Type          string // Beads dependency type (blocks, related, parent-child)
}

DependencyInfo represents a dependency to be created after issue import. Stored separately since we need all issues imported before linking dependencies.

type Issue

type Issue struct {
	ID           int        `json:"id"`  // Global issue ID
	IID          int        `json:"iid"` // Project-scoped issue ID
	ProjectID    int        `json:"project_id"`
	Title        string     `json:"title"`
	Description  string     `json:"description"`
	State        string     `json:"state"` // "opened", "closed", "reopened"
	CreatedAt    *time.Time `json:"created_at"`
	UpdatedAt    *time.Time `json:"updated_at"`
	ClosedAt     *time.Time `json:"closed_at,omitempty"`
	ClosedBy     *User      `json:"closed_by,omitempty"`
	Labels       []string   `json:"labels"`
	Assignee     *User      `json:"assignee,omitempty"`
	Assignees    []User     `json:"assignees,omitempty"`
	Author       *User      `json:"author,omitempty"`
	Milestone    *Milestone `json:"milestone,omitempty"`
	WebURL       string     `json:"web_url"`
	DueDate      string     `json:"due_date,omitempty"` // YYYY-MM-DD format
	Weight       int        `json:"weight,omitempty"`   // GitLab Premium feature
	Type         string     `json:"type,omitempty"`     // "issue", "incident", "test_case", "task"
	Confidential bool       `json:"confidential"`

	// Links contains related URLs (populated in some API responses)
	Links *IssueLinks `json:"links,omitempty"`

	// IssueLinksData holds related issue links fetched via the /issues/:iid/links API.
	// Not part of the standard issue response; populated separately during sync.
	IssueLinksData []IssueLink `json:"-"`
}

Issue represents an issue from the GitLab API.

type IssueConversion

type IssueConversion struct {
	Issue        *types.Issue
	Dependencies []DependencyInfo
}

IssueConversion holds the result of converting a GitLab issue to Beads. It includes the issue and any dependencies that should be created.

func GitLabIssueToBeads

func GitLabIssueToBeads(gl *Issue, config *MappingConfig) *IssueConversion

GitLabIssueToBeads converts a GitLab Issue to a beads Issue.

type IssueFilter added in v0.63.0

type IssueFilter struct {
	Labels    string // Comma-separated label names (AND logic)
	ProjectID int    // Filter to issues from this project (client-side, group mode only)
	Milestone string // Milestone title
	Assignee  string // Assignee username
}

IssueFilter holds optional filters for fetching issues. All fields are optional; zero values mean "no filter".

type IssueLink struct {
	SourceIssue *Issue `json:"source_issue"`
	TargetIssue *Issue `json:"target_issue"`
	LinkType    string `json:"link_type"` // "relates_to", "blocks", "is_blocked_by"
}

IssueLink represents a link between two issues.

type IssueLinks struct {
	Self       string `json:"self,omitempty"`
	Notes      string `json:"notes,omitempty"`
	AwardEmoji string `json:"award_emoji,omitempty"`
	Project    string `json:"project,omitempty"`
}

IssueLinks contains related URLs for an issue.

type Label

type Label struct {
	ID                int    `json:"id"`
	Name              string `json:"name"`
	Color             string `json:"color"`
	Description       string `json:"description,omitempty"`
	TextColor         string `json:"text_color,omitempty"`
	Priority          *int   `json:"priority,omitempty"`
	IsProjectLabel    bool   `json:"is_project_label,omitempty"`
	SubscribedBoolean bool   `json:"subscribed,omitempty"`
}

Label represents a GitLab label.

type MappingConfig

type MappingConfig struct {
	PriorityMap  map[string]int    // priority label value → beads priority (0-4)
	StateMap     map[string]string // GitLab state → beads status
	LabelTypeMap map[string]string // type label value → beads issue type
	RelationMap  map[string]string // GitLab link type → beads dependency type
}

MappingConfig configures how GitLab fields map to beads fields.

func DefaultMappingConfig

func DefaultMappingConfig() *MappingConfig

DefaultMappingConfig returns the default mapping configuration. Uses exported mapping constants from types.go as the single source of truth.

type Milestone

type Milestone struct {
	ID          int        `json:"id"`
	IID         int        `json:"iid"`
	ProjectID   int        `json:"project_id,omitempty"`
	GroupID     int        `json:"group_id,omitempty"`
	Title       string     `json:"title"`
	Description string     `json:"description,omitempty"`
	State       string     `json:"state"` // "active", "closed"
	DueDate     string     `json:"due_date,omitempty"`
	StartDate   string     `json:"start_date,omitempty"`
	CreatedAt   *time.Time `json:"created_at,omitempty"`
	UpdatedAt   *time.Time `json:"updated_at,omitempty"`
	WebURL      string     `json:"web_url,omitempty"`
}

Milestone represents a GitLab milestone.

type Namespace

type Namespace struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Path     string `json:"path"`
	Kind     string `json:"kind"` // "user" or "group"
	FullPath string `json:"full_path"`
	WebURL   string `json:"web_url,omitempty"`
}

Namespace represents a GitLab namespace (group or user).

type Project

type Project struct {
	ID                int        `json:"id"`
	Name              string     `json:"name"`
	Path              string     `json:"path"`
	PathWithNamespace string     `json:"path_with_namespace"`
	Description       string     `json:"description,omitempty"`
	WebURL            string     `json:"web_url"`
	DefaultBranch     string     `json:"default_branch,omitempty"`
	Namespace         *Namespace `json:"namespace,omitempty"`
}

Project represents a GitLab project.

type PullStats

type PullStats struct {
	Created     int
	Updated     int
	Skipped     int
	Incremental bool     // Whether this was an incremental sync
	SyncedSince string   // Timestamp we synced since (if incremental)
	Warnings    []string // Non-fatal warnings encountered during pull
}

PullStats tracks pull operation statistics.

type PushStats

type PushStats struct {
	Created int
	Updated int
	Skipped int
	Errors  int
}

PushStats tracks push operation statistics.

type SyncResult

type SyncResult struct {
	Success  bool      `json:"success"`
	Stats    SyncStats `json:"stats"`
	LastSync string    `json:"last_sync,omitempty"`
	Error    string    `json:"error,omitempty"`
	Warnings []string  `json:"warnings,omitempty"`
}

SyncResult represents the result of a GitLab sync operation.

type SyncStats

type SyncStats struct {
	Pulled    int `json:"pulled"`
	Pushed    int `json:"pushed"`
	Created   int `json:"created"`
	Updated   int `json:"updated"`
	Skipped   int `json:"skipped"`
	Errors    int `json:"errors"`
	Conflicts int `json:"conflicts"`
}

SyncStats tracks statistics for a GitLab sync operation.

type Tracker added in v0.50.3

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

Tracker implements tracker.IssueTracker for GitLab.

func (*Tracker) BuildExternalRef added in v0.50.3

func (t *Tracker) BuildExternalRef(issue *tracker.TrackerIssue) string

func (*Tracker) Close added in v0.50.3

func (t *Tracker) Close() error

func (*Tracker) ConfigPrefix added in v0.50.3

func (t *Tracker) ConfigPrefix() string

func (*Tracker) CreateIssue added in v0.50.3

func (t *Tracker) CreateIssue(ctx context.Context, issue *types.Issue) (*tracker.TrackerIssue, error)

func (*Tracker) DisplayName added in v0.50.3

func (t *Tracker) DisplayName() string

func (*Tracker) ExtractIdentifier added in v0.50.3

func (t *Tracker) ExtractIdentifier(ref string) string

ExtractIdentifier extracts the issue IID from a GitLab URL or shorthand ref.

func (*Tracker) FetchIssue added in v0.50.3

func (t *Tracker) FetchIssue(ctx context.Context, identifier string) (*tracker.TrackerIssue, error)

func (*Tracker) FetchIssues added in v0.50.3

func (t *Tracker) FetchIssues(ctx context.Context, opts tracker.FetchOptions) ([]tracker.TrackerIssue, error)

func (*Tracker) FieldMapper added in v0.50.3

func (t *Tracker) FieldMapper() tracker.FieldMapper

func (*Tracker) Init added in v0.50.3

func (t *Tracker) Init(ctx context.Context, store storage.Storage) error

func (*Tracker) IsExternalRef added in v0.50.3

func (t *Tracker) IsExternalRef(ref string) bool

IsExternalRef checks if a ref belongs to this GitLab tracker. It recognizes both full GitLab URLs and the "gitlab:{id}" shorthand format produced by BuildExternalRef when a URL is unavailable.

func (*Tracker) IsMilestoneRef added in v1.0.0

func (t *Tracker) IsMilestoneRef(ref string) bool

IsMilestoneRef checks if an external_ref points to a milestone (not an issue).

func (*Tracker) Name added in v0.50.3

func (t *Tracker) Name() string

func (*Tracker) SetFilter added in v0.63.0

func (t *Tracker) SetFilter(filter *IssueFilter)

SetFilter overrides the tracker's issue filter. CLI flags use this to override config-based defaults.

func (*Tracker) UpdateIssue added in v0.50.3

func (t *Tracker) UpdateIssue(ctx context.Context, externalID string, issue *types.Issue) (*tracker.TrackerIssue, error)

func (*Tracker) Validate added in v0.50.3

func (t *Tracker) Validate() error

type User

type User struct {
	ID        int    `json:"id"`
	Username  string `json:"username"`
	Name      string `json:"name"`
	Email     string `json:"email,omitempty"`
	AvatarURL string `json:"avatar_url,omitempty"`
	WebURL    string `json:"web_url,omitempty"`
	State     string `json:"state,omitempty"` // "active", "blocked", etc.
}

User represents a GitLab user.

type WorkItem added in v1.0.0

type WorkItem struct {
	ID    string `json:"id"`  // Global ID (gid://gitlab/WorkItem/123)
	IID   string `json:"iid"` // Project-scoped ID
	Title string `json:"title"`
	Type  string `json:"type"` // Work item type name
}

WorkItem represents a GitLab work item from the GraphQL API.

Jump to

Keyboard shortcuts

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