Skip to content

livery.forge._gitlab

livery.forge._gitlab

The GitLab backend: livery.forge.Forge over REST v4.

The odd one out, and the reason several protocol rules exist: merge requests and issues are addressed by their per-project iid (which is the number a person sees, so the protocol's number is the iid and the global id never crosses the boundary), pipelines are the canonical CI answer rather than commit statuses, and the owner may be a group or subgroup path. The full endpoint mapping is the package's docs/gitlab.md.

Construction and the token rule: livery.forge.GitlabForge.connect resolves the server once, an explicit url beating the configured GITLAB_URL, and reads GITLAB_TOKEN, then the token glab holds for the host, unless a token is passed. The token belongs to the configured host and no other.

Capabilities: auto_merge (merge when pipeline succeeds), ci_secrets (masked variables), and schedule_events (reconstructed from system notes and state events) are supported; min_approvals is probed per instance, because GitLab licence-gates approval rules. force_cancel and required_contexts are declined by name: pipelines have plain cancel only, and no tier's protection names required check contexts.

Classes:

Name Description
GitlabForge

One GitLab server, spoken to through livery.forge.Forge's verbs.

Functions:

Name Description
gitlab_configured_host

The host GITLAB_TOKEN belongs to, from GITLAB_URL, lowercased.

gitlab_is_configured_host

Whether host is the server this environment holds a token for.

GitlabForge

GitlabForge(api_base: str, *, token: str, opener: Opener | None = None)

One GitLab server, spoken to through livery.forge.Forge's verbs.

Build with livery.forge.GitlabForge.connect; the constructor takes the resolved values and applies no environment fallbacks.

Parameters:

Name Type Description Default
api_base str

The API root, <server>/api/v4.

required
token str

The token sent on every request; empty reads anonymously.

required
opener Opener | None

The network seam; the redirect-refusing default when omitted.

None

Bind the client to api_base with token.

The timeout is generous: a single-node GitLab under load legitimately takes tens of seconds for its heaviest writes (project creation), and "slow" must stay distinguishable from "unreachable".

Methods:

Name Description
connect

The server, resolved once, never inferred from ambient state.

whoami

The authenticated user's login name (GET /user).

server_version

The server's version string (GET /version).

registry_url

Decline every kind, each naming its reason.

supports

Honest per instance: approvals depend on the licence.

repository

The view onto one repository. Cheap, no network.

members

The group's member usernames; a user namespace is its login.

teams

GitLab's teams are its subgroups: their full paths.

codeowners

GitLab's dialect: .gitlab/CODEOWNERS with sections.

user_url

The address of login's profile; nothing on the wire.

create_repo

Create the project under a group path or the token's own user.

get_repo

The project's settings, or None when it does not exist.

delete_repo

Delete the project; one already gone is success.

Attributes:

Name Type Description
token str

The credential this connection authenticates with; empty when anonymous.

Source code in packages/forge/src/livery/forge/_gitlab.py
def __init__(
    self, api_base: str, *, token: str, opener: Opener | None = None
) -> None:
    """Bind the client to *api_base* with *token*.

    The timeout is generous: a single-node GitLab under load
    legitimately takes tens of seconds for its heaviest writes
    (project creation), and "slow" must stay distinguishable from
    "unreachable".
    """
    headers = {"PRIVATE-TOKEN": token} if token else {}
    self._client = JsonClient(api_base, headers=headers, opener=opener, timeout=120)
    self._token = token
    # GitLab serves the API under /api/v4 on the web host.
    self._web_root = api_base.rstrip("/").removesuffix("/api/v4")
    #: The licence probe's cached answer; None until first asked.
    self._min_approvals: bool | None = None

token property

token: str

The credential this connection authenticates with; empty when anonymous.

connect classmethod

connect(*, url: str = '', token: str | None = None, opener: Opener | None = None) -> GitlabForge

The server, resolved once, never inferred from ambient state.

An explicit url wins; GITLAB_URL is the configured default. token resolves as GITLAB_TOKEN first, then the token glab holds for the server's host (glab config get token --host); nothing found raises rather than silently reading anonymously. Pass token="" to read anonymously on purpose.

Source code in packages/forge/src/livery/forge/_gitlab.py
@classmethod
def connect(
    cls,
    *,
    url: str = "",
    token: str | None = None,
    opener: Opener | None = None,
) -> GitlabForge:
    """The server, resolved once, never inferred from ambient state.

    An explicit *url* wins; ``GITLAB_URL`` is the configured
    default. *token* resolves as ``GITLAB_TOKEN`` first, then the
    token ``glab`` holds for the server's host (``glab config get
    token --host``); nothing found raises rather than silently
    reading anonymously. Pass ``token=""`` to read anonymously on
    purpose.
    """
    web = url or os.environ.get("GITLAB_URL", "")
    if not web:
        raise ForgeError(
            "no GitLab server to connect to: pass url= or set GITLAB_URL"
        )
    resolved = _resolve_token(web) if token is None else token
    if token is None and not resolved:
        raise ForgeError(
            "no GitLab credential: set GITLAB_TOKEN or sign in with"
            " `glab auth login`"
        )
    return cls(f"{web.rstrip('/')}/api/v4", token=resolved, opener=opener)

whoami

whoami() -> str

The authenticated user's login name (GET /user).

Source code in packages/forge/src/livery/forge/_gitlab.py
def whoami(self) -> str:
    """The authenticated user's login name (``GET /user``)."""
    data = self._client.request("/user")
    return str(data.get("username", ""))

server_version

server_version() -> str

The server's version string (GET /version).

Source code in packages/forge/src/livery/forge/_gitlab.py
def server_version(self) -> str:
    """The server's version string (``GET /version``)."""
    data = self._client.request("/version")
    return str(data.get("version", ""))

registry_url

registry_url(kind: RegistryKind, owner: str) -> str

Decline every kind, each naming its reason.

GitLab's python and conan registries are addressed by project id, not by owner and name, and its container registry lives on a per-install host the API base does not reveal; the contract's declaration is the path on GitLab until a project-resolved surface earns its keep.

Source code in packages/forge/src/livery/forge/_gitlab.py
def registry_url(self, kind: RegistryKind, owner: str) -> str:
    """Decline every kind, each naming its reason.

    GitLab's python and conan registries are addressed by project
    id, not by owner and name, and its container registry lives
    on a per-install host the API base does not reveal; the
    contract's declaration is the path on GitLab until a
    project-resolved surface earns its keep.
    """
    raise Unsupported(
        f"gitlab's {kind} registry is not derivable from the API base"
        " (project-id or per-install-host addressed); declare it in"
        " the contract"
    )

supports

supports(capability: Capability) -> bool

Honest per instance: approvals depend on the licence.

auto_merge, ci_secrets, and schedule_events are every tier's. min_approvals is probed once per connection and cached: GitLab licence-gates approval rules, so the first ask reads a visible project's approval-rules endpoint, which an unlicensed server answers with 404. force_cancel and required_contexts are declined at every tier: no tier cancels a run harder than plain cancel, and no tier's protection names check contexts.

Source code in packages/forge/src/livery/forge/_gitlab.py
def supports(self, capability: Capability) -> bool:
    """Honest per instance: approvals depend on the licence.

    ``auto_merge``, ``ci_secrets``, and ``schedule_events`` are
    every tier's. ``min_approvals`` is probed once per connection
    and cached: GitLab licence-gates approval rules, so the first
    ask reads a visible project's approval-rules endpoint, which
    an unlicensed server answers with 404. ``force_cancel`` and
    ``required_contexts`` are declined at every tier: no tier
    cancels a run harder than plain cancel, and no tier's
    protection names check contexts.
    """
    if capability == "min_approvals":
        return self._probe_min_approvals()
    return capability in (
        "auto_merge",
        "ci_secrets",
        "schedule_events",
        "pipeline_schedules",
    )

repository

repository(owner: str, name: str) -> Repository

The view onto one repository. Cheap, no network.

Source code in packages/forge/src/livery/forge/_gitlab.py
def repository(self, owner: str, name: str) -> Repository:
    """The view onto one repository. Cheap, no network."""
    return _GitlabRepository(self, self._client, owner, name)

members

members(owner: str) -> tuple[str, ...]

The group's member usernames; a user namespace is its login.

Source code in packages/forge/src/livery/forge/_gitlab.py
def members(self, owner: str) -> tuple[str, ...]:
    """The group's member usernames; a user namespace is its login."""
    try:
        rows = self._client.paginate(
            lambda page: self._client.request(
                f"/groups/{quote(owner, safe='')}/members?per_page=100&page={page}"
            ),
            subject=f"/groups/{owner}/members",
        )
    except ForgeError as error:
        if error.status == 404:
            return (owner,)
        raise
    return tuple(sorted(str(row.get("username", "")) for row in rows))

teams

teams(owner: str) -> tuple[str, ...]

GitLab's teams are its subgroups: their full paths.

A personal namespace has no subgroups and answers empty.

Source code in packages/forge/src/livery/forge/_gitlab.py
def teams(self, owner: str) -> tuple[str, ...]:
    """GitLab's teams are its subgroups: their full paths.

    A personal namespace has no subgroups and answers empty.
    """
    try:
        rows = self._client.paginate(
            lambda page: self._client.request(
                f"/groups/{quote(owner, safe='')}/subgroups?per_page=100"
                f"&page={page}"
            ),
            subject=f"/groups/{owner}/subgroups",
        )
    except ForgeError as error:
        if error.status == 404:
            return ()
        raise
    return tuple(sorted(str(row.get("full_path", "")) for row in rows))

codeowners

codeowners(entries: tuple[CodeownersEntry, ...]) -> Codeowners

GitLab's dialect: .gitlab/CODEOWNERS with sections.

A section headed [name][n] carries the per-path approval count in the file itself, the one dialect that can; nothing is approximated. Every entry after a heading belongs to that section until the next one, so the plain entries render first and each counted entry gets its own section after them: order in the input can never leak a count onto a neighbour. Enforcing the counts still needs a paid tier, which the min_approvals capability declines.

Source code in packages/forge/src/livery/forge/_gitlab.py
def codeowners(self, entries: tuple[CodeownersEntry, ...]) -> Codeowners:
    """GitLab's dialect: ``.gitlab/CODEOWNERS`` with sections.

    A section headed ``[name][n]`` carries the per-path approval
    count in the file itself, the one dialect that can; nothing
    is approximated. Every entry after a heading belongs to that
    section until the next one, so the plain entries render
    first and each counted entry gets its own section after
    them: order in the input can never leak a count onto a
    neighbour. Enforcing the counts still needs a paid tier,
    which the ``min_approvals`` capability declines.
    """
    plain = [entry for entry in entries if entry.min_approvals <= 1]
    counted = [entry for entry in entries if entry.min_approvals > 1]
    lines = []
    for entry in plain:
        owners = " ".join(f"@{name}" for name in entry.owners)
        lines.append(f"{entry.path} {owners}")
    for index, entry in enumerate(counted, 1):
        owners = " ".join(f"@{name}" for name in entry.owners)
        lines.append(f"[owners-{index}][{entry.min_approvals}]")
        lines.append(f"{entry.path} {owners}")
    return Codeowners(
        path=".gitlab/CODEOWNERS",
        content="\n".join(lines) + "\n" if lines else "",
        notes=(),
    )

user_url

user_url(login: str) -> str

The address of login's profile; nothing on the wire.

Source code in packages/forge/src/livery/forge/_gitlab.py
def user_url(self, login: str) -> str:
    """The address of *login*'s profile; nothing on the wire."""
    return f"{self._web_root}/{login}"

create_repo

create_repo(owner: str, name: str, *, private: bool = True, description: str = '') -> Repository

Create the project under a group path or the token's own user.

initialize_with_readme gives it the default branch the protocol requires. A group or subgroup owner resolves to its namespace id first. GitLab protects a new project's default branch on creation (the instance or group default, maintainers push and no force push); that rule is removed, so the creator can push its history over the init commit, as on every other forge, and protection starts when the caller configures it.

Source code in packages/forge/src/livery/forge/_gitlab.py
def create_repo(
    self,
    owner: str,
    name: str,
    *,
    private: bool = True,
    description: str = "",
) -> Repository:
    """Create the project under a group path or the token's own user.

    ``initialize_with_readme`` gives it the default branch the
    protocol requires. A group or subgroup owner resolves to its
    namespace id first. GitLab protects a new project's default
    branch on creation (the instance or group default, maintainers
    push and no force push); that rule is removed, so the creator
    can push its history over the init commit, as on every other
    forge, and protection starts when the caller configures it.
    """
    body: dict[str, Any] = {
        "name": name,
        "path": name,
        "visibility": "private" if private else "public",
        "description": description,
        "initialize_with_readme": True,
    }
    me = self.whoami()
    if owner != me:
        body["namespace_id"] = self._namespace_id(owner)
    created = self._client.request("/projects", method="POST", data=body)
    branch = str((created or {}).get("default_branch") or "main")
    if self._default_branch_protected(owner, me):
        self._unprotect_new_default(owner, name, branch)
    return self.repository(owner, name)

get_repo

get_repo(owner: str, name: str) -> RepoInfo | None

The project's settings, or None when it does not exist.

A deleting project is renamed to a corpse path and the old path answers as moved for a moment; a redirect here therefore means "no project at this path" and reads as None, never followed.

Source code in packages/forge/src/livery/forge/_gitlab.py
def get_repo(self, owner: str, name: str) -> RepoInfo | None:
    """The project's settings, or None when it does not exist.

    A deleting project is renamed to a corpse path and the old
    path answers as moved for a moment; a redirect here therefore
    means "no project at this path" and reads as None, never
    followed.
    """
    try:
        data = self._client.request(
            f"/projects/{_path(owner, name)}", none_on=(404,)
        )
    except ForgeError as exc:
        if exc.status is not None and 300 <= exc.status < 400:
            return None
        raise
    if data is None:
        return None
    if str(data.get("path_with_namespace")) != f"{owner}/{name}":
        # A redirect route answered for the old path: the project
        # that came back is a renamed corpse, not the one asked
        # for. The subject of the answer is verified, never
        # assumed.
        return None
    return RepoInfo(
        owner=owner,
        name=name,
        default_branch=str(data.get("default_branch") or ""),
        private=str(data.get("visibility")) == "private",
    )

delete_repo

delete_repo(owner: str, name: str) -> None

Delete the project; one already gone is success.

GitLab deletes asynchronously: the project is renamed to a corpse path, the old path answers 405 ("Non GET methods are not allowed for moved projects") until the rename lands, and the path can stay reserved for a short while after. The 405 on a moved project IS the already-deleting case, so it reads as success; a creator reusing a just-deleted path retries on the refusal.

Source code in packages/forge/src/livery/forge/_gitlab.py
def delete_repo(self, owner: str, name: str) -> None:
    """Delete the project; one already gone is success.

    GitLab deletes asynchronously: the project is renamed to a
    corpse path, the old path answers 405 ("Non GET methods are
    not allowed for moved projects") until the rename lands, and
    the path can stay reserved for a short while after. The 405 on
    a moved project IS the already-deleting case, so it reads as
    success; a creator reusing a just-deleted path retries on the
    refusal.
    """
    try:
        self._client.request(
            f"/projects/{_path(owner, name)}", method="DELETE", none_on=(404,)
        )
    except ForgeError as exc:
        already_deleting = exc.status == 405 and "moved" in exc.detail
        already_marked = exc.status == 400 and "marked for deletion" in exc.detail
        if already_deleting or already_marked:
            return
        raise

gitlab_configured_host

gitlab_configured_host() -> str

The host GITLAB_TOKEN belongs to, from GITLAB_URL, lowercased.

Source code in packages/forge/src/livery/forge/_gitlab.py
def gitlab_configured_host() -> str:
    """The host ``GITLAB_TOKEN`` belongs to, from ``GITLAB_URL``, lowercased."""
    url = os.environ.get("GITLAB_URL", "")
    return url.split("://", 1)[-1].strip("/").lower()

gitlab_is_configured_host

gitlab_is_configured_host(host: str) -> bool

Whether host is the server this environment holds a token for.

Source code in packages/forge/src/livery/forge/_gitlab.py
def gitlab_is_configured_host(host: str) -> bool:
    """Whether *host* is the server this environment holds a token for."""
    return bool(host) and host.lower() == gitlab_configured_host()