gitlab

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 25 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package gitlab is the forge adapter for GitLab: gitlab.com or a self-managed instance (config.GitLab.BaseURL).

Auth model

The adapter uses one project or group access token with the api scope, sent as PRIVATE-TOKEN to the REST API v4. The token's bot user is the account kōjō acts as: its username is what people mention.

Webhooks are authenticated by the secret token GitLab sends in X-Gitlab-Token, compared in constant time before anything is decoded. A Forge without a webhook secret rejects every delivery.

Writes

CreateBranch and CommitFiles refuse any branch that is not kojo/*. CommitFiles uses the commits API, one commit with one action per file, so no git binary and no repository hook runs in the core. It accepts regular files only: modes 100644 and 100755, and no path inside .git. With forge.WithExpectedHead it writes only while the branch is at that commit, and names each updated or deleted file's last commit (last_commit_id), so GitLab refuses the commit when a push in between changed one of them.

Limitations

  • CloneCredentials cannot return a short-lived or read-only credential: GitLab has no equivalent of an installation token. It returns the configured token itself, which can write. The egress proxy is then the only thing between a sandbox and a push; keep the allowlist of a GitLab skill to what it needs. Expires is the token's own expiry date, or zero when it has none.
  • Git and the API share one host and want different headers, so CloneCredentials returns two credentials for the same host: Authorization (Basic oauth2:<token>) for git and PRIVATE-TOKEN for the API.
  • Issues and merge requests are numbered separately in GitLab, but GetIssue, ListComments and Comment take one number. The mark of forge.WithPullRequest in the context says which is meant. Without it the adapter looks for both and returns ErrAmbiguousNumber when both exist, rather than risk a comment on the wrong thread.
  • GitLab cannot rebase and merge in one call: MergePR accepts merge and squash. It takes a merge request out of draft before merging.
  • A push payload carries at most 20 commits. Event.ChangedPaths is nil when a push has more, which means "unknown", not "nothing changed".
  • Required reviews come from approval rules, which only paid tiers have. RequiredChecks is ["pipeline"] when the project only merges with a successful pipeline.
  • ListRepos does not fill RepoInfo.HeadSHA. GetRepo does.
  • GitLab's list of merge requests has no diff_refs, so ListPullRequests leaves BaseSHA empty unless ListPullRequestsOptions.WithBaseSHA is set, which costs one more request per merge request. GetPR fills it. BaseSHA is diff_refs.base_sha, the merge base of the latest diff version. MergeCommitSHA is merge_commit_sha, else squash_commit_sha, else, for a fast-forward without squashing, sha (the head).
  • Mentions inside quoted text or code blocks count as mentions.

Index

Constants

View Source
const Name = "gitlab"

Name is the forge name of this adapter.

Variables

View Source
var ErrAmbiguousNumber = errors.New("gitlab: the number is both an issue and a merge request")

ErrAmbiguousNumber is returned by GetIssue, ListComments and Comment when a project has both an issue and a merge request with the number and the context does not say which is meant (see forge.WithPullRequest).

Functions

This section is empty.

Types

type Forge

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

Forge is a GitLab instance reached with one access token. It is safe for concurrent use.

func New

func New(cfg config.GitLab, opts ...Option) (*Forge, error)

New builds the adapter from the deployment config. It makes no request.

func (*Forge) BotLogin

func (f *Forge) BotLogin(ctx context.Context) (string, error)

BotLogin is the username of the token's user. For a project or group access token that is its bot user (project_123_bot_...).

func (*Forge) BranchProtection

func (f *Forge) BranchProtection(ctx context.Context, repo forge.Repo, name string) (*forge.Protection, error)

BranchProtection reports whether a branch is protected (wildcard rules included). For a protected branch, RequiredReviews is the largest approval rule that applies to it, on tiers that have approval rules, and RequiredChecks is ["pipeline"] when the project only merges with a successful pipeline.

func (*Forge) Check

func (f *Forge) Check(ctx context.Context) error

Check verifies that GitLab answers, that the token is valid and that it has the api scope. It returns one joined error naming every problem.

func (*Forge) CheckRuns

func (f *Forge) CheckRuns(ctx context.Context, repo forge.Repo, sha string) ([]forge.CheckRun, error)

CheckRuns lists the jobs of a commit's pipelines (the latest pipeline per ref and source, as ChecksStatus counts them), and for a failed job its failure reason and the end of its log, read from GET /jobs/{id}/trace for the first maxJobLogs of them. A commit without pipelines lists its commit statuses with their descriptions. A job allowed to fail counts as passed, a skipped one too; one that has not finished is pending.

func (*Forge) ChecksStatus

func (f *Forge) ChecksStatus(ctx context.Context, repo forge.Repo, sha string) (forge.ChecksState, error)

ChecksStatus summarizes the pipelines of a commit: the latest one per ref and source. A commit without pipelines falls back to its commit statuses. A cancelled pipeline counts as a failure; one waiting for a manual job as pending; a skipped one does not count.

func (*Forge) CloneCredentials

func (f *Forge) CloneCredentials(ctx context.Context, repo forge.Repo) ([]sandbox.HostCredential, error)

CloneCredentials returns the configured token as two credentials for the GitLab host: Basic auth for git over HTTPS and PRIVATE-TOKEN for the API.

The token is neither short-lived nor read-only: GitLab cannot mint a narrower one on demand (see the package documentation). Expires is the token's expiry date when GitLab reports one.

func (*Forge) Comment

func (f *Forge) Comment(ctx context.Context, repo forge.Repo, number int, body string) (*forge.Comment, error)

Comment posts a comment on an issue or merge request. forge.WithPullRequest says which one a number means.

func (*Forge) CommitFiles

func (f *Forge) CommitFiles(ctx context.Context, repo forge.Repo, branch, message string, changes []forge.FileChange) (string, error)

CommitFiles writes one commit on top of branch, which must be kojo/* and exist, and returns the commit's SHA. It looks at the branch to choose between create and update for each file, and adds a chmod action where the executable bit has to change. GitLab applies all actions or none; when the branch changed in between so that an action no longer fits, the commit is refused.

With forge.WithExpectedHead it starts only when the branch is at that commit, looks at the files there, and names for each update and delete the last commit that changed the file (last_commit_id): GitLab refuses the commit when a push that landed after the branch was read changed one of those files, and that is forge.ErrHeadMoved too. A push that changed other files stays, under the new commit.

func (*Forge) CreateBranch

func (f *Forge) CreateBranch(ctx context.Context, repo forge.Repo, name, fromSHA string) error

CreateBranch creates the branch name at fromSHA. name must be kojo/*. It fails if the branch exists.

func (*Forge) GetFile

func (f *Forge) GetFile(ctx context.Context, repo forge.Repo, ref, filePath string) ([]byte, error)

GetFile reads one file at ref (a branch, tag or commit; empty means the default branch).

func (*Forge) GetIssue

func (f *Forge) GetIssue(ctx context.Context, repo forge.Repo, number int) (*forge.Issue, error)

GetIssue reads an issue, or the issue side of a merge request with IsPR set. forge.WithPullRequest says which one a number means.

func (*Forge) GetPR

func (f *Forge) GetPR(ctx context.Context, repo forge.Repo, number int) (*forge.PullRequest, error)

GetPR reads a merge request.

func (*Forge) GetPRDiff

func (f *Forge) GetPRDiff(ctx context.Context, repo forge.Repo, number int) (string, error)

GetPRDiff returns the unified diff of a merge request. It asks for the raw diff (GitLab 17.9 and later); on an older instance it builds one from the per-file diffs, where GitLab leaves out the hunks of very large files.

func (*Forge) GetRepo

func (f *Forge) GetRepo(ctx context.Context, repo forge.Repo) (*forge.RepoInfo, error)

GetRepo describes a project and the head of its default branch. HeadSHA is empty for a project without commits.

func (*Forge) ListComments

func (f *Forge) ListComments(ctx context.Context, repo forge.Repo, number int) ([]forge.Comment, error)

ListComments lists the comments of an issue or merge request, oldest first, without GitLab's system notes ("changed the description"). forge.WithPullRequest says which one a number means.

func (*Forge) ListFiles

func (f *Forge) ListFiles(ctx context.Context, repo forge.Repo, ref, dir string) ([]string, error)

ListFiles lists the files under dir at ref, recursively and sorted, as paths relative to the repository root. Submodules are left out. A ref that does not exist is forge.ErrNotFound; a dir that does not exist is an empty list.

func (*Forge) ListIssues

func (f *Forge) ListIssues(ctx context.Context, repo forge.Repo, opts forge.ListIssuesOptions) ([]forge.Issue, error)

ListIssues lists issues, newest first. Merge requests are never part of the list.

func (*Forge) ListPullRequests

func (f *Forge) ListPullRequests(ctx context.Context, repo forge.Repo, opts forge.ListPullRequestsOptions) ([]forge.PullRequest, error)

ListPullRequests lists merge requests, the most recently updated first. GitLab filters by state (its closed is closed without merging) and by updated_after itself. Its list has no diff_refs, so BaseSHA is empty unless opts.WithBaseSHA asks for each merge request to be read again.

func (*Forge) ListRepos

func (f *Forge) ListRepos(ctx context.Context) ([]forge.RepoInfo, error)

ListRepos lists the projects the token's user is a member of, archived ones left out. For a project access token that is its one project; for a group access token, the projects of the group. HeadSHA is not filled.

func (*Forge) ListReviewComments

func (f *Forge) ListReviewComments(ctx context.Context, repo forge.Repo, number int) ([]forge.ReviewComment, error)

ListReviewComments lists the comments on lines of a merge request's diff, oldest first: the notes that have a position. GitLab's review verdict is an approval without text, so there is no review summary to list; a comment on the merge request itself is ListComments'.

func (*Forge) MergePR

func (f *Forge) MergePR(ctx context.Context, repo forge.Repo, number int, method, headSHA string) error

MergePR merges a merge request. method is merge (the default: whatever the project's merge method is) or squash. A draft is taken out of draft first, by removing the title prefix.

GitLab checks mergeability in the background: a merge right after a push or after leaving draft can be refused until it has. The caller retries.

func (*Forge) Name

func (f *Forge) Name() string

Name is "gitlab".

func (*Forge) OpenPR

func (f *Forge) OpenPR(ctx context.Context, repo forge.Repo, req forge.PRRequest) (*forge.PullRequest, error)

OpenPR opens a merge request from req.Head into req.Base. A draft gets the "Draft: " title prefix, which is how GitLab marks one.

func (*Forge) ParseWebhook

func (f *Forge) ParseWebhook(r *http.Request, body []byte) (*forge.Event, error)

ParseWebhook checks the secret token of a delivery and normalizes it.

It returns forge.ErrBadSignature when X-Gitlab-Token is missing or wrong, and forge.ErrIgnored for an event or action kōjō does not handle, a comment on an issue that does not mention the bot and anything the bot did itself. A failed pipeline, a merged or closed merge request and a push are reported whoever caused them, except a push by the bot to one of its own kojo/* branches.

The confidential variants of the issue and note hooks are handled like the public ones: GitLab only sends them to a webhook that asked for them.

func (*Forge) Permission

func (f *Forge) Permission(ctx context.Context, repo forge.Repo, user string) (forge.Permission, error)

Permission maps a member's access level onto the forge scale: Guest is read, Planner and Reporter are triage, Developer is write, Maintainer is maintain and Owner is admin. Inherited (group) membership counts. Someone who is not a member has PermissionRead on a public project and PermissionNone elsewhere.

func (*Forge) UpdatePR

func (f *Forge) UpdatePR(ctx context.Context, repo forge.Repo, number int, title, body string) error

UpdatePR changes a merge request's title and description. An empty title or body is left out, so that one stays as it is; with both empty nothing is sent. GitLab reads a draft from the title, so a new title keeps the merge request's draft state: it gets the "Draft: " prefix on a draft and loses any draft prefix on a merge request that is ready. That takes a read first; a new description alone is one request.

type Option

type Option func(*Forge)

Option configures New.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock. The default is time.Now.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client. The default has a 30 second timeout.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger. The default is slog.Default.

Jump to

Keyboard shortcuts

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