quality-graph-github 0.1.7__tar.gz → 0.1.8__tar.gz

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 (21) hide show
  1. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/PKG-INFO +2 -2
  2. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/pyproject.toml +2 -2
  3. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/commands.py +21 -14
  4. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/compiler.py +26 -5
  5. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/publication.py +57 -12
  6. quality_graph_github-0.1.8/src/qg_github/required_checks.py +389 -0
  7. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/runtime.py +8 -1
  8. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/.gitignore +0 -0
  9. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/README.md +0 -0
  10. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/__init__.py +0 -0
  11. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/annotations.py +0 -0
  12. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/approvals.py +0 -0
  13. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/artifacts.py +0 -0
  14. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/comments.py +0 -0
  15. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/controls.py +0 -0
  16. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/dashboard.py +0 -0
  17. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/github.py +0 -0
  18. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/labels.py +0 -0
  19. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/provider.py +0 -0
  20. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/py.typed +0 -0
  21. {quality_graph_github-0.1.7 → quality_graph_github-0.1.8}/src/qg_github/reporting.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quality-graph-github
3
- Version: 0.1.7
3
+ Version: 0.1.8
4
4
  Summary: GitHub provider and Action runtime for Quality Graph
5
5
  Project-URL: Homepage, https://alchemmist.github.io/quality-graph/
6
6
  Project-URL: Documentation, https://alchemmist.github.io/quality-graph/
@@ -9,7 +9,7 @@ Requires-Python: >=3.12
9
9
  Requires-Dist: httpx>=0.28.1
10
10
  Requires-Dist: jinja2>=3.1.6
11
11
  Requires-Dist: pyyaml>=6.0.2
12
- Requires-Dist: quality-graph-core==0.1.7
12
+ Requires-Dist: quality-graph-core==0.1.8
13
13
  Description-Content-Type: text/markdown
14
14
 
15
15
  # Quality Graph GitHub Provider
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "quality-graph-github"
7
- version = "0.1.7"
7
+ version = "0.1.8"
8
8
  description = "GitHub provider and Action runtime for Quality Graph"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -13,7 +13,7 @@ dependencies = [
13
13
  "httpx>=0.28.1",
14
14
  "jinja2>=3.1.6",
15
15
  "pyyaml>=6.0.2",
16
- "quality-graph-core==0.1.7",
16
+ "quality-graph-core==0.1.8",
17
17
  ]
18
18
 
19
19
  [project.urls]
@@ -185,7 +185,7 @@ def _command_context(port: GitHubPort, number: int) -> CommandContext:
185
185
  base = _object(pull.get("base"), "pull request base")
186
186
  head_sha = _string(head.get("sha"), "pull request head SHA")
187
187
  base_sha = _string(base.get("sha"), "pull request base SHA")
188
- graph = Graph.from_yaml(_repository_file(port, "quality-graph.yml", base_sha))
188
+ graph = Graph.from_yaml(_repository_file(port, "qg.yaml", base_sha))
189
189
  compiled = compile_graph(graph)
190
190
  graph = project_graph(graph, "pull-request")
191
191
  run = _latest_run(port, number)
@@ -208,20 +208,27 @@ def _command_context(port: GitHubPort, number: int) -> CommandContext:
208
208
 
209
209
 
210
210
  def _latest_run(port: GitHubPort, number: int) -> dict[str, JsonValue]:
211
- path = (
212
- "/actions/workflows/quality-graph.yml/runs?event=pull_request"
213
- f"&per_page={GITHUB_PAGE_SIZE}&page=1"
214
- )
215
- response = _object(port.request("GET", path), "workflow runs")
216
- runs = [
217
- run
218
- for value in _array(response.get("workflow_runs", []), "workflow runs")
219
- for run in (_object(value, "workflow run"),)
220
- if any(
221
- _object(pull, "workflow pull request").get("number") == number
222
- for pull in _array(run.get("pull_requests", []), "workflow pull requests")
211
+ runs: list[dict[str, JsonValue]] = []
212
+ page = 1
213
+ while True:
214
+ path = (
215
+ "/actions/workflows/quality-graph.yml/runs?event=pull_request"
216
+ f"&per_page={GITHUB_PAGE_SIZE}&page={page}"
217
+ )
218
+ response = _object(port.request("GET", path), "workflow runs")
219
+ values = _array(response.get("workflow_runs", []), "workflow runs")
220
+ runs.extend(
221
+ run
222
+ for value in values
223
+ for run in (_object(value, "workflow run"),)
224
+ if any(
225
+ _object(pull, "workflow pull request").get("number") == number
226
+ for pull in _array(run.get("pull_requests", []), "workflow pull requests")
227
+ )
223
228
  )
224
- ]
229
+ if len(values) < GITHUB_PAGE_SIZE:
230
+ break
231
+ page += 1
225
232
  if not runs:
226
233
  message = f"no Quality Graph workflow run found for PR #{number}"
227
234
  raise ValueError(message)
@@ -20,8 +20,7 @@ if TYPE_CHECKING:
20
20
  from quality_graph_core.result import JsonValue
21
21
 
22
22
  GENERATED_NOTICE = (
23
- "Generated by Quality Graph. DO NOT EDIT MANUALLY. "
24
- "Update quality-graph.yml and run qg generate."
23
+ "Generated by Quality Graph. DO NOT EDIT MANUALLY. Update qg.yaml and run qg generate."
25
24
  )
26
25
  GENERATED_HEADER = f"# {GENERATED_NOTICE}\n---\n"
27
26
  EXECUTION_WORKFLOW = PurePosixPath(".github/workflows/quality-graph.yml")
@@ -66,6 +65,7 @@ class _GitHubConfiguration:
66
65
  publisher_action: str
67
66
  upload_artifact_action: str
68
67
  default_branch: str
68
+ merge_required: bool
69
69
 
70
70
 
71
71
  class WorkflowDumper(yaml.SafeDumper):
@@ -86,7 +86,7 @@ def _validate_github_graph(graph: Graph) -> _GitHubConfiguration:
86
86
  if graph.provider.name != "github":
87
87
  message = f"GitHub provider cannot compile provider '{graph.provider.name}'"
88
88
  raise ValueError(message)
89
- unknown = graph.provider.values.keys() - {"default-branch", "runtime"}
89
+ unknown = graph.provider.values.keys() - {"default-branch", "runtime", "merge"}
90
90
  if unknown:
91
91
  message = f"GitHub provider contains unknown configuration: {', '.join(sorted(unknown))}"
92
92
  raise ValueError(message)
@@ -101,6 +101,7 @@ def _validate_github_graph(graph: Graph) -> _GitHubConfiguration:
101
101
  publisher_action = _runtime_action(runtime.get("publisher-action", action), "publisher")
102
102
  upload_artifact_action = _upload_artifact_action(runtime)
103
103
  default_branch = _default_branch(graph.provider.values.get("default-branch"))
104
+ merge_required = _merge_required(graph.provider.values.get("merge", {}))
104
105
  if publisher_action.partition("@")[0] != action.partition("@")[0]:
105
106
  message = "GitHub publisher action must use the runtime action repository"
106
107
  raise ValueError(message)
@@ -115,7 +116,27 @@ def _validate_github_graph(graph: Graph) -> _GitHubConfiguration:
115
116
  message = "GitHub dashboard requires unique node titles"
116
117
  raise ValueError(message)
117
118
  _event_projections(graph)
118
- return _GitHubConfiguration(action, publisher_action, upload_artifact_action, default_branch)
119
+ return _GitHubConfiguration(
120
+ action,
121
+ publisher_action,
122
+ upload_artifact_action,
123
+ default_branch,
124
+ merge_required,
125
+ )
126
+
127
+
128
+ def _merge_required(merge: JsonValue) -> bool:
129
+ if not isinstance(merge, dict):
130
+ message = "GitHub merge configuration must be an object"
131
+ raise TypeError(message)
132
+ if merge.keys() - {"required"}:
133
+ message = "GitHub merge configuration contains unknown fields"
134
+ raise ValueError(message)
135
+ merge_required = merge.get("required", False)
136
+ if not isinstance(merge_required, bool):
137
+ message = "GitHub merge required must be a boolean"
138
+ raise TypeError(message)
139
+ return merge_required
119
140
 
120
141
 
121
142
  def _event_projections(graph: Graph) -> tuple[EventProjection, ...]:
@@ -542,7 +563,7 @@ def _publication_workflow(runtime_action: str) -> dict[str, JsonValue]:
542
563
  "on": {
543
564
  "workflow_run": {
544
565
  "workflows": ["Quality Graph"],
545
- "types": ["requested", "in_progress", "completed"],
566
+ "types": ["requested", "completed"],
546
567
  },
547
568
  "issue_comment": {"types": ["created", "edited"]},
548
569
  },
@@ -34,6 +34,8 @@ if TYPE_CHECKING:
34
34
 
35
35
  from quality_graph_core.result import Result
36
36
 
37
+ PUBLISH_POLL_INTERVAL_SECONDS = 30.0
38
+
37
39
 
38
40
  @dataclass(frozen=True)
39
41
  class WorkflowRunEvent:
@@ -108,7 +110,17 @@ def publish_workflow_run(
108
110
  return PublicationOutcome(published=False)
109
111
  if not _is_latest_run(port, event, number):
110
112
  return PublicationOutcome(published=False)
111
- graph = Graph.from_yaml(_repository_file(port, "quality-graph.yml", pull.base_sha))
113
+ graph = Graph.from_yaml(_repository_file(port, "qg.yaml", pull.base_sha))
114
+ return _publish_completed_workflow_run(port, event, number, pull, graph)
115
+
116
+
117
+ def _publish_completed_workflow_run(
118
+ port: GitHubPort,
119
+ event: WorkflowRunEvent,
120
+ number: int,
121
+ pull: PullRequestState,
122
+ graph: Graph,
123
+ ) -> PublicationOutcome:
112
124
  compiled = compile_graph(graph)
113
125
  graph = project_graph(graph, "pull-request")
114
126
  run = DashboardRun(event.id, event.attempt, pull.head_sha, event.url)
@@ -140,12 +152,12 @@ def watch_workflow_run(
140
152
  port: GitHubPort,
141
153
  event_value: JsonValue,
142
154
  *,
143
- poll_interval: float = 5.0,
155
+ poll_interval: float = PUBLISH_POLL_INTERVAL_SECONDS,
144
156
  sleep: Callable[[float], None] = time.sleep,
145
157
  ) -> PublicationOutcome:
146
158
  """Serialize live dashboard updates from authoritative GitHub job state."""
147
159
  event = WorkflowRunEvent.from_value(event_value)
148
- if event.event != "pull_request" or event.action not in {"requested", "in_progress"}:
160
+ if event.event != "pull_request" or event.action != "requested":
149
161
  return PublicationOutcome(published=False)
150
162
  number = event.pull_request or _resolve_pull_request(port, event.workflow_head_sha)
151
163
  if number is None:
@@ -155,18 +167,20 @@ def watch_workflow_run(
155
167
  return PublicationOutcome(published=False)
156
168
  if not _is_latest_run(port, event, number):
157
169
  return PublicationOutcome(published=False)
158
- graph = Graph.from_yaml(_repository_file(port, "quality-graph.yml", pull.base_sha))
159
- graph = project_graph(graph, "pull-request")
160
- nodes = tuple(DashboardNode(node.id, node.title) for node in graph.nodes)
170
+ graph = Graph.from_yaml(_repository_file(port, "qg.yaml", pull.base_sha))
171
+ projected = project_graph(graph, "pull-request")
172
+ nodes = tuple(DashboardNode(node.id, node.title) for node in projected.nodes)
161
173
  run = DashboardRun(event.id, event.attempt, pull.head_sha, event.url)
162
- _publish_check(port, pending_dashboard(graph, run))
174
+ _publish_check(port, pending_dashboard(projected, run))
163
175
 
164
176
  def is_current() -> bool:
165
177
  return _is_latest_run(port, event, number)
166
178
 
167
179
  while not publish_workflow_jobs(port, number, nodes, run, is_current=is_current):
168
180
  sleep(poll_interval)
169
- return PublicationOutcome(published=True, status=ResultStatus.IN_PROGRESS)
181
+ if not is_current():
182
+ return PublicationOutcome(published=False)
183
+ return _publish_completed_workflow_run(port, event, number, pull, graph)
170
184
 
171
185
 
172
186
  def publish_workflow_jobs(
@@ -185,6 +199,8 @@ def publish_workflow_jobs(
185
199
  )
186
200
  if terminal or not is_current():
187
201
  return True
202
+ if len(statuses) < len(nodes) and _workflow_run_completed(port, run.id):
203
+ return True
188
204
  existing = find_managed_comment(port, number, DASHBOARD_MARKER)
189
205
  previous_labels = parse_label_state(existing.body) if existing is not None else frozenset()
190
206
  model = live_dashboard(nodes, statuses, run, managed_labels=tuple(sorted(previous_labels)))
@@ -192,6 +208,11 @@ def publish_workflow_jobs(
192
208
  return terminal
193
209
 
194
210
 
211
+ def _workflow_run_completed(port: GitHubPort, run_id: int) -> bool:
212
+ run = _object(port.request("GET", f"/actions/runs/{run_id}"), "workflow run")
213
+ return _string(run.get("status"), "workflow run status") == "completed"
214
+
215
+
195
216
  def _workflow_jobs(port: GitHubPort, run_id: int) -> tuple[JsonValue, ...]:
196
217
  jobs: list[JsonValue] = []
197
218
  page = 1
@@ -319,15 +340,15 @@ def _is_latest_run(port: GitHubPort, event: WorkflowRunEvent, number: int) -> bo
319
340
  )
320
341
  response = _object(port.request("GET", path), "workflow runs")
321
342
  runs = _array(response.get("workflow_runs", []), "workflow runs")
322
- matching_ids = [
323
- run_id
343
+ matching_runs = [
344
+ (run_id, _integer(run.get("run_attempt", 1), "workflow run attempt"))
324
345
  for value in runs
325
346
  for run in (_object(value, "workflow run"),)
326
347
  if _run_has_pull(run, number)
327
348
  for run_id in (_optional_integer(run.get("id"), "workflow run id"),)
328
349
  if run_id is not None
329
350
  ]
330
- return not matching_ids or event.id >= max(matching_ids)
351
+ return not matching_runs or (event.id, event.attempt) >= max(matching_runs)
331
352
 
332
353
 
333
354
  def _run_has_pull(run: Mapping[str, JsonValue], number: int) -> bool:
@@ -354,9 +375,11 @@ def _repository_file(port: GitHubPort, path: str, ref: str) -> str:
354
375
 
355
376
  def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
356
377
  completed = model.status not in {ResultStatus.WAITING, ResultStatus.IN_PROGRESS}
378
+ external_id = f"quality-graph:{model.run_id}:{model.run_attempt}"
357
379
  payload: dict[str, JsonValue] = {
358
380
  "name": "Quality Graph",
359
381
  "head_sha": model.head_sha,
382
+ "external_id": external_id,
360
383
  "status": "completed" if completed else "in_progress",
361
384
  "details_url": next((row.logs_url for row in model.rows), ""),
362
385
  "output": {
@@ -366,7 +389,29 @@ def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
366
389
  }
367
390
  if completed:
368
391
  payload["conclusion"] = "success" if model.status is ResultStatus.PASSED else "failure"
369
- port.request("POST", "/check-runs", payload)
392
+ name = urllib.parse.quote("Quality Graph", safe="")
393
+ response = _object(
394
+ port.request(
395
+ "GET",
396
+ f"/commits/{model.head_sha}/check-runs"
397
+ f"?check_name={name}&filter=all&per_page={GITHUB_PAGE_SIZE}",
398
+ ),
399
+ "check runs",
400
+ )
401
+ check_id = next(
402
+ (
403
+ _optional_integer(check.get("id"), "check run id")
404
+ for value in _array(response.get("check_runs", []), "check runs")
405
+ for check in (_object(value, "check run"),)
406
+ if check.get("external_id") == external_id
407
+ ),
408
+ None,
409
+ )
410
+ if check_id is None:
411
+ port.request("POST", "/check-runs", payload)
412
+ return
413
+ update = {key: value for key, value in payload.items() if key != "head_sha"}
414
+ port.request("PATCH", f"/check-runs/{check_id}", update)
370
415
 
371
416
 
372
417
  def read_event_json(value: str) -> dict[str, JsonValue]:
@@ -0,0 +1,389 @@
1
+ """Synchronize GitHub merge requirements from the graph declaration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import urllib.parse
6
+ from dataclasses import dataclass, replace
7
+ from http import HTTPStatus
8
+ from typing import TYPE_CHECKING, cast
9
+
10
+ from qg_github.compiler import _validate_github_graph
11
+ from qg_github.github import GitHubError
12
+
13
+ if TYPE_CHECKING:
14
+ from qg_github.github import GitHubPort
15
+ from quality_graph_core.graph import Graph
16
+ from quality_graph_core.result import JsonValue
17
+
18
+ QUALITY_GRAPH_CONTEXT = "Quality Graph"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class RequiredChecksPlan:
23
+ """Describe one deterministic settings mutation before it is applied."""
24
+
25
+ surface: str
26
+ branch: str
27
+ method: str | None
28
+ path: str | None
29
+ payload: JsonValue
30
+ before: tuple[str, ...]
31
+ after: tuple[str, ...]
32
+
33
+ @property
34
+ def changed(self) -> bool:
35
+ """Return whether applying the plan would mutate GitHub."""
36
+ return self.method is not None
37
+
38
+ def render(self) -> str:
39
+ """Render the planned context diff for human confirmation."""
40
+ removed = sorted(set(self.before) - set(self.after))
41
+ added = sorted(set(self.after) - set(self.before))
42
+ changes = [*(f"- {item}" for item in removed), *(f"+ {item}" for item in added)]
43
+ detail = "\n".join(changes) if changes else " unchanged"
44
+ return f"Required checks plan ({self.surface}, {self.branch}):\n{detail}\n"
45
+
46
+
47
+ def plan_required_checks(port: GitHubPort, graph: Graph) -> RequiredChecksPlan:
48
+ """Read effective protection and return a preservation-safe mutation plan."""
49
+ configuration = _validate_github_graph(graph)
50
+ branch = configuration.default_branch
51
+ encoded = urllib.parse.quote(branch, safe="")
52
+ rules = _array(_request(port, "GET", f"/rules/branches/{encoded}"), "branch rules")
53
+ sources = {
54
+ (
55
+ _string(rule.get("ruleset_source_type"), "ruleset source type"),
56
+ _integer(rule.get("ruleset_id"), "ruleset id"),
57
+ )
58
+ for value in rules
59
+ for rule in (_object(value, "branch rule"),)
60
+ }
61
+ required_sources = {
62
+ source
63
+ for value in rules
64
+ for rule in (_object(value, "branch rule"),)
65
+ for source in (
66
+ (
67
+ _string(rule.get("ruleset_source_type"), "ruleset source type"),
68
+ _integer(rule.get("ruleset_id"), "ruleset id"),
69
+ ),
70
+ )
71
+ if rule.get("type") == "required_status_checks"
72
+ }
73
+ required_repository = [source for source in required_sources if source[0] == "Repository"]
74
+ required_organization = [source for source in required_sources if source[0] == "Organization"]
75
+ if required_organization:
76
+ message = (
77
+ "Required checks are controlled by an organization ruleset; "
78
+ "synchronize it with organization Administration write permission"
79
+ )
80
+ raise PermissionError(message)
81
+ classic_path = f"/branches/{encoded}/protection/required_status_checks"
82
+ classic_status = _request(port, "GET", classic_path)
83
+ if required_repository and classic_status is not None:
84
+ message = (
85
+ "Required checks are configured in both classic protection and a repository ruleset"
86
+ )
87
+ raise ValueError(message)
88
+ repository = required_repository or [source for source in sources if source[0] == "Repository"]
89
+ if len(required_repository) == 1:
90
+ return _ruleset_plan(port, branch, repository[0][1], required=configuration.merge_required)
91
+ if classic_status is not None:
92
+ return _classic_plan(
93
+ port,
94
+ branch,
95
+ encoded,
96
+ classic_status,
97
+ required=configuration.merge_required,
98
+ )
99
+ if len(repository) == 1:
100
+ return _ruleset_plan(port, branch, repository[0][1], required=configuration.merge_required)
101
+ if len(repository) > 1:
102
+ message = "Expected exactly one applicable repository ruleset"
103
+ raise ValueError(message)
104
+ return _classic_plan(
105
+ port,
106
+ branch,
107
+ encoded,
108
+ classic_status,
109
+ required=configuration.merge_required,
110
+ )
111
+
112
+
113
+ def apply_required_checks(port: GitHubPort, plan: RequiredChecksPlan) -> None:
114
+ """Apply a previously displayed synchronization plan."""
115
+ if plan.method is not None and plan.path is not None:
116
+ _request(port, plan.method, plan.path, plan.payload)
117
+
118
+
119
+ def _ruleset_plan(
120
+ port: GitHubPort,
121
+ branch: str,
122
+ ruleset_id: int,
123
+ *,
124
+ required: bool,
125
+ ) -> RequiredChecksPlan:
126
+ path = f"/rulesets/{ruleset_id}"
127
+ ruleset = _object(_request(port, "GET", path), "repository ruleset")
128
+ rules = _array(ruleset.get("rules"), "repository ruleset rules")
129
+ index = next(
130
+ (
131
+ position
132
+ for position, value in enumerate(rules)
133
+ if _object(value, "ruleset rule").get("type") == "required_status_checks"
134
+ ),
135
+ None,
136
+ )
137
+ if index is None:
138
+ if not required:
139
+ return RequiredChecksPlan("repository ruleset", branch, None, None, None, (), ())
140
+ desired_rules: list[JsonValue] = list(rules)
141
+ desired_rules.append(
142
+ {
143
+ "type": "required_status_checks",
144
+ "parameters": {
145
+ "do_not_enforce_on_create": False,
146
+ "required_status_checks": [{"context": QUALITY_GRAPH_CONTEXT}],
147
+ "strict_required_status_checks_policy": False,
148
+ },
149
+ }
150
+ )
151
+ plan = RequiredChecksPlan(
152
+ "repository ruleset", branch, None, None, None, (), (QUALITY_GRAPH_CONTEXT,)
153
+ )
154
+ return _ruleset_update(ruleset, desired_rules, path, plan)
155
+ current_rule = _object(rules[index], "required status checks rule")
156
+ parameters = _object(current_rule.get("parameters"), "required status checks parameters")
157
+ checks = _array(parameters.get("required_status_checks"), "required status checks")
158
+ before = tuple(
159
+ _string(_object(value, "required status check").get("context"), "status context")
160
+ for value in checks
161
+ )
162
+ desired_checks = _desired_check_objects(checks, required=required)
163
+ after = tuple(
164
+ _string(_object(value, "required status check").get("context"), "status context")
165
+ for value in desired_checks
166
+ )
167
+ if checks == desired_checks:
168
+ return RequiredChecksPlan("repository ruleset", branch, None, None, None, before, after)
169
+ desired_rules = list(rules)
170
+ if desired_checks:
171
+ desired_rule = current_rule | {
172
+ "parameters": parameters | {"required_status_checks": desired_checks}
173
+ }
174
+ desired_rules[index] = desired_rule
175
+ else:
176
+ desired_rules.pop(index)
177
+ plan = RequiredChecksPlan("repository ruleset", branch, None, None, None, before, after)
178
+ return _ruleset_update(ruleset, desired_rules, path, plan)
179
+
180
+
181
+ def _ruleset_update(
182
+ ruleset: dict[str, JsonValue],
183
+ rules: list[JsonValue],
184
+ path: str,
185
+ plan: RequiredChecksPlan,
186
+ ) -> RequiredChecksPlan:
187
+ payload: dict[str, JsonValue] = {
188
+ key: ruleset[key]
189
+ for key in ("name", "target", "enforcement", "bypass_actors", "conditions")
190
+ if key in ruleset
191
+ }
192
+ payload["rules"] = rules
193
+ return replace(plan, method="PUT", path=path, payload=payload)
194
+
195
+
196
+ def _classic_plan(
197
+ port: GitHubPort,
198
+ branch: str,
199
+ encoded: str,
200
+ status: JsonValue,
201
+ *,
202
+ required: bool,
203
+ ) -> RequiredChecksPlan:
204
+ path = f"/branches/{encoded}/protection/required_status_checks"
205
+ full_protection: dict[str, JsonValue] | None = None
206
+ if status is None:
207
+ if not required:
208
+ return RequiredChecksPlan("classic branch protection", branch, None, None, None, (), ())
209
+ protection = _request(port, "GET", f"/branches/{encoded}/protection")
210
+ if protection is None:
211
+ message = "Default branch has neither branch protection nor an applicable ruleset"
212
+ raise ValueError(message)
213
+ before: tuple[str, ...] = ()
214
+ strict = False
215
+ checks: list[JsonValue] | None = None
216
+ full_protection = _object(protection, "branch protection")
217
+ else:
218
+ value = _object(status, "required status check protection")
219
+ strict = bool(value.get("strict", False))
220
+ raw_checks = value.get("checks")
221
+ checks = None if raw_checks is None else _array(raw_checks, "status checks")
222
+ if checks is None:
223
+ contexts = _array(value.get("contexts", []), "status contexts")
224
+ before = tuple(_string(item, "status context") for item in contexts)
225
+ else:
226
+ before = tuple(
227
+ _string(_object(item, "status check").get("context"), "status context")
228
+ for item in checks
229
+ )
230
+ desired = _desired_contexts(before, required=required)
231
+ if before == desired:
232
+ return RequiredChecksPlan(
233
+ "classic branch protection", branch, None, None, None, before, desired
234
+ )
235
+ if status is None:
236
+ protection_payload = cast("dict[str, JsonValue]", full_protection)
237
+ required_checks: JsonValue = {"strict": strict, "contexts": list(desired)}
238
+ put_payload = _branch_protection_payload(protection_payload, required_checks)
239
+ return RequiredChecksPlan(
240
+ "classic branch protection",
241
+ branch,
242
+ "PUT",
243
+ f"/branches/{encoded}/protection",
244
+ put_payload,
245
+ before,
246
+ desired,
247
+ )
248
+ if checks is None:
249
+ payload: JsonValue = {"strict": strict, "contexts": list(desired)}
250
+ else:
251
+ desired_checks = _desired_check_objects(checks, required=required)
252
+ payload = {"strict": strict, "checks": desired_checks}
253
+ return RequiredChecksPlan(
254
+ "classic branch protection", branch, "PATCH", path, payload, before, desired
255
+ )
256
+
257
+
258
+ def _branch_protection_payload(
259
+ protection: dict[str, JsonValue], required_checks: JsonValue
260
+ ) -> JsonValue:
261
+ payload: dict[str, JsonValue] = {
262
+ "required_status_checks": required_checks,
263
+ "enforce_admins": _enabled_or_none(protection.get("enforce_admins")),
264
+ "required_pull_request_reviews": _pull_request_reviews(
265
+ protection.get("required_pull_request_reviews")
266
+ ),
267
+ "restrictions": _restrictions(protection.get("restrictions")),
268
+ }
269
+ for key in (
270
+ "required_linear_history",
271
+ "allow_force_pushes",
272
+ "allow_deletions",
273
+ "block_creations",
274
+ "required_conversation_resolution",
275
+ "lock_branch",
276
+ "allow_fork_syncing",
277
+ ):
278
+ if key in protection:
279
+ payload[key] = _enabled(protection[key], key)
280
+ return payload
281
+
282
+
283
+ def _pull_request_reviews(value: JsonValue) -> JsonValue:
284
+ if value is None:
285
+ return None
286
+ reviews = _object(value, "pull request review protection")
287
+ payload: dict[str, JsonValue] = {
288
+ key: reviews[key]
289
+ for key in (
290
+ "dismiss_stale_reviews",
291
+ "require_code_owner_reviews",
292
+ "required_approving_review_count",
293
+ "require_last_push_approval",
294
+ )
295
+ if key in reviews
296
+ }
297
+ for key in ("dismissal_restrictions", "bypass_pull_request_allowances"):
298
+ if key in reviews:
299
+ payload[key] = _restrictions(reviews[key])
300
+ return payload
301
+
302
+
303
+ def _restrictions(value: JsonValue) -> JsonValue:
304
+ if value is None:
305
+ return None
306
+ restrictions = _object(value, "branch restrictions")
307
+ return {
308
+ "users": _actor_names(restrictions.get("users", []), "login"),
309
+ "teams": _actor_names(restrictions.get("teams", []), "slug"),
310
+ "apps": _actor_names(restrictions.get("apps", []), "slug"),
311
+ }
312
+
313
+
314
+ def _actor_names(value: JsonValue, field: str) -> list[JsonValue]:
315
+ return [
316
+ _string(_object(actor, "branch restriction actor").get(field), field)
317
+ for actor in _array(value, "branch restriction actors")
318
+ ]
319
+
320
+
321
+ def _enabled_or_none(value: JsonValue) -> JsonValue:
322
+ return None if value is None else _enabled(value, "branch protection")
323
+
324
+
325
+ def _enabled(value: JsonValue, context: str) -> bool:
326
+ enabled = _object(value, context).get("enabled")
327
+ if not isinstance(enabled, bool):
328
+ message = f"{context} enabled must be a boolean"
329
+ raise TypeError(message)
330
+ return enabled
331
+
332
+
333
+ def _desired_check_objects(checks: list[JsonValue], *, required: bool) -> list[JsonValue]:
334
+ managed = [
335
+ item
336
+ for item in checks
337
+ if _object(item, "status check").get("context") == QUALITY_GRAPH_CONTEXT
338
+ ]
339
+ if required and managed:
340
+ return list(checks)
341
+ desired = [item for item in checks if item not in managed]
342
+ if required:
343
+ desired.append({"context": QUALITY_GRAPH_CONTEXT})
344
+ return desired
345
+
346
+
347
+ def _desired_contexts(contexts: tuple[str, ...], *, required: bool) -> tuple[str, ...]:
348
+ if required and QUALITY_GRAPH_CONTEXT in contexts:
349
+ return contexts
350
+ desired = tuple(item for item in contexts if item != QUALITY_GRAPH_CONTEXT)
351
+ return (*desired, QUALITY_GRAPH_CONTEXT) if required else desired
352
+
353
+
354
+ def _request(port: GitHubPort, method: str, path: str, payload: JsonValue = None) -> JsonValue:
355
+ try:
356
+ return port.request(method, path, payload)
357
+ except GitHubError as error:
358
+ if error.status_code == HTTPStatus.FORBIDDEN:
359
+ message = "GitHub token requires repository Administration write permission"
360
+ raise PermissionError(message) from error
361
+ raise
362
+
363
+
364
+ def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
365
+ if not isinstance(value, dict):
366
+ message = f"{context} must be an object"
367
+ raise TypeError(message)
368
+ return value
369
+
370
+
371
+ def _array(value: JsonValue, context: str) -> list[JsonValue]:
372
+ if not isinstance(value, list):
373
+ message = f"{context} must be an array"
374
+ raise TypeError(message)
375
+ return value
376
+
377
+
378
+ def _string(value: JsonValue, context: str) -> str:
379
+ if not isinstance(value, str):
380
+ message = f"{context} must be a string"
381
+ raise TypeError(message)
382
+ return value
383
+
384
+
385
+ def _integer(value: JsonValue, context: str) -> int:
386
+ if not isinstance(value, int) or isinstance(value, bool):
387
+ message = f"{context} must be an integer"
388
+ raise TypeError(message)
389
+ return value
@@ -92,9 +92,16 @@ def collect(request: CollectionRequest) -> Result:
92
92
  try:
93
93
  if request.adapter is AdapterKind.EXIT_CODE:
94
94
  state = "passed" if request.context.command_succeeded else "failed"
95
+ output = f"The declared command {state}."
96
+ if request.report_path is not None:
97
+ try:
98
+ output = read_report(request.workspace, request.report_path).decode()
99
+ except UnicodeDecodeError as error:
100
+ message = "Exit-code command output must be UTF-8"
101
+ raise AdapterError(message) from error
95
102
  return _with_policy_controls(
96
103
  request,
97
- adapt_exit(request.context, f"The declared command {state}."),
104
+ adapt_exit(request.context, output),
98
105
  )
99
106
  report = _structured_report(request)
100
107
  if request.adapter is AdapterKind.NATIVE: