Skip to content

livery.workshop._ci_context

livery.workshop._ci_context

The CI run this process belongs to, and the state store built with its policy.

The run context reads the runner's environment: GitHub's and Gitea's GITHUB_* variables, GitLab's CI_*. livery.workshop.state_store builds the livery.git.StateStore every verb reads and writes the workshop's series through, with the three answers the store takes as construction data: whether this is a CI run, the identity every commit carries, and the variable a published listing travels in.

Classes:

Name Description
RunContext

The CI run this process belongs to, as the runner's environment names it.

Functions:

Name Description
state_store

Open the state store of the checkout at root, with the workshop's policy.

event_payload

The runner's event payload, or None when there is none to read.

dispatch_inputs

The dispatch inputs names, as the run received them; "" for one it did not.

run_context

The CI run this process runs in, or None outside CI.

ci_run

The CI run this process belongs to, or None at a desk.

Attributes:

Name Type Description
LEG_VARIABLE
POINT_VARIABLE
SNAPSHOT_VARIABLE
GITLAB_EVENTS

LEG_VARIABLE module-attribute

LEG_VARIABLE = 'WORKSHOP_LEG'

POINT_VARIABLE module-attribute

POINT_VARIABLE = 'WORKSHOP_POINT'

SNAPSHOT_VARIABLE module-attribute

SNAPSHOT_VARIABLE = 'WORKSHOP_SNAPSHOT'

GITLAB_EVENTS module-attribute

GITLAB_EVENTS = {'merge_request_event': 'pull_request', 'api': 'workflow_dispatch', 'trigger': 'workflow_dispatch', 'web': 'workflow_dispatch'}

RunContext dataclass

RunContext(forge: str, run_id: str, event: str, ref: str, head_sha: str = '', base_ref: str = '', leg: str = '', head_ref: str = '', labels: tuple[str, ...] = (), attempt: str = '')

The CI run this process belongs to, as the runner's environment names it.

Attributes:

Name Type Description
forge str

github, gitea, or gitlab.

run_id str

The forge's identifier of the run (GitLab: the pipeline).

event str

What started the run (push, pull_request, ...).

ref str

The ref the run is for, as the runner spells it.

head_sha str

The commit the forge files the run under. On a pull request the checkout is the merge commit the forge synthesised, and the run's own head is the pull request's head, which the event payload names; on a push both are the same commit. Empty when the runner did not say.

base_ref str

The branch a pull request proposes into, as the event payload names it (GitLab: the merge request's target); empty on a push or when the runner did not say.

leg str

The check leg this process runs in (check-ubuntu-latest-3.14), as the job runner names it in WORKSHOP_LEG for every entry it spawns; empty outside a scheduled job.

head_ref str

The branch a pull request comes from, as the event payload names it (GitLab: the merge request's source), the base of the branch's own coverage record; empty on a push or when the runner did not say.

labels tuple[str, ...]

The pull request's label names, as the event payload names them (GitLab: CI_MERGE_REQUEST_LABELS); empty on a push, on a payload that does not name them, or when the runner did not say.

attempt str

Which attempt of the run this is, as the runner counts them from 1 (GitHub's and Gitea's GITHUB_RUN_ATTEMPT); a rerun of some or all jobs is the next attempt. Empty on GitLab, and when the runner did not say. A shard records it, so the gate job's fold can tell shards of two attempts apart.

forge instance-attribute

forge: str

run_id instance-attribute

run_id: str

event instance-attribute

event: str

ref instance-attribute

ref: str

head_sha class-attribute instance-attribute

head_sha: str = ''

base_ref class-attribute instance-attribute

base_ref: str = ''

leg class-attribute instance-attribute

leg: str = ''

head_ref class-attribute instance-attribute

head_ref: str = ''

labels class-attribute instance-attribute

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

attempt class-attribute instance-attribute

attempt: str = ''

shard property

shard: Shard

The shard the leg runs as, read from the end of leg; one of one without.

check-windows-latest-3.14-2of4 runs as the second of four shards; check-ubuntu-latest-3.14, and an empty leg, as the one shard of one. The label is the only source, so the shard and the leg cannot disagree. A livery.workshop.Shard.

Raises:

Type Description
ValueError

When the label ends in a shard spelling outside the form, such as 0of2, naming it.

state_store

state_store(root: Path) -> StateStore

Open the state store of the checkout at root, with the workshop's policy.

A CI run may write a ci_only series and a desk may not; every commit the store makes is by the tools' identity (livery.git.tool_identity); a published listing travels in the WORKSHOP_SNAPSHOT variable. Every series the workshop and its extensions keep is read and written through it.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def state_store(root: Path) -> git.StateStore:
    """Open the state store of the checkout at *root*, with the workshop's policy.

    A CI run may write a ``ci_only`` series and a desk may not; every
    commit the store makes is by the tools' identity
    ([livery.git.tool_identity][]); a published listing travels in the
    ``WORKSHOP_SNAPSHOT`` variable. Every series the workshop and its
    extensions keep is read and written through it.
    """
    prog = footman.prog()
    return git.StateStore(
        root,
        in_ci=run_context() is not None,
        identity=git.tool_identity(prog),
        snapshot_variable=SNAPSHOT_VARIABLE,
        prog=prog,
    )

event_payload

event_payload(environ: Mapping[str, str] | None = None) -> dict[str, Any] | None

The runner's event payload, or None when there is none to read.

GitHub and Gitea write the event that started the run to the file GITHUB_EVENT_PATH names; a payload that is missing or does not parse reads as none, so a caller falls back rather than fails. GitLab writes no file and carries the same facts as variables, so a merge request pipeline answers with the payload's pull_request shape built from CI_MERGE_REQUEST_*: the iid as the number, the title, the source branch and head sha, and the target branch. Any other GitLab pipeline has no payload.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def event_payload(environ: Mapping[str, str] | None = None) -> dict[str, Any] | None:
    """The runner's event payload, or ``None`` when there is none to read.

    GitHub and Gitea write the event that started the run to the file
    ``GITHUB_EVENT_PATH`` names; a payload that is missing or does not
    parse reads as none, so a caller falls back rather than fails.
    GitLab writes no file and carries the same facts as variables, so a
    merge request pipeline answers with the payload's ``pull_request``
    shape built from ``CI_MERGE_REQUEST_*``: the iid as the number, the
    title, the source branch and head sha, and the target branch. Any
    other GitLab pipeline has no payload.
    """
    env = os.environ if environ is None else environ
    path = env.get("GITHUB_EVENT_PATH", "")
    if not path:
        if env.get("GITLAB_CI") == "true" and env.get("CI_MERGE_REQUEST_IID"):
            return {
                "pull_request": {
                    "number": int(env["CI_MERGE_REQUEST_IID"]),
                    "title": env.get("CI_MERGE_REQUEST_TITLE", ""),
                    "head": {
                        "ref": env.get("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", ""),
                        "sha": env.get("CI_COMMIT_SHA", ""),
                    },
                    "base": {"ref": env.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "")},
                }
            }
        return None
    try:
        payload = json.loads(Path(path).read_text("utf-8"))
    except (OSError, ValueError):
        return None
    return payload if isinstance(payload, dict) else None

dispatch_inputs

dispatch_inputs(names: tuple[str, ...], environ: Mapping[str, str] | None = None) -> dict[str, str]

The dispatch inputs names, as the run received them; "" for one it did not.

GitHub and Gitea carry a dispatch's inputs in the event payload under inputs; GitLab carries them as pipeline variables, which arrive as environment variables named by the input. A run that no dispatch started, or a process outside CI, has none, and every name reads empty.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def dispatch_inputs(
    names: tuple[str, ...], environ: Mapping[str, str] | None = None
) -> dict[str, str]:
    """The dispatch inputs *names*, as the run received them; ``""`` for one it did not.

    GitHub and Gitea carry a dispatch's inputs in the event payload
    under ``inputs``; GitLab carries them as pipeline variables, which
    arrive as environment variables named by the input. A run that no
    dispatch started, or a process outside CI, has none, and every
    name reads empty.
    """
    env = os.environ if environ is None else environ
    payload = event_payload(env)
    carried = (payload or {}).get("inputs") or {}
    found: dict[str, str] = {}
    for name in names:
        if isinstance(carried, dict) and carried.get(name) not in (None, ""):
            found[name] = str(carried[name])
        else:
            found[name] = env.get(name, "")
    return found

run_context

run_context(environ: dict[str, str] | None = None) -> RunContext | None

The CI run this process runs in, or None outside CI.

GitHub and Gitea both speak the GITHUB_* variables (the act_runner keeps GitHub's names and adds GITEA_ACTIONS); GitLab speaks GITLAB_CI and CI_*, and its pipeline source is read through GITLAB_EVENTS, so a merge request pipeline narrows, records and checks titles the way a pull request run does.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def run_context(environ: dict[str, str] | None = None) -> RunContext | None:
    """The CI run this process runs in, or ``None`` outside CI.

    GitHub and Gitea both speak the ``GITHUB_*`` variables (the
    act_runner keeps GitHub's names and adds ``GITEA_ACTIONS``);
    GitLab speaks ``GITLAB_CI`` and ``CI_*``, and its pipeline source
    is read through `GITLAB_EVENTS`, so a merge request pipeline
    narrows, records and checks titles the way a pull request run does.
    """
    env = os.environ if environ is None else environ
    if env.get("GITHUB_ACTIONS") == "true":
        forge = "gitea" if env.get("GITEA_ACTIONS") == "true" else "github"
        return RunContext(
            forge,
            env.get("GITHUB_RUN_ID", ""),
            env.get("GITHUB_EVENT_NAME", ""),
            env.get("GITHUB_REF", ""),
            _event_head_sha(env),
            _event_base_ref(env),
            env.get(LEG_VARIABLE, ""),
            _event_head_ref(env),
            _event_labels(env),
            env.get("GITHUB_RUN_ATTEMPT", ""),
        )
    if env.get("GITLAB_CI") == "true":
        source = env.get("CI_PIPELINE_SOURCE", "")
        return RunContext(
            "gitlab",
            env.get("CI_PIPELINE_ID", ""),
            GITLAB_EVENTS.get(source, source),
            env.get("CI_COMMIT_REF_NAME", ""),
            env.get("CI_COMMIT_SHA", ""),
            env.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", ""),
            env.get(LEG_VARIABLE, ""),
            env.get("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", ""),
            _event_labels(env),
        )
    return None

ci_run

ci_run(environ: dict[str, str] | None = None) -> RunContext | None

The CI run this process belongs to, or None at a desk.

Read from the runner's environment, environ when given, the process's own otherwise: GitHub's and Gitea's GITHUB_* variables, GitLab's CI_*. An extension that behaves differently in CI asks this, never a variable of one forge.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def ci_run(environ: dict[str, str] | None = None) -> RunContext | None:
    """The CI run this process belongs to, or None at a desk.

    Read from the runner's environment, *environ* when given, the
    process's own otherwise: GitHub's and Gitea's ``GITHUB_*``
    variables, GitLab's ``CI_*``. An extension that behaves
    differently in CI asks this, never a variable of one forge.
    """
    return run_context(environ)