Coverage for packages/workshop/src/livery/workshop/_ci_context.py: 100%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""The CI run this process belongs to, and the state store built with its policy.
2
3The run context reads the runner's environment: GitHub's and Gitea's
4``GITHUB_*`` variables, GitLab's ``CI_*``. [livery.workshop.state_store][]
5builds the [livery.git.StateStore][] every verb reads and writes the
6workshop's series through, with the three answers the store takes as
7construction data: whether this is a CI run, the identity every commit
8carries, and the variable a published listing travels in.
9"""
10
11from __future__ import annotations(empty)
12
13import json(empty)
14import os(empty)
15from collections.abc import Mapping(empty)
16from dataclasses import dataclass(empty)
17from pathlib import Path(empty)
18from typing import TYPE_CHECKING, Any(empty)
19
20import livery.footman as footman(empty)
21from livery import git(empty)
22
23if TYPE_CHECKING:(empty)
24 from livery.workshop._shard import Shard
25
26#: The variable the job runner sets for every entry it spawns, naming
27#: the check leg (``check-ubuntu-latest-3.14``): the key of the leg's
28#: rows and stamps.
29LEG_VARIABLE = "WORKSHOP_LEG"(empty)
30
31#: The environment variable naming the CI point a process runs at:
32#: ``gate``, ``merge``, ``nightly`` or ``release``. The job runner sets
33#: it for every entry it spawns. The points plugin selects the tests of
34#: that point by it, and a verb reads it to learn where it runs; a
35#: process without it runs at the gate. It lives in a module that
36#: imports no pytest, so a verb reads it without pytest.
37POINT_VARIABLE = "WORKSHOP_POINT"(empty)
38
39#: The variable a published snapshot's file is named in: the job
40#: runner takes one listing for the whole job and every entry it
41#: spawns reads through it instead of listing again.
42SNAPSHOT_VARIABLE = "WORKSHOP_SNAPSHOT"(empty)
43
44
45def state_store(root: Path) -> git.StateStore:(empty)
46 """Open the state store of the checkout at *root*, with the workshop's policy.
47
48 A CI run may write a ``ci_only`` series and a desk may not; every
49 commit the store makes is by the tools' identity
50 ([livery.git.tool_identity][]); a published listing travels in the
51 ``WORKSHOP_SNAPSHOT`` variable. Every series the workshop and its
52 extensions keep is read and written through it.
53 """
54 prog = footman.prog()
55 return git.StateStore(
56 root,
57 in_ci=run_context() is not None,
58 identity=git.tool_identity(prog),
59 snapshot_variable=SNAPSHOT_VARIABLE,
60 prog=prog,
61 )
62
63
64@dataclass(frozen=True)(empty)
65class RunContext:(empty)
66 """The CI run this process belongs to, as the runner's environment names it.
67
68 Attributes:
69 forge: ``github``, ``gitea``, or ``gitlab``.
70 run_id: The forge's identifier of the run (GitLab: the pipeline).
71 event: What started the run (``push``, ``pull_request``, ...).
72 ref: The ref the run is for, as the runner spells it.
73 head_sha: The commit the forge files the run under. On a pull
74 request the checkout is the merge commit the forge
75 synthesised, and the run's own head is the pull request's
76 head, which the event payload names; on a push both are
77 the same commit. Empty when the runner did not say.
78 base_ref: The branch a pull request proposes into, as the event
79 payload names it (GitLab: the merge request's target);
80 empty on a push or when the runner did not say.
81 leg: The check leg this process runs in (``check-ubuntu-latest-3.14``),
82 as the job runner names it in ``WORKSHOP_LEG`` for every entry it
83 spawns; empty outside a scheduled job.
84 head_ref: The branch a pull request comes from, as the event
85 payload names it (GitLab: the merge request's source), the
86 base of the branch's own coverage record; empty on a push
87 or when the runner did not say.
88 labels: The pull request's label names, as the event payload
89 names them (GitLab: ``CI_MERGE_REQUEST_LABELS``); empty on
90 a push, on a payload that does not name them, or when the
91 runner did not say.
92 attempt: Which attempt of the run this is, as the runner
93 counts them from 1 (GitHub's and Gitea's
94 ``GITHUB_RUN_ATTEMPT``); a rerun of some or all jobs is the
95 next attempt. Empty on GitLab, and when the runner did not
96 say. A shard records it, so the gate job's fold can tell
97 shards of two attempts apart.
98 """
99
100 forge: str(empty)
101 run_id: str(empty)
102 event: str(empty)
103 ref: str(empty)
104 head_sha: str = ""(empty)
105 base_ref: str = ""(empty)
106 leg: str = ""(empty)
107 head_ref: str = ""(empty)
108 labels: tuple[str, ...] = ()(empty)
109 attempt: str = ""(empty)
110
111 @property(empty)
112 def shard(self) -> Shard:(empty)
113 """The shard the leg runs as, read from the end of `leg`; one of one without.
114
115 ``check-windows-latest-3.14-2of4`` runs as the second of four
116 shards; ``check-ubuntu-latest-3.14``, and an empty leg, as the
117 one shard of one. The label is the only source, so the shard
118 and the leg cannot disagree. A [livery.workshop.Shard][].
119
120 Raises:
121 ValueError: When the label ends in a shard spelling outside
122 the form, such as ``0of2``, naming it.
123 """
124 # Imported here: the shard module opens the state store through
125 # this one, so a module-level import would be a cycle.
126 from livery.workshop._shard import shard_of
127
128 return shard_of(self.leg)
129
130
131def event_payload(environ: Mapping[str, str] | None = None) -> dict[str, Any] | None:(empty)
132 """The runner's event payload, or ``None`` when there is none to read.
133
134 GitHub and Gitea write the event that started the run to the file
135 ``GITHUB_EVENT_PATH`` names; a payload that is missing or does not
136 parse reads as none, so a caller falls back rather than fails.
137 GitLab writes no file and carries the same facts as variables, so a
138 merge request pipeline answers with the payload's ``pull_request``
139 shape built from ``CI_MERGE_REQUEST_*``: the iid as the number, the
140 title, the source branch and head sha, and the target branch. Any
141 other GitLab pipeline has no payload.
142 """
143 env = os.environ if environ is None else environ
144 path = env.get("GITHUB_EVENT_PATH", "")
145 if not path:
146 if env.get("GITLAB_CI") == "true" and env.get("CI_MERGE_REQUEST_IID"):
147 return {
148 "pull_request": {
149 "number": int(env["CI_MERGE_REQUEST_IID"]),
150 "title": env.get("CI_MERGE_REQUEST_TITLE", ""),
151 "head": {
152 "ref": env.get("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", ""),
153 "sha": env.get("CI_COMMIT_SHA", ""),
154 },
155 "base": {"ref": env.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "")},
156 }
157 }
158 return None
159 try:
160 payload = json.loads(Path(path).read_text("utf-8"))
161 except (OSError, ValueError):
162 return None
163 return payload if isinstance(payload, dict) else None
164
165
166def dispatch_inputs((empty)
167 names: tuple[str, ...], environ: Mapping[str, str] | None = None
168) -> dict[str, str]:
169 """The dispatch inputs *names*, as the run received them; ``""`` for one it did not.
170
171 GitHub and Gitea carry a dispatch's inputs in the event payload
172 under ``inputs``; GitLab carries them as pipeline variables, which
173 arrive as environment variables named by the input. A run that no
174 dispatch started, or a process outside CI, has none, and every
175 name reads empty.
176 """
177 env = os.environ if environ is None else environ
178 payload = event_payload(env)
179 carried = (payload or {}).get("inputs") or {}
180 found: dict[str, str] = {}
181 for name in names:
182 if isinstance(carried, dict) and carried.get(name) not in (None, ""):
183 found[name] = str(carried[name])
184 else:
185 found[name] = env.get(name, "")
186 return found
187
188
189def _event_head_sha(env: Mapping[str, str]) -> str:(empty)
190 """The pull request's head from the event payload, or the pushed commit.
191
192 A payload that is missing or does not parse falls back to the
193 pushed commit: the lookup then works on a push and misses on a
194 pull request, which the collect names rather than fails on.
195 """
196 payload = event_payload(env)
197 if payload is not None:
198 head = (payload.get("pull_request") or {}).get("head") or {}
199 if isinstance(head, dict) and head.get("sha"):
200 return str(head["sha"])
201 return env.get("GITHUB_SHA", "")
202
203
204def _event_base_ref(env: Mapping[str, str]) -> str:(empty)
205 """The pull request's base branch from the event payload, or empty."""
206 payload = event_payload(env)
207 if payload is None:
208 return ""
209 base = (payload.get("pull_request") or {}).get("base") or {}
210 if isinstance(base, dict) and base.get("ref"):
211 return str(base["ref"])
212 return ""
213
214
215def _event_head_ref(env: Mapping[str, str]) -> str:(empty)
216 """The pull request's source branch: the payload's, else the runner's variable."""
217 payload = event_payload(env)
218 if payload is not None:
219 head = (payload.get("pull_request") or {}).get("head") or {}
220 if isinstance(head, dict) and head.get("ref"):
221 return str(head["ref"])
222 return env.get("GITHUB_HEAD_REF", "")
223
224
225def _event_labels(env: Mapping[str, str]) -> tuple[str, ...]:(empty)
226 """The pull request's label names: the payload's, else GitLab's variable.
227
228 GitHub and Gitea write each label as an object under
229 ``pull_request.labels``; GitLab carries the names comma-joined in
230 ``CI_MERGE_REQUEST_LABELS``. A payload that is missing, does not
231 parse, or names no labels reads as none, so a caller treats the
232 run as unlabelled rather than fails.
233 """
234 payload = event_payload(env) or {}
235 raw = (payload.get("pull_request") or {}).get("labels")
236 if isinstance(raw, list):
237 return tuple(
238 str(label["name"])
239 for label in raw
240 if isinstance(label, dict) and label.get("name")
241 )
242 joined = env.get("CI_MERGE_REQUEST_LABELS", "")
243 return tuple(name.strip() for name in joined.split(",") if name.strip())
244
245
246#: GitLab's pipeline sources in the one event vocabulary the verbs
247#: read: a merge request pipeline is a pull request run, and an API-,
248#: trigger- or web-created pipeline is a dispatch, as the forge
249#: backend maps a listed pipeline. A source not named here (``push``,
250#: ``schedule``) is already the vocabulary's word.
251GITLAB_EVENTS = {(empty)
252 "merge_request_event": "pull_request",
253 "api": "workflow_dispatch",
254 "trigger": "workflow_dispatch",
255 "web": "workflow_dispatch",
256}
257
258
259def run_context(environ: dict[str, str] | None = None) -> RunContext | None:(empty)
260 """The CI run this process runs in, or ``None`` outside CI.
261
262 GitHub and Gitea both speak the ``GITHUB_*`` variables (the
263 act_runner keeps GitHub's names and adds ``GITEA_ACTIONS``);
264 GitLab speaks ``GITLAB_CI`` and ``CI_*``, and its pipeline source
265 is read through `GITLAB_EVENTS`, so a merge request pipeline
266 narrows, records and checks titles the way a pull request run does.
267 """
268 env = os.environ if environ is None else environ
269 if env.get("GITHUB_ACTIONS") == "true":
270 forge = "gitea" if env.get("GITEA_ACTIONS") == "true" else "github"
271 return RunContext(
272 forge,
273 env.get("GITHUB_RUN_ID", ""),
274 env.get("GITHUB_EVENT_NAME", ""),
275 env.get("GITHUB_REF", ""),
276 _event_head_sha(env),
277 _event_base_ref(env),
278 env.get(LEG_VARIABLE, ""),
279 _event_head_ref(env),
280 _event_labels(env),
281 env.get("GITHUB_RUN_ATTEMPT", ""),
282 )
283 if env.get("GITLAB_CI") == "true":
284 source = env.get("CI_PIPELINE_SOURCE", "")
285 return RunContext(
286 "gitlab",
287 env.get("CI_PIPELINE_ID", ""),
288 GITLAB_EVENTS.get(source, source),
289 env.get("CI_COMMIT_REF_NAME", ""),
290 env.get("CI_COMMIT_SHA", ""),
291 env.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", ""),
292 env.get(LEG_VARIABLE, ""),
293 env.get("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", ""),
294 _event_labels(env),
295 )
296 return None
297
298
299def ci_run(environ: dict[str, str] | None = None) -> RunContext | None:(empty)
300 """The CI run this process belongs to, or None at a desk.
301
302 Read from the runner's environment, *environ* when given, the
303 process's own otherwise: GitHub's and Gitea's ``GITHUB_*``
304 variables, GitLab's ``CI_*``. An extension that behaves
305 differently in CI asks this, never a variable of one forge.
306 """
307 return run_context(environ)