api

package
v1.59.2 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

This is a silly wrapper for gitlab client-go but helps maintain consistency

Index

Constants

View Source
const (
	NoToken authType = iota
	OAuthToken
	PrivateToken
)
View Source
const (
	NamespaceKindUser  = "user"
	NamespaceKindGroup = "group"
)

Describe namespace kinds which is either group or user See docs: https://docs.gitlab.com/api/namespaces/

View Source
const MaxPerPage = 100

MaxPerPage is the maximum number of items per page supported by the GitLab API. https://docs.gitlab.com/api/rest/#offset-based-pagination

Variables

View Source
var AddIssueTimeSpent = func(client *gitlab.Client, projectID any, issueIDD int, opts *gitlab.AddSpentTimeOptions) (*gitlab.TimeStats, error) {
	timeStats, _, err := client.Issues.AddSpentTime(projectID, issueIDD, opts)
	if err != nil {
		return nil, err
	}

	return timeStats, nil
}
View Source
var AgentNotFoundErr = errors.New("agent not found")
View Source
var ApproveMR = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.ApproveMergeRequestOptions) (*gitlab.MergeRequestApprovals, error) {
	mr, _, err := client.MergeRequestApprovals.ApproveMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var CancelPipelineJob = func(client *gitlab.Client, repo string, jobID int) (*gitlab.Job, error) {
	pipe, _, err := client.Jobs.CancelJob(repo, jobID)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var CreateAgentToken = func(client *gitlab.Client, projectID any, agentID int, recreateOnLimit bool) (*gitlab.AgentToken, bool, error) {
	recreated := false

	if recreateOnLimit {
		tokens, _, err := client.ClusterAgents.ListAgentTokens(projectID, agentID, &gitlab.ListAgentTokensOptions{PerPage: agentTokenLimit})
		if err != nil {
			return nil, false, err
		}
		if len(tokens) == agentTokenLimit {
			slices.SortFunc(tokens, agentTokenSortFunc)
			longestUnusedToken := tokens[0]

			_, err := client.ClusterAgents.RevokeAgentToken(projectID, agentID, longestUnusedToken.ID)
			if err != nil {
				return nil, false, err
			}
			recreated = true
		}
	}

	token, _, err := client.ClusterAgents.CreateAgentToken(projectID, agentID, &gitlab.CreateAgentTokenOptions{
		Name:        gitlab.Ptr(fmt.Sprintf("glab-bootstrap-%d", time.Now().UTC().Unix())),
		Description: gitlab.Ptr("Created by the `glab cluster agent bootstrap command"),
	})
	return token, recreated, err
}
View Source
var CreateBranch = func(client *gitlab.Client, projectID any, opts *gitlab.CreateBranchOptions) (*gitlab.Branch, error) {
	branch, _, err := client.Branches.CreateBranch(projectID, opts)
	if err != nil {
		return nil, err
	}

	return branch, nil
}
View Source
var CreateFile = func(client *gitlab.Client, projectID any, path string, content []byte, ref string) error {
	_, _, err := client.RepositoryFiles.CreateFile(projectID, path, &gitlab.CreateFileOptions{
		Branch:        gitlab.Ptr(ref),
		Content:       gitlab.Ptr(string(content)),
		CommitMessage: gitlab.Ptr(fmt.Sprintf("Add %s via glab file sync", path)),
		AuthorName:    gitlab.Ptr(commitAuthorName),
		AuthorEmail:   gitlab.Ptr(commitAuthorEmail),
	})
	return err
}
View Source
var CreateGroupAccessToken = func(client *gitlab.Client, gid any, opts *gitlab.CreateGroupAccessTokenOptions) (*gitlab.GroupAccessToken, error) {
	token, _, err := client.GroupAccessTokens.CreateGroupAccessToken(gid, opts)
	return token, err
}
View Source
var CreateGroupVariable = func(client *gitlab.Client, groupID any, opts *gitlab.CreateGroupVariableOptions) (*gitlab.GroupVariable, error) {
	vars, _, err := client.GroupVariables.CreateVariable(groupID, opts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var CreateIssue = func(client *gitlab.Client, projectID any, opts *gitlab.CreateIssueOptions) (*gitlab.Issue, error) {
	issue, _, err := client.Issues.CreateIssue(projectID, opts)
	if err != nil {
		return nil, err
	}

	return issue, nil
}
View Source
var CreateIssueBoard = func(client *gitlab.Client, projectID any, opts *gitlab.CreateIssueBoardOptions) (*gitlab.IssueBoard, error) {
	board, _, err := client.Boards.CreateIssueBoard(projectID, opts)
	if err != nil {
		return nil, err
	}

	return board, nil
}
View Source
var CreateIssueNote = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.CreateIssueNoteOptions) (*gitlab.Note, error) {
	note, _, err := client.Notes.CreateIssueNote(projectID, mrID, opts)
	if err != nil {
		return note, err
	}

	return note, nil
}
View Source
var CreateLabel = func(client *gitlab.Client, projectID any, opts *gitlab.CreateLabelOptions) (*gitlab.Label, error) {
	label, _, err := client.Labels.CreateLabel(projectID, opts)
	if err != nil {
		return nil, err
	}
	return label, nil
}
View Source
var CreateMR = func(client *gitlab.Client, projectID any, opts *gitlab.CreateMergeRequestOptions) (*gitlab.MergeRequest, error) {
	mr, _, err := client.MergeRequests.CreateMergeRequest(projectID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var CreateMRNote = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.CreateMergeRequestNoteOptions) (*gitlab.Note, error) {
	note, _, err := client.Notes.CreateMergeRequestNote(projectID, mrID, opts)
	if err != nil {
		return note, err
	}

	return note, nil
}
View Source
var CreatePersonalAccessToken = func(client *gitlab.Client, uid int, opts *gitlab.CreatePersonalAccessTokenOptions) (*gitlab.PersonalAccessToken, error) {
	token, _, err := client.Users.CreatePersonalAccessToken(uid, opts)
	return token, err
}
View Source
var CreatePersonalAccessTokenForCurrentUser = func(client *gitlab.Client, name string, scopes []string, expiresAt time.Time) (*gitlab.PersonalAccessToken, error) {
	expiresAtISO := gitlab.ISOTime(expiresAt)
	options := &gitlab.CreatePersonalAccessTokenForCurrentUserOptions{
		Name:      gitlab.Ptr(name),
		Scopes:    &scopes,
		ExpiresAt: &expiresAtISO,
	}

	pat, _, err := client.Users.CreatePersonalAccessTokenForCurrentUser(options)
	if err != nil {
		return nil, err
	}
	return pat, nil
}
View Source
var CreatePipeline = func(client *gitlab.Client, projectID any, opts *gitlab.CreatePipelineOptions) (*gitlab.Pipeline, error) {
	pipe, _, err := client.Pipelines.CreatePipeline(projectID, opts)
	return pipe, err
}
View Source
var CreateProject = func(client *gitlab.Client, opts *gitlab.CreateProjectOptions) (*gitlab.Project, error) {
	project, _, err := client.Projects.CreateProject(opts)
	if err != nil {
		return nil, err
	}
	return project, nil
}
View Source
var CreateProjectAccessToken = func(client *gitlab.Client, pid any, opts *gitlab.CreateProjectAccessTokenOptions) (*gitlab.ProjectAccessToken, error) {
	token, _, err := client.ProjectAccessTokens.CreateProjectAccessToken(pid, opts)
	return token, err
}
View Source
var CreateProjectSnippet = func(
	client *gitlab.Client,
	projectID any,
	opts *gitlab.CreateProjectSnippetOptions,
) (*gitlab.Snippet, error) {
	snippet, _, err := client.ProjectSnippets.CreateSnippet(projectID, opts)
	if err != nil {
		return nil, err
	}

	return snippet, nil
}

CreateProjectSnippet inside the project

View Source
var CreateProjectVariable = func(client *gitlab.Client, projectID any, opts *gitlab.CreateProjectVariableOptions) (*gitlab.ProjectVariable, error) {
	vars, _, err := client.ProjectVariables.CreateVariable(projectID, opts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var CreatePullMirror = func(
	client *gitlab.Client,
	projectID any,
	opts *CreatePullMirrorOptions,
) error {
	opt := &gitlab.EditProjectOptions{
		ImportURL:                   &opts.Url,
		Mirror:                      &opts.Enabled,
		OnlyMirrorProtectedBranches: &opts.OnlyProtectedBranches,
	}
	_, _, err := client.Projects.EditProject(projectID, opt)
	return err
}
View Source
var CreatePushMirror = func(
	client *gitlab.Client,
	projectID any,
	opts *CreatePushMirrorOptions,
) (*gitlab.ProjectMirror, error) {
	opt := &gitlab.AddProjectMirrorOptions{
		URL:                   &opts.Url,
		Enabled:               &opts.Enabled,
		OnlyProtectedBranches: &opts.OnlyProtectedBranches,
		KeepDivergentRefs:     &opts.KeepDivergentRefs,
	}
	pm, _, err := client.ProjectMirrors.AddProjectMirror(projectID, opt)
	return pm, err
}
View Source
var CreateRelease = func(client *gitlab.Client, projectID any, opts *gitlab.CreateReleaseOptions) (*gitlab.Release, error) {
	release, _, err := client.Releases.CreateRelease(projectID, opts)
	if err != nil {
		return nil, err
	}

	return release, nil
}
View Source
var CreateSchedule = func(client *gitlab.Client, repo string, scheduleOpts *gitlab.CreatePipelineScheduleOptions, opts ...gitlab.RequestOptionFunc) (error, *gitlab.PipelineSchedule) {
	schedule, _, err := client.PipelineSchedules.CreatePipelineSchedule(repo, scheduleOpts, opts...)
	if err != nil {
		return fmt.Errorf("creating scheduled pipeline status: %w", err), nil
	}

	return nil, schedule
}
View Source
var CreateScheduleVariable = func(client *gitlab.Client, repo string, scheduleId int, scheduleVarOpts *gitlab.CreatePipelineScheduleVariableOptions, opts ...gitlab.RequestOptionFunc) error {
	_, _, err := client.PipelineSchedules.CreatePipelineScheduleVariable(repo, scheduleId, scheduleVarOpts, opts...)
	if err != nil {
		return fmt.Errorf("creating scheduled pipeline status: %w", err)
	}

	return nil
}
View Source
var CreateSecureFile = func(client *gitlab.Client, projectID any, filename string, content io.Reader) error {
	opts := &gitlab.CreateSecureFileOptions{
		Name: &filename,
	}
	_, _, err := client.SecureFiles.CreateSecureFile(projectID, content, opts)
	return err
}
View Source
var CreateSnippet = func(
	client *gitlab.Client,
	opts *gitlab.CreateSnippetOptions,
) (*gitlab.Snippet, error) {
	snippet, _, err := client.Snippets.CreateSnippet(opts)
	if err != nil {
		return nil, err
	}
	return snippet, nil
}

CreateSnippet for the user inside the users snippets

View Source
var CurrentUser = func(client *gitlab.Client) (*gitlab.User, error) {
	u, _, err := client.Users.CurrentUser()
	if err != nil {
		return nil, err
	}
	return u, nil
}
View Source
var CurrentUserEvents = func(client *gitlab.Client, opts *gitlab.ListContributionEventsOptions) ([]*gitlab.ContributionEvent, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	events, _, err := client.Events.ListCurrentUserContributionEvents(opts)
	if err != nil {
		return nil, err
	}
	return events, nil
}
View Source
var DefaultListLimit = 30
View Source
var DeleteGroupVariable = func(client *gitlab.Client, groupID any, key string) error {
	_, err := client.GroupVariables.RemoveVariable(groupID, key, nil)
	if err != nil {
		return err
	}

	return nil
}
View Source
var DeleteIssue = func(client *gitlab.Client, projectID any, issueID int) error {
	_, err := client.Issues.DeleteIssue(projectID, issueID)
	if err != nil {
		return err
	}

	return nil
}
View Source
var DeleteLabel = func(client *gitlab.Client, projectID any, label string, opts *gitlab.DeleteLabelOptions) error {
	_, err := client.Labels.DeleteLabel(projectID, label, opts)
	if err != nil {
		return err
	}
	return nil
}
View Source
var DeleteMR = func(client *gitlab.Client, projectID any, mrID int) error {
	_, err := client.MergeRequests.DeleteMergeRequest(projectID, mrID)
	if err != nil {
		return err
	}

	return nil
}
View Source
var DeletePipeline = func(client *gitlab.Client, projectID any, pipeID int) error {
	_, err := client.Pipelines.DeletePipeline(projectID, pipeID)
	if err != nil {
		return err
	}
	return nil
}
View Source
var DeleteProject = func(client *gitlab.Client, projectID any) (*gitlab.Response, error) {
	project, err := client.Projects.DeleteProject(projectID, nil)
	if err != nil {
		return nil, err
	}
	return project, nil
}
View Source
var DeleteProjectVariable = func(client *gitlab.Client, projectID any, key string, scope string) error {
	reqOpts := &gitlab.RemoveProjectVariableOptions{
		Filter: &gitlab.VariableFilter{
			EnvironmentScope: scope,
		},
	}
	_, err := client.ProjectVariables.RemoveVariable(projectID, key, reqOpts)
	if err != nil {
		return err
	}

	return nil
}
View Source
var DeleteSchedule = func(client *gitlab.Client, scheduleId int, repo string, opts ...gitlab.RequestOptionFunc) (err error) {
	_, err = client.PipelineSchedules.DeletePipelineSchedule(repo, scheduleId, opts...)
	if err != nil {
		return fmt.Errorf("deleting scheduled pipeline status: %w", err)
	}
	return nil
}
View Source
var DeleteScheduleVariable = func(client *gitlab.Client, repo string, scheduleId int, variableKey string, opts ...gitlab.RequestOptionFunc) (err error) {
	_, _, err = client.PipelineSchedules.DeletePipelineScheduleVariable(repo, scheduleId, variableKey, opts...)
	if err != nil {
		return fmt.Errorf("deleting scheduled pipeline status: %w", err)
	}

	return nil
}
View Source
var DisableHTTPKeepAlives = false
View Source
var DownloadArtifactJob = func(client *gitlab.Client, repo string, ref string, opts *gitlab.DownloadArtifactsFileOptions) (*bytes.Reader, error) {
	if opts == nil {
		opts = &gitlab.DownloadArtifactsFileOptions{}
	}
	jobs, _, err := client.Jobs.DownloadArtifactsFile(repo, ref, opts, nil)
	if err != nil {
		return nil, err
	}
	return jobs, nil
}
View Source
var DownloadSecureFile = func(client *gitlab.Client, projectID any, id int) (io.Reader, error) {
	reader, _, err := client.SecureFiles.DownloadSecureFile(projectID, id)
	if err != nil {
		return nil, err
	}
	return reader, nil
}
View Source
var EditSchedule = func(client *gitlab.Client, repo string, scheduleId int, scheduleOpts *gitlab.EditPipelineScheduleOptions, opts ...gitlab.RequestOptionFunc) (*gitlab.PipelineSchedule, error) {
	schedule, _, err := client.PipelineSchedules.EditPipelineSchedule(repo, scheduleId, scheduleOpts, opts...)
	if err != nil {
		return nil, fmt.Errorf("editing scheduled pipeline status: %w", err)
	}

	return schedule, nil
}
View Source
var EditScheduleVariable = func(client *gitlab.Client, repo string, scheduleId int, variableKey string, scheduleVarOpts *gitlab.EditPipelineScheduleVariableOptions, opts ...gitlab.RequestOptionFunc) error {
	_, _, err := client.PipelineSchedules.EditPipelineScheduleVariable(repo, scheduleId, variableKey, scheduleVarOpts, opts...)
	if err != nil {
		return fmt.Errorf("editing scheduled pipeline status: %w", err)
	}

	return nil
}
View Source
var ErasePipelineJob = func(client *gitlab.Client, pid int, repo string) (*gitlab.Job, error) {
	pipe, _, err := client.Jobs.EraseJob(repo, pid)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var ErrIssuableUserAlreadySubscribed = errors.New("you are already subscribed to this issue")

ErrIssuableUserAlreadySubscribed received when trying to subscribe to an issue the user is already subscribed to

View Source
var ErrIssuableUserNotSubscribed = errors.New("you are not subscribed to this issue")

ErrIssuableUserNotSubscribed received when trying to unsubscribe from an issue the user is not subscribed to

View Source
var ErrTodoExists = errors.New("To-do already exists.")
View Source
var ForkProject = func(client *gitlab.Client, projectID any, opts *gitlab.ForkProjectOptions) (*gitlab.Project, error) {
	project, _, err := client.Projects.ForkProject(projectID, opts)
	if err != nil {
		return nil, err
	}
	return project, nil
}
View Source
var GenerateChangelog = func(client *gitlab.Client, projectID any, options *gitlab.GenerateChangelogDataOptions) (*gitlab.ChangelogData, error) {
	changelog, _, err := client.Repositories.GenerateChangelogData(projectID, *options)
	if err != nil {
		return nil, err
	}

	return changelog, nil
}
View Source
var GetAgent = func(client *gitlab.Client, projectID any, agentID int) (*gitlab.Agent, error) {
	agent, _, err := client.ClusterAgents.GetAgent(projectID, agentID)
	if err != nil {
		return nil, err
	}

	return agent, nil
}
View Source
var GetAgentByName = func(client *gitlab.Client, projectID any, agentName string) (*gitlab.Agent, error) {
	opts := &gitlab.ListAgentsOptions{
		Page:    1,
		PerPage: 100,
	}

	for opts.Page != 0 {
		paginatedAgents, resp, err := client.ClusterAgents.ListAgents(projectID, opts)
		if err != nil {
			return nil, err
		}

		for _, agent := range paginatedAgents {
			if agent.Name == agentName {

				return agent, nil
			}
		}
		opts.Page = resp.NextPage
	}

	return nil, AgentNotFoundErr
}
View Source
var GetCommit = func(client *gitlab.Client, repo string, ref string) (*gitlab.Commit, error) {
	c, _, err := client.Commits.GetCommit(repo, ref, nil)
	if err != nil {
		return nil, err
	}
	return c, nil
}
View Source
var GetCommitStatuses = func(client *gitlab.Client, pid any, sha string) ([]*gitlab.CommitStatus, error) {
	opt := &gitlab.GetCommitStatusesOptions{
		All: gitlab.Ptr(true),
	}

	statuses, _, err := client.Commits.GetCommitStatuses(pid, sha, opt, nil)
	if err != nil {
		return nil, err
	}
	return statuses, nil
}
View Source
var GetFile = func(client *gitlab.Client, projectID any, path string, ref string) (*gitlab.File, error) {
	fileOpts := &gitlab.GetFileOptions{
		Ref: &ref,
	}
	file, _, err := client.RepositoryFiles.GetFile(projectID, path, fileOpts)
	if err != nil {
		return nil, err
	}

	return file, nil
}

GetFile retrieves a file from repository. Note that file content is Base64 encoded.

View Source
var GetGroup = func(client *gitlab.Client, groupID any) (*gitlab.Group, error) {
	group, _, err := client.Groups.GetGroup(groupID, &gitlab.GetGroupOptions{})
	if err != nil {
		return nil, err
	}
	return group, nil
}
View Source
var GetGroupIssueBoardLists = func(client *gitlab.Client, groupID any, boardID int, opts *gitlab.ListGroupIssueBoardListsOptions) ([]*gitlab.BoardList, error) {
	boardLists, _, err := client.GroupIssueBoards.ListGroupIssueBoardLists(groupID, boardID, opts)
	if err != nil {
		return nil, err
	}

	return boardLists, nil
}
View Source
var GetGroupVariable = func(client *gitlab.Client, groupID any, key string, scope string) (*gitlab.GroupVariable, error) {
	reqOpts := &gitlab.GetGroupVariableOptions{
		Filter: &gitlab.VariableFilter{
			EnvironmentScope: scope,
		},
	}
	vars, _, err := client.GroupVariables.GetVariable(groupID, key, reqOpts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var GetIssue = func(client *gitlab.Client, projectID any, issueID int) (*gitlab.Issue, error) {
	issue, _, err := client.Issues.GetIssue(projectID, issueID)
	if err != nil {
		return nil, err
	}

	return issue, nil
}
View Source
var GetIssueBoardLists = func(client *gitlab.Client, projectID any, boardID int, opts *gitlab.GetIssueBoardListsOptions) ([]*gitlab.BoardList, error) {
	boardLists, _, err := client.Boards.GetIssueBoardLists(projectID, boardID, opts)
	if err != nil {
		return nil, err
	}

	return boardLists, nil
}
View Source
var GetJobs = func(client *gitlab.Client, repo string, opts *gitlab.ListJobsOptions) ([]*gitlab.Job, error) {
	if opts == nil {
		opts = &gitlab.ListJobsOptions{}
	}
	jobs, _, err := client.Jobs.ListProjectJobs(repo, opts)
	if err != nil {
		return nil, err
	}
	return jobs, nil
}
View Source
var GetLatestPipeline = func(client *gitlab.Client, repo string, ref string) (*gitlab.Pipeline, error) {
	l := &gitlab.GetLatestPipelineOptions{
		Ref: gitlab.Ptr(ref),
	}

	pipeline, _, err := client.Pipelines.GetLatestPipeline(repo, l)
	if err != nil {
		return nil, err
	}

	return pipeline, nil
}
View Source
var GetMR = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.GetMergeRequestsOptions) (*gitlab.MergeRequest, error) {
	mr, _, err := client.MergeRequests.GetMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var GetMRApprovalState = func(client *gitlab.Client, projectID any, mrID int, opts ...gitlab.RequestOptionFunc) (*gitlab.MergeRequestApprovalState, error) {
	mrApprovals, _, err := client.MergeRequestApprovals.GetApprovalState(projectID, mrID, opts...)
	if err != nil {
		return nil, err
	}

	return mrApprovals, nil
}
View Source
var GetMRLinkedIssues = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.GetIssuesClosedOnMergeOptions) ([]*gitlab.Issue, error) {
	mrIssues, _, err := client.MergeRequests.GetIssuesClosedOnMerge(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mrIssues, nil
}
View Source
var GetMetadata = func(client *gitlab.Client) (*gitlab.Metadata, error) {
	md, _, err := client.Metadata.GetMetadata()
	if err != nil {
		return nil, err
	}

	return md, nil
}
View Source
var GetPipeline = func(client *gitlab.Client, pid int, l *gitlab.RequestOptionFunc, repo any) (*gitlab.Pipeline, error) {
	pipe, _, err := client.Pipelines.GetPipeline(repo, pid)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var GetPipelineFromBranch = func(client *gitlab.Client, ref, repo string) ([]*gitlab.Job, error) {
	var err error
	if ref == "" {
		ref, err = git.CurrentBranch()
		if err != nil {
			return nil, err
		}
	}

	pipeline, err := GetLatestPipeline(client, repo, ref)
	if err != nil {
		return nil, err
	}
	jobs, err := GetPipelineJobs(client, pipeline.ID, repo)
	if err != nil {
		return nil, err
	}
	return jobs, nil
}
View Source
var GetPipelineJob = func(client *gitlab.Client, jid int, repo string) (*gitlab.Job, error) {
	job, _, err := client.Jobs.GetJob(repo, jid)
	return job, err
}
View Source
var GetPipelineJobLog = func(client *gitlab.Client, jobID int, repo string) (io.Reader, error) {
	pipeJoblog, _, err := client.Jobs.GetTraceFile(repo, jobID)
	if err != nil {
		return nil, err
	}
	return pipeJoblog, nil
}
View Source
var GetPipelineJobs = func(client *gitlab.Client, pid int, repo string) ([]*gitlab.Job, error) {
	pipeJobs := make([]*gitlab.Job, 0, 10)
	listOptions := &gitlab.ListJobsOptions{
		ListOptions: gitlab.ListOptions{
			PerPage: 100,
		},
	}
	for {
		pageJobs, resp, err := client.Jobs.ListPipelineJobs(repo, pid, listOptions)
		if err != nil {
			return nil, err
		}
		pipeJobs = append(pipeJobs, pageJobs...)
		if resp.CurrentPage == resp.TotalPages {
			break
		}
		listOptions.Page = resp.NextPage
		if resp.CurrentPage >= resp.TotalPages {
			break
		}
	}
	return pipeJobs, nil
}
View Source
var GetPipelineVariables = func(client *gitlab.Client, pid int, l *gitlab.RequestOptionFunc, projectID int) ([]*gitlab.PipelineVariable, error) {
	pipelineVars, _, err := client.Pipelines.GetPipelineVariables(projectID, pid)
	if err != nil {
		return nil, err
	}
	return pipelineVars, nil
}
View Source
var GetPipelines = func(client *gitlab.Client, l *gitlab.ListProjectPipelinesOptions, repo any) ([]*gitlab.PipelineInfo, error) {
	if l.PerPage == 0 {
		l.PerPage = DefaultListLimit
	}

	pipes, _, err := client.Pipelines.ListProjectPipelines(repo, l)
	if err != nil {
		return nil, err
	}
	return pipes, nil
}
View Source
var GetProject = func(client *gitlab.Client, projectID any) (*gitlab.Project, error) {
	opts := &gitlab.GetProjectOptions{
		License:              gitlab.Ptr(true),
		WithCustomAttributes: gitlab.Ptr(true),
	}
	project, _, err := client.Projects.GetProject(projectID, opts)
	if err != nil {
		return nil, err
	}
	return project, nil
}
View Source
var GetProjectVariable = func(client *gitlab.Client, projectID any, key string, scope string) (*gitlab.ProjectVariable, error) {
	reqOpts := &gitlab.GetProjectVariableOptions{
		Filter: &gitlab.VariableFilter{
			EnvironmentScope: scope,
		},
	}
	vars, _, err := client.ProjectVariables.GetVariable(projectID, key, reqOpts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var GetRelease = func(client *gitlab.Client, projectID any, tag string) (*gitlab.Release, error) {
	release, _, err := client.Releases.GetRelease(projectID, tag)
	if err != nil {
		return nil, err
	}

	return release, nil
}
View Source
var GetSchedules = func(client *gitlab.Client, l *gitlab.ListPipelineSchedulesOptions, repo string) ([]*gitlab.PipelineSchedule, error) {
	if l.PerPage == 0 {
		l.PerPage = DefaultListLimit
	}

	schedules, _, err := client.PipelineSchedules.ListPipelineSchedules(repo, l)
	if err != nil {
		return nil, err
	}
	return schedules, nil
}
View Source
var GetSecureFile = func(client *gitlab.Client, projectID any, id int) (*gitlab.SecureFile, error) {
	file, _, err := client.SecureFiles.ShowSecureFileDetails(projectID, id)
	return file, err
}
View Source
var GetSinglePipeline = func(client *gitlab.Client, pid int, repo string) (*gitlab.Pipeline, error) {
	pipes, _, err := client.Pipelines.GetPipeline(repo, pid)
	if err != nil {
		return nil, err
	}
	return pipes, nil
}
View Source
var LinkIssues = func(client *gitlab.Client, projectID any, issueIDD int, opts *gitlab.CreateIssueLinkOptions) (*gitlab.Issue, *gitlab.Issue, error) {
	issueLink, _, err := client.IssueLinks.CreateIssueLink(projectID, issueIDD, opts)
	if err != nil {
		return nil, nil, err
	}

	return issueLink.SourceIssue, issueLink.TargetIssue, nil
}
View Source
var ListAgents = func(client *gitlab.Client, projectID any, opts *gitlab.ListAgentsOptions) ([]*gitlab.Agent, error) {
	agents, _, err := client.ClusterAgents.ListAgents(projectID, opts)
	if err != nil {
		return nil, err
	}

	return agents, nil
}
View Source
var ListAllMilestones = func(client *gitlab.Client, projectID any, opts *ListMilestonesOptions) ([]*Milestone, error) {
	project, err := GetProject(client, projectID)
	if err != nil {
		return nil, err
	}

	errGroup := &errgroup.Group{}
	projectMilestones := []*gitlab.Milestone{}
	groupMilestones := []*gitlab.GroupMilestone{}

	errGroup.Go(func() error {
		var err error
		projectMilestones, err = ListProjectMilestones(client, projectID, opts.ListProjectMilestonesOptions())
		return err
	})

	if project.Namespace.Kind == NamespaceKindGroup {
		errGroup.Go(func() error {
			var err error
			groupMilestones, err = ListGroupMilestones(client, project.Namespace.ID, opts.ListGroupMilestonesOptions())
			return err
		})
	}

	if err := errGroup.Wait(); err != nil {
		return nil, fmt.Errorf("failed to get all project related milestones. %w", err)
	}

	milestones := make([]*Milestone, 0, len(projectMilestones)+len(groupMilestones))
	for _, v := range projectMilestones {
		milestones = append(milestones, NewProjectMilestone(v))
	}

	for _, v := range groupMilestones {
		milestones = append(milestones, NewGroupMilestone(v))
	}

	return milestones, nil
}
View Source
var ListGroupAccessTokens = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupAccessTokensOptions) ([]*gitlab.GroupAccessToken, error) {
	perPage := opts.PerPage
	if perPage == 0 {
		perPage = 100
	}
	tokens := make([]*gitlab.GroupAccessToken, 0, perPage)
	for {
		results, response, err := client.GroupAccessTokens.ListGroupAccessTokens(groupID, opts)
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, results...)

		if response.CurrentPage >= response.TotalPages {
			break
		}
		opts.Page = response.NextPage
	}

	return tokens, nil
}
View Source
var ListGroupIssueBoards = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupIssueBoardsOptions) ([]*gitlab.GroupIssueBoard, error) {
	boards, _, err := client.GroupIssueBoards.ListGroupIssueBoards(groupID, opts)
	if err != nil {
		return nil, err
	}

	return boards, nil
}
View Source
var ListGroupIssues = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupIssuesOptions) ([]*gitlab.Issue, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}
	issues, _, err := client.Issues.ListGroupIssues(groupID, opts)
	if err != nil {
		return nil, err
	}

	return issues, nil
}
View Source
var ListGroupIterations = func(client *gitlab.Client, groupID interface{}, opts *ListProjectIterationsOptions) ([]*gitlab.GroupIteration, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	iterations, _, err := client.GroupIterations.ListGroupIterations(groupID, opts.ListGroupIterationsOptions())
	if err != nil {
		return nil, err
	}
	return iterations, nil
}
View Source
var ListGroupLabels = func(client *gitlab.Client, groupID any, opts *ListLabelsOptions) ([]*gitlab.GroupLabel, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	labels, _, err := client.GroupLabels.ListGroupLabels(groupID, opts.ListGroupLabelsOptions())
	if err != nil {
		return nil, err
	}
	return labels, nil
}
View Source
var ListGroupMRs = func(client *gitlab.Client, projectID any, opts *gitlab.ListGroupMergeRequestsOptions, listOpts ...CliListMROption) ([]*gitlab.BasicMergeRequest, error) {
	composedListOpts := composeCliListMROptions(listOpts...)
	assigneeIds, reviewerIds := composedListOpts.assigneeIds, composedListOpts.reviewerIds

	if len(assigneeIds) > 0 || len(reviewerIds) > 0 {
		return listGroupMRsWithAssigneesOrReviewers(client, projectID, opts, assigneeIds, reviewerIds)
	} else {
		return listGroupMRsBase(client, projectID, opts)
	}
}

ListGroupMRs retrieves merge requests for a given group with optional filtering by assignees or reviewers.

Parameters:

  • client: A GitLab client instance.
  • groupID: The ID or name of the group.
  • opts: GitLab-specific options for listing group merge requests.
  • listOpts: Optional list of arguments to filter by assignees or reviewers. May be any combination of api.WithMRAssignees and api.WithMRReviewers.

Returns:

  • A slice of GitLab merge request objects and an error, if any.

Example usage:

groupMRs, err := api.ListGroupMRs(client, "my-group", &gitlab.ListGroupMergeRequestsOptions{},
	api.WithMRAssignees([]int{123}),
	api.WithMRReviewers([]int{456, 789}))
View Source
var ListGroupMilestones = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupMilestonesOptions) ([]*gitlab.GroupMilestone, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	milestone, _, err := client.GroupMilestones.ListGroupMilestones(groupID, opts)
	if err != nil {
		return nil, err
	}
	return milestone, nil
}
View Source
var ListGroupProjects = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupProjectsOptions) ([]*gitlab.Project, *gitlab.Response, error) {
	project, resp, err := client.Groups.ListGroupProjects(groupID, opts)
	if err != nil {
		return nil, nil, err
	}
	return project, resp, nil
}
View Source
var ListGroupVariables = func(client *gitlab.Client, groupID any, opts *gitlab.ListGroupVariablesOptions) ([]*gitlab.GroupVariable, error) {
	vars, _, err := client.GroupVariables.ListVariables(groupID, opts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var ListIssueBoards = func(client *gitlab.Client, projectID any, opts *gitlab.ListIssueBoardsOptions) ([]*gitlab.IssueBoard, error) {
	boards, _, err := client.Boards.ListIssueBoards(projectID, opts)
	if err != nil {
		return nil, err
	}

	return boards, nil
}
View Source
var ListIssueNotes = func(client *gitlab.Client, projectID any, issueID int, opts *gitlab.ListIssueNotesOptions) ([]*gitlab.Note, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}
	notes, _, err := client.Notes.ListIssueNotes(projectID, issueID, opts)
	if err != nil {
		return nil, err
	}
	return notes, nil
}
View Source
var ListLabels = func(client *gitlab.Client, projectID any, opts *ListLabelsOptions) ([]*gitlab.Label, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	label, _, err := client.Labels.ListLabels(projectID, opts.ListLabelsOptions())
	if err != nil {
		return nil, err
	}
	return label, nil
}
View Source
var ListMRNotes = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.ListMergeRequestNotesOptions) ([]*gitlab.Note, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	notes, _, err := client.Notes.ListMergeRequestNotes(projectID, mrID, opts)
	if err != nil {
		return notes, err
	}

	return notes, nil
}
View Source
var ListMRs = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectMergeRequestsOptions, listOpts ...CliListMROption) ([]*gitlab.BasicMergeRequest, error) {
	composedListOpts := composeCliListMROptions(listOpts...)
	assigneeIds, reviewerIds := composedListOpts.assigneeIds, composedListOpts.reviewerIds

	if len(assigneeIds) > 0 || len(reviewerIds) > 0 {
		return listMRsWithAssigneesOrReviewers(client, projectID, opts, assigneeIds, reviewerIds)
	} else {
		return listMRsBase(client, projectID, opts)
	}
}

ListMRs retrieves merge requests for a given project with optional filtering by assignees or reviewers.

Parameters:

  • client: A GitLab client instance.
  • projectID: The ID or name of the project.
  • opts: GitLab-specific options for listing merge requests.
  • listOpts: Optional list of arguments to filter by assignees or reviewers. May be any combination of api.WithMRAssignees and api.WithMRReviewers.

Returns:

  • A slice of GitLab merge request objects and an error, if any.

Example usage:

mrs, err := api.ListMRs(client, "my-group", &gitlab.ListProjectMergeRequestsOptions{},
	api.WithMRAssignees([]int{123, 456}),
	api.WithMRReviewers([]int{789}))
View Source
var ListPersonalAccessTokens = func(client *gitlab.Client, opts *gitlab.ListPersonalAccessTokensOptions) ([]*gitlab.PersonalAccessToken, error) {
	perPage := opts.PerPage
	if perPage == 0 {
		perPage = 100
	}
	tokens := make([]*gitlab.PersonalAccessToken, 0, perPage)
	for {
		results, response, err := client.PersonalAccessTokens.ListPersonalAccessTokens(opts)
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, results...)

		if response.CurrentPage >= response.TotalPages {
			break
		}
		opts.Page = response.NextPage
	}

	return tokens, nil
}
View Source
var ListProjectAccessTokens = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectAccessTokensOptions) ([]*gitlab.ProjectAccessToken, error) {
	perPage := opts.PerPage
	if perPage == 0 {
		perPage = 100
	}
	tokens := make([]*gitlab.ProjectAccessToken, 0, perPage)
	for {
		results, response, err := client.ProjectAccessTokens.ListProjectAccessTokens(projectID, opts)
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, results...)

		if response.CurrentPage >= response.TotalPages {
			break
		}
		opts.Page = response.NextPage
	}

	return tokens, nil
}
View Source
var ListProjectIssues = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectIssuesOptions) ([]*gitlab.Issue, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}
	issues, _, err := client.Issues.ListProjectIssues(projectID, opts)
	if err != nil {
		return nil, err
	}

	return issues, nil
}
View Source
var ListProjectIterations = func(client *gitlab.Client, projectID interface{}, opts *ListProjectIterationsOptions) ([]*gitlab.ProjectIteration, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	iteration, _, err := client.ProjectIterations.ListProjectIterations(projectID, opts.ListProjectIterationsOptions())
	if err != nil {
		return nil, err
	}
	return iteration, nil
}
View Source
var ListProjectMembers = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectMembersOptions) ([]*gitlab.ProjectMember, error) {
	members, _, err := client.ProjectMembers.ListAllProjectMembers(projectID, opts)
	if err != nil {
		return nil, err
	}
	return members, nil
}
View Source
var ListProjectMilestones = func(client *gitlab.Client, projectID any, opts *gitlab.ListMilestonesOptions) ([]*gitlab.Milestone, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	milestone, _, err := client.Milestones.ListMilestones(projectID, opts)
	if err != nil {
		return nil, err
	}
	return milestone, nil
}
View Source
var ListProjectPipelines = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectPipelinesOptions) ([]*gitlab.PipelineInfo, error) {
	pipes, _, err := client.Pipelines.ListProjectPipelines(projectID, opts)
	if err != nil {
		return pipes, err
	}
	return pipes, nil
}
View Source
var ListProjectVariables = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectVariablesOptions) ([]*gitlab.ProjectVariable, error) {
	vars, _, err := client.ProjectVariables.ListVariables(projectID, opts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var ListProjectsGroups = func(client *gitlab.Client, projectID any, opts *gitlab.ListProjectGroupOptions) ([]*gitlab.ProjectGroup, error) {
	groups, _, err := client.Projects.ListProjectsGroups(projectID, opts)
	if err != nil {
		return nil, err
	}
	return groups, nil
}
View Source
var ListReleases = func(client *gitlab.Client, projectID any, opts *gitlab.ListReleasesOptions) ([]*gitlab.Release, error) {
	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	releases, _, err := client.Releases.ListReleases(projectID, opts)
	if err != nil {
		return nil, err
	}

	return releases, nil
}
View Source
var ListSecureFiles = func(client *gitlab.Client, l *gitlab.ListProjectSecureFilesOptions, projectID any) ([]*gitlab.SecureFile, error) {
	if l == nil {
		l = &gitlab.ListProjectSecureFilesOptions{
			Page:    1,
			PerPage: DefaultListLimit,
		}
	} else {
		if l.PerPage == 0 {
			l.PerPage = DefaultListLimit
		}
		if l.Page == 0 {
			l.Page = 1
		}
	}

	files, _, err := client.SecureFiles.ListProjectSecureFiles(projectID, l)
	if err != nil {
		return nil, err
	}
	return files, nil
}
View Source
var MRTodo = func(client *gitlab.Client, projectID any, mrID int, opts gitlab.RequestOptionFunc) (*gitlab.Todo, error) {
	mr, resp, err := client.MergeRequests.CreateTodo(projectID, mrID, opts)

	if resp.StatusCode == http.StatusNotModified {
		return nil, ErrTodoExists
	}

	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var MergeMR = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.AcceptMergeRequestOptions) (*gitlab.MergeRequest, *gitlab.Response, error) {
	mrs, resp, err := client.MergeRequests.AcceptMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, resp, err
	}

	return mrs, resp, nil
}
View Source
var PipelineJobWithSha = func(client *gitlab.Client, pid any, sha, name string) (*gitlab.Job, error) {
	jobs, _, err := PipelineJobsWithSha(client, pid, sha)
	if len(jobs) == 0 || err != nil {
		return nil, err
	}
	var (
		job          *gitlab.Job
		lastRunning  *gitlab.Job
		firstPending *gitlab.Job
	)

	for _, j := range jobs {
		if j.Status == "running" {
			lastRunning = j
		}
		if j.Status == "pending" && firstPending == nil {
			firstPending = j
		}
		if j.Name == name {
			job = j

		}
	}
	if job == nil {
		job = lastRunning
	}
	if job == nil {
		job = firstPending
	}
	if job == nil {
		job = jobs[len(jobs)-1]
	}
	return job, err
}
View Source
var PipelineJobsWithID = func(client *gitlab.Client, pid any, ppid int) ([]*gitlab.Job, []*gitlab.Bridge, error) {
	opts := &gitlab.ListJobsOptions{
		ListOptions: gitlab.ListOptions{
			PerPage: 500,
		},
	}
	jobsList := make([]*gitlab.Job, 0)
	for {
		jobs, resp, err := client.Jobs.ListPipelineJobs(pid, ppid, opts)
		if err != nil {
			return nil, nil, err
		}
		opts.Page = resp.NextPage
		jobsList = append(jobsList, jobs...)
		if resp.CurrentPage == resp.TotalPages {
			break
		}
	}
	opts.Page = 0
	bridgesList := make([]*gitlab.Bridge, 0)
	for {
		bridges, resp, err := client.Jobs.ListPipelineBridges(pid, ppid, opts)
		if err != nil {
			return nil, nil, err
		}
		opts.Page = resp.NextPage
		bridgesList = append(bridgesList, bridges...)
		if resp.CurrentPage == resp.TotalPages {
			break
		}
	}

	sort.Sort(JobSort{Jobs: jobsList})
	sort.Sort(BridgeSort{Bridges: bridgesList})
	return jobsList, bridgesList, nil
}

PipelineJobsWithID returns a list of jobs in a pipeline for a id. The jobs are returned in the order in which they were created

View Source
var PipelineJobsWithSha = func(client *gitlab.Client, pid any, sha string) ([]*gitlab.Job, []*gitlab.Bridge, error) {
	pipelines, err := GetPipelines(client, &gitlab.ListProjectPipelinesOptions{
		SHA: gitlab.Ptr(sha),
	}, pid)
	if len(pipelines) == 0 || err != nil {
		return nil, nil, err
	}
	return PipelineJobsWithID(client, pid, pipelines[0].ID)
}

PipelineJobsWithSha returns a list of jobs in a pipeline for a given commit sha. The jobs are returned in the order in which they were created

View Source
var PlayOrRetryJobs = func(client *gitlab.Client, repo string, jobID int, status string) (*gitlab.Job, error) {
	switch status {
	case "pending", "running":
		return nil, nil
	case "manual":
		j, err := PlayPipelineJob(client, jobID, repo)
		if err != nil {
			return nil, err
		}
		return j, nil
	default:

		j, err := RetryPipelineJob(client, jobID, repo)
		if err != nil {
			return nil, err
		}

		return j, nil
	}
}
View Source
var PlayPipelineJob = func(client *gitlab.Client, pid int, repo string) (*gitlab.Job, error) {
	playOptions := gitlab.PlayJobOptions{}
	pipe, _, err := client.Jobs.PlayJob(repo, pid, &playOptions)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var ProjectListIssueOptionsToGroup = func(l *gitlab.ListProjectIssuesOptions) *gitlab.ListGroupIssuesOptions {
	var assigneeID *gitlab.AssigneeIDValue
	if l.AssigneeID != nil {
		assigneeID = gitlab.AssigneeID(*l.AssigneeID)
	}
	return &gitlab.ListGroupIssuesOptions{
		ListOptions:        l.ListOptions,
		State:              l.State,
		Labels:             l.Labels,
		NotLabels:          l.NotLabels,
		WithLabelDetails:   l.WithLabelDetails,
		IIDs:               l.IIDs,
		Milestone:          l.Milestone,
		Scope:              l.Scope,
		AuthorID:           l.AuthorID,
		NotAuthorID:        l.NotAuthorID,
		AssigneeID:         assigneeID,
		NotAssigneeID:      l.NotAssigneeID,
		AssigneeUsername:   l.AssigneeUsername,
		MyReactionEmoji:    l.MyReactionEmoji,
		NotMyReactionEmoji: l.NotMyReactionEmoji,
		OrderBy:            l.OrderBy,
		Sort:               l.Sort,
		Search:             l.Search,
		In:                 l.In,
		CreatedAfter:       l.CreatedAfter,
		CreatedBefore:      l.CreatedBefore,
		UpdatedAfter:       l.UpdatedAfter,
		UpdatedBefore:      l.UpdatedBefore,
		IssueType:          l.IssueType,
	}
}
View Source
var ProjectListMROptionsToGroup = func(l *gitlab.ListProjectMergeRequestsOptions) *gitlab.ListGroupMergeRequestsOptions {
	return &gitlab.ListGroupMergeRequestsOptions{
		ListOptions:            l.ListOptions,
		State:                  l.State,
		OrderBy:                l.OrderBy,
		Sort:                   l.Sort,
		Milestone:              l.Milestone,
		View:                   l.View,
		Labels:                 l.Labels,
		NotLabels:              l.NotLabels,
		WithLabelsDetails:      l.WithLabelsDetails,
		WithMergeStatusRecheck: l.WithMergeStatusRecheck,
		CreatedAfter:           l.CreatedAfter,
		CreatedBefore:          l.CreatedBefore,
		UpdatedAfter:           l.UpdatedAfter,
		UpdatedBefore:          l.UpdatedBefore,
		Scope:                  l.Scope,
		AuthorID:               l.AuthorID,
		AssigneeID:             l.AssigneeID,
		ReviewerID:             l.ReviewerID,
		ReviewerUsername:       l.ReviewerUsername,
		MyReactionEmoji:        l.MyReactionEmoji,
		SourceBranch:           l.SourceBranch,
		TargetBranch:           l.TargetBranch,
		Search:                 l.Search,
		WIP:                    l.WIP,
	}
}
View Source
var ProjectMilestoneByTitle = func(client *gitlab.Client, projectID any, name string) (*gitlab.Milestone, error) {
	opts := &gitlab.ListMilestonesOptions{Title: gitlab.Ptr(name), IncludeParentMilestones: gitlab.Ptr(true)}

	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	milestones, _, err := client.Milestones.ListMilestones(projectID, opts)
	if err != nil {
		return nil, err
	}

	if len(milestones) != 1 {
		return nil, fmt.Errorf("failed to find milestone by title: %s", name)
	}

	return milestones[0], nil
}
View Source
var ProjectNamespaceLint = func(client *gitlab.Client, projectID int, content string, ref string, dryRun bool, includeJobs bool) (*gitlab.ProjectLintResult, error) {
	c, _, err := client.Validate.ProjectNamespaceLint(
		projectID,
		&gitlab.ProjectNamespaceLintOptions{
			Content:     &content,
			DryRun:      &dryRun,
			Ref:         &ref,
			IncludeJobs: &includeJobs,
		},
	)
	if err != nil {
		return nil, err
	}
	return c, nil
}
View Source
var RebaseMR = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.RebaseMergeRequestOptions) error {
	_, err := client.MergeRequests.RebaseMergeRequest(projectID, mrID, opts)
	if err != nil {
		return err
	}

	return nil
}
View Source
var RegisterAgent = func(client *gitlab.Client, projectID any, agentName string) (*gitlab.Agent, error) {
	agent, _, err := client.ClusterAgents.RegisterAgent(projectID, &gitlab.RegisterAgentOptions{Name: gitlab.Ptr(agentName)})
	if err != nil {
		return nil, err
	}

	return agent, nil
}
View Source
var RemoveSecureFile = func(client *gitlab.Client, projectID any, id int) error {
	_, err := client.SecureFiles.RemoveSecureFile(projectID, id)
	return err
}
View Source
var RetryPipeline = func(client *gitlab.Client, pid int, repo string) (*gitlab.Pipeline, error) {
	pipe, _, err := client.Pipelines.RetryPipelineBuild(repo, pid)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var RetryPipelineJob = func(client *gitlab.Client, pid int, repo string) (*gitlab.Job, error) {
	pipe, _, err := client.Jobs.RetryJob(repo, pid)
	if err != nil {
		return nil, err
	}
	return pipe, nil
}
View Source
var RevokeGroupAccessToken = func(client *gitlab.Client, gid any, id int) error {
	_, err := client.GroupAccessTokens.RevokeGroupAccessToken(gid, id)
	return err
}
View Source
var RevokePersonalAccessToken = func(client *gitlab.Client, id int) error {
	_, err := client.PersonalAccessTokens.RevokePersonalAccessToken(id)
	return err
}
View Source
var RevokeProjectAccessToken = func(client *gitlab.Client, pid any, id int) error {
	_, err := client.ProjectAccessTokens.RevokeProjectAccessToken(pid, id)
	return err
}
View Source
var RotateGroupAccessToken = func(client *gitlab.Client, gid any, id int, opts *gitlab.RotateGroupAccessTokenOptions) (*gitlab.GroupAccessToken, error) {
	token, _, err := client.GroupAccessTokens.RotateGroupAccessToken(gid, id, opts)
	return token, err
}
View Source
var RotatePersonalAccessToken = func(client *gitlab.Client, id int, opts *gitlab.RotatePersonalAccessTokenOptions) (*gitlab.PersonalAccessToken, error) {
	token, _, err := client.PersonalAccessTokens.RotatePersonalAccessToken(id, opts)
	return token, err
}
View Source
var RotateProjectAccessToken = func(client *gitlab.Client, pid any, id int, opts *gitlab.RotateProjectAccessTokenOptions) (*gitlab.ProjectAccessToken, error) {
	token, _, err := client.ProjectAccessTokens.RotateProjectAccessToken(pid, id, opts)
	return token, err
}
View Source
var RunPipelineTrigger = func(client *gitlab.Client, projectID any, opts *gitlab.RunPipelineTriggerOptions) (*gitlab.Pipeline, error) {
	pipe, _, err := client.PipelineTriggers.RunPipelineTrigger(projectID, opts)
	return pipe, err
}
View Source
var RunSchedule = func(client *gitlab.Client, repo string, schedule int, opts ...gitlab.RequestOptionFunc) error {
	_, err := client.PipelineSchedules.RunPipelineSchedule(repo, schedule, opts...)
	if err != nil {
		return fmt.Errorf("running scheduled pipeline status: %w", err)
	}

	return nil
}
View Source
var SetIssueTimeEstimate = func(client *gitlab.Client, projectID any, issueIDD int, opts *gitlab.SetTimeEstimateOptions) (*gitlab.TimeStats, error) {
	timeStats, _, err := client.Issues.SetTimeEstimate(projectID, issueIDD, opts)
	if err != nil {
		return nil, err
	}

	return timeStats, nil
}
View Source
var SubscribeToIssue = func(client *gitlab.Client, projectID any, issueID int, opts gitlab.RequestOptionFunc) (*gitlab.Issue, error) {
	issue, resp, err := client.Issues.SubscribeToIssue(projectID, issueID, opts)
	if err != nil {
		if resp != nil {

			if resp.StatusCode == http.StatusNotModified {
				return nil, ErrIssuableUserAlreadySubscribed
			}
		}
		return issue, err
	}

	return issue, nil
}
View Source
var SubscribeToMR = func(client *gitlab.Client, projectID any, mrID int, opts gitlab.RequestOptionFunc) (*gitlab.MergeRequest, error) {
	mr, _, err := client.MergeRequests.SubscribeToMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var SyncFile = func(client *gitlab.Client, projectID any, path string, content []byte, ref string) error {
	_, resp, err := client.RepositoryFiles.GetFileMetaData(projectID, path, &gitlab.GetFileMetaDataOptions{
		Ref: gitlab.Ptr(ref),
	})
	if err != nil {
		if resp.StatusCode != http.StatusNotFound {
			return err
		}

		_, _, err := client.RepositoryFiles.CreateFile(projectID, path, &gitlab.CreateFileOptions{
			Branch:        gitlab.Ptr(ref),
			Content:       gitlab.Ptr(string(content)),
			CommitMessage: gitlab.Ptr(fmt.Sprintf("Add %s via glab file sync", path)),
			AuthorName:    gitlab.Ptr(commitAuthorName),
			AuthorEmail:   gitlab.Ptr(commitAuthorEmail),
		})
		return err
	}

	_, _, err = client.RepositoryFiles.UpdateFile(projectID, path, &gitlab.UpdateFileOptions{
		Branch:        gitlab.Ptr(ref),
		Content:       gitlab.Ptr(string(content)),
		CommitMessage: gitlab.Ptr(fmt.Sprintf("Update %s via glab file sync", path)),
		AuthorName:    gitlab.Ptr(commitAuthorName),
		AuthorEmail:   gitlab.Ptr(commitAuthorEmail),
	})
	return err
}

SyncFile syncs (add or update) a file in the repository

View Source
var UnapproveMR = func(client *gitlab.Client, projectID any, mrID int) error {
	_, err := client.MergeRequestApprovals.UnapproveMergeRequest(projectID, mrID)
	if err != nil {
		return err
	}

	return nil
}
View Source
var UnsubscribeFromIssue = func(client *gitlab.Client, projectID any, issueID int, opts gitlab.RequestOptionFunc) (*gitlab.Issue, error) {
	issue, resp, err := client.Issues.UnsubscribeFromIssue(projectID, issueID, opts)
	if err != nil {
		if resp != nil {

			if resp.StatusCode == http.StatusNotModified {
				return nil, ErrIssuableUserNotSubscribed
			}
		}
		return issue, err
	}

	return issue, nil
}
View Source
var UnsubscribeFromMR = func(client *gitlab.Client, projectID any, mrID int, opts gitlab.RequestOptionFunc) (*gitlab.MergeRequest, error) {
	mr, _, err := client.MergeRequests.UnsubscribeFromMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var UpdateFile = func(client *gitlab.Client, projectID any, path string, content []byte, ref string) error {
	_, _, err := client.RepositoryFiles.UpdateFile(projectID, path, &gitlab.UpdateFileOptions{
		Branch:        gitlab.Ptr(ref),
		Content:       gitlab.Ptr(string(content)),
		CommitMessage: gitlab.Ptr(fmt.Sprintf("Update %s via glab file sync", path)),
		AuthorName:    gitlab.Ptr(commitAuthorName),
		AuthorEmail:   gitlab.Ptr(commitAuthorEmail),
	})
	return err
}
View Source
var UpdateGroupVariable = func(client *gitlab.Client, groupID any, key string, opts *gitlab.UpdateGroupVariableOptions) (*gitlab.GroupVariable, error) {
	vars, _, err := client.GroupVariables.UpdateVariable(groupID, key, opts)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var UpdateIssue = func(client *gitlab.Client, projectID any, issueID int, opts *gitlab.UpdateIssueOptions) (*gitlab.Issue, error) {
	issue, _, err := client.Issues.UpdateIssue(projectID, issueID, opts)
	if err != nil {
		return nil, err
	}

	return issue, nil
}
View Source
var UpdateMR = func(client *gitlab.Client, projectID any, mrID int, opts *gitlab.UpdateMergeRequestOptions) (*gitlab.MergeRequest, error) {
	mr, _, err := client.MergeRequests.UpdateMergeRequest(projectID, mrID, opts)
	if err != nil {
		return nil, err
	}

	return mr, nil
}
View Source
var UpdateProjectVariable = func(client *gitlab.Client, projectID any, key string, opts *gitlab.UpdateProjectVariableOptions) (*gitlab.ProjectVariable, error) {
	filter := func(request *retryablehttp.Request) error {
		q := request.URL.Query()
		q.Add("filter[environment_scope]", *opts.EnvironmentScope)

		request.URL.RawQuery = q.Encode()

		return nil
	}

	vars, _, err := client.ProjectVariables.UpdateVariable(projectID, key, opts, filter)
	if err != nil {
		return nil, err
	}

	return vars, nil
}
View Source
var UserByName = func(client *gitlab.Client, name string) (*gitlab.User, error) {
	opts := &gitlab.ListUsersOptions{Username: gitlab.Ptr(name)}

	if opts.PerPage == 0 {
		opts.PerPage = DefaultListLimit
	}

	if name == "@me" {
		return CurrentUser(client)
	}

	users, _, err := client.Users.ListUsers(opts)
	if err != nil {
		return nil, err
	}

	if len(users) != 1 {
		return nil, fmt.Errorf("failed to find user by name: %s", name)
	}

	return users[0], nil
}
View Source
var UsersByNames = func(client *gitlab.Client, names []string) ([]*gitlab.User, error) {
	users := make([]*gitlab.User, 0)
	for _, name := range names {
		user, err := UserByName(client, name)
		if err != nil {
			return nil, err
		}

		users = append(users, user)
	}
	return users, nil
}

Functions

func HTTPClient

func HTTPClient() *http.Client

HTTPClient returns the httpClient instance used to initialise the gitlab api client

func Is404 added in v1.48.0

func Is404(err error) bool

Is404 checks if the error represents a 404 response

func IsValidToken

func IsValidToken(token string) bool

IsValidToken checks if a token provided is valid. The token string must be 26 characters in length and have the 'glpat-' prefix or just be 20 characters long to be recognized as a valid personal access token. token can be 64 characters to include oauth tokens TODO: check if token has minimum scopes required by glab

func NewHTTPRequest

func NewHTTPRequest(c *Client, method string, baseURL *url.URL, body io.Reader, headers []string, bodyIsJSON bool) (*http.Request, error)

func OverrideHTTPClient

func OverrideHTTPClient(client *http.Client)

OverrideHTTPClient overrides the default http client

func RefreshClient

func RefreshClient()

RefreshClient re-initializes the api client

func SetProtocol

func SetProtocol(protocol string)

func SetUserAgent added in v1.26.0

func SetUserAgent(version string, platform string, architecture string)

func Token

func Token() string

Token returns the authentication token

Types

type BridgeSort added in v1.32.0

type BridgeSort struct {
	Bridges []*gitlab.Bridge
}

func (BridgeSort) Len added in v1.32.0

func (s BridgeSort) Len() int

func (BridgeSort) Less added in v1.32.0

func (s BridgeSort) Less(i, j int) bool

func (BridgeSort) Swap added in v1.32.0

func (s BridgeSort) Swap(i, j int)

type CliListMROption added in v1.46.0

type CliListMROption func(*cliListMROptions)

func WithMRAssignees added in v1.46.0

func WithMRAssignees(assigneeIds []int) CliListMROption

func WithMRReviewers added in v1.46.0

func WithMRReviewers(reviewerIds []int) CliListMROption

type Client

type Client struct {
	// LabClient represents GitLab API client.
	// Note: this is exported for tests. Do not access it directly. Use Lab() method
	LabClient *gitlab.Client

	// Token type used to make authenticated API calls.
	AuthType authType

	// Protocol: host url protocol to make requests. Default is https
	Protocol string
	// contains filtered or unexported fields
}

Client represents an argument to NewClient

func GetClient

func GetClient() *Client

GetClient returns the global Client instance.

func NewClient

func NewClient(host, token string, allowInsecure bool, isGraphQL bool, isOAuth2 bool, isJobToken bool) (*Client, error)

NewClient initializes a api client for use throughout glab.

func NewClientWithCfg

func NewClientWithCfg(repoHost string, cfg config.Config, isGraphQL bool) (client *Client, err error)

NewClientWithCfg initializes the global api with the config data

func NewClientWithCustomCA

func NewClientWithCustomCA(host, token, caFile string, isGraphQL bool, isOAuth2 bool, isJobToken bool) (*Client, error)

NewClientWithCustomCA initializes the global api client with a self-signed certificate

func NewClientWithCustomCAClientCert

func NewClientWithCustomCAClientCert(host, token, caFile string, certFile string, keyFile string, isGraphQL bool, isOAuth2 bool, isJobToken bool) (*Client, error)

NewClientWithCustomCAClientCert initializes the global api client with a self-signed certificate and client certificates

func TestClient

func TestClient(httpClient *http.Client, token, host string, isGraphQL bool) (*Client, error)

func (*Client) BaseURL

func (c *Client) BaseURL() *url.URL

BaseURL returns a copy of the BaseURL

func (*Client) HTTPClient

func (c *Client) HTTPClient() *http.Client

func (*Client) Lab

func (c *Client) Lab() *gitlab.Client

Lab returns the initialized GitLab client. Initializes a new GitLab Client if not initialized but error is ignored

func (*Client) NewLab

func (c *Client) NewLab() error

NewLab initializes the GitLab Client

func (*Client) OverrideHTTPClient

func (c *Client) OverrideHTTPClient(client *http.Client)

func (*Client) SetProtocol

func (c *Client) SetProtocol(protocol string)

func (*Client) Token

func (c *Client) Token() string

type CreatePullMirrorOptions

type CreatePullMirrorOptions struct {
	Url                   string
	Enabled               bool
	OnlyProtectedBranches bool
}

type CreatePushMirrorOptions

type CreatePushMirrorOptions struct {
	Url                   string
	Enabled               bool
	OnlyProtectedBranches bool
	KeepDivergentRefs     bool
}

type JobSort

type JobSort struct {
	Jobs []*gitlab.Job
}

func (JobSort) Len

func (s JobSort) Len() int

func (JobSort) Less

func (s JobSort) Less(i, j int) bool

func (JobSort) Swap

func (s JobSort) Swap(i, j int)

type ListLabelsOptions added in v1.50.0

type ListLabelsOptions struct {
	WithCounts *bool
	PerPage    int
	Page       int
}

func (*ListLabelsOptions) ListGroupLabelsOptions added in v1.50.0

func (opts *ListLabelsOptions) ListGroupLabelsOptions() *gitlab.ListGroupLabelsOptions

func (*ListLabelsOptions) ListLabelsOptions added in v1.50.0

func (opts *ListLabelsOptions) ListLabelsOptions() *gitlab.ListLabelsOptions

type ListMilestonesOptions

type ListMilestonesOptions struct {
	IIDs                    []int
	State                   *string
	Title                   *string
	Search                  *string
	IncludeParentMilestones *bool
	PerPage                 int
	Page                    int
}

func (*ListMilestonesOptions) ListGroupMilestonesOptions

func (opts *ListMilestonesOptions) ListGroupMilestonesOptions() *gitlab.ListGroupMilestonesOptions

func (*ListMilestonesOptions) ListProjectMilestonesOptions

func (opts *ListMilestonesOptions) ListProjectMilestonesOptions() *gitlab.ListMilestonesOptions

type ListProjectIterationsOptions added in v1.58.0

type ListProjectIterationsOptions struct {
	IncludeAncestors *bool
	PerPage          int
	Page             int
}

func (*ListProjectIterationsOptions) ListGroupIterationsOptions added in v1.58.0

func (opts *ListProjectIterationsOptions) ListGroupIterationsOptions() *gitlab.ListGroupIterationsOptions

func (*ListProjectIterationsOptions) ListProjectIterationsOptions added in v1.58.0

func (opts *ListProjectIterationsOptions) ListProjectIterationsOptions() *gitlab.ListProjectIterationsOptions

type Milestone

type Milestone struct {
	ID    int
	Title string
}

func NewGroupMilestone

func NewGroupMilestone(m *gitlab.GroupMilestone) *Milestone

func NewProjectMilestone

func NewProjectMilestone(m *gitlab.Milestone) *Milestone

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳