gitlab

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 15 Imported by: 0

README

forge-gitlab

GitLab release provider for forge

Go Reference Pipeline Coverage phpboyscout Go toolkit

Part of the phpboyscout Go toolkit. Full documentation lives on the core module's site: forge.go.phpboyscout.uk


Implements the forge.Provider contract for GitLab releases, using gitlab-org/api/client-go.

It is its own module so a tool that only supports GitLab never compiles GitHub's client, Gitea's, or Bitbucket's. A depfootprint guard asserts that.

Use it

Blank-import to register, then resolve through the registry — your code never names a GitLab type:

import (
    "gitlab.com/phpboyscout/go/forge"

    _ "gitlab.com/phpboyscout/go/forge-gitlab"
)

factory, err := forge.Lookup("gitlab")
provider, err := factory(source, cfg)
go get gitlab.com/phpboyscout/go/forge-gitlab

Configuration

Key Purpose
gitlab.auth.value The token, read through forge.ConfigCredential
gitlab.auth.client_id OAuth app client ID for device-flow login (else GITLAB_CLIENT_ID)
gitlab.url.api Override the API endpoint
GITLAB_TOKEN Well-known fallback

[!IMPORTANT] gitlab.auth.env and gitlab.auth.keychain are no longer read. Ordering now belongs to your config stack rather than to a ladder inside this module: an environment reference becomes an env layer (or forge.EnvCredential), and a keychain reference becomes a config-keychain layer. Configuration still carrying either key reports forge.ErrStaleAuthKeys, but only when nothing else supplied a credential — so a stale key beside a working variable stays quiet. See the migration table in forge's README.

ReleaseSource.Host selects a self-hosted instance; empty means gitlab.com. A token is optional — public projects resolve unauthenticated.

Platform differences

GitLab's release model differs from GitHub's in ways the shared contract cannot hide:

Contract On GitLab
GetDraft() Always false — GitLab has no draft-release concept, so there is nothing to report. Code branching on it will treat every GitLab release as published.
DownloadReleaseAsset redirect Always empty. Only GitHub redirects asset requests to a CDN.
GetLatestRelease Fetches the first page of releases sorted newest-first, rather than a dedicated latest endpoint.

Security

The PRIVATE-TOKEN credential is attached only to asset downloads on the configured instance, via forge.HostTrusted. Asset URLs come from release metadata that a release author controls, so an unpinned credential is an exfiltration primitive. Host, port and scheme must all match, which also refuses a downgrade to plaintext HTTP.

Documentation

Guides, the provider contract, and how to author your own: forge.go.phpboyscout.uk.

API reference: pkg.go.dev.

License

See LICENSE.

Documentation

Overview

Package gitlab implements the VCS release provider for GitLab repositories, supporting both public and token-authenticated access; the owner may be a slash-separated group path passed through to the GitLab API. Provider construction uses package-owned Settings; GTB config integration lives in SettingsFromConfig.

Index

Constants

View Source
const DefaultClientIDEnv = "GITLAB_CLIENT_ID"

DefaultClientIDEnv is the well-known environment variable consulted for the OAuth application client ID the interactive device-flow login ([Authenticator]) requires, when Settings.ClientID is empty.

View Source
const DefaultTokenEnv = "GITLAB_TOKEN"

DefaultTokenEnv is the well-known environment variable the default credential composition consults last. See SettingsFromConfig.

This is the one rung of the old resolution chain that layer composition cannot express — an unprefixed, forge-chosen variable name — and it is what CI injects, so it is preserved as a composed default rather than dropped.

Variables

This section is empty.

Functions

func NewReleaseProvider

func NewReleaseProvider(ctx context.Context, settings Settings) (forge.Provider, error)

NewReleaseProvider builds a GitLab release provider from explicit typed settings. A public repository needs no credential; Host selects the instance, empty means gitlab.com, and APIURL can override the derived API endpoint.

The credential comes from Settings.Credential, or — when that is nil — from DefaultTokenEnv. The context bounds its resolution: a source the caller supplied may reach a keychain or a remote secret store.

Types

type GitLabReleaseProvider

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

GitLabReleaseProvider implements forge.Provider.

func (*GitLabReleaseProvider) CreateIssue added in v0.4.0

func (p *GitLabReleaseProvider) CreateIssue(
	ctx context.Context, owner, repo string, draft forge.IssueDraft,
) (forge.Issue, error)

CreateIssue files an issue.

Sanitisation

Title and Body go through forge.Sanitise unless the draft opts out, and the idempotency trailer is appended AFTERWARDS. The order is contractual: an opaque key of 41 or more characters trips redact's long-token pattern, so sanitising last would rewrite the key and the pre-create search would then look for one the issue does not carry — breaking at-most-once silently.

At-most-once

GitLab offers no idempotency primitive. Its create endpoint accepts an `iid`, which would serve, but it is documented as requiring administrator or project owner rights — incompatible with the least-privilege token this capability is meant to be usable with. So the key is written into the body as a searchable marker and looked for first.

func (*GitLabReleaseProvider) DownloadReleaseAsset

func (p *GitLabReleaseProvider) DownloadReleaseAsset(ctx context.Context, owner, repo string, asset forge.ReleaseAsset) (io.ReadCloser, string, error)

DownloadReleaseAsset is more complex for GitLab.

func (*GitLabReleaseProvider) GetFile added in v0.3.0

func (p *GitLabReleaseProvider) GetFile(
	ctx context.Context, owner, repo, path, ref string, maxBytes int64,
) ([]byte, error)

GetFile reads one file at a ref without cloning.

The bound is enforced by asking for the size FIRST. client-go's GetRawFile copies the whole response body into a buffer before returning it, so checking len() afterwards would be a measurement rather than a limit. GetRawFileMetaData issues a HEAD and reports Size, which lets an oversized file be refused before a byte of it is fetched.

The length is re-checked after the read, catching a file that grew between the two calls. What remains uncovered is a server that LIES about the size — which is acceptable here in a way it would not be for a release asset, because this URL is the pinned API host the provider authenticated against rather than a URL a release author chose.

func (*GitLabReleaseProvider) GetIssue added in v0.4.0

func (p *GitLabReleaseProvider) GetIssue(
	ctx context.Context, owner, repo string, number int,
) (forge.Issue, error)

GetIssue returns one issue by its per-project number (GitLab's iid).

func (*GitLabReleaseProvider) GetLatestRelease

func (p *GitLabReleaseProvider) GetLatestRelease(ctx context.Context, owner, repo string) (forge.Release, error)

func (*GitLabReleaseProvider) GetReleaseByTag

func (p *GitLabReleaseProvider) GetReleaseByTag(ctx context.Context, owner, repo, tag string) (forge.Release, error)

func (*GitLabReleaseProvider) GetSite added in v0.3.0

func (p *GitLabReleaseProvider) GetSite(
	ctx context.Context, owner, repo string,
) (forge.Site, error)

GetSite reports a project's GitLab Pages site.

Reading Pages settings requires the Maintainer or Owner role, so a 403 is routine rather than exceptional here — and it is deliberately NOT folded into ErrNotFound. Telling a caller "this project has no site" when the truth is "your token could not ask" is how a repository silently drops out of a corpus.

func (*GitLabReleaseProvider) ListComments added in v0.4.0

func (p *GitLabReleaseProvider) ListComments(
	ctx context.Context,
	owner, repo string,
	number int,
	q forge.CommentQuery,
	yield func(forge.Comment) bool,
) error

ListComments yields an issue's comments.

Emulating Since

GitLab's notes endpoint has no created_after parameter — ListIssueNotesOptions carries only order_by and sort. So Since is honoured by asking for newest-first and stopping as soon as a note older than Since appears: the caller still pays only for what it asked for, rather than for the whole history filtered afterwards.

The consequence is that this provider yields NEWEST-FIRST while a forge with a server-side filter yields oldest-first. The contract promises no order for exactly this reason, because making them agree would mean buffering everything — which is what Since exists to avoid.

func (*GitLabReleaseProvider) ListReleases

func (p *GitLabReleaseProvider) ListReleases(ctx context.Context, owner, repo string, limit int) ([]forge.Release, error)

ListReleases returns up to limit releases, paginating across GitLab's pages (signalled by the X-Next-Page header) until the limit is met or history is exhausted. A limit <= 0 means "no explicit bound" — the natural first page. See forge.Provider.

func (*GitLabReleaseProvider) ListRepositories added in v0.3.0

func (p *GitLabReleaseProvider) ListRepositories(
	ctx context.Context,
	namespace string,
	opts forge.RepositoryListOptions,
	yield func(forge.Repository) bool,
) error

ListRepositories enumerates the projects in a GitLab group.

WithShared is pinned to false, and that is the load-bearing line in this file. GitLab documents with_shared as defaulting to TRUE, so the natural call returns projects merely SHARED into the group alongside those owned by it — carrying their own, foreign namespace paths. A caller whose question is "is this in my group?" would get a different question answered, in the permissive direction, and the forge conformance harness checks the containment property precisely because this default is invisible in any fixture without a shared project.

func (*GitLabReleaseProvider) Login added in v0.2.0

func (p *GitLabReleaseProvider) Login(ctx context.Context, prompter forge.Prompter) (string, error)

Login implements the optional forge.Authenticator capability via GitLab's OAuth device flow (RFC 8628): it requests a device code, surfaces it through the forge.Prompter for the user to enter in a browser, then polls for the access token. Presentation — including whether to open a browser at the verification URL — belongs to the Prompter; this adapter speaks only the protocol.

It returns an error wrapping forge.ErrNotSupported when no OAuth client ID is configured (Settings.ClientID or DefaultClientIDEnv), so the caller falls back to manual token entry.

func (*GitLabReleaseProvider) SearchIssues added in v0.4.0

func (p *GitLabReleaseProvider) SearchIssues(
	ctx context.Context,
	owner, repo string,
	q forge.IssueQuery,
	yield func(forge.Issue) bool,
) error

SearchIssues yields issues matching q.

GitLab searches title and description server-side via `search` + `in`, so the text filter costs nothing extra here — unlike a forge whose search is weaker and has to filter client-side.

func (*GitLabReleaseProvider) UploadKey added in v0.2.0

func (p *GitLabReleaseProvider) UploadKey(ctx context.Context, name string, publicKey []byte) error

UploadKey implements the optional forge.KeyManager capability: it registers an OpenSSH-format public key on the authenticated account via GitLab's user-keys API. The provider's resolved token (see [Settings.Auth]) authorises the call; name is the label shown in the account's key list.

It returns an error wrapping forge.ErrNotSupported when no token is configured, since GitLab's key API requires authentication — the caller then instructs the user to add the key manually.

type Settings

type Settings struct {
	ReleaseSource forge.ReleaseSourceConfig
	APIURL        string `json:"api_url" yaml:"api_url"`

	// Credential yields the token this provider authenticates with.
	//
	// Nil is not an error: [NewReleaseProvider] falls back to
	// [DefaultTokenEnv], so construction from configuration alone keeps
	// working and a public repository needs nothing at all. Set it to take
	// over entirely — including to hand in a token directly:
	//
	//	Credential: forge.StaticCredential(token)
	Credential forge.CredentialSource

	// Logger receives this provider's diagnostics. Nil discards them, and is
	// never [slog.Default]. See [forge.WithLogger] for the registry route.
	Logger *slog.Logger

	// ClientID is the OAuth app client ID used by the interactive device-flow
	// login ([Authenticator]). Empty falls back to [DefaultClientIDEnv]; when
	// neither is set the provider reports the capability as unsupported.
	ClientID string `json:"client_id" yaml:"client_id"`

	// Scopes overrides the OAuth scopes requested at login. Empty uses a
	// sensible default (GitLab `api`).
	Scopes []string `json:"scopes" yaml:"scopes"`
}

Settings contains the typed configuration needed to construct a GitLab release provider without binding the provider to GTB config.

Fields are populated by the config adapter via the narrow forge.Config seam, not decoded with mapstructure. The json/yaml tags are for documentation and serialisation only.

func SettingsFromConfig

func SettingsFromConfig(src forge.ReleaseSourceConfig, cfg forge.Config) Settings

SettingsFromConfig adapts the gitlab config subtree into typed provider settings. It preserves the existing `url.api` and `auth.client_id` keys.

The credential composition IS the precedence, and it is written here rather than hidden in a resolution chain: the configured key, then the well-known variable. A caller wanting a different order — or a different key entirely — builds their own forge.CredentialSource and assigns Settings.Credential.

A nil cfg is not special-cased: forge.ConfigCredential treats a nil config as contributing nothing, so a config-free public lookup still reaches the environment fallback.

Jump to

Keyboard shortcuts

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