basstler-github 4.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. basstler/github/__init__.py +0 -0
  2. basstler/github/actions_budget.py +428 -0
  3. basstler/github/actions_secret.py +25 -0
  4. basstler/github/actions_settings.py +162 -0
  5. basstler/github/actions_usage.py +297 -0
  6. basstler/github/basstler_project.py +75 -0
  7. basstler/github/branch_pull_request.py +24 -0
  8. basstler/github/client.py +452 -0
  9. basstler/github/comparison.py +60 -0
  10. basstler/github/constants.py +197 -0
  11. basstler/github/credential.py +85 -0
  12. basstler/github/exceptions.py +264 -0
  13. basstler/github/file_proposal.py +440 -0
  14. basstler/github/fork_sync.py +44 -0
  15. basstler/github/git_objects.py +57 -0
  16. basstler/github/graphql.py +101 -0
  17. basstler/github/issue.py +221 -0
  18. basstler/github/label.py +78 -0
  19. basstler/github/login_lending.py +46 -0
  20. basstler/github/main_failure.py +289 -0
  21. basstler/github/permission_level.py +33 -0
  22. basstler/github/pull_request.py +74 -0
  23. basstler/github/pull_request_changes.py +141 -0
  24. basstler/github/pull_request_description.py +145 -0
  25. basstler/github/pull_request_ends.py +58 -0
  26. basstler/github/pull_request_form.py +136 -0
  27. basstler/github/pull_request_models.py +321 -0
  28. basstler/github/pull_request_record.py +369 -0
  29. basstler/github/pull_request_source.py +395 -0
  30. basstler/github/pull_request_state.py +437 -0
  31. basstler/github/queries/pull_request_for_branch.graphql +17 -0
  32. basstler/github/queries/review_threads_page.graphql +72 -0
  33. basstler/github/query_documents.py +37 -0
  34. basstler/github/release_version.py +565 -0
  35. basstler/github/remote.py +36 -0
  36. basstler/github/repository.py +532 -0
  37. basstler/github/repository_access.py +459 -0
  38. basstler/github/repository_attachment.py +95 -0
  39. basstler/github/repository_details.py +98 -0
  40. basstler/github/repository_option.py +43 -0
  41. basstler/github/repository_resources.py +133 -0
  42. basstler/github/rest_models.py +353 -0
  43. basstler/github/review_models.py +223 -0
  44. basstler/github/run_listing.py +148 -0
  45. basstler/github/stack_configuration.py +178 -0
  46. basstler/github/states.py +257 -0
  47. basstler/github/token_form.py +360 -0
  48. basstler/github/tooling_labels.py +83 -0
  49. basstler/github/user_steps.py +170 -0
  50. basstler/github/web_form.py +56 -0
  51. basstler/github/web_page.py +33 -0
  52. basstler/github/wire_form.py +159 -0
  53. basstler/github/workflow_run.py +126 -0
  54. basstler/github/workflows.py +561 -0
  55. basstler/templates/actions_budget.py.jinja +26 -0
  56. basstler_github-4.2.0.dist-info/METADATA +16 -0
  57. basstler_github-4.2.0.dist-info/RECORD +60 -0
  58. basstler_github-4.2.0.dist-info/WHEEL +4 -0
  59. basstler_github-4.2.0.dist-info/licenses/LICENSE +202 -0
  60. basstler_github-4.2.0.dist-info/licenses/NOTICE +13 -0
@@ -0,0 +1,321 @@
1
+ """
2
+ Models of a pull request and the checks reported against its head commit, as GitHub's
3
+ GraphQL API returns them, and the snapshot a report is rendered from.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Annotated, Literal
10
+
11
+ from pydantic import AliasPath, Field
12
+
13
+ from basstler.github.repository import PullRequestReference
14
+ from basstler.github.wire_form import PullRequestNumber
15
+ from basstler.github.graphql import GraphQLConnection
16
+ from basstler.github.review_models import (
17
+ BranchPullRequest,
18
+ Review,
19
+ ReviewThread,
20
+ ReviewThreadPage,
21
+ )
22
+ from basstler.github.states import CheckOutcome, CombinedCheckState, ConclusionOutcome
23
+ from basstler.github.web_page import AbsentAsEmpty
24
+ from basstler.json_model import ValidatedJSONModel
25
+
26
+ # %% models mirroring the pull request
27
+
28
+
29
+ class CheckResult(ValidatedJSONModel):
30
+ """
31
+ One check reported against the pull request's head commit: a check run, such as a
32
+ GitHub Actions job, or a status posted through the commit-status API.
33
+
34
+ Each shape GitHub reports a check in is a subclass naming its own keys.
35
+ """
36
+
37
+ name: str
38
+ """
39
+ What the check calls itself.
40
+ """
41
+
42
+ outcome: ConclusionOutcome
43
+ """
44
+ Where the check stands.
45
+ """
46
+
47
+ target_url: Annotated[str, AbsentAsEmpty()]
48
+ """
49
+ Where the check's own output is, empty when it reported none.
50
+ """
51
+
52
+ @property
53
+ def succeeded(self) -> bool:
54
+ """:return: Whether this check reported success."""
55
+ return self.outcome is CheckOutcome.SUCCESS
56
+
57
+
58
+ class GraphQLCheckRun(CheckResult):
59
+ """
60
+ A check run, as GraphQL lists it among a commit's checks.
61
+ """
62
+
63
+ kind: Annotated[Literal["CheckRun"], Field(alias="__typename")]
64
+ """
65
+ The GraphQL type a check of this shape carries.
66
+ """
67
+
68
+ outcome: Annotated[ConclusionOutcome, Field(alias="conclusion")]
69
+ """
70
+ Where the run stands, pending while it has no conclusion.
71
+ """
72
+
73
+ target_url: Annotated[str, AbsentAsEmpty(), Field(alias="detailsUrl")]
74
+ """
75
+ The run's page, empty when it has none.
76
+ """
77
+
78
+
79
+ class GraphQLStatusContext(CheckResult):
80
+ """
81
+ A commit status, as GraphQL lists it among a commit's checks.
82
+ """
83
+
84
+ kind: Annotated[Literal["StatusContext"], Field(alias="__typename")]
85
+ """
86
+ The GraphQL type a check of this shape carries.
87
+ """
88
+
89
+ name: Annotated[str, Field(alias="context")]
90
+ """
91
+ The context the status was posted under, which names it.
92
+ """
93
+
94
+ outcome: Annotated[ConclusionOutcome, Field(alias="state")]
95
+ """
96
+ The state the status was posted with.
97
+ """
98
+
99
+ target_url: Annotated[str, AbsentAsEmpty(), Field(alias="targetUrl")]
100
+ """
101
+ The link the status was posted with, empty when it has none.
102
+ """
103
+
104
+
105
+ GraphQLCheck = Annotated[
106
+ GraphQLCheckRun | GraphQLStatusContext, Field(discriminator="kind")
107
+ ]
108
+ """
109
+ One of a commit's checks in GraphQL, read as the shape its GraphQL type names.
110
+ """
111
+
112
+
113
+ class CheckStatus(ValidatedJSONModel):
114
+ """
115
+ Every check reported against the pull request, with GitHub's verdict over them.
116
+ """
117
+
118
+ state: CombinedCheckState
119
+ """
120
+ The verdict GitHub computed over all of them.
121
+ """
122
+
123
+ results: list[CheckResult]
124
+ """
125
+ Every check, in the order GitHub returned them.
126
+ """
127
+
128
+ @classmethod
129
+ def over(cls, results: list[CheckResult]) -> CheckStatus | None:
130
+ """
131
+ Gather checks read one by one, computing the verdict GitHub would give them.
132
+
133
+ :param results: Every check, in the order to report them.
134
+ :return: The status, or ``None`` when nothing has reported.
135
+ """
136
+ if not results:
137
+ return None
138
+ return cls(
139
+ state=CombinedCheckState.over([result.outcome for result in results]),
140
+ results=results,
141
+ )
142
+
143
+ @property
144
+ def unsuccessful(self) -> list[CheckResult]:
145
+ """:return: The checks that did not report success."""
146
+ return [result for result in self.results if not result.succeeded]
147
+
148
+
149
+ class GraphQLCheckStatus(CheckStatus):
150
+ """
151
+ The checks of a commit, as GitHub's GraphQL API rolls them up.
152
+ """
153
+
154
+ results: Annotated[GraphQLConnection[GraphQLCheck], Field(alias="contexts")]
155
+ """
156
+ Every check, in the order GitHub returned them.
157
+ """
158
+
159
+
160
+ class Commit(ValidatedJSONModel):
161
+ """
162
+ A commit, carrying the checks reported against it.
163
+ """
164
+
165
+ checks: Annotated[GraphQLCheckStatus | None, Field(alias="statusCheckRollup")]
166
+ """
167
+ The checks reported against this commit, absent when none have reported.
168
+ """
169
+
170
+
171
+ class PullRequestCommit(ValidatedJSONModel):
172
+ """
173
+ One entry of a pull request's commit list, which wraps the commit itself.
174
+ """
175
+
176
+ commit: Commit
177
+ """
178
+ The commit this entry stands for.
179
+ """
180
+
181
+
182
+ class PullRequest(ValidatedJSONModel):
183
+ """
184
+ One upstream pull request, as a single page of the review-threads query reads it.
185
+ """
186
+
187
+ reference: Annotated[
188
+ PullRequestReference, Field(alias="number"), PullRequestNumber()
189
+ ]
190
+ """
191
+ The pull request, on the repository it was read from.
192
+ """
193
+
194
+ title: str
195
+ """
196
+ Its title.
197
+ """
198
+
199
+ commits: GraphQLConnection[PullRequestCommit]
200
+ """
201
+ The commits the query selected, which is the head commit alone.
202
+ """
203
+
204
+ reviews: GraphQLConnection[Review]
205
+ """
206
+ Every submitted review, oldest first.
207
+ """
208
+
209
+ review_threads: Annotated[ReviewThreadPage, Field(alias="reviewThreads")]
210
+ """
211
+ The page of review threads this response carried.
212
+ """
213
+
214
+ @property
215
+ def checks(self) -> CheckStatus | None:
216
+ """
217
+ The checks reported against the head commit.
218
+
219
+ GitHub hangs the combined checks off the commit rather than the pull request.
220
+
221
+ :return: The checks, or ``None`` when nothing has reported.
222
+ """
223
+ if not self.commits:
224
+ return None
225
+ return self.commits[-1].commit.checks
226
+
227
+
228
+ @dataclass(frozen=True)
229
+ class UpstreamPullRequestSnapshot:
230
+ """
231
+ Everything read from one upstream pull request in a single run.
232
+ """
233
+
234
+ reference: PullRequestReference
235
+ """
236
+ The pull request, on the upstream repository.
237
+ """
238
+
239
+ title: str
240
+ """
241
+ The pull request's title.
242
+ """
243
+
244
+ reviews: list[Review]
245
+ """
246
+ Every submitted review, oldest first.
247
+ """
248
+
249
+ threads: list[ReviewThread]
250
+ """
251
+ Every review thread, in the order GitHub returned them.
252
+ """
253
+
254
+ checks: CheckStatus | None
255
+ """
256
+ The checks reported against the head commit, absent when none have reported.
257
+ """
258
+
259
+ @classmethod
260
+ def assemble(
261
+ cls, pull_request: PullRequest, threads: list[ReviewThread]
262
+ ) -> UpstreamPullRequestSnapshot:
263
+ """
264
+ Combine a parsed pull request with every thread its pages carried.
265
+
266
+ :param pull_request: The pull request, as the last page read it.
267
+ :param threads: Every thread gathered across the paged reads.
268
+ :return: The assembled snapshot.
269
+ """
270
+ return cls(
271
+ reference=pull_request.reference,
272
+ title=pull_request.title,
273
+ reviews=pull_request.reviews,
274
+ threads=threads,
275
+ checks=pull_request.checks,
276
+ )
277
+
278
+ @property
279
+ def unresolved_threads(self) -> list[ReviewThread]:
280
+ """:return: The threads still awaiting action."""
281
+ return [thread for thread in self.threads if not thread.is_resolved]
282
+
283
+ def thread(self, identifier: str) -> ReviewThread:
284
+ """
285
+ Look one thread up by its node identifier.
286
+
287
+ :param identifier: The thread's node identifier.
288
+ :return: The matching thread.
289
+ :raises KeyError: If no thread carries that identifier.
290
+ """
291
+ for thread in self.threads:
292
+ if thread.identifier == identifier:
293
+ return thread
294
+ raise KeyError(identifier)
295
+
296
+
297
+ class PullRequestForBranchResult(ValidatedJSONModel):
298
+ """
299
+ What :attr:`GraphQLDocument.PULL_REQUEST_FOR_BRANCH` returns.
300
+ """
301
+
302
+ pull_requests: Annotated[
303
+ GraphQLConnection[BranchPullRequest],
304
+ Field(validation_alias=AliasPath("repository", "pullRequests")),
305
+ ]
306
+ """
307
+ Every pull request the head-branch search matched, newest first.
308
+ """
309
+
310
+
311
+ class ReviewThreadsPageResult(ValidatedJSONModel):
312
+ """
313
+ What :attr:`GraphQLDocument.REVIEW_THREADS_PAGE` returns.
314
+ """
315
+
316
+ pull_request: Annotated[
317
+ PullRequest, Field(validation_alias=AliasPath("repository", "pullRequest"))
318
+ ]
319
+ """
320
+ The pull request, carrying one page of its review threads.
321
+ """
@@ -0,0 +1,369 @@
1
+ """
2
+ A pull request as GitHub's REST API answers it, read field by field.
3
+
4
+ A fetch that drops a field is not partially correct, so every field is declared with
5
+ how to read it and whether it may be absent, and a record omitting a required one is
6
+ rejected rather than defaulted.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ from abc import ABC, abstractmethod
13
+ from collections.abc import Iterable, Mapping
14
+ from dataclasses import dataclass
15
+ from enum import Enum, StrEnum
16
+ from typing import Any
17
+
18
+ from basstler.class_property import classproperty
19
+ from basstler.exit_codes import CommandFailure, StackExitCode
20
+ from basstler.github.states import CombinedCheckState
21
+
22
+ PullRequestRecord = Mapping[str, Any]
23
+ """
24
+ One pull request as the REST API answers it, before any field is read.
25
+ """
26
+
27
+ # %% the fields a pull request is read from
28
+
29
+
30
+ class PullRequestHeadKey(StrEnum):
31
+ """
32
+ The keys of the object a pull request's head arrives as.
33
+ """
34
+
35
+ REFERENCE = "ref"
36
+ """
37
+ The head branch's name.
38
+ """
39
+
40
+ HEAD_REPOSITORY = "repo"
41
+ """
42
+ The repository the head branch lives in, ``null`` once that repository is deleted.
43
+ """
44
+
45
+ FULL_NAME = "full_name"
46
+ """
47
+ A repository's ``owner/name``, under :attr:`HEAD_REPOSITORY`.
48
+ """
49
+
50
+ COMMIT = "sha"
51
+ """
52
+ The commit the head branch points at.
53
+ """
54
+
55
+
56
+ class AccountField(StrEnum):
57
+ """
58
+ The fields of an account the API describes.
59
+ """
60
+
61
+ LOGIN = "login"
62
+ """
63
+ The account's login.
64
+ """
65
+
66
+
67
+ class PullRequestFieldShape(StrEnum):
68
+ """
69
+ How one pull-request field's value has to be read.
70
+
71
+ The API answers some fields with a nested object where a plain value would do, so
72
+ reading is per-field rather than uniform.
73
+ """
74
+
75
+ VALUE = "value"
76
+ """
77
+ Taken as it comes.
78
+ """
79
+
80
+ BRANCH_REFERENCE = "branch-reference"
81
+ """
82
+ A branch, given either plainly or as an object carrying a ``ref``.
83
+ """
84
+
85
+ LABEL_NAMES = "label-names"
86
+ """
87
+ A list of labels, each given either plainly or as an object carrying a ``name``.
88
+ """
89
+
90
+ ACCOUNT_LOGINS = "account-logins"
91
+ """
92
+ A list of accounts, each an object carrying a ``login``.
93
+ """
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class PullRequestFieldSpecification:
98
+ """
99
+ What one pull-request field is called, how to read it, and whether it may be absent.
100
+ """
101
+
102
+ key: str
103
+ """
104
+ The key the API answers under.
105
+ """
106
+
107
+ shape: PullRequestFieldShape = PullRequestFieldShape.VALUE
108
+ """
109
+ How its value has to be read.
110
+ """
111
+
112
+ required: bool = False
113
+ """
114
+ Whether a record omitting it is rejected rather than read.
115
+ """
116
+
117
+
118
+ class PullRequestField(PullRequestFieldSpecification, Enum):
119
+ """
120
+ Every pull-request field this executor reads, and how to read it.
121
+
122
+ Each member *is* a specification, so nothing outside this enum knows that ``head``
123
+ arrives nested while ``draft`` does not, or which fields a board cannot be derived
124
+ without.
125
+
126
+ A member is written as the specification it carries, and :meth:`__init__` unpacks it
127
+ onto the member itself - so ``PullRequestField.HEAD.key`` reads directly and the
128
+ member is a :class:`PullRequestFieldSpecification` in its own right.
129
+ """
130
+
131
+ def __init__(self, specification: PullRequestFieldSpecification) -> None:
132
+ """
133
+ Carry the specification's values on the member itself.
134
+
135
+ Without this the mixin would receive the whole specification as its first
136
+ argument - silently, landing the instance in :attr:`key` - since an enum passes
137
+ a member's value straight to the type it mixes in.
138
+
139
+ :param specification: What this field is called and how to read it.
140
+ """
141
+ for field in dataclasses.fields(PullRequestFieldSpecification):
142
+ object.__setattr__(self, field.name, getattr(specification, field.name))
143
+
144
+ NUMBER = PullRequestFieldSpecification(key="number", required=True)
145
+ """
146
+ The pull request's number.
147
+ """
148
+ HEAD = PullRequestFieldSpecification(
149
+ key="head", shape=PullRequestFieldShape.BRANCH_REFERENCE, required=True
150
+ )
151
+ """The branch the pull request would merge - the stack node it names."""
152
+ BASE = PullRequestFieldSpecification(
153
+ key="base", shape=PullRequestFieldShape.BRANCH_REFERENCE, required=True
154
+ )
155
+ """The branch it would merge into - its parent in the stack."""
156
+ DRAFT = PullRequestFieldSpecification(key="draft", required=True)
157
+ """
158
+ Whether its author has yet reviewed it themselves.
159
+ """
160
+ LABELS = PullRequestFieldSpecification(
161
+ key="labels", shape=PullRequestFieldShape.LABEL_NAMES, required=True
162
+ )
163
+ """
164
+ The labels it carries, which the workflow reads as state.
165
+ """
166
+ BODY = PullRequestFieldSpecification(key="body")
167
+ """
168
+ Its description, read for the session link and the promotion prefill.
169
+ """
170
+ TITLE = PullRequestFieldSpecification(key="title")
171
+ """
172
+ Its title, which prefills the upstream pull request.
173
+ """
174
+ MERGEABLE_STATE = PullRequestFieldSpecification(key="mergeable_state")
175
+ """
176
+ GitHub's own verdict on whether it currently conflicts with its base.
177
+ """
178
+ STATE = PullRequestFieldSpecification(key="state")
179
+ """
180
+ Whether it is open or closed, a merged one included among the closed.
181
+ """
182
+ MERGED_AT = PullRequestFieldSpecification(key="merged_at")
183
+ """
184
+ When GitHub merged it, absent for one never merged through GitHub.
185
+ """
186
+ HTML_URL = PullRequestFieldSpecification(key="html_url")
187
+ """
188
+ Its page on GitHub, which the issues API answers under the same key.
189
+ """
190
+ ASSIGNEES = PullRequestFieldSpecification(
191
+ key="assignees", shape=PullRequestFieldShape.ACCOUNT_LOGINS
192
+ )
193
+ """
194
+ The logins of the accounts it is assigned to.
195
+ """
196
+
197
+ def read(self, record: PullRequestRecord, number: int | None = None) -> Any:
198
+ """
199
+ Read this field out of a fetched pull request.
200
+
201
+ :param record: The fetched pull request.
202
+ :param number: The pull request being read, named in any rejection.
203
+ :return: The field's value, read according to its shape.
204
+ :raises MissingPullRequestFieldError: If a required field is absent, or its
205
+ value carries no name where its shape says one belongs.
206
+ """
207
+ value = record.get(self.key)
208
+ if value is None:
209
+ if self.required:
210
+ raise MissingPullRequestFieldError(self, number)
211
+ return None
212
+ match self.shape:
213
+ case PullRequestFieldShape.BRANCH_REFERENCE:
214
+ return self._branch_reference(value, number)
215
+ case PullRequestFieldShape.LABEL_NAMES:
216
+ return [
217
+ label if isinstance(label, str) else str(label["name"])
218
+ for label in value
219
+ ]
220
+ case PullRequestFieldShape.ACCOUNT_LOGINS:
221
+ return [str(account[AccountField.LOGIN]) for account in value]
222
+ case _:
223
+ return value
224
+
225
+ def _branch_reference(self, value: Any, number: int | None) -> str:
226
+ """:param value: The field's value, plain or nested.
227
+ :param number: The pull request being read, named in any rejection.
228
+ :return: The branch it names.
229
+ :raises MissingPullRequestFieldError: If it names none."""
230
+ if isinstance(value, str):
231
+ return value
232
+ if isinstance(value, Mapping) and value.get(PullRequestHeadKey.REFERENCE):
233
+ return str(value[PullRequestHeadKey.REFERENCE])
234
+ raise MissingPullRequestFieldError(self, number)
235
+
236
+
237
+ @dataclass
238
+ class MissingPullRequestFieldError(CommandFailure, ValueError):
239
+ """
240
+ Raised when a fetched pull request omits a field the board is derived from.
241
+
242
+ A fetch that drops a field is not partially correct: absent and legitimately empty
243
+ are different facts, and defaulting one to the other is what makes bad board data
244
+ indistinguishable from good.
245
+ """
246
+
247
+ @classproperty
248
+ def exit_code(cls) -> StackExitCode:
249
+ """:return: The status this kind of error ends a command with."""
250
+ return StackExitCode.USAGE
251
+
252
+ field_name: PullRequestField
253
+ """
254
+ The field that was absent.
255
+ """
256
+
257
+ pull_request_number: int | None
258
+ """
259
+ The pull request it was absent from, or ``None`` when the number itself is.
260
+ """
261
+
262
+ def __str__(self) -> str:
263
+ """:return: Which field is missing, and from where."""
264
+ subject = (
265
+ f"pull request {self.pull_request_number}"
266
+ if self.pull_request_number is not None
267
+ else "a fetched pull request"
268
+ )
269
+ return (
270
+ f"{subject} has no '{self.field_name}'; the board cannot be derived from a "
271
+ f"fetch that omits it"
272
+ )
273
+
274
+
275
+ # %% the pull request's head
276
+
277
+
278
+ @dataclass(frozen=True)
279
+ class PullRequestHead:
280
+ """
281
+ The branch a pull request would merge, where it lives, and the commit it is at.
282
+ """
283
+
284
+ branch: str
285
+ """
286
+ The head branch's name.
287
+ """
288
+
289
+ repository: str | None
290
+ """
291
+ The ``owner/name`` of the repository the head branch lives in, ``None`` once that
292
+ repository is deleted.
293
+ """
294
+
295
+ commit: str
296
+ """
297
+ The commit the head branch points at.
298
+ """
299
+
300
+ @staticmethod
301
+ def commit_in(record: PullRequestRecord) -> str | None:
302
+ """
303
+ :param record: The fetched pull request.
304
+ :return: The commit its head points at, or ``None`` when the record carries no
305
+ head object naming one.
306
+ """
307
+ head = record.get(PullRequestField.HEAD.key)
308
+ if not isinstance(head, Mapping):
309
+ return None
310
+ return head.get(PullRequestHeadKey.COMMIT)
311
+
312
+ @classmethod
313
+ def numbers_by_branch(
314
+ cls, records: Iterable[PullRequestRecord], repository: str
315
+ ) -> dict[str, int]:
316
+ """
317
+ :param records: Fetched pull requests.
318
+ :param repository: The ``owner/name`` of a repository their heads may live in.
319
+ :return: The number of the pull request opened from each branch of *repository*.
320
+ :raises MissingPullRequestFieldError: If a record omits its number or its head.
321
+ """
322
+ numbers_by_branch = {}
323
+ for record in records:
324
+ number = int(PullRequestField.NUMBER.read(record))
325
+ head = cls.from_record(record, number)
326
+ if head.repository == repository:
327
+ numbers_by_branch[head.branch] = number
328
+ return numbers_by_branch
329
+
330
+ @classmethod
331
+ def from_record(cls, record: PullRequestRecord, number: int) -> PullRequestHead:
332
+ """
333
+ :param record: The fetched pull request.
334
+ :param number: The pull request being read, named in any rejection.
335
+ :return: Its head.
336
+ :raises MissingPullRequestFieldError: If the head does not say where it lives or
337
+ which commit it is at.
338
+ """
339
+ head = record.get(PullRequestField.HEAD.key)
340
+ if (
341
+ not isinstance(head, Mapping)
342
+ or PullRequestHeadKey.HEAD_REPOSITORY not in head
343
+ or not head.get(PullRequestHeadKey.COMMIT)
344
+ ):
345
+ raise MissingPullRequestFieldError(PullRequestField.HEAD, number)
346
+ repository = head[PullRequestHeadKey.HEAD_REPOSITORY]
347
+ return cls(
348
+ branch=PullRequestField.HEAD.read(record, number),
349
+ repository=(
350
+ None
351
+ if repository is None
352
+ else str(repository[PullRequestHeadKey.FULL_NAME])
353
+ ),
354
+ commit=str(head[PullRequestHeadKey.COMMIT]),
355
+ )
356
+
357
+
358
+ # %% the checks on a pull request's head
359
+
360
+
361
+ class CommitChecks(ABC):
362
+ """
363
+ Reading the verdict over the checks reported on one commit.
364
+ """
365
+
366
+ @abstractmethod
367
+ def check_state(self, commit: str) -> CombinedCheckState:
368
+ """:param commit: The commit the checks ran on.
369
+ :return: The verdict over every check run and commit status reported on it."""