Skip to content

livery.forge._github

livery.forge._github

The GitHub backend: livery.forge.Forge over REST v3 plus one GraphQL pair.

REST carries everything except auto-merge, which GitHub exposes only as the GraphQL mutations enablePullRequestAutoMerge and disablePullRequestAutoMerge.

Construction and the token rule: livery.forge.GithubForge.connect resolves the server once (github.com unless a GitHub Enterprise URL is given) and the token as GITHUB_TOKEN first, then gh auth token, so a machine with a signed-in gh CLI needs no configuration. The token belongs to the resolved host and no other.

Capabilities: auto_merge, force_cancel, required_contexts, schedule_events, and min_approvals are supported. ci_secrets depends on the github-secrets extra: the secrets API demands sealed-box encryption (libsodium), which PyNaCl provides and the standard library cannot, so livery-forge[github-secrets] turns the capability on and a bare install declines it by name. The import is lazy; nothing outside the secrets path ever loads it.

Classes:

Name Description
GithubForge

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

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