Skip to content

livery.forge._gitea

livery.forge._gitea

The Gitea backend: livery.forge.Forge over Gitea's REST v1 API.

Server floor: the 1.28 line, the first with workflow-run cancellation. Every other operation works on earlier servers; livery.forge.Checks.cancel_run probes the version once and raises livery.forge.Unsupported naming it when the server predates the endpoint.

Construction and the token rule: livery.forge.GiteaForge.connect resolves the server once, an explicit url beating the configured GITEA_URL, and reads GITEA_TOKEN unless a token is passed. The token belongs to the configured host and no other: livery.forge.gitea_is_configured_host is the test to apply before constructing a client for a checkout's remote, and a foreign host is read anonymously (token="") instead of being sent a token it never issued.

Classes:

Name Description
GiteaForge

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

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.

Attributes:

Name Type Description
CANCEL_FLOOR

CANCEL_FLOOR module-attribute

CANCEL_FLOOR = (1, 28)

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

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