Skip to content

livery.forge

livery.forge

One interface to GitHub, Gitea, and GitLab.

The protocols are the whole surface: livery.forge.Forge for one server, livery.forge.Repository for one repository on it, and livery.forge.Registry for one package index. Every verb exists because a development workflow uses it; a verb no workflow uses is removed. The protocols are frozen: every backend, the verified fake included, passes the one conformance suite in livery.forge.testing, and a change to a verb now is a compatibility event, not a draft edit.

Runtime dependencies are the standard library and nothing else; a workspace test enforces it.

Modules:

Name Description
testing

What every consumer tests against: the verified fake and the fixtures.

Classes:

Name Description
ForgeError

Raised when a forge operation fails.

RateLimited

Raised when the forge refuses a request because its API budget is spent.

Unsupported

Raised when a forge cannot honour a protocol operation.

GiteaForge

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

GithubForge

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

GitlabForge

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

MergeState

One classified merge hold.

Checks

One repository's CI: the combined verdict, runs, jobs, and logs.

Forge

One forge server: identity, capabilities, and its repositories.

Issues

One repository's issues: text in both directions.

PullRequests

One repository's pull requests: open, find, merge, arm, comment.

Registry

One package index, apart from the forge.

Releases

One repository's releases, addressed by tag.

Repository

One repository on one forge.

Schedules

One repository's pipeline schedules, addressed by description.

SimpleRegistry

A simple-API index, addressed by its simple root.

Asset

One file attached to a release.

Codeowners

A rendered codeowners file: where it lives and what it says.

CodeownersEntry

One neutral ownership declaration a codeowners file expresses.

CombinedStatus

The one CI answer for a commit, whatever the forge calls it underneath.

Comment

One comment on an issue's thread.

Issue

One issue, body included.

Job

One job of a run.

Label

One issue label, spoken by name everywhere.

Protection

The branch protection a forge reports for one branch.

PullRequest

One pull request, as the forge reports it.

RateBudget

The API budget a forge reports on its responses.

Release

One release, addressed by its tag.

RepoConfig

The desired repository settings livery.forge.Repository.configure asserts.

RepoInfo

What livery.forge.Forge.get_repo reports about an existing repository.

Review

One submitted pull request review.

Run

One CI run: a workflow run on GitHub or Gitea, a pipeline on GitLab.

Schedule

One pipeline schedule: the forge's clock for a workflow the file cannot time.

ScheduleEvent

One event in a pull request's merge-scheduling history.

Step

One step of a job, as the forge times it.

Functions:

Name Description
gitea_configured_host

The host GITEA_TOKEN belongs to, from GITEA_URL, lowercased.

gitea_is_configured_host

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

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.

classify_gitea_merge_refusal

Gitea's 405 prose as a merge state; the inputs disambiguate.

classify_github_mergeable_state

GitHub's mergeable_state value as a merge state.

classify_gitlab_detailed_status

GitLab's detailed_merge_status value as a merge state.

classify_merge_refusal

Classify a merge-endpoint refusal by the forge kind.

merge_state

The vocabulary member state, carrying native verbatim.

Attributes:

Name Type Description
MergeCategory TypeAlias

What a caller does with a state: follow, act, stop, or walk past.

Capability TypeAlias

What livery.forge.Forge.supports answers for, by name.

CheckState TypeAlias

The combined verdict for one commit.

Conclusion TypeAlias

How a completed run or job ended. Empty until the run completes.

RegistryKind TypeAlias

The artifact registries the ecosystem speaks, by protocol.

ReviewState TypeAlias

A submitted review's verdict, normalised across the forges.

RunStatus TypeAlias

Where a run is in its life. Only completed runs carry a conclusion.

ScheduleEventKind TypeAlias

What happened to a pull request's merge schedule, normalised.

StateFilter TypeAlias

Which pull requests or issues a listing includes.

__version__

TYPE_CHECKING module-attribute

TYPE_CHECKING = False

MergeCategory module-attribute

MergeCategory: TypeAlias = Literal['in-progress', 'recoverable', 'terminal', 'success']

What a caller does with a state: follow, act, stop, or walk past.

Capability module-attribute

Capability: TypeAlias = Literal['auto_merge', 'force_cancel', 'required_contexts', 'ci_secrets', 'schedule_events', 'min_approvals', 'pages_config', 'pipeline_schedules']

What livery.forge.Forge.supports answers for, by name.

  • auto_merge: the forge can schedule a merge that fires when the checks go green (livery.forge.PullRequests.arm).
  • force_cancel: the forge can cancel a run whose runner stopped answering (force=True on livery.forge.Checks.cancel_run).
  • required_contexts: branch protection can name the check contexts that must pass before a merge.
  • ci_secrets: livery.forge.RepoConfig.secrets can be stored through the backend. GitHub's backend declines: its secrets API demands sealed-box encryption the standard library cannot provide, and no workflow stores a secret there, because trusted publishing replaces tokens on GitHub.
  • min_approvals: protection can require a number of approving reviews (and a codeowner's), applied by livery.forge.Repository.configure. GitLab ties required approval rules to paid tiers, so its backend declines; the decline is what keeps a one-assignee, one-approver policy honest there.
  • schedule_events: the merge-scheduling history of a pull request can be read back (livery.forge.PullRequests.schedule_events). GitLab's backend declines: its system notes carry no reliable scheduling record.
  • pages_config: the forge's static-site hosting can be enabled through the API (livery.forge.Repository.ensure_pages). Only GitHub has one to configure: Gitea ships no Pages, and GitLab Pages exists implicitly through pipeline artifacts.
  • pipeline_schedules: the forge keeps the clock outside the workflow file, as a project setting the API creates (livery.forge.Repository.schedule). GitLab's pipeline schedules are that; GitHub and Gitea decline, since their clock is the schedule trigger in the file.

CheckState module-attribute

CheckState: TypeAlias = Literal['none', 'pending', 'success', 'failure']

The combined verdict for one commit.

none means nothing has reported for the commit at all, which must stay distinguishable from pending: a commit no run ever started on looks identical to a live run otherwise, and a poll loop would wait on it forever.

Conclusion module-attribute

Conclusion: TypeAlias = Literal['', 'success', 'failure', 'cancelled', 'skipped']

How a completed run or job ended. Empty until the run completes.

RegistryKind module-attribute

RegistryKind: TypeAlias = Literal['python', 'conan', 'container']

The artifact registries the ecosystem speaks, by protocol.

python is the simple index and its upload endpoint; conan is a conan 2 remote; container is an OCI distribution registry. The handles that speak these protocols are host-generic: any server or folder speaking the protocol works. A forge answers which of them it hosts through livery.forge.Forge.registry_url.

ReviewState module-attribute

ReviewState: TypeAlias = Literal['approved', 'changes_requested', 'commented']

A submitted review's verdict, normalised across the forges.

Only approved and changes_requested decide anything; a commented review supersedes nothing. Unsubmitted drafts are never reported.

RunStatus module-attribute

RunStatus: TypeAlias = Literal['queued', 'running', 'completed']

Where a run is in its life. Only completed runs carry a conclusion.

ScheduleEventKind module-attribute

ScheduleEventKind: TypeAlias = Literal['scheduled', 'unscheduled', 'merged', 'closed', 'reopened', 'pushed']

What happened to a pull request's merge schedule, normalised.

StateFilter module-attribute

StateFilter: TypeAlias = Literal['open', 'closed', 'all']

Which pull requests or issues a listing includes.

__version__ module-attribute

__version__ = '0.8.0'

__all__ module-attribute

__all__ = ['Asset', 'Capability', 'CheckState', 'Checks', 'Codeowners', 'CodeownersEntry', 'CombinedStatus', 'Comment', 'Conclusion', 'Forge', 'ForgeError', 'GiteaForge', 'GithubForge', 'GitlabForge', 'Issue', 'Issues', 'Job', 'Label', 'MergeCategory', 'MergeState', 'Protection', 'PullRequest', 'PullRequests', 'RateBudget', 'RateLimited', 'Registry', 'RegistryKind', 'Release', 'Releases', 'RepoConfig', 'RepoInfo', 'Repository', 'Review', 'ReviewState', 'Run', 'RunStatus', 'Schedule', 'ScheduleEvent', 'ScheduleEventKind', 'Schedules', 'SimpleRegistry', 'StateFilter', 'Step', 'Unsupported', '__version__', 'classify_gitea_merge_refusal', 'classify_github_mergeable_state', 'classify_gitlab_detailed_status', 'classify_merge_refusal', 'gitea_configured_host', 'gitea_is_configured_host', 'gitlab_configured_host', 'gitlab_is_configured_host', 'merge_state', 'testing']

ForgeError

ForgeError(message: str, *, status: int | None = None, method: str = '', endpoint: str = '', detail: str = '')

Bases: Exception

Raised when a forge operation fails.

The message says what failed, in the words of the server that refused it. A caller that branches on the failure reads the attributes, never the message text.

Attributes:

Name Type Description
status

The HTTP status code, or None when the server never answered. An unreachable server is a different decision for the caller than any code it could have returned.

method

The HTTP method of the failing request, when known.

endpoint

The endpoint of the failing request, when known.

detail

The response body, verbatim.

Carry message plus the request facts a caller branches on.

Source code in packages/forge/src/livery/forge/_errors.py
def __init__(
    self,
    message: str,
    *,
    status: int | None = None,
    method: str = "",
    endpoint: str = "",
    detail: str = "",
) -> None:
    """Carry *message* plus the request facts a caller branches on."""
    super().__init__(message)
    self.status = status
    self.method = method
    self.endpoint = endpoint
    self.detail = detail

status instance-attribute

status = status

method instance-attribute

method = method

endpoint instance-attribute

endpoint = endpoint

detail instance-attribute

detail = detail

RateLimited

RateLimited(message: str, *, reset_at: float | None, status: int | None = None, method: str = '', endpoint: str = '', detail: str = '')

Bases: ForgeError

Raised when the forge refuses a request because its API budget is spent.

Asking again before the budget returns gets the same answer. A caller that can wait (a watch that follows a pull request) sleeps until then and continues; one that cannot names the time.

Attributes:

Name Type Description
reset_at

When the budget returns, as seconds since the epoch; None when the forge did not say.

Carry message, the request facts, and when the budget returns.

Source code in packages/forge/src/livery/forge/_errors.py
def __init__(
    self,
    message: str,
    *,
    reset_at: float | None,
    status: int | None = None,
    method: str = "",
    endpoint: str = "",
    detail: str = "",
) -> None:
    """Carry *message*, the request facts, and when the budget returns."""
    super().__init__(
        message, status=status, method=method, endpoint=endpoint, detail=detail
    )
    self.reset_at = reset_at

reset_at instance-attribute

reset_at = reset_at

Unsupported

Bases: Exception

Raised when a forge cannot honour a protocol operation.

The message says why: a server version that predates the operation, or a capability the forge declines by name. Kept apart from livery.forge.ForgeError because retrying cannot change the answer: the forge is reachable, and the operation is one it does not offer. Probe with livery.forge.Forge.supports before relying on a capability-gated operation.

GiteaForge

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

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

Build with livery.forge.GiteaForge.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/v1.

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.

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), cached.

registry_url

Gitea hosts all three: its package registry serves them.

supports

Gitea offers every named capability.

repository

The view onto one repository. Cheap, no network.

members

The org's member logins; a user namespace is its one login.

teams

The org's team names; a user namespace has none.

codeowners

Gitea's dialect: .gitea/CODEOWNERS, @owner lines.

user_url

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

create_repo

Create the repository under an org or the token's own user.

get_repo

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

delete_repo

Delete the repository; 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/_gitea.py
def __init__(
    self, api_base: str, *, token: str, opener: Opener | None = None
) -> None:
    """Bind the client to *api_base* with *token*."""
    headers = {"Authorization": f"token {token}"} if token else {}
    headers["Accept"] = "application/json"
    self._client = JsonClient(api_base, headers=headers, opener=opener)
    self._token = token
    self._version: str | None = None
    # Gitea serves the API under /api/v1 on the web host.
    self._web_root = api_base.rstrip("/").removesuffix("/api/v1")

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) -> GiteaForge

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

An explicit url wins; GITEA_URL is the configured default. token defaults to GITEA_TOKEN; a missing token raises rather than silently reading anonymously, because an unauthenticated write fails later and further from the cause. tea prints no token of its own, so there is no CLI to fall back to. Pass token="" to read a foreign or public server anonymously on purpose.

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

    An explicit *url* wins; ``GITEA_URL`` is the configured
    default. *token* defaults to ``GITEA_TOKEN``; a missing token
    raises rather than silently reading anonymously, because an
    unauthenticated write fails later and further from the cause.
    ``tea`` prints no token of its own, so there is no CLI to fall
    back to. Pass ``token=""`` to read a foreign or public server
    anonymously on purpose.
    """
    web = url or os.environ.get("GITEA_URL", "")
    if not web:
        raise ForgeError(
            "no Gitea server to connect to: pass url= or set GITEA_URL"
        )
    resolved = os.environ.get("GITEA_TOKEN", "") if token is None else token
    if token is None and not resolved:
        raise ForgeError("no Gitea credential: set GITEA_TOKEN")
    return cls(f"{web.rstrip('/')}/api/v1", token=resolved, opener=opener)

whoami

whoami() -> str

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

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

server_version

server_version() -> str

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

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

registry_url

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

Gitea hosts all three: its package registry serves them.

python answers the pypi registry base (its /simple child is the read index, the base itself takes uploads); conan the conan remote; container the image reference prefix, which on Gitea is the web host itself.

Source code in packages/forge/src/livery/forge/_gitea.py
def registry_url(self, kind: RegistryKind, owner: str) -> str:
    """Gitea hosts all three: its package registry serves them.

    ``python`` answers the pypi registry base (its ``/simple``
    child is the read index, the base itself takes uploads);
    ``conan`` the conan remote; ``container`` the image
    reference prefix, which on Gitea is the web host itself.
    """
    host = self._web_root
    if kind == "python":
        return f"{host}/api/packages/{owner}/pypi"
    if kind == "conan":
        return f"{host}/api/packages/{owner}/conan"
    bare = host.split("://", 1)[-1]
    return f"{bare}/{owner}"

supports

supports(capability: Capability) -> bool

Gitea offers every named capability.

Source code in packages/forge/src/livery/forge/_gitea.py
def supports(self, capability: Capability) -> bool:
    """Gitea offers every named capability."""
    return capability in (
        "auto_merge",
        "force_cancel",
        "required_contexts",
        "min_approvals",
        "ci_secrets",
        "schedule_events",
    )

repository

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

The view onto one repository. Cheap, no network.

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

members

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

The org's member logins; a user namespace is its one login.

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

teams

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

The org's team names; a user namespace has none.

Source code in packages/forge/src/livery/forge/_gitea.py
def teams(self, owner: str) -> tuple[str, ...]:
    """The org's team names; a user namespace has none."""
    try:
        rows = self._client.paginate(
            lambda page: self._client.request(
                f"/orgs/{quote(owner)}/teams?limit=50&page={page}"
            ),
            subject=f"/orgs/{owner}/teams",
        )
    except ForgeError as error:
        if error.status == 404:
            return ()
        raise
    return tuple(sorted(str(row.get("name", "")) for row in rows))

codeowners

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

Gitea's dialect: .gitea/CODEOWNERS, @owner lines.

Same shape as GitHub's; a per-path approval count is approximated repository-wide through protection.

Source code in packages/forge/src/livery/forge/_gitea.py
def codeowners(self, entries: tuple[CodeownersEntry, ...]) -> Codeowners:
    """Gitea's dialect: ``.gitea/CODEOWNERS``, ``@owner`` lines.

    Same shape as GitHub's; a per-path approval count is
    approximated repository-wide through protection.
    """
    lines = []
    notes = []
    for entry in entries:
        owners = " ".join(f"@{name}" for name in entry.owners)
        lines.append(f"{entry.path} {owners}")
        if entry.min_approvals > 1:
            notes.append(
                f"{entry.path}: {entry.min_approvals} approvals wanted;"
                " Gitea expresses one repository-wide count through"
                " protection, not per path"
            )
    return Codeowners(
        path=".gitea/CODEOWNERS",
        content="\n".join(lines) + "\n" if lines else "",
        notes=tuple(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/_gitea.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 repository under an org or the token's own user.

auto_init gives it the default branch the protocol requires. Creating under a user other than the token's own is not a thing Gitea offers and raises.

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

    ``auto_init`` gives it the default branch the protocol
    requires. Creating under a user other than the token's own is
    not a thing Gitea offers and raises.
    """
    body = {
        "name": name,
        "private": private,
        "description": description,
        "auto_init": True,
    }
    if self._client.request(f"/orgs/{quote(owner)}", none_on=(404,)) is not None:
        self._client.request(
            f"/orgs/{quote(owner)}/repos", method="POST", data=body
        )
    elif owner == self.whoami():
        self._client.request("/user/repos", method="POST", data=body)
    else:
        raise ForgeError(
            f"cannot create {owner}/{name}: {owner} is neither an"
            " organisation nor the token's own user"
        )
    return self.repository(owner, name)

get_repo

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

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

Source code in packages/forge/src/livery/forge/_gitea.py
def get_repo(self, owner: str, name: str) -> RepoInfo | None:
    """The repository's settings, or None when it does not exist."""
    data = self._client.request(
        f"/repos/{quote(owner)}/{quote(name)}", none_on=(404,)
    )
    if data is None:
        return None
    return RepoInfo(
        owner=owner,
        name=name,
        default_branch=str(data.get("default_branch", "")),
        private=bool(data.get("private", False)),
    )

delete_repo

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

Delete the repository; one already gone is success.

Gitea deletes a repository with a long run history slowly (a loop repository with 1,400 runs outran a 30 s wait), so the request is given two minutes; the deletion completes on the server whether or not the client waits for it.

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

    Gitea deletes a repository with a long run history slowly (a
    loop repository with 1,400 runs outran a 30 s wait), so the
    request is given two minutes; the deletion completes on the
    server whether or not the client waits for it.
    """
    self._client.request(
        f"/repos/{quote(owner)}/{quote(name)}",
        method="DELETE",
        none_on=(404,),
        timeout=120.0,
    )

GithubForge

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

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

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

Parameters:

Name Type Description Default
api_base str

The API root: https://api.github.com, or a GitHub Enterprise server's <url>/api/v3.

required
token str

The token sent on every request.

required
opener Opener | None

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

None

Bind the client to api_base with token.

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 Enterprise version from GET /meta, or github.com.

registry_url

GitHub hosts a container registry; the others decline.

supports

Honest per-install: ci_secrets needs the extra installed.

repository

The view onto one repository. Cheap, no network.

members

The org's member logins; a user namespace is its one login.

teams

The org's team slugs; a user namespace has none.

codeowners

GitHub's dialect: .github/CODEOWNERS, @owner lines.

user_url

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

create_repo

Create the repository under an org or the token's own user.

get_repo

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

delete_repo

Delete the repository; one already gone is success.

graphql

One GraphQL call; errors raise with GitHub's words verbatim.

Attributes:

Name Type Description
token str

The credential this connection authenticates with; empty when anonymous.

Source code in packages/forge/src/livery/forge/_github.py
def __init__(
    self, api_base: str, *, token: str, opener: Opener | None = None
) -> None:
    """Bind the client to *api_base* with *token*."""
    headers = {
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    if token:
        headers["Authorization"] = f"Bearer {token}"
    self._client = JsonClient(api_base, headers=headers, opener=opener)
    self._token = token
    self._opener = opener
    # github.com's API lives on its own host; an Enterprise server
    # serves the API under /api/v3 on the web host.
    stripped = api_base.rstrip("/")
    if stripped == "https://api.github.com":
        self._web_root = "https://github.com"
    else:
        self._web_root = stripped.removesuffix("/api/v3")

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) -> GithubForge

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

github.com unless url names a GitHub Enterprise server (its API is at <url>/api/v3). token resolves as GITHUB_TOKEN first, then gh auth token; nothing found raises, because an unauthenticated write fails later and further from the cause. Pass token="" to read anonymously on purpose.

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

    github.com unless *url* names a GitHub Enterprise server (its
    API is at ``<url>/api/v3``). *token* resolves as
    ``GITHUB_TOKEN`` first, then ``gh auth token``; nothing found
    raises, because an unauthenticated write fails later and
    further from the cause. Pass ``token=""`` to read anonymously
    on purpose.
    """
    web = (url or "https://github.com").rstrip("/")
    if web in ("https://github.com", "http://github.com"):
        api = "https://api.github.com"
    else:
        api = f"{web}/api/v3"
    resolved = _resolve_token() if token is None else token
    if token is None and not resolved:
        raise ForgeError(
            "no GitHub credential: set GITHUB_TOKEN or sign in with `gh auth login`"
        )
    return cls(api, token=resolved, opener=opener)

whoami

whoami() -> str

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

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

server_version

server_version() -> str

The Enterprise version from GET /meta, or github.com.

github.com carries no version; the constant string satisfies the protocol's non-empty answer and names the host class.

Source code in packages/forge/src/livery/forge/_github.py
def server_version(self) -> str:
    """The Enterprise version from ``GET /meta``, or ``github.com``.

    github.com carries no version; the constant string satisfies
    the protocol's non-empty answer and names the host class.
    """
    data = self._client.request("/meta")
    return str(data.get("installed_version") or "github.com")

registry_url

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

GitHub hosts a container registry; the others decline.

container answers the ghcr prefix on github.com (an enterprise install's registry host is not derivable from the API base, so it declines there too, and the contract's own declaration is the path). python declines: GitHub hosts no python index, and pypi.org is the resolution ladder's ecosystem default, not this forge's registry. conan declines: GitHub has no conan registry at all.

Source code in packages/forge/src/livery/forge/_github.py
def registry_url(self, kind: RegistryKind, owner: str) -> str:
    """GitHub hosts a container registry; the others decline.

    ``container`` answers the ghcr prefix on github.com (an
    enterprise install's registry host is not derivable from the
    API base, so it declines there too, and the contract's own
    declaration is the path). ``python`` declines: GitHub hosts
    no python index, and pypi.org is the resolution ladder's
    ecosystem default, not this forge's registry. ``conan``
    declines: GitHub has no conan registry at all.
    """
    if kind == "container" and self._web_root == "https://github.com":
        return f"ghcr.io/{owner}"
    raise Unsupported(
        f"github hosts no {kind} registry"
        + (
            " (an enterprise install's registry host is not derivable;"
            " declare it in the contract)"
            if kind == "container"
            else ""
        )
    )

supports

supports(capability: Capability) -> bool

Honest per-install: ci_secrets needs the extra installed.

Source code in packages/forge/src/livery/forge/_github.py
def supports(self, capability: Capability) -> bool:
    """Honest per-install: ``ci_secrets`` needs the extra installed."""
    if capability == "ci_secrets":
        return importlib.util.find_spec("nacl") is not None
    return capability in (
        "auto_merge",
        "force_cancel",
        "required_contexts",
        "schedule_events",
        "min_approvals",
        "pages_config",
    )

repository

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

The view onto one repository. Cheap, no network.

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

members

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

The org's member logins; a user namespace is its one login.

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

teams

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

The org's team slugs; a user namespace has none.

Source code in packages/forge/src/livery/forge/_github.py
def teams(self, owner: str) -> tuple[str, ...]:
    """The org's team slugs; a user namespace has none."""
    try:
        rows = self._client.paginate(
            lambda page: self._client.request(
                f"/orgs/{quote(owner)}/teams?per_page=100&page={page}"
            ),
            subject=f"/orgs/{owner}/teams",
        )
    except ForgeError as error:
        if error.status == 404:
            return ()
        raise
    return tuple(sorted(str(row.get("slug", "")) for row in rows))

codeowners

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

GitHub's dialect: .github/CODEOWNERS, @owner lines.

A per-path approval count has no spelling here; protection approximates it repository-wide, and the note says so.

Source code in packages/forge/src/livery/forge/_github.py
def codeowners(self, entries: tuple[CodeownersEntry, ...]) -> Codeowners:
    """GitHub's dialect: ``.github/CODEOWNERS``, ``@owner`` lines.

    A per-path approval count has no spelling here; protection
    approximates it repository-wide, and the note says so.
    """
    lines = []
    notes = []
    for entry in entries:
        owners = " ".join(f"@{name}" for name in entry.owners)
        lines.append(f"{entry.path} {owners}")
        if entry.min_approvals > 1:
            notes.append(
                f"{entry.path}: {entry.min_approvals} approvals wanted;"
                " GitHub expresses one repository-wide count through"
                " protection, not per path"
            )
    return Codeowners(
        path=".github/CODEOWNERS",
        content="\n".join(lines) + "\n" if lines else "",
        notes=tuple(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/_github.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 repository under an org or the token's own user.

auto_init gives it the default branch the protocol requires.

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

    ``auto_init`` gives it the default branch the protocol
    requires.
    """
    body = {
        "name": name,
        "private": private,
        "description": description,
        "auto_init": True,
    }
    if owner == self.whoami():
        self._client.request("/user/repos", method="POST", data=body)
    else:
        self._client.request(
            f"/orgs/{quote(owner)}/repos", method="POST", data=body
        )
    return self.repository(owner, name)

get_repo

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

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

Source code in packages/forge/src/livery/forge/_github.py
def get_repo(self, owner: str, name: str) -> RepoInfo | None:
    """The repository's settings, or None when it does not exist."""
    data = self._client.request(
        f"/repos/{quote(owner)}/{quote(name)}", none_on=(404,)
    )
    if data is None:
        return None
    return RepoInfo(
        owner=owner,
        name=name,
        default_branch=str(data.get("default_branch", "")),
        private=bool(data.get("private", False)),
    )

delete_repo

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

Delete the repository; one already gone is success.

The token needs the delete_repo scope; a 403 quotes GitHub's refusal verbatim.

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

    The token needs the ``delete_repo`` scope; a 403 quotes
    GitHub's refusal verbatim.
    """
    self._client.request(
        f"/repos/{quote(owner)}/{quote(name)}", method="DELETE", none_on=(404,)
    )

graphql

graphql(query: str, variables: dict[str, Any]) -> dict[str, Any]

One GraphQL call; errors raise with GitHub's words verbatim.

GraphQL failures answer 200 with an errors array, so the HTTP layer cannot see them; this is where they become livery.forge.ForgeError.

Source code in packages/forge/src/livery/forge/_github.py
def graphql(self, query: str, variables: dict[str, Any]) -> dict[str, Any]:
    """One GraphQL call; errors raise with GitHub's words verbatim.

    GraphQL failures answer 200 with an ``errors`` array, so the
    HTTP layer cannot see them; this is where they become
    livery.forge.ForgeError.
    """
    data = self._client.request(
        "/graphql", method="POST", data={"query": query, "variables": variables}
    )
    errors = data.get("errors") or []
    if errors:
        said = "; ".join(str(e.get("message", "")) for e in errors)
        raise ForgeError(
            f"GraphQL refused: {said}",
            method="POST",
            endpoint="/graphql",
            detail=said,
        )
    result: dict[str, Any] = data.get("data") or {}
    return result

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

MergeState dataclass

MergeState(state: str, category: MergeCategory, message: str, native: str = '')

One classified merge hold.

Attributes:

Name Type Description
state str

The union vocabulary member (computing, checks-red, behind, ...).

category MergeCategory

What a caller does with it; see livery.forge.MergeCategory.

message str

One user-facing sentence: the situation, and for a recoverable state what would recover it.

native str

The forge's own words, verbatim; empty when the forge expressed the state as data rather than prose.

state instance-attribute

state: str

category instance-attribute

category: MergeCategory

message instance-attribute

message: str

native class-attribute instance-attribute

native: str = ''

Checks

Bases: Protocol

One repository's CI: the combined verdict, runs, jobs, and logs.

GitHub and Gitea run workflows, GitLab runs pipelines. A run here is either; livery.forge.Run says how the two map.

Methods:

Name Description
status

The one CI verdict for commit sha.

runs

The repository's runs, newest first.

jobs

Every job of run run.

job_log

The raw log text of job job.

rerun

Re-run run: its failed jobs, or all of them.

cancel_run

Cancel run and its jobs.

dispatch

Trigger workflow on ref; return the run's id when the forge names it.

status

status(sha: str) -> CombinedStatus

The one CI verdict for commit sha.

Polling this is the observation model: a workflow that armed a merge watches the verdict here and observes the merge through livery.forge.PullRequests.get. A commit nothing has reported for answers none, never pending.

Source code in packages/forge/src/livery/forge/_protocol.py
def status(self, sha: str) -> CombinedStatus:
    """The one CI verdict for commit *sha*.

    Polling this is the observation model: a workflow that armed a
    merge watches the verdict here and observes the merge through
    livery.forge.PullRequests.get. A commit nothing has reported
    for answers ``none``, never ``pending``.
    """
    ...

runs

runs(*, head_sha: str = '', event: str = '', workflow: str = '', limit: int = 0) -> tuple[Run, ...]

The repository's runs, newest first.

head_sha and event filter when given. workflow names a workflow file (release.yml): GitHub and Gitea list that workflow's runs alone, and GitLab, whose pipelines carry a name only when dispatched, keeps the unnamed ones as well. With limit, the newest limit runs: the listing is read only until there are enough. Without it, the tuple is complete for the query or the call raises; a truncated listing is never returned as the answer.

Source code in packages/forge/src/livery/forge/_protocol.py
def runs(
    self,
    *,
    head_sha: str = "",
    event: str = "",
    workflow: str = "",
    limit: int = 0,
) -> tuple[Run, ...]:
    """The repository's runs, newest first.

    *head_sha* and *event* filter when given. *workflow* names a
    workflow file (``release.yml``): GitHub and Gitea list that
    workflow's runs alone, and GitLab, whose pipelines carry a name
    only when dispatched, keeps the unnamed ones as well. With
    *limit*, the newest *limit* runs: the listing is read only until
    there are enough. Without it, the tuple is complete for the
    query or the call raises; a truncated listing is never returned
    as the answer.
    """
    ...

jobs

jobs(run: int) -> tuple[Job, ...]

Every job of run run.

Source code in packages/forge/src/livery/forge/_protocol.py
def jobs(self, run: int) -> tuple[Job, ...]:
    """Every job of run *run*."""
    ...

job_log

job_log(job: int) -> str

The raw log text of job job.

The failure evidence: triage reads this, quotes it verbatim, and never reduces it to a boolean.

Source code in packages/forge/src/livery/forge/_protocol.py
def job_log(self, job: int) -> str:
    """The raw log text of job *job*.

    The failure evidence: triage reads this, quotes it verbatim,
    and never reduces it to a boolean.
    """
    ...

rerun

rerun(run: int, *, failed_only: bool = True) -> None

Re-run run: its failed jobs, or all of them.

failed_only is the cheap and usually correct choice: a green matrix leg does not need re-running to re-test a red one. Raises livery.forge.ForgeError while the run is still in progress, because there is nothing to re-run yet.

Source code in packages/forge/src/livery/forge/_protocol.py
def rerun(self, run: int, *, failed_only: bool = True) -> None:
    """Re-run *run*: its failed jobs, or all of them.

    ``failed_only`` is the cheap and usually correct choice: a
    green matrix leg does not need re-running to re-test a red
    one. Raises livery.forge.ForgeError while the run is still in
    progress, because there is nothing to re-run yet.
    """
    ...

cancel_run

cancel_run(run: int, *, force: bool = False) -> None

Cancel run and its jobs.

Required on every forge: superseded pushes cancel their stale runs, a dispatch storm is withdrawn, a starving queue is relieved by this verb instead of a wait. Raises livery.forge.ForgeError when the run is already terminal, so a caller re-running its workflow probes the run's status first.

force=True marks the jobs cancelled immediately and discards later runner reports, for a run whose runner stopped answering. It is capability-gated: a forge without force_cancel raises livery.forge.Unsupported naming the capability, and plain cancel remains available.

Source code in packages/forge/src/livery/forge/_protocol.py
def cancel_run(self, run: int, *, force: bool = False) -> None:
    """Cancel *run* and its jobs.

    Required on every forge: superseded pushes cancel their stale
    runs, a dispatch storm is withdrawn, a starving queue is
    relieved by this verb instead of a wait. Raises
    livery.forge.ForgeError when the run is already terminal, so a
    caller re-running its workflow probes the run's status first.

    ``force=True`` marks the jobs cancelled immediately and
    discards later runner reports, for a run whose runner stopped
    answering. It is capability-gated: a forge without
    ``force_cancel`` raises livery.forge.Unsupported naming the
    capability, and plain cancel remains available.
    """
    ...

dispatch

dispatch(workflow: str, *, ref: str, inputs: Mapping[str, str] | None = None) -> int | None

Trigger workflow on ref; return the run's id when the forge names it.

workflow is the workflow file name as GitHub and Gitea address one. GitLab has one pipeline definition per repository: its backend triggers the pipeline on ref and passes workflow through as a variable for the pipeline's rules to route on.

Returns:

Type Description
int | None

The id of the run the dispatch started, as

int | None

livery.forge.Checks.runs lists it, when the forge's answer

int | None

names it: GitLab answers with the pipeline it created,

int | None

GitHub and Gitea with the run's details. None when the

int | None

answer names no run, as a GitHub or Gitea server without

int | None

the run's details answers: the caller finds the run in the

int | None

listing by its event, its ref and its head commit, and two

int | None

runs dispatched together on one ref and commit cannot be

int | None

told apart there.

Source code in packages/forge/src/livery/forge/_protocol.py
def dispatch(
    self, workflow: str, *, ref: str, inputs: Mapping[str, str] | None = None
) -> int | None:
    """Trigger *workflow* on *ref*; return the run's id when the forge names it.

    *workflow* is the workflow file name as GitHub and Gitea
    address one. GitLab has one pipeline definition per
    repository: its backend triggers the pipeline on *ref* and
    passes *workflow* through as a variable for the pipeline's
    rules to route on.

    Returns:
        The id of the run the dispatch started, as
        [livery.forge.Checks.runs][] lists it, when the forge's answer
        names it: GitLab answers with the pipeline it created,
        GitHub and Gitea with the run's details. None when the
        answer names no run, as a GitHub or Gitea server without
        the run's details answers: the caller finds the run in the
        listing by its event, its ref and its head commit, and two
        runs dispatched together on one ref and commit cannot be
        told apart there.
    """
    ...

Forge

Bases: Protocol

One forge server: identity, capabilities, and its repositories.

Construction is a backend concern, not part of the protocol. Each backend states the server and resolves its token once, and a token belongs to exactly one host: a foreign host is never sent it.

Methods:

Name Description
whoami

The authenticated user's login name.

server_version

The server's version string.

registry_url

The root of this forge's own hosted registry of kind.

supports

Whether this forge offers capability.

repository

The view onto one repository. Cheap, no network.

members

The login names under owner, an organisation or group.

teams

The team names under owner, as the forge spells them.

codeowners

Render entries as this forge's codeowners file.

user_url

The address of login's profile page.

create_repo

Create the repository and return its view.

get_repo

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

delete_repo

Delete the repository.

Attributes:

Name Type Description
token str

The credential this connection authenticates with.

token property

token: str

The credential this connection authenticates with.

Empty for a connection deliberately opened anonymously. The backend resolved it once at connect time, its own dialect variables included, so a caller needing the lane's credential asks here instead of re-deriving it.

whoami

whoami() -> str

The authenticated user's login name.

The first probe of anything unattended: a wrong-host token dies here, not mid-workflow.

Source code in packages/forge/src/livery/forge/_protocol.py
def whoami(self) -> str:
    """The authenticated user's login name.

    The first probe of anything unattended: a wrong-host token
    dies here, not mid-workflow.
    """
    ...

server_version

server_version() -> str

The server's version string.

Backends with a version floor check it here and raise livery.forge.Unsupported naming the version when the server predates an operation.

Source code in packages/forge/src/livery/forge/_protocol.py
def server_version(self) -> str:
    """The server's version string.

    Backends with a version floor check it here and raise
    livery.forge.Unsupported naming the version when the server
    predates an operation.
    """
    ...

registry_url

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

The root of this forge's own hosted registry of kind.

For python the returned root is the registry base whose /simple child is the read index and which itself accepts uploads (the forge-registry shape); conan answers the remote URL a conan client configures; container answers the reference prefix an image tag starts with. Raises livery.forge.Unsupported, naming the kind, where this forge hosts no such registry. The forge is the default provider, never the owner: resolution and external declarations are the caller's business.

Source code in packages/forge/src/livery/forge/_protocol.py
def registry_url(self, kind: RegistryKind, owner: str) -> str:
    """The root of this forge's own hosted registry of *kind*.

    For ``python`` the returned root is the registry base whose
    ``/simple`` child is the read index and which itself accepts
    uploads (the forge-registry shape); ``conan`` answers the
    remote URL a conan client configures; ``container`` answers
    the reference prefix an image tag starts with. Raises
    livery.forge.Unsupported, naming the kind, where this forge
    hosts no such registry. The forge is the default provider,
    never the owner: resolution and external declarations are
    the caller's business.
    """
    ...

supports

supports(capability: Capability) -> bool

Whether this forge offers capability.

The honesty valve: a caller that can degrade asks here first, and a backend never pretends. The names are the livery.forge.Capability vocabulary.

Source code in packages/forge/src/livery/forge/_protocol.py
def supports(self, capability: Capability) -> bool:
    """Whether this forge offers *capability*.

    The honesty valve: a caller that can degrade asks here first,
    and a backend never pretends. The names are the
    livery.forge.Capability vocabulary.
    """
    ...

repository

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

The view onto one repository. Cheap, no network.

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

members

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

The login names under owner, an organisation or group.

A personal namespace answers exactly its one login: the governance declarations validate against this listing, and a solo repository's only member is its owner.

Source code in packages/forge/src/livery/forge/_protocol.py
def members(self, owner: str) -> tuple[str, ...]:
    """The login names under *owner*, an organisation or group.

    A personal namespace answers exactly its one login: the
    governance declarations validate against this listing, and a
    solo repository's only member is its owner.
    """
    ...

teams

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

The team names under owner, as the forge spells them.

GitHub and Gitea answer team slugs; GitLab's teams are its subgroups and it answers group paths. A personal namespace has none and answers empty.

Source code in packages/forge/src/livery/forge/_protocol.py
def teams(self, owner: str) -> tuple[str, ...]:
    """The team names under *owner*, as the forge spells them.

    GitHub and Gitea answer team slugs; GitLab's teams are its
    subgroups and it answers group paths. A personal namespace
    has none and answers empty.
    """
    ...

codeowners

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

Render entries as this forge's codeowners file.

Pure string building, nothing on the wire: the canonical location and syntax are the forge's, the declarations are neutral. What a dialect cannot express (a per-path approval count outside GitLab's sections) is approximated and named in the result's notes, never dropped silently.

Source code in packages/forge/src/livery/forge/_protocol.py
def codeowners(self, entries: tuple[CodeownersEntry, ...]) -> Codeowners:
    """Render *entries* as this forge's codeowners file.

    Pure string building, nothing on the wire: the canonical
    location and syntax are the forge's, the declarations are
    neutral. What a dialect cannot express (a per-path approval
    count outside GitLab's sections) is approximated and named
    in the result's notes, never dropped silently.
    """
    ...

user_url

user_url(login: str) -> str

The address of login's profile page.

String building from the server the backend is bound to; nothing goes on the wire and the login is not verified.

Source code in packages/forge/src/livery/forge/_protocol.py
def user_url(self, login: str) -> str:
    """The address of *login*'s profile page.

    String building from the server the backend is bound to;
    nothing goes on the wire and the login is not verified.
    """
    ...

create_repo

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

Create the repository and return its view.

The repository is initialised with a default branch that carries no protection: the creator may push its own history over the initial commit, and protection starts when the caller configures it. Raises livery.forge.ForgeError when it already exists; ensure-exists callers probe with livery.forge.Forge.get_repo first. On GitLab, owner may be a group path.

Source code in packages/forge/src/livery/forge/_protocol.py
def create_repo(
    self,
    owner: str,
    name: str,
    *,
    private: bool = True,
    description: str = "",
) -> Repository:
    """Create the repository and return its view.

    The repository is initialised with a default branch that
    carries no protection: the creator may push its own history
    over the initial commit, and protection starts when the caller
    configures it. Raises livery.forge.ForgeError when it already
    exists; ensure-exists callers probe with
    livery.forge.Forge.get_repo first. On GitLab, *owner* may be a
    group path.
    """
    ...

get_repo

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

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

The probe that makes repository creation safe to re-run.

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

    The probe that makes repository creation safe to re-run.
    """
    ...

delete_repo

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

Delete the repository.

Idempotent: a repository already gone is success, not an error.

Source code in packages/forge/src/livery/forge/_protocol.py
def delete_repo(self, owner: str, name: str) -> None:
    """Delete the repository.

    Idempotent: a repository already gone is success, not an
    error.
    """
    ...

Issues

Bases: Protocol

One repository's issues: text in both directions.

An issue's body is carried in full on create, get, list, and search, because the body is the work order in issue-driven workflows and the marker text in deduplication probes.

Methods:

Name Description
create

Open an issue and return it.

get

The issue number, body included, or None when it does not exist.

list

The repository's issues in state. Pull requests never appear.

search

The issues whose title or body contains text.

assign

Add assignee to the issue's assignees.

unassign

Remove the authenticated user from the issue's assignees.

assigned_to_me

The open issues assigned to the authenticated user.

update

Rewrite issue number's title, body, or both.

comment

Post body as a comment on issue number.

comments

The comments on issue number, oldest first, each in full.

close

Close issue number; closing a closed issue is a no-op.

reopen

Reopen issue number; reopening an open issue is a no-op.

create

create(title: str, *, body: str = '', labels: tuple[str, ...] = (), assignee: str = '') -> Issue

Open an issue and return it.

labels are label names; ensure they exist first with livery.forge.Repository.configure. A creator that must not file duplicates searches for its marker text with livery.forge.Issues.search before creating.

Source code in packages/forge/src/livery/forge/_protocol.py
def create(
    self,
    title: str,
    *,
    body: str = "",
    labels: tuple[str, ...] = (),
    assignee: str = "",
) -> Issue:
    """Open an issue and return it.

    *labels* are label names; ensure they exist first with
    livery.forge.Repository.configure. A creator that must not
    file duplicates searches for its marker text with
    livery.forge.Issues.search before creating.
    """
    ...

get

get(number: int) -> Issue | None

The issue number, body included, or None when it does not exist.

The existence probe every write to an issue runs first: the subject of a write is verified, never assumed.

Source code in packages/forge/src/livery/forge/_protocol.py
def get(self, number: int) -> Issue | None:
    """The issue *number*, body included, or None when it does not exist.

    The existence probe every write to an issue runs first: the
    subject of a write is verified, never assumed.
    """
    ...

list

list(*, state: StateFilter = 'open') -> tuple[Issue, ...]

The repository's issues in state. Pull requests never appear.

Source code in packages/forge/src/livery/forge/_protocol.py
def list(self, *, state: StateFilter = "open") -> tuple[Issue, ...]:
    """The repository's issues in *state*. Pull requests never appear."""
    ...

search

search(text: str, *, state: StateFilter = 'open', labels: tuple[str, ...] = ()) -> tuple[Issue, ...]

The issues whose title or body contains text.

labels narrows to issues carrying every named label. The deduplication probe: an unattended creator searches for its marker text and label before it files.

Source code in packages/forge/src/livery/forge/_protocol.py
def search(
    self,
    text: str,
    *,
    state: StateFilter = "open",
    labels: tuple[str, ...] = (),
) -> tuple[Issue, ...]:
    """The issues whose title or body contains *text*.

    *labels* narrows to issues carrying every named label. The
    deduplication probe: an unattended creator searches for its
    marker text and label before it files.
    """
    ...

assign

assign(number: int, assignee: str) -> None

Add assignee to the issue's assignees.

Adds rather than replaces, so a colleague's assignment survives; how many assignees an issue may carry is workspace policy, enforced by the caller, because the forges' own limits differ (GitLab's free tier carries one).

Source code in packages/forge/src/livery/forge/_protocol.py
def assign(self, number: int, assignee: str) -> None:
    """Add *assignee* to the issue's assignees.

    Adds rather than replaces, so a colleague's assignment
    survives; how many assignees an issue may carry is workspace
    policy, enforced by the caller, because the forges' own
    limits differ (GitLab's free tier carries one).
    """
    ...

unassign

unassign(number: int) -> None

Remove the authenticated user from the issue's assignees.

Only the caller's own assignment: a colleague's stays. Not being assigned is a no-op, so re-running is the recovery.

Source code in packages/forge/src/livery/forge/_protocol.py
def unassign(self, number: int) -> None:
    """Remove the authenticated user from the issue's assignees.

    Only the caller's own assignment: a colleague's stays. Not
    being assigned is a no-op, so re-running is the recovery.
    """
    ...

assigned_to_me

assigned_to_me() -> tuple[Issue, ...]

The open issues assigned to the authenticated user.

Source code in packages/forge/src/livery/forge/_protocol.py
def assigned_to_me(self) -> tuple[Issue, ...]:
    """The open issues assigned to the authenticated user."""
    ...

update

update(number: int, *, title: str = '', body: str = '') -> None

Rewrite issue number's title, body, or both.

Only the provided (non-empty) fields change; clearing a text to empty is not part of the contract. A number that names nothing raises livery.forge.ForgeError.

Source code in packages/forge/src/livery/forge/_protocol.py
def update(self, number: int, *, title: str = "", body: str = "") -> None:
    """Rewrite issue *number*'s title, body, or both.

    Only the provided (non-empty) fields change; clearing a text
    to empty is not part of the contract. A number that names
    nothing raises [livery.forge.ForgeError][].
    """
    ...

comment

comment(number: int, body: str) -> None

Post body as a comment on issue number.

Source code in packages/forge/src/livery/forge/_protocol.py
def comment(self, number: int, body: str) -> None:
    """Post *body* as a comment on issue *number*."""
    ...

comments

comments(number: int) -> tuple[Comment, ...]

The comments on issue number, oldest first, each in full.

The thread continues the work order the body opened, so it is read whole, the way the body is. Only what people wrote is a comment: a forge's own system notes are left out. Raises livery.forge.ForgeError with status 404 when the issue does not exist.

Source code in packages/forge/src/livery/forge/_protocol.py
def comments(self, number: int) -> tuple[Comment, ...]:
    """The comments on issue *number*, oldest first, each in full.

    The thread continues the work order the body opened, so it is
    read whole, the way the body is. Only what people wrote is a
    comment: a forge's own system notes are left out. Raises
    livery.forge.ForgeError with status 404 when the issue does
    not exist.
    """
    ...

close

close(number: int) -> None

Close issue number; closing a closed issue is a no-op.

Idempotent so re-running is the recovery. The reason belongs in a comment posted before the close: every forge keeps the thread, none has a first-class close reason worth abstracting.

Source code in packages/forge/src/livery/forge/_protocol.py
def close(self, number: int) -> None:
    """Close issue *number*; closing a closed issue is a no-op.

    Idempotent so re-running is the recovery. The reason belongs
    in a comment posted before the close: every forge keeps the
    thread, none has a first-class close reason worth abstracting.
    """
    ...

reopen

reopen(number: int) -> None

Reopen issue number; reopening an open issue is a no-op.

The inverse of close, for an issue a merge closed before its work was done. A missing number raises.

Source code in packages/forge/src/livery/forge/_protocol.py
def reopen(self, number: int) -> None:
    """Reopen issue *number*; reopening an open issue is a no-op.

    The inverse of `close`, for an issue a merge closed before its
    work was done. A missing number raises.
    """
    ...

PullRequests

Bases: Protocol

One repository's pull requests: open, find, merge, arm, comment.

GitLab calls them merge requests; the operations map one to one and the protocol keeps one vocabulary.

Methods:

Name Description
open

Open a pull request from head into base and return it.

find_by_head

The pull request whose head branch is branch, or None.

find_by_head_sha

The pull request whose head commit is sha, or None.

get

The pull request number, or None when it does not exist.

list

The repository's pull requests in state, newest first.

update_title

Retitle pull request number.

update_body

Replace the description of pull request number.

close

Close pull request number without merging.

reopen

Reopen the closed, unmerged pull request number.

merge_now

Merge pull request number immediately.

arm

Schedule pull request number to merge when its checks go green.

disarm

Cancel a scheduled merge on pull request number.

is_armed

Whether pull request number currently has a merge scheduled.

merge_hold

The forge's published mergeability state of number, verbatim.

reviews

The submitted reviews on pull request number.

schedule_events

The merge-scheduling history of pull request number.

comment

Post body as a comment on pull request number.

add_labels

Put the labels names on pull request number.

open

open(head: str, base: str, title: str, body: str = '') -> PullRequest

Open a pull request from head into base and return it.

Raises livery.forge.ForgeError when an open pull request for head already exists; find and reuse it with livery.forge.PullRequests.find_by_head first.

Source code in packages/forge/src/livery/forge/_protocol.py
def open(self, head: str, base: str, title: str, body: str = "") -> PullRequest:
    """Open a pull request from *head* into *base* and return it.

    Raises livery.forge.ForgeError when an open pull request for
    *head* already exists; find and reuse it with
    livery.forge.PullRequests.find_by_head first.
    """
    ...

find_by_head

find_by_head(branch: str, *, state: StateFilter = 'open') -> PullRequest | None

The pull request whose head branch is branch, or None.

Reliable for open pull requests. A merged pull request whose head branch was auto-deleted may no longer carry the branch name on some forges, so "None" here does not prove no such pull request ever existed: find a finished one by livery.forge.PullRequests.find_by_head_sha instead.

Source code in packages/forge/src/livery/forge/_protocol.py
def find_by_head(
    self, branch: str, *, state: StateFilter = "open"
) -> PullRequest | None:
    """The pull request whose head branch is *branch*, or None.

    Reliable for open pull requests. A merged pull request whose
    head branch was auto-deleted may no longer carry the branch
    name on some forges, so "None" here does not prove no such
    pull request ever existed: find a finished one by
    livery.forge.PullRequests.find_by_head_sha instead.
    """
    ...

find_by_head_sha

find_by_head_sha(sha: str) -> PullRequest | None

The pull request whose head commit is sha, or None.

The head sha outlives the head branch, so this finds a merged pull request after the branch is gone.

Source code in packages/forge/src/livery/forge/_protocol.py
def find_by_head_sha(self, sha: str) -> PullRequest | None:
    """The pull request whose head commit is *sha*, or None.

    The head sha outlives the head branch, so this finds a merged
    pull request after the branch is gone.
    """
    ...

get

get(number: int) -> PullRequest | None

The pull request number, or None when it does not exist.

Source code in packages/forge/src/livery/forge/_protocol.py
def get(self, number: int) -> PullRequest | None:
    """The pull request *number*, or None when it does not exist."""
    ...

list

list(*, state: StateFilter = 'open') -> tuple[PullRequest, ...]

The repository's pull requests in state, newest first.

closed holds the merged pull requests and the ones closed without merging, as livery.forge.PullRequests.find_by_head reads the filter; merged tells the two apart. Each row carries the fields livery.forge.PullRequests.get answers for its number. Complete or raising, like every listing.

Source code in packages/forge/src/livery/forge/_protocol.py
def list(self, *, state: StateFilter = "open") -> tuple[PullRequest, ...]:
    """The repository's pull requests in *state*, newest first.

    ``closed`` holds the merged pull requests and the ones closed
    without merging, as [livery.forge.PullRequests.find_by_head][]
    reads the filter; ``merged`` tells the two apart. Each row
    carries the fields [livery.forge.PullRequests.get][] answers
    for its number. Complete or raising, like every listing.
    """
    ...

update_title

update_title(number: int, title: str) -> None

Retitle pull request number.

The title is the review-facing name and, on a squash-only repository, the merge armed after this call carries it as the commit subject.

Source code in packages/forge/src/livery/forge/_protocol.py
def update_title(self, number: int, title: str) -> None:
    """Retitle pull request *number*.

    The title is the review-facing name and, on a squash-only
    repository, the merge armed after this call carries it as the
    commit subject.
    """
    ...

update_body

update_body(number: int, body: str) -> None

Replace the description of pull request number.

The body is the review-facing text and, on a squash-only repository, the merge armed after this call carries it as the commit message.

Source code in packages/forge/src/livery/forge/_protocol.py
def update_body(self, number: int, body: str) -> None:
    """Replace the description of pull request *number*.

    The body is the review-facing text and, on a squash-only
    repository, the merge armed after this call carries it as the
    commit message.
    """
    ...

close

close(number: int) -> None

Close pull request number without merging.

Source code in packages/forge/src/livery/forge/_protocol.py
def close(self, number: int) -> None:
    """Close pull request *number* without merging."""
    ...

reopen

reopen(number: int) -> None

Reopen the closed, unmerged pull request number.

Reopening reuses the pull request, history and discussion intact, rather than opening a duplicate.

Source code in packages/forge/src/livery/forge/_protocol.py
def reopen(self, number: int) -> None:
    """Reopen the closed, unmerged pull request *number*.

    Reopening reuses the pull request, history and discussion
    intact, rather than opening a duplicate.
    """
    ...

merge_now

merge_now(number: int, *, title: str, message: str = '') -> None

Merge pull request number immediately.

title is the squash commit subject, message its body. A refusal raises livery.forge.ForgeError with the status a caller branches on: 405 when the checks are not green, 409 on a conflict. A caller that can wait arms instead (livery.forge.PullRequests.arm).

Merging an already merged pull request is success: re-running a verb is its recovery procedure, and backends whose forge refuses the second merge absorb that refusal after verifying the pull request really merged.

Source code in packages/forge/src/livery/forge/_protocol.py
def merge_now(self, number: int, *, title: str, message: str = "") -> None:
    """Merge pull request *number* immediately.

    *title* is the squash commit subject, *message* its body. A
    refusal raises livery.forge.ForgeError with the status a
    caller branches on: 405 when the checks are not green, 409 on
    a conflict. A caller that can wait arms instead
    (livery.forge.PullRequests.arm).

    Merging an already merged pull request is success: re-running
    a verb is its recovery procedure, and backends whose forge
    refuses the second merge absorb that refusal after verifying
    the pull request really merged.
    """
    ...

arm

arm(number: int, *, title: str, message: str = '') -> None

Schedule pull request number to merge when its checks go green.

title is the squash commit subject the merge will carry, message its body. A forge that limits the subject's length carries a longer one cut at a word boundary, so a long title never stops the arm: livery.forge.GithubForge cuts at 320 UTF-8 bytes. Arming an already armed pull request replaces the schedule, title included. The merge itself happens server-side: the caller observes it through livery.forge.Checks.status and livery.forge.PullRequests.get, never performs it. Push to an armed pull request only after livery.forge.PullRequests.disarm: a push into a live schedule races the merge, and the merge can take the pre-push head.

Raises livery.forge.Unsupported on a forge without the auto_merge capability.

Source code in packages/forge/src/livery/forge/_protocol.py
def arm(self, number: int, *, title: str, message: str = "") -> None:
    """Schedule pull request *number* to merge when its checks go green.

    *title* is the squash commit subject the merge will carry,
    *message* its body. A forge that limits the subject's length
    carries a longer one cut at a word boundary, so a long title
    never stops the arm: [livery.forge.GithubForge][] cuts at 320
    UTF-8 bytes. Arming an already armed pull request replaces
    the schedule, title included. The merge itself
    happens server-side: the caller observes it through
    livery.forge.Checks.status and livery.forge.PullRequests.get,
    never performs it. Push to an armed pull request only after
    livery.forge.PullRequests.disarm: a push into a live schedule
    races the merge, and the merge can take the pre-push head.

    Raises livery.forge.Unsupported on a forge without the
    ``auto_merge`` capability.
    """
    ...

disarm

disarm(number: int) -> bool

Cancel a scheduled merge on pull request number.

Returns True when a schedule was cancelled and False when there was nothing to cancel. Idempotent: disarming an unarmed pull request is not an error.

Source code in packages/forge/src/livery/forge/_protocol.py
def disarm(self, number: int) -> bool:
    """Cancel a scheduled merge on pull request *number*.

    Returns True when a schedule was cancelled and False when there
    was nothing to cancel. Idempotent: disarming an unarmed pull
    request is not an error.
    """
    ...

is_armed

is_armed(number: int) -> bool

Whether pull request number currently has a merge scheduled.

A pull request that left the open state reads unarmed, however it left it.

Source code in packages/forge/src/livery/forge/_protocol.py
def is_armed(self, number: int) -> bool:
    """Whether pull request *number* currently has a merge scheduled.

    A pull request that left the open state reads unarmed, however
    it left it.
    """
    ...

merge_hold

merge_hold(number: int) -> str

The forge's published mergeability state of number, verbatim.

GitLab's detailed_merge_status and GitHub's mergeable_state; empty on a forge that publishes none (Gitea says why in the merge refusal's prose instead). livery.forge.classify_merge_refusal reads it to classify a refusal on those forges. Raises livery.forge.ForgeError with status 404 when the pull request does not exist.

Source code in packages/forge/src/livery/forge/_protocol.py
def merge_hold(self, number: int) -> str:
    """The forge's published mergeability state of *number*, verbatim.

    GitLab's ``detailed_merge_status`` and GitHub's
    ``mergeable_state``; empty on a forge that publishes none
    (Gitea says why in the merge refusal's prose instead).
    [livery.forge.classify_merge_refusal][] reads it to classify a
    refusal on those forges. Raises livery.forge.ForgeError with
    status 404 when the pull request does not exist.
    """
    ...

reviews

reviews(number: int) -> tuple[Review, ...]

The submitted reviews on pull request number.

Only verdicts arrive (approved, changes requested, commented); drafts never do. Complete or raising, like every listing.

Source code in packages/forge/src/livery/forge/_protocol.py
def reviews(self, number: int) -> tuple[Review, ...]:
    """The submitted reviews on pull request *number*.

    Only verdicts arrive (approved, changes requested, commented);
    drafts never do. Complete or raising, like every listing.
    """
    ...

schedule_events

schedule_events(number: int) -> tuple[ScheduleEvent, ...]

The merge-scheduling history of pull request number.

Oldest first. The record that shows a created-then-lost schedule. Raises livery.forge.Unsupported on a forge without the schedule_events capability; ask livery.forge.Forge.supports first.

Source code in packages/forge/src/livery/forge/_protocol.py
def schedule_events(self, number: int) -> tuple[ScheduleEvent, ...]:
    """The merge-scheduling history of pull request *number*.

    Oldest first. The record that shows a created-then-lost
    schedule. Raises livery.forge.Unsupported on a forge without
    the ``schedule_events`` capability; ask
    livery.forge.Forge.supports first.
    """
    ...

comment

comment(number: int, body: str) -> None

Post body as a comment on pull request number.

The evidence channel: conflict reports and failure summaries that the pull request body cannot carry land here.

Source code in packages/forge/src/livery/forge/_protocol.py
def comment(self, number: int, body: str) -> None:
    """Post *body* as a comment on pull request *number*.

    The evidence channel: conflict reports and failure summaries
    that the pull request body cannot carry land here.
    """
    ...

add_labels

add_labels(number: int, names: tuple[str, ...]) -> None

Put the labels names on pull request number.

Adds to the labels the pull request carries; a name already on it stays, so a re-run is the recovery procedure. Every name must already be a label of the repository: one that is not raises livery.forge.ForgeError naming it, before anything is written, on every backend. Ensure the labels exist first with livery.forge.Repository.configure. A number that names no pull request raises livery.forge.ForgeError with status 404.

Source code in packages/forge/src/livery/forge/_protocol.py
def add_labels(self, number: int, names: tuple[str, ...]) -> None:
    """Put the labels *names* on pull request *number*.

    Adds to the labels the pull request carries; a name already on
    it stays, so a re-run is the recovery procedure. Every name must
    already be a label of the repository: one that is not raises
    [livery.forge.ForgeError][] naming it, before anything is
    written, on every backend. Ensure the labels exist first with
    [livery.forge.Repository.configure][]. A number that names no
    pull request raises [livery.forge.ForgeError][] with status
    404.
    """
    ...

Registry

Bases: Protocol

One package index, apart from the forge.

A forge and a registry are only sometimes the same server, so "which versions of this name are published" is its own one-method interface, with a backend per ecosystem.

Methods:

Name Description
versions

The published versions of package name, oldest first.

versions

versions(name: str) -> tuple[str, ...]

The published versions of package name, oldest first.

An unpublished name answers the empty tuple; an unreachable index raises livery.forge.ForgeError. The release train's "does the index see it yet" probe.

Source code in packages/forge/src/livery/forge/_protocol.py
def versions(self, name: str) -> tuple[str, ...]:
    """The published versions of package *name*, oldest first.

    An unpublished name answers the empty tuple; an unreachable
    index raises livery.forge.ForgeError. The release train's
    "does the index see it yet" probe.
    """
    ...

Releases

Bases: Protocol

One repository's releases, addressed by tag.

Methods:

Name Description
create

Create the release for tag and return it.

get

The release for tag, or None when the tag has none.

upload_asset

Attach data to tag's release as the file name; the asset.

assets

The files attached to tag's release, in the forge's order.

download_asset

The bytes of the asset name on tag's release.

create

create(tag: str, *, name: str, body: str = '', prerelease: bool = False) -> Release

Create the release for tag and return it.

Raises livery.forge.ForgeError when tag already has a release. A re-run therefore probes with livery.forge.Releases.get first and skips the create: that pair is the idempotent whole.

Source code in packages/forge/src/livery/forge/_protocol.py
def create(
    self, tag: str, *, name: str, body: str = "", prerelease: bool = False
) -> Release:
    """Create the release for *tag* and return it.

    Raises livery.forge.ForgeError when *tag* already has a
    release. A re-run therefore probes with
    livery.forge.Releases.get first and skips the create: that
    pair is the idempotent whole.
    """
    ...

get

get(tag: str) -> Release | None

The release for tag, or None when the tag has none.

The probe that makes release creation safe to re-run.

Source code in packages/forge/src/livery/forge/_protocol.py
def get(self, tag: str) -> Release | None:
    """The release for *tag*, or None when the tag has none.

    The probe that makes release creation safe to re-run.
    """
    ...

upload_asset

upload_asset(tag: str, name: str, data: bytes, *, content_type: str = 'application/octet-stream') -> Asset

Attach data to tag's release as the file name; the asset.

Raises livery.forge.ForgeError when tag has no release, or when the release already carries an asset named name. A re-run therefore probes with livery.forge.Releases.assets first and skips the upload: that pair is the idempotent whole.

Source code in packages/forge/src/livery/forge/_protocol.py
def upload_asset(
    self,
    tag: str,
    name: str,
    data: bytes,
    *,
    content_type: str = "application/octet-stream",
) -> Asset:
    """Attach *data* to *tag*'s release as the file *name*; the asset.

    Raises livery.forge.ForgeError when *tag* has no release, or
    when the release already carries an asset named *name*. A
    re-run therefore probes with livery.forge.Releases.assets
    first and skips the upload: that pair is the idempotent whole.
    """
    ...

assets

assets(tag: str) -> tuple[Asset, ...]

The files attached to tag's release, in the forge's order.

Raises livery.forge.ForgeError when tag has no release.

Source code in packages/forge/src/livery/forge/_protocol.py
def assets(self, tag: str) -> tuple[Asset, ...]:
    """The files attached to *tag*'s release, in the forge's order.

    Raises livery.forge.ForgeError when *tag* has no release.
    """
    ...

download_asset

download_asset(tag: str, name: str) -> bytes

The bytes of the asset name on tag's release.

The forge reads its own store: a private repository needs the lane's credential, and each forge addresses the bytes its own way, so a caller never builds the download URL itself.

Raises livery.forge.ForgeError when tag has no release or the release carries no asset named name.

Source code in packages/forge/src/livery/forge/_protocol.py
def download_asset(self, tag: str, name: str) -> bytes:
    """The bytes of the asset *name* on *tag*'s release.

    The forge reads its own store: a private repository needs the
    lane's credential, and each forge addresses the bytes its own
    way, so a caller never builds the download URL itself.

    Raises livery.forge.ForgeError when *tag* has no release or
    the release carries no asset named *name*.
    """
    ...

Repository

Bases: Protocol

One repository on one forge.

A cheap value bound to the owner and name, obtained from livery.forge.Forge.repository. The operation groups mirror the workflow vocabulary: pr.open, checks.status, issue.search, release.get.

Methods:

Name Description
ensure_pages

Enable the forge's static-site hosting for this repository.

rate_budget

The API budget the forge last reported to this view's client.

configure

Assert the repository settings config states.

tags

Every tag name on the repository, or every one starting with prefix.

branch_exists

Whether branch exists on the repository.

protection

The protection configured for branch, or None when none is.

web_url

The repository's home page address.

pr_url

The address of pull request number.

issue_url

The address of issue number.

commit_url

The address of commit sha.

compare_url

The address comparing base to head (refs or shas).

tag_url

The address of tag's release or tag view.

delete_branch

Delete branch from the repository.

Attributes:

Name Type Description
owner str

The user, organisation, or group path that owns the repository.

name str

The repository name within the owner.

pr PullRequests

The pull request operations.

checks Checks

The CI operations.

issue Issues

The issue operations.

release Releases

The release operations.

schedule Schedules

The pipeline schedule operations (capability pipeline_schedules).

owner property

owner: str

The user, organisation, or group path that owns the repository.

name property

name: str

The repository name within the owner.

pr property

The pull request operations.

checks property

checks: Checks

The CI operations.

issue property

issue: Issues

The issue operations.

release property

release: Releases

The release operations.

schedule property

schedule: Schedules

The pipeline schedule operations (capability pipeline_schedules).

ensure_pages

ensure_pages(*, build_type: str = 'workflow') -> None

Enable the forge's static-site hosting for this repository.

Idempotent: hosting already enabled with build_type is left alone, and a different build type is moved to it. Raises livery.forge.Unsupported where the forge has no Pages API to configure (capability pages_config).

Source code in packages/forge/src/livery/forge/_protocol.py
def ensure_pages(self, *, build_type: str = "workflow") -> None:
    """Enable the forge's static-site hosting for this repository.

    Idempotent: hosting already enabled with *build_type* is left
    alone, and a different build type is moved to it. Raises
    livery.forge.Unsupported where the forge has no Pages API to
    configure (capability ``pages_config``).
    """
    ...

rate_budget

rate_budget() -> RateBudget | None

The API budget the forge last reported to this view's client.

None before any response, and from a forge that reports none. A caller that polls reads it to space its requests out before the budget is spent, which ends every other caller's work with it.

Source code in packages/forge/src/livery/forge/_protocol.py
def rate_budget(self) -> RateBudget | None:
    """The API budget the forge last reported to this view's client.

    None before any response, and from a forge that reports none. A
    caller that polls reads it to space its requests out before the
    budget is spent, which ends every other caller's work with it.
    """
    ...

configure

configure(config: RepoConfig) -> None

Assert the repository settings config states.

Idempotent drift repair: fields left None are untouched, stated fields are made true whether or not they already were. Project birth and release aftercare run the same call.

Raises livery.forge.Unsupported when a stated field needs a capability the forge declines by name: required_contexts on GitLab, min_approvals on an unlicensed GitLab instance, ci_secrets on a GitHub install without the github-secrets extra. A decline can land after other stated fields already applied, so probe supports() first when that matters.

Source code in packages/forge/src/livery/forge/_protocol.py
def configure(self, config: RepoConfig) -> None:
    """Assert the repository settings *config* states.

    Idempotent drift repair: fields left None are untouched,
    stated fields are made true whether or not they already were.
    Project birth and release aftercare run the same call.

    Raises livery.forge.Unsupported when a stated field needs a
    capability the forge declines by name: ``required_contexts``
    on GitLab, ``min_approvals`` on an unlicensed GitLab
    instance, ``ci_secrets`` on a GitHub install without the
    ``github-secrets`` extra. A decline can land after other
    stated fields already applied, so probe ``supports()`` first
    when that matters.
    """
    ...

tags

tags(prefix: str = '') -> tuple[str, ...]

Every tag name on the repository, or every one starting with prefix.

Complete or raising, like every listing: release trains probe "does this tag exist" here, and a truncated answer would turn that probe into a guess. A prefix is matched by the forge, so a package's tags cost one query however many tags others have.

Source code in packages/forge/src/livery/forge/_protocol.py
def tags(self, prefix: str = "") -> tuple[str, ...]:
    """Every tag name on the repository, or every one starting with *prefix*.

    Complete or raising, like every listing: release trains probe
    "does this tag exist" here, and a truncated answer would turn
    that probe into a guess. A *prefix* is matched by the forge, so
    a package's tags cost one query however many tags others have.
    """
    ...

branch_exists

branch_exists(branch: str) -> bool

Whether branch exists on the repository.

Source code in packages/forge/src/livery/forge/_protocol.py
def branch_exists(self, branch: str) -> bool:
    """Whether *branch* exists on the repository."""
    ...

protection

protection(branch: str) -> Protection | None

The protection configured for branch, or None when none is.

The read side of livery.forge.RepoConfig, normalised per livery.forge.Protection: a flag the forge cannot express reads as its inert value. Reading protection may need an administrating token on some forges; a refusal raises livery.forge.ForgeError for the caller to degrade on.

Source code in packages/forge/src/livery/forge/_protocol.py
def protection(self, branch: str) -> Protection | None:
    """The protection configured for *branch*, or None when none is.

    The read side of livery.forge.RepoConfig, normalised per
    livery.forge.Protection: a flag the forge cannot express reads
    as its inert value. Reading protection may need an
    administrating token on some forges; a refusal raises
    livery.forge.ForgeError for the caller to degrade on.
    """
    ...

web_url

web_url() -> str

The repository's home page address.

Every *_url method builds strings from what the backend already knows; nothing goes on the wire, and the address is not probed for existence.

Source code in packages/forge/src/livery/forge/_protocol.py
def web_url(self) -> str:
    """The repository's home page address.

    Every ``*_url`` method builds strings from what the backend
    already knows; nothing goes on the wire, and the address is
    not probed for existence.
    """
    ...

pr_url

pr_url(number: int) -> str

The address of pull request number.

Source code in packages/forge/src/livery/forge/_protocol.py
def pr_url(self, number: int) -> str:
    """The address of pull request *number*."""
    ...

issue_url

issue_url(number: int) -> str

The address of issue number.

Source code in packages/forge/src/livery/forge/_protocol.py
def issue_url(self, number: int) -> str:
    """The address of issue *number*."""
    ...

commit_url

commit_url(sha: str) -> str

The address of commit sha.

Source code in packages/forge/src/livery/forge/_protocol.py
def commit_url(self, sha: str) -> str:
    """The address of commit *sha*."""
    ...

compare_url

compare_url(base: str, head: str) -> str

The address comparing base to head (refs or shas).

Source code in packages/forge/src/livery/forge/_protocol.py
def compare_url(self, base: str, head: str) -> str:
    """The address comparing *base* to *head* (refs or shas)."""
    ...

tag_url

tag_url(tag: str) -> str

The address of tag's release or tag view.

Source code in packages/forge/src/livery/forge/_protocol.py
def tag_url(self, tag: str) -> str:
    """The address of *tag*'s release or tag view."""
    ...

delete_branch

delete_branch(branch: str) -> None

Delete branch from the repository.

Idempotent: a branch already gone is success, not an error. The abort path's cleanup; merge-path deletion is repository configuration (delete_branch_on_merge), not this call.

Source code in packages/forge/src/livery/forge/_protocol.py
def delete_branch(self, branch: str) -> None:
    """Delete *branch* from the repository.

    Idempotent: a branch already gone is success, not an error.
    The abort path's cleanup; merge-path deletion is repository
    configuration (``delete_branch_on_merge``), not this call.
    """
    ...

Schedules

Bases: Protocol

One repository's pipeline schedules, addressed by description.

The clock for a forge that keeps it outside the workflow file (capability pipeline_schedules). A forge whose clock is in the file raises livery.forge.Unsupported naming the capability from every method.

Methods:

Name Description
list

Every schedule of the repository, with its variables.

ensure

Make the schedule described description say ref, cron and variables.

delete

Delete the schedule described description; False when there is none.

list

list() -> tuple[Schedule, ...]

Every schedule of the repository, with its variables.

Source code in packages/forge/src/livery/forge/_protocol.py
def list(self) -> tuple[Schedule, ...]:
    """Every schedule of the repository, with its variables."""
    ...

ensure

ensure(description: str, *, ref: str, cron: str, variables: Mapping[str, str] | None = None) -> Schedule

Make the schedule described description say ref, cron and variables.

Idempotent: a schedule with that description is updated in place, none is created, and the schedule as the forge now holds it comes back. Variables named are set; variables the schedule has that variables does not name are left as they are.

Source code in packages/forge/src/livery/forge/_protocol.py
def ensure(
    self,
    description: str,
    *,
    ref: str,
    cron: str,
    variables: Mapping[str, str] | None = None,
) -> Schedule:
    """Make the schedule described *description* say *ref*, *cron* and *variables*.

    Idempotent: a schedule with that description is updated in
    place, none is created, and the schedule as the forge now
    holds it comes back. Variables named are set; variables the
    schedule has that *variables* does not name are left as
    they are.
    """
    ...

delete

delete(description: str) -> bool

Delete the schedule described description; False when there is none.

Source code in packages/forge/src/livery/forge/_protocol.py
def delete(self, description: str) -> bool:
    """Delete the schedule described *description*; False when there is none."""
    ...

SimpleRegistry

SimpleRegistry(base: str, *, token: str = '', username: str = '')

A simple-API index, addressed by its simple root.

Parameters:

Name Type Description Default
base str

The index's simple root (https://pypi.org/simple, or a forge registry's equivalent), with or without a trailing slash.

required
token str

Sent as HTTP basic auth when the index needs it; empty reads anonymously. Basic covers the union: a forge registry takes its account name and token, and an API-token index takes __token__ as the user.

''
username str

The basic-auth user beside token; __token__ when empty, which is what an API-token index expects. Meaningless without a token.

''

Methods:

Name Description
versions

The published versions of name, oldest first.

Source code in packages/forge/src/livery/forge/_registry.py
def __init__(self, base: str, *, token: str = "", username: str = "") -> None:
    self._base = base.rstrip("/")
    self._token = token
    self._username = username

versions

versions(name: str) -> tuple[str, ...]

The published versions of name, oldest first.

An unpublished name answers the empty tuple (the index's 404 is that answer, not an error); an unreachable index raises livery.forge.ForgeError with the reason, and so does an index whose answer is neither PEP 691 JSON nor PEP 503 HTML.

Source code in packages/forge/src/livery/forge/_registry.py
def versions(self, name: str) -> tuple[str, ...]:
    """The published versions of *name*, oldest first.

    An unpublished name answers the empty tuple (the index's 404
    is that answer, not an error); an unreachable index raises
    livery.forge.ForgeError with the reason, and so does an index
    whose answer is neither PEP 691 JSON nor PEP 503 HTML.
    """
    canonical = name.replace("_", "-").lower()
    if self._token:
        pair = f"{self._username or '__token__'}:{self._token}".encode()
        authorization = {
            "Authorization": f"Basic {base64.b64encode(pair).decode()}"
        }
    else:
        authorization = {}
    request = urllib.request.Request(
        f"{self._base}/{canonical}/",
        headers={
            # HTML is the fallback, declared so an index honouring
            # content negotiation still answers JSON first.
            "Accept": "application/vnd.pypi.simple.v1+json, text/html;q=0.1",
            **authorization,
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as answer:
            body = answer.read()
    except urllib.error.HTTPError as exc:
        if exc.code == 404:
            return ()
        raise ForgeError(
            f"the index refused {canonical}: HTTP {exc.code}",
            status=exc.code,
        ) from exc
    except (urllib.error.URLError, TimeoutError) as exc:
        raise ForgeError(
            f"the index at {self._base} is unreachable: {exc}"
        ) from exc
    text = body.decode("utf-8", errors="replace")
    try:
        payload = json.loads(text)
    except json.JSONDecodeError:
        found = _versions_from_html(text, canonical)
        if found or "<a" in text.lower() or "<html" in text.lower():
            return found
        raise ForgeError(
            f"the index at {self._base} answered neither PEP 691"
            f" JSON nor PEP 503 HTML for {canonical}"
        ) from None
    return tuple(str(v) for v in payload.get("versions") or [])

Asset dataclass

Asset(name: str, url: str, size: int = 0, digest: str = '')

One file attached to a release.

Attributes:

Name Type Description
name str

The file name, unique within the release.

url str

Where the bytes download from, for a reader with access to the repository.

size int

The byte count the forge reports; 0 when it reports none.

digest str

The content digest the forge reports, "<algorithm>:<hex>"; empty when it reports none. A consumer that stages the bytes elsewhere verifies against it, and treats an empty digest as a forge that cannot prove the content.

name instance-attribute

name: str

url instance-attribute

url: str

size class-attribute instance-attribute

size: int = 0

digest class-attribute instance-attribute

digest: str = ''

Codeowners dataclass

Codeowners(path: str, content: str, notes: tuple[str, ...] = ())

A rendered codeowners file: where it lives and what it says.

Attributes:

Name Type Description
path str

The forge's canonical location for the file, relative to the repository root.

content str

The file's text in the forge's syntax.

notes tuple[str, ...]

What the rendering approximated rather than expressed, one sentence each; empty when everything was expressed.

path instance-attribute

path: str

content instance-attribute

content: str

notes class-attribute instance-attribute

notes: tuple[str, ...] = ()

CodeownersEntry dataclass

CodeownersEntry(path: str, owners: tuple[str, ...], min_approvals: int = 0)

One neutral ownership declaration a codeowners file expresses.

Attributes:

Name Type Description
path str

The repository path the owners review (a directory or glob, forge-neutral, / separators).

owners tuple[str, ...]

User logins and team names, without any @ sigil; the backend adds its forge's spelling.

min_approvals int

Approvals this path needs. Only GitLab's sections express a per-path count in the file itself; the other forges approximate through protection and say so in the rendering's notes.

path instance-attribute

path: str

owners instance-attribute

owners: tuple[str, ...]

min_approvals class-attribute instance-attribute

min_approvals: int = 0

CombinedStatus dataclass

CombinedStatus(state: CheckState, contexts: int)

The one CI answer for a commit, whatever the forge calls it underneath.

GitHub folds check runs and commit statuses into it, Gitea aggregates commit statuses, GitLab reports the commit's latest pipeline. The caller sees one verdict either way.

Attributes:

Name Type Description
state CheckState

The combined verdict. none when nothing has reported for the commit, which is not pending: see livery.forge.CheckState.

contexts int

How many checks the verdict aggregates. Zero exactly when state is none.

state instance-attribute

state: CheckState

contexts instance-attribute

contexts: int

Comment dataclass

Comment(author: str, created_at: str, body: str)

One comment on an issue's thread.

Attributes:

Name Type Description
author str

The login of who wrote it, the same namespace as livery.forge.Forge.whoami.

created_at str

When it was posted, as the forge reports it; empty when the forge does not say.

body str

The comment text, in full.

author instance-attribute

author: str

created_at instance-attribute

created_at: str

body instance-attribute

body: str

Issue dataclass

Issue(number: int, title: str, body: str, state: ItemState, labels: tuple[str, ...] = (), assignees: tuple[str, ...] = (), url: str = '')

One issue, body included.

Attributes:

Name Type Description
number int

The number a person sees in the forge's own UI. On GitLab this is the issue iid, never the global id.

title str

The issue title.

body str

The issue text, in full. The body is the work order for issue-driven workflows, so it is always carried, never truncated.

state ItemState

open or closed.

labels tuple[str, ...]

The label names on the issue.

assignees tuple[str, ...]

The login names assigned to the issue.

url str

The issue's page, for printing to a person.

number instance-attribute

number: int

title instance-attribute

title: str

body instance-attribute

body: str

state instance-attribute

state: ItemState

labels class-attribute instance-attribute

labels: tuple[str, ...] = ()

assignees class-attribute instance-attribute

assignees: tuple[str, ...] = ()

url class-attribute instance-attribute

url: str = ''

Job dataclass

Job(id: int, name: str, status: RunStatus, conclusion: Conclusion, started_at: str = '', completed_at: str = '', steps: tuple[Step, ...] = ())

One job of a run.

Attributes:

Name Type Description
id int

The identifier livery.forge.Checks.job_log takes.

name str

The job name as the workflow declares it.

status RunStatus

Where the job is in its life.

conclusion Conclusion

How the job ended. Empty until status is completed.

started_at str

When the job started on a runner, ISO 8601. Empty until it has, or when the forge did not say.

completed_at str

When it ended, the same way.

steps tuple[Step, ...]

The job's steps with their times, in order; empty on a forge that serves none.

id instance-attribute

id: int

name instance-attribute

name: str

status instance-attribute

status: RunStatus

conclusion instance-attribute

conclusion: Conclusion

started_at class-attribute instance-attribute

started_at: str = ''

completed_at class-attribute instance-attribute

completed_at: str = ''

steps class-attribute instance-attribute

steps: tuple[Step, ...] = ()

Label dataclass

Label(name: str, color: str, description: str = '')

One issue label, spoken by name everywhere.

The protocol never exposes label ids: backends that key labels by id resolve the name at the boundary.

Attributes:

Name Type Description
name str

The label text, unique within the repository.

color str

Six hex digits, no leading #.

description str

One line saying when the label applies.

name instance-attribute

name: str

color instance-attribute

color: str

description class-attribute instance-attribute

description: str = ''

Protection dataclass

Protection(required_approvals: int = 0, require_codeowner_review: bool | None = None, block_on_outdated: bool = False, block_on_rejected: bool = False, required_contexts: tuple[str, ...] = ())

The branch protection a forge reports for one branch.

The read side of livery.forge.RepoConfig, normalised and honest: a field a forge cannot express reads as its inert value, so a caller gating on a flag never invents a blocker the forge would not enforce.

Attributes:

Name Type Description
required_approvals int

Approving reviews the merge requires; 0 when none.

require_codeowner_review bool | None

True when a codeowner's approval is required; None when the forge cannot say.

block_on_outdated bool

True when a head behind its base may not merge.

block_on_rejected bool

True when a requested-changes review blocks the merge.

required_contexts tuple[str, ...]

The check contexts protection requires.

required_approvals class-attribute instance-attribute

required_approvals: int = 0

require_codeowner_review class-attribute instance-attribute

require_codeowner_review: bool | None = None

block_on_outdated class-attribute instance-attribute

block_on_outdated: bool = False

block_on_rejected class-attribute instance-attribute

block_on_rejected: bool = False

required_contexts class-attribute instance-attribute

required_contexts: tuple[str, ...] = ()

PullRequest dataclass

PullRequest(number: int, title: str, body: str, state: ItemState, merged: bool, head_branch: str, head_sha: str, base_branch: str, url: str = '', author: str = '', merged_sha: str = '', labels: tuple[str, ...] = ())

One pull request, as the forge reports it.

Attributes:

Name Type Description
number int

The number a person sees in the forge's own UI. On GitLab this is the merge request iid, never the global id.

title str

The pull request title.

body str

The pull request description, in full.

state ItemState

open or closed. A merged pull request is closed with merged True.

merged bool

True when the pull request has merged.

head_branch str

The branch the pull request proposes. May be empty on a merged pull request whose head branch was deleted; find a merged pull request by livery.forge.PullRequests.find_by_head_sha instead.

head_sha str

The head commit. Persists after the branch is gone.

base_branch str

The branch the pull request targets.

url str

The pull request's page, for printing to a person.

author str

The login of whoever opened it; empty when the forge does not say. Compare with livery.forge.Forge.whoami, the same namespace.

merged_sha str

The commit the merge produced, empty until it has merged. On a squash-only repository this is the squash, and it is the only way to follow a pull request into what ran on the base afterwards: the base's own runs are filed under this commit, and nothing on the pull request itself names it.

labels tuple[str, ...]

The label names on the pull request, as livery.forge.PullRequests.add_labels sets them and a person sets them on the forge.

number instance-attribute

number: int

title instance-attribute

title: str

body instance-attribute

body: str

state instance-attribute

state: ItemState

merged instance-attribute

merged: bool

head_branch instance-attribute

head_branch: str

head_sha instance-attribute

head_sha: str

base_branch instance-attribute

base_branch: str

url class-attribute instance-attribute

url: str = ''

author class-attribute instance-attribute

author: str = ''

merged_sha class-attribute instance-attribute

merged_sha: str = ''

labels class-attribute instance-attribute

labels: tuple[str, ...] = ()

RateBudget dataclass

RateBudget(remaining: int, limit: int, reset_at: float | None = None)

The API budget a forge reports on its responses.

Attributes:

Name Type Description
remaining int

The requests left in the current window.

limit int

The requests the window allows.

reset_at float | None

When the window renews, as seconds since the epoch; None when the forge does not say.

remaining instance-attribute

remaining: int

limit instance-attribute

limit: int

reset_at class-attribute instance-attribute

reset_at: float | None = None

Release dataclass

Release(tag: str, name: str, body: str, prerelease: bool = False, url: str = '', id: int = 0)

One release, addressed by its tag.

Attributes:

Name Type Description
tag str

The tag the release describes. The tag is the identity; the release is its prose.

name str

The display name.

body str

The release notes, in full.

prerelease bool

True when the release is marked as a prerelease.

url str

The release's page, for printing to a person.

id int

The forge's own number for the release, for the calls that address a release by it (an asset upload); 0 on a forge that addresses releases by tag alone.

tag instance-attribute

tag: str

name instance-attribute

name: str

body instance-attribute

body: str

prerelease class-attribute instance-attribute

prerelease: bool = False

url class-attribute instance-attribute

url: str = ''

id class-attribute instance-attribute

id: int = 0

RepoConfig dataclass

RepoConfig(default_branch: str | None = None, squash_only: bool | None = None, delete_branch_on_merge: bool | None = None, allow_auto_merge: bool | None = None, required_contexts: tuple[str, ...] | None = None, protected_tag_patterns: tuple[str, ...] | None = None, require_pipeline_success: bool | None = None, min_approvals: int | None = None, require_codeowner_review: bool | None = None, secrets: Mapping[str, str] | None = None, variables: Mapping[str, str] | None = None, labels: tuple[Label, ...] | None = None)

The desired repository settings livery.forge.Repository.configure asserts.

Every field defaults to None, which means "leave this setting as it is". Configure applies only the fields a caller states, so one config value can repair one drifted setting without touching the rest.

Attributes:

Name Type Description
default_branch str | None

The branch pull requests target by default.

squash_only bool | None

True allows only squash merges.

delete_branch_on_merge bool | None

True deletes a pull request's head branch when it merges.

allow_auto_merge bool | None

True lets a merge be scheduled to fire when the checks go green.

required_contexts tuple[str, ...] | None

The check contexts the default branch's protection requires before a merge. Setting this on a forge without the required_contexts capability raises livery.forge.Unsupported.

require_pipeline_success bool | None

True makes the server refuse merges while the head's checks are not green, for everyone, the forge's own UI included. GitHub and Gitea already enforce exactly this through required_contexts and ignore the field; GitLab maps it to its merge-only-when-the-pipeline-succeeds switch, the one server-side block its protection offers. On a repository with several pipeline sources that switch blocks on any red pipeline, which is as precise as GitLab's data gets.

min_approvals int | None

Approving reviews the default branch's protection requires before a merge. Applied with admins bound: protection that exempts admins is a bypass nobody reviewed, so configure never leaves one open. Needs the min_approvals capability.

require_codeowner_review bool | None

True also requires an approval from a codeowner of the touched paths. Rides the same capability. Gitea has no codeowner toggle and substitutes blocking on official review requests, which the codeowners file feeds; the read side answers through the same field.

protected_tag_patterns tuple[str, ...] | None

Tag name patterns (glob) whose tags, once created, cannot be deleted or re-pointed by an ordinary push. Who may create them follows each forge's nearest model: GitLab restricts creation to maintainers and blocks push-deletion for everyone (the web interface with a deliberate unprotect is the only way); GitHub leaves creation open and blocks deletion and movement through a tag ruleset; Gitea ties creation, deletion, and movement to one whitelist holding the configuring identity, so its protection binds everyone outside that lane rather than the lane itself. Patterns already protected are left as they are.

secrets Mapping[str, str] | None

CI secrets to store, by name. Write-only: no protocol operation reads a secret back. Setting this on a forge without the ci_secrets capability raises livery.forge.Unsupported.

variables Mapping[str, str] | None

Plain CI variables to store, by name.

labels tuple[Label, ...] | None

The labels the repository must offer. Labels already present keep their issues; labels absent from this tuple are left alone, never deleted.

default_branch class-attribute instance-attribute

default_branch: str | None = None

squash_only class-attribute instance-attribute

squash_only: bool | None = None

delete_branch_on_merge class-attribute instance-attribute

delete_branch_on_merge: bool | None = None

allow_auto_merge class-attribute instance-attribute

allow_auto_merge: bool | None = None

required_contexts class-attribute instance-attribute

required_contexts: tuple[str, ...] | None = None

protected_tag_patterns class-attribute instance-attribute

protected_tag_patterns: tuple[str, ...] | None = None

require_pipeline_success class-attribute instance-attribute

require_pipeline_success: bool | None = None

min_approvals class-attribute instance-attribute

min_approvals: int | None = None

require_codeowner_review class-attribute instance-attribute

require_codeowner_review: bool | None = None

secrets class-attribute instance-attribute

secrets: Mapping[str, str] | None = None

variables class-attribute instance-attribute

variables: Mapping[str, str] | None = None

labels class-attribute instance-attribute

labels: tuple[Label, ...] | None = None

RepoInfo dataclass

RepoInfo(owner: str, name: str, default_branch: str, private: bool)

What livery.forge.Forge.get_repo reports about an existing repository.

Attributes:

Name Type Description
owner str

The user, organisation, or group path that owns the repository.

name str

The repository name within the owner.

default_branch str

The branch pull requests target by default.

private bool

True when the repository is not publicly visible.

owner instance-attribute

owner: str

name instance-attribute

name: str

default_branch instance-attribute

default_branch: str

private instance-attribute

private: bool

Review dataclass

Review(author: str, state: ReviewState)

One submitted pull request review.

Attributes:

Name Type Description
author str

The login of the reviewer, the same namespace as livery.forge.Forge.whoami.

state ReviewState

The verdict, per livery.forge.ReviewState.

author instance-attribute

author: str

state instance-attribute

state: ReviewState

Run dataclass

Run(id: int, workflow: str, head_sha: str, event: str, status: RunStatus, conclusion: Conclusion, url: str = '', created_at: str = '', started_at: str = '', completed_at: str = '', ref: str = '')

One CI run: a workflow run on GitHub or Gitea, a pipeline on GitLab.

Attributes:

Name Type Description
id int

The identifier every livery.forge.Checks method takes. Backends that also number runs per repository translate; the protocol speaks one handle.

workflow str

The workflow that ran, as the forge names it. A workflow file name on GitHub and Gitea; on GitLab, which has one pipeline definition per repository, the pipeline's name, which a document sets from $FORGE_WORKFLOW so a dispatched pipeline carries the workflow asked for, and empty for a pipeline the document does not name.

head_sha str

The commit the run checked.

event str

What triggered the run, in the forge's own vocabulary.

status RunStatus

Where the run is in its life.

conclusion Conclusion

How the run ended. Empty until status is completed.

url str

The run's page, for printing to a person.

created_at str

When the forge accepted the run, ISO 8601; the queue wait starts here. Empty when the forge did not say.

started_at str

When the first job started, the same way. GitLab's pipeline listing does not carry it.

completed_at str

When the run ended, the same way. GitHub reports no end for a run; its last update stands in once the run is complete.

ref str

The branch or tag the run checked out, by its short name (main, v1.2.0): the head branch GitHub and Gitea name, the ref GitLab names. A caller that dispatched a workflow on a ref tells its run from another ref's by this. Empty when the forge did not say.

id instance-attribute

id: int

workflow instance-attribute

workflow: str

head_sha instance-attribute

head_sha: str

event instance-attribute

event: str

status instance-attribute

status: RunStatus

conclusion instance-attribute

conclusion: Conclusion

url class-attribute instance-attribute

url: str = ''

created_at class-attribute instance-attribute

created_at: str = ''

started_at class-attribute instance-attribute

started_at: str = ''

completed_at class-attribute instance-attribute

completed_at: str = ''

ref class-attribute instance-attribute

ref: str = ''

Schedule dataclass

Schedule(id: int, description: str, ref: str, cron: str, active: bool = True, variables: tuple[tuple[str, str], ...] = ())

One pipeline schedule: the forge's clock for a workflow the file cannot time.

Attributes:

Name Type Description
id int

The forge's identifier of the schedule.

description str

The name a caller addresses it by; unique per repository as livery.forge.Schedules keeps it.

ref str

The branch the scheduled pipeline runs on.

cron str

When it runs, in cron's five fields, UTC.

active bool

Whether the clock is on.

variables tuple[tuple[str, str], ...]

The variables each scheduled pipeline starts with, as (key, value) pairs in the forge's order.

id instance-attribute

id: int

description instance-attribute

description: str

ref instance-attribute

ref: str

cron instance-attribute

cron: str

active class-attribute instance-attribute

active: bool = True

variables class-attribute instance-attribute

variables: tuple[tuple[str, str], ...] = ()

ScheduleEvent dataclass

ScheduleEvent(kind: ScheduleEventKind, actor: str = '', created: str = '')

One event in a pull request's merge-scheduling history.

The record that shows a created-then-lost schedule, which no current-state read can. Available only where the forge keeps the history (the schedule_events capability).

Attributes:

Name Type Description
kind ScheduleEventKind

What happened, per livery.forge.ScheduleEventKind.

actor str

The login that caused it; empty when the forge does not say.

created str

When it happened, the forge's own timestamp string.

kind instance-attribute

actor class-attribute instance-attribute

actor: str = ''

created class-attribute instance-attribute

created: str = ''

Step dataclass

Step(name: str, conclusion: Conclusion, started_at: str = '', completed_at: str = '')

One step of a job, as the forge times it.

GitHub and Gitea time every step, the runner's own setup and teardown included; GitLab runs a job as one script and serves no steps.

Attributes:

Name Type Description
name str

The step's name as the workflow spells it, or the runner's name for a step it adds itself.

conclusion Conclusion

How the step ended. Empty while it runs.

started_at str

When it started, ISO 8601. Empty when the forge did not say.

completed_at str

When it ended, the same way.

name instance-attribute

name: str

conclusion instance-attribute

conclusion: Conclusion

started_at class-attribute instance-attribute

started_at: str = ''

completed_at class-attribute instance-attribute

completed_at: str = ''

gitea_configured_host

gitea_configured_host() -> str

The host GITEA_TOKEN belongs to, from GITEA_URL, lowercased.

Empty when no server is configured. Never a checkout's remote: the point is to have something to compare a remote against.

Source code in packages/forge/src/livery/forge/_gitea.py
def gitea_configured_host() -> str:
    """The host ``GITEA_TOKEN`` belongs to, from ``GITEA_URL``, lowercased.

    Empty when no server is configured. Never a checkout's remote: the
    point is to have something to compare a remote against.
    """
    url = os.environ.get("GITEA_URL", "")
    return url.split("://", 1)[-1].strip("/").lower()

gitea_is_configured_host

gitea_is_configured_host(host: str) -> bool

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

Apply this before constructing a client for a host taken from a checkout's remote; a foreign host is read with token="" rather than sent a token it never issued.

Source code in packages/forge/src/livery/forge/_gitea.py
def gitea_is_configured_host(host: str) -> bool:
    """Whether *host* is the server this environment holds a token for.

    Apply this before constructing a client for a host taken from a
    checkout's remote; a foreign host is read with ``token=""`` rather
    than sent a token it never issued.
    """
    return bool(host) and host.lower() == gitea_configured_host()

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()

classify_gitea_merge_refusal

classify_gitea_merge_refusal(native: str, *, combined: CombinedStatus, item_state: ItemState, merged: bool) -> MergeState

Gitea's 405 prose as a merge state; the inputs disambiguate.

Gitea has no state field, so the message plus the checks API decide. "Please try again later" is the mergeability recompute. "Not all required status checks successful" is three states in one sentence: red checks, checks still running, or the beat where the protection view trails a green run; the combined status tells them apart. A caller entering contexts-settling should first verify every required context has a reporter, because a context nothing reports never settles (contexts-misreported); that cross-check needs the caller's knowledge of reported context names.

Source code in packages/forge/src/livery/forge/_merge_state.py
def classify_gitea_merge_refusal(
    native: str,
    *,
    combined: CombinedStatus,
    item_state: ItemState,
    merged: bool,
) -> MergeState:
    """Gitea's 405 prose as a merge state; the inputs disambiguate.

    Gitea has no state field, so the message plus the checks API
    decide. "Please try again later" is the mergeability recompute.
    "Not all required status checks successful" is three states in
    one sentence: red checks, checks still running, or the beat
    where the protection view trails a green run; the combined
    status tells them apart. A caller entering ``contexts-settling``
    should first verify every required context has a reporter,
    because a context nothing reports never settles
    (``contexts-misreported``); that cross-check needs the caller's
    knowledge of reported context names.
    """
    if merged:
        return merge_state("merged", native)
    if item_state == "closed":
        return merge_state("closed", native)
    lowered = native.lower()
    if "try again later" in lowered:
        return merge_state("computing", native)
    if "status checks" in lowered:
        if combined.state == "failure":
            return merge_state("checks-red", native)
        if combined.state in ("pending", "none"):
            return merge_state("ci-running", native)
        return merge_state("contexts-settling", native)
    if "work in progress" in lowered:
        return merge_state("draft", native)
    if "approv" in lowered:
        return merge_state("approvals-missing", native)
    if "review" in lowered and "reject" in lowered:
        return merge_state("changes-requested", native)
    if "behind" in lowered or "out-of-date" in lowered:
        return merge_state("behind", native)
    if "conflict" in lowered:
        return merge_state("conflict", native)
    if "merge style" in lowered or "merge method" in lowered:
        return merge_state("merge-method-not-allowed", native)
    raise _unmapped("gitea", native)

classify_github_mergeable_state

classify_github_mergeable_state(value: str, *, item_state: ItemState = 'open', merged: bool = False) -> MergeState

GitHub's mergeable_state value as a merge state.

blocked folds required checks and missing approvals together, which is as fine as GitHub's own data gets on this path; the message stays the checks one, and the native value rides along for the person reading.

Source code in packages/forge/src/livery/forge/_merge_state.py
def classify_github_mergeable_state(
    value: str, *, item_state: ItemState = "open", merged: bool = False
) -> MergeState:
    """GitHub's ``mergeable_state`` value as a merge state.

    ``blocked`` folds required checks and missing approvals
    together, which is as fine as GitHub's own data gets on this
    path; the message stays the checks one, and the native value
    rides along for the person reading.
    """
    if item_state == "closed":
        return merge_state("merged" if merged else "closed", value)
    mapped = _GITHUB_MERGEABLE_STATE.get(value)
    if mapped is None:
        raise _unmapped("github", value)
    return merge_state(mapped, value)

classify_gitlab_detailed_status

classify_gitlab_detailed_status(value: str, *, item_state: ItemState = 'open', merged: bool = False) -> MergeState

GitLab's detailed_merge_status value as a merge state.

mergeable never reaches here: it is the go, not a hold. not_open splits by the merged flag.

Source code in packages/forge/src/livery/forge/_merge_state.py
def classify_gitlab_detailed_status(
    value: str, *, item_state: ItemState = "open", merged: bool = False
) -> MergeState:
    """GitLab's ``detailed_merge_status`` value as a merge state.

    ``mergeable`` never reaches here: it is the go, not a hold.
    ``not_open`` splits by the merged flag.
    """
    if value == "not_open":
        return merge_state("merged" if merged else "closed", value)
    mapped = _GITLAB_DETAILED.get(value)
    if mapped is None:
        raise _unmapped("gitlab", value)
    return merge_state(mapped, value)

classify_merge_refusal

classify_merge_refusal(kind: str, native: str, *, combined: CombinedStatus, item_state: ItemState, merged: bool, hold: str = '') -> MergeState

Classify a merge-endpoint refusal by the forge kind.

The identity states resolve first on every forge: a merged pull request is success whatever the words, a closed one terminal. Gitea's prose classifier handles gitea and the empty kind (the fake speaks Gitea's words). GitLab and GitHub classify hold, their published state field read after the refusal through livery.forge.PullRequests.merge_hold; a refusal while that field already reads as the go (mergeable, clean) is the recompute the refusal raced, and follows through as computing. An empty hold on those forges is unmapped: nothing waits on a state the forge did not publish.

Source code in packages/forge/src/livery/forge/_merge_state.py
def classify_merge_refusal(
    kind: str,
    native: str,
    *,
    combined: CombinedStatus,
    item_state: ItemState,
    merged: bool,
    hold: str = "",
) -> MergeState:
    """Classify a merge-endpoint refusal by the forge *kind*.

    The identity states resolve first on every forge: a merged pull
    request is success whatever the words, a closed one terminal.
    Gitea's prose classifier handles ``gitea`` and the empty kind
    (the fake speaks Gitea's words). GitLab and GitHub classify
    *hold*, their published state field read after the refusal
    through [livery.forge.PullRequests.merge_hold][]; a refusal
    while that field already reads as the go (``mergeable``,
    ``clean``) is the recompute the refusal raced, and follows
    through as ``computing``. An empty *hold* on those forges is
    unmapped: nothing waits on a state the forge did not publish.
    """
    if merged:
        return merge_state("merged", native)
    if item_state == "closed":
        return merge_state("closed", native)
    if kind in ("gitea", ""):
        return classify_gitea_merge_refusal(
            native, combined=combined, item_state=item_state, merged=merged
        )
    if kind == "gitlab" and hold:
        if hold == "mergeable":
            return merge_state("computing", native)
        classified = classify_gitlab_detailed_status(
            hold, item_state=item_state, merged=merged
        )
        return MergeState(
            classified.state, classified.category, classified.message, native
        )
    if kind == "github" and hold:
        if hold == "clean":
            return merge_state("computing", native)
        classified = classify_github_mergeable_state(
            hold, item_state=item_state, merged=merged
        )
        return MergeState(
            classified.state, classified.category, classified.message, native
        )
    raise _unmapped(kind, native)

merge_state

merge_state(state: str, native: str = '') -> MergeState

The vocabulary member state, carrying native verbatim.

Source code in packages/forge/src/livery/forge/_merge_state.py
def merge_state(state: str, native: str = "") -> MergeState:
    """The vocabulary member *state*, carrying *native* verbatim."""
    category, message = MERGE_STATES[state]
    return MergeState(state=state, category=category, message=message, native=native)

__getattr__

__getattr__(name: str) -> object

Serve a public name from its module on first use, then keep it.

Source code in packages/forge/src/livery/forge/__init__.py
def __getattr__(name: str) -> object:
    """Serve a public name from its module on first use, then keep it."""
    import importlib

    if name in _PACKAGES:
        value: object = importlib.import_module(f"livery.forge.{name}")
    else:
        module = _EXPORTS.get(name)
        if module is None:
            raise AttributeError(f"module 'livery.forge' has no attribute {name!r}")
        value = getattr(importlib.import_module(module), name)
    globals()[name] = value
    return value