quality-graph-github 0.1.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.
- qg_github/__init__.py +5 -0
- qg_github/annotations.py +93 -0
- qg_github/approvals.py +172 -0
- qg_github/artifacts.py +216 -0
- qg_github/commands.py +333 -0
- qg_github/comments.py +104 -0
- qg_github/compiler.py +398 -0
- qg_github/controls.py +67 -0
- qg_github/dashboard.py +267 -0
- qg_github/github.py +183 -0
- qg_github/labels.py +133 -0
- qg_github/provider.py +20 -0
- qg_github/publication.py +303 -0
- qg_github/py.typed +1 -0
- qg_github/reporting.py +97 -0
- qg_github/runtime.py +195 -0
- quality_graph_github-0.1.0.dist-info/METADATA +19 -0
- quality_graph_github-0.1.0.dist-info/RECORD +20 -0
- quality_graph_github-0.1.0.dist-info/WHEEL +4 -0
- quality_graph_github-0.1.0.dist-info/entry_points.txt +2 -0
qg_github/publication.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Publish trusted live and final pull-request Quality Graph state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import urllib.parse
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from typing import TYPE_CHECKING, cast
|
|
10
|
+
|
|
11
|
+
from qg_github.approvals import approval_ledger
|
|
12
|
+
from qg_github.artifacts import ArtifactError, ArtifactExpectation, download_results
|
|
13
|
+
from qg_github.comments import find_managed_comment, upsert_managed_comment
|
|
14
|
+
from qg_github.compiler import compile_graph
|
|
15
|
+
from qg_github.dashboard import (
|
|
16
|
+
DASHBOARD_MARKER,
|
|
17
|
+
DashboardModel,
|
|
18
|
+
DashboardRun,
|
|
19
|
+
final_dashboard,
|
|
20
|
+
pending_dashboard,
|
|
21
|
+
render_dashboard,
|
|
22
|
+
)
|
|
23
|
+
from qg_github.github import GITHUB_PAGE_SIZE, GitHubPort
|
|
24
|
+
from qg_github.labels import parse_label_state, reconcile_labels
|
|
25
|
+
from quality_graph_core.graph import Graph
|
|
26
|
+
from quality_graph_core.policy import effective_graph
|
|
27
|
+
from quality_graph_core.result import JsonValue, ResultStatus
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from collections.abc import Mapping
|
|
31
|
+
|
|
32
|
+
from quality_graph_core.result import Result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class WorkflowRunEvent:
|
|
37
|
+
"""Carry trusted workflow-run identity from one GitHub event."""
|
|
38
|
+
|
|
39
|
+
action: str
|
|
40
|
+
event: str
|
|
41
|
+
id: int
|
|
42
|
+
attempt: int
|
|
43
|
+
workflow_head_sha: str
|
|
44
|
+
pull_head_sha: str | None
|
|
45
|
+
url: str
|
|
46
|
+
pull_request: int | None
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_value(cls, value: JsonValue) -> WorkflowRunEvent:
|
|
50
|
+
"""Narrow an untrusted GitHub event payload."""
|
|
51
|
+
event = _object(value, "workflow event")
|
|
52
|
+
run = _object(event.get("workflow_run"), "workflow run")
|
|
53
|
+
pulls = _array(run.get("pull_requests", []), "workflow pull requests")
|
|
54
|
+
pull_number: int | None = None
|
|
55
|
+
pull_head: str | None = None
|
|
56
|
+
if pulls:
|
|
57
|
+
pull = _object(pulls[0], "workflow pull request")
|
|
58
|
+
pull_number = _optional_integer(pull.get("number"), "pull request number")
|
|
59
|
+
head = pull.get("head")
|
|
60
|
+
if isinstance(head, dict):
|
|
61
|
+
pull_head = _optional_string(head.get("sha"), "pull request head SHA")
|
|
62
|
+
return cls(
|
|
63
|
+
_string(event.get("action"), "workflow action"),
|
|
64
|
+
_string(run.get("event"), "workflow trigger event"),
|
|
65
|
+
_integer(run.get("id"), "workflow run id"),
|
|
66
|
+
_integer(run.get("run_attempt", 1), "workflow run attempt"),
|
|
67
|
+
_string(run.get("head_sha"), "workflow head SHA"),
|
|
68
|
+
pull_head,
|
|
69
|
+
_string(run.get("html_url"), "workflow run URL"),
|
|
70
|
+
pull_number,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class PullRequestState:
|
|
76
|
+
"""Carry current trusted pull-request and base revision state."""
|
|
77
|
+
|
|
78
|
+
number: int
|
|
79
|
+
head_sha: str
|
|
80
|
+
base_sha: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class PublicationOutcome:
|
|
85
|
+
"""Describe whether and what the publisher updated."""
|
|
86
|
+
|
|
87
|
+
published: bool
|
|
88
|
+
status: ResultStatus | None = None
|
|
89
|
+
comment_id: int | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def publish_workflow_run(
|
|
93
|
+
port: GitHubPort,
|
|
94
|
+
event_value: JsonValue,
|
|
95
|
+
) -> PublicationOutcome:
|
|
96
|
+
"""Publish one trusted workflow-run event if it is current."""
|
|
97
|
+
event = WorkflowRunEvent.from_value(event_value)
|
|
98
|
+
if event.event != "pull_request":
|
|
99
|
+
return PublicationOutcome(published=False)
|
|
100
|
+
number = event.pull_request or _resolve_pull_request(port, event.workflow_head_sha)
|
|
101
|
+
if number is None:
|
|
102
|
+
return PublicationOutcome(published=False)
|
|
103
|
+
pull = _pull_request(port, number)
|
|
104
|
+
if event.pull_head_sha is not None and event.pull_head_sha != pull.head_sha:
|
|
105
|
+
return PublicationOutcome(published=False)
|
|
106
|
+
if not _is_latest_run(port, event, number):
|
|
107
|
+
return PublicationOutcome(published=False)
|
|
108
|
+
graph = Graph.from_yaml(_repository_file(port, "quality-graph.yml", pull.base_sha))
|
|
109
|
+
compiled = compile_graph(graph)
|
|
110
|
+
run = DashboardRun(event.id, event.attempt, pull.head_sha, event.url)
|
|
111
|
+
effective_results: Mapping[str, Result] | None = None
|
|
112
|
+
if event.action in {"requested", "in_progress"}:
|
|
113
|
+
model = pending_dashboard(graph, run)
|
|
114
|
+
elif event.action == "completed":
|
|
115
|
+
model, effective_results = _completed_dashboard(
|
|
116
|
+
port,
|
|
117
|
+
graph,
|
|
118
|
+
compiled.graph_digest,
|
|
119
|
+
pull,
|
|
120
|
+
run,
|
|
121
|
+
)
|
|
122
|
+
else:
|
|
123
|
+
message = f"unsupported workflow_run action: {event.action}"
|
|
124
|
+
raise ValueError(message)
|
|
125
|
+
existing = find_managed_comment(port, number, DASHBOARD_MARKER)
|
|
126
|
+
previous_labels = parse_label_state(existing.body) if existing is not None else frozenset()
|
|
127
|
+
if effective_results is None and previous_labels:
|
|
128
|
+
model = replace(model, managed_labels=tuple(sorted(previous_labels)))
|
|
129
|
+
comment = upsert_managed_comment(port, number, DASHBOARD_MARKER, render_dashboard(model))
|
|
130
|
+
_publish_check(port, model)
|
|
131
|
+
if effective_results is not None:
|
|
132
|
+
reconcile_labels(
|
|
133
|
+
port,
|
|
134
|
+
number,
|
|
135
|
+
graph,
|
|
136
|
+
effective_results,
|
|
137
|
+
previous_owned=previous_labels,
|
|
138
|
+
)
|
|
139
|
+
return PublicationOutcome(published=True, status=model.status, comment_id=comment.id)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _completed_dashboard(
|
|
143
|
+
port: GitHubPort,
|
|
144
|
+
graph: Graph,
|
|
145
|
+
graph_digest: str,
|
|
146
|
+
pull: PullRequestState,
|
|
147
|
+
run: DashboardRun,
|
|
148
|
+
) -> tuple[DashboardModel, Mapping[str, Result] | None]:
|
|
149
|
+
expectation = ArtifactExpectation(
|
|
150
|
+
port.repository,
|
|
151
|
+
pull.number,
|
|
152
|
+
pull.head_sha,
|
|
153
|
+
run.id,
|
|
154
|
+
graph_digest,
|
|
155
|
+
frozenset(node.id for node in graph.nodes),
|
|
156
|
+
)
|
|
157
|
+
try:
|
|
158
|
+
results = download_results(port, expectation)
|
|
159
|
+
_require_complete_results(results, expectation.node_ids)
|
|
160
|
+
except ArtifactError as error:
|
|
161
|
+
pending = pending_dashboard(graph, run)
|
|
162
|
+
return (
|
|
163
|
+
replace(
|
|
164
|
+
pending,
|
|
165
|
+
status=ResultStatus.FAILED,
|
|
166
|
+
message=f"The final dashboard could not be assembled: {error}",
|
|
167
|
+
),
|
|
168
|
+
None,
|
|
169
|
+
)
|
|
170
|
+
approvals = approval_ledger(port, pull.number)
|
|
171
|
+
effective = effective_graph(graph, results, approvals)
|
|
172
|
+
return final_dashboard(graph, effective.results, run), effective.results
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _require_complete_results(
|
|
176
|
+
results: Mapping[str, object],
|
|
177
|
+
node_ids: frozenset[str],
|
|
178
|
+
) -> None:
|
|
179
|
+
missing = node_ids - results.keys()
|
|
180
|
+
if missing:
|
|
181
|
+
message = f"missing result artifacts for nodes: {', '.join(sorted(missing))}"
|
|
182
|
+
raise ArtifactError(message)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _pull_request(port: GitHubPort, number: int) -> PullRequestState:
|
|
186
|
+
pull = _object(port.request("GET", f"/pulls/{number}"), "pull request")
|
|
187
|
+
head = _object(pull.get("head"), "pull request head")
|
|
188
|
+
base = _object(pull.get("base"), "pull request base")
|
|
189
|
+
return PullRequestState(
|
|
190
|
+
number,
|
|
191
|
+
_string(head.get("sha"), "pull request head SHA"),
|
|
192
|
+
_string(base.get("sha"), "pull request base SHA"),
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _resolve_pull_request(port: GitHubPort, head_sha: str) -> int | None:
|
|
197
|
+
pulls = _array(port.request("GET", f"/commits/{head_sha}/pulls"), "commit pull requests")
|
|
198
|
+
numbers: list[int] = []
|
|
199
|
+
for value in pulls:
|
|
200
|
+
pull = _object(value, "commit pull request")
|
|
201
|
+
number = _optional_integer(pull.get("number"), "pull request number")
|
|
202
|
+
if number is not None:
|
|
203
|
+
numbers.append(number)
|
|
204
|
+
return max(numbers) if numbers else None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _is_latest_run(port: GitHubPort, event: WorkflowRunEvent, number: int) -> bool:
|
|
208
|
+
path = (
|
|
209
|
+
"/actions/workflows/quality-graph.yml/runs?event=pull_request"
|
|
210
|
+
f"&per_page={GITHUB_PAGE_SIZE}&page=1"
|
|
211
|
+
)
|
|
212
|
+
response = _object(port.request("GET", path), "workflow runs")
|
|
213
|
+
runs = _array(response.get("workflow_runs", []), "workflow runs")
|
|
214
|
+
matching_ids = [
|
|
215
|
+
run_id
|
|
216
|
+
for value in runs
|
|
217
|
+
for run in (_object(value, "workflow run"),)
|
|
218
|
+
if _run_has_pull(run, number)
|
|
219
|
+
for run_id in (_optional_integer(run.get("id"), "workflow run id"),)
|
|
220
|
+
if run_id is not None
|
|
221
|
+
]
|
|
222
|
+
return not matching_ids or event.id >= max(matching_ids)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _run_has_pull(run: Mapping[str, JsonValue], number: int) -> bool:
|
|
226
|
+
return any(
|
|
227
|
+
_object(value, "workflow pull request").get("number") == number
|
|
228
|
+
for value in _array(run.get("pull_requests", []), "workflow pull requests")
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _repository_file(port: GitHubPort, path: str, ref: str) -> str:
|
|
233
|
+
encoded_path = urllib.parse.quote(path, safe="")
|
|
234
|
+
encoded_ref = urllib.parse.quote(ref, safe="")
|
|
235
|
+
response = _object(
|
|
236
|
+
port.request("GET", f"/contents/{encoded_path}?ref={encoded_ref}"),
|
|
237
|
+
"repository file",
|
|
238
|
+
)
|
|
239
|
+
content = _string(response.get("content"), "repository file content")
|
|
240
|
+
try:
|
|
241
|
+
return base64.b64decode(content.replace("\n", ""), validate=True).decode()
|
|
242
|
+
except (ValueError, UnicodeDecodeError) as error:
|
|
243
|
+
message = f"repository file is not valid base64 UTF-8: {path}"
|
|
244
|
+
raise ValueError(message) from error
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _publish_check(port: GitHubPort, model: DashboardModel) -> None:
|
|
248
|
+
completed = model.status not in {ResultStatus.WAITING, ResultStatus.IN_PROGRESS}
|
|
249
|
+
payload: dict[str, JsonValue] = {
|
|
250
|
+
"name": "Quality Graph",
|
|
251
|
+
"head_sha": model.head_sha,
|
|
252
|
+
"status": "completed" if completed else "in_progress",
|
|
253
|
+
"details_url": next((row.logs_url for row in model.rows), ""),
|
|
254
|
+
"output": {
|
|
255
|
+
"title": "Quality Graph",
|
|
256
|
+
"summary": model.message,
|
|
257
|
+
},
|
|
258
|
+
}
|
|
259
|
+
if completed:
|
|
260
|
+
payload["conclusion"] = "success" if model.status is ResultStatus.PASSED else "failure"
|
|
261
|
+
port.request("POST", "/check-runs", payload)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def read_event_json(value: str) -> dict[str, JsonValue]:
|
|
265
|
+
"""Decode and narrow one GitHub event JSON document."""
|
|
266
|
+
event = cast("JsonValue", json.loads(value))
|
|
267
|
+
return _object(event, "GitHub event")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
|
|
271
|
+
if not isinstance(value, dict):
|
|
272
|
+
message = f"{context} must be an object"
|
|
273
|
+
raise TypeError(message)
|
|
274
|
+
return value
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _array(value: JsonValue, context: str) -> list[JsonValue]:
|
|
278
|
+
if not isinstance(value, list):
|
|
279
|
+
message = f"{context} must be an array"
|
|
280
|
+
raise TypeError(message)
|
|
281
|
+
return value
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _string(value: JsonValue, context: str) -> str:
|
|
285
|
+
if not isinstance(value, str):
|
|
286
|
+
message = f"{context} must be a string"
|
|
287
|
+
raise TypeError(message)
|
|
288
|
+
return value
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _optional_string(value: JsonValue, context: str) -> str | None:
|
|
292
|
+
return None if value is None else _string(value, context)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _integer(value: JsonValue, context: str) -> int:
|
|
296
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
297
|
+
message = f"{context} must be an integer"
|
|
298
|
+
raise TypeError(message)
|
|
299
|
+
return value
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _optional_integer(value: JsonValue, context: str) -> int | None:
|
|
303
|
+
return None if value is None else _integer(value, context)
|
qg_github/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
qg_github/reporting.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Render portable results for GitHub Job Summaries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from quality_graph_core.result import Finding, Result, ResultStatus
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
MAX_SUMMARY_FINDINGS = 50
|
|
14
|
+
MAX_JOB_SUMMARY_CHARACTERS = 1_000_000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def render_job_summary(result: Result) -> str:
|
|
18
|
+
"""Render one complete bounded GitHub Job Summary."""
|
|
19
|
+
lines = [
|
|
20
|
+
f'<a id="quality-graph-{html.escape(result.node_id)}"></a>',
|
|
21
|
+
f"## {_status_icon(result.status)} {html.escape(result.title)}",
|
|
22
|
+
]
|
|
23
|
+
if result.summary:
|
|
24
|
+
lines.extend(("", result.summary))
|
|
25
|
+
if result.metrics:
|
|
26
|
+
lines.extend(("", "| Metric | Value |", "| --- | --- |"))
|
|
27
|
+
lines.extend(
|
|
28
|
+
f"| {_table(metric.label)} | {_table(metric.value)} |" for metric in result.metrics
|
|
29
|
+
)
|
|
30
|
+
if result.findings:
|
|
31
|
+
lines.extend(("", "### Findings", ""))
|
|
32
|
+
lines.extend(_finding_line(finding) for finding in result.findings[:MAX_SUMMARY_FINDINGS])
|
|
33
|
+
omitted = len(result.findings) - MAX_SUMMARY_FINDINGS
|
|
34
|
+
if omitted > 0:
|
|
35
|
+
notice = f"_{omitted} additional findings are available in the result artifact._"
|
|
36
|
+
lines.extend(("", notice))
|
|
37
|
+
if result.diagnostics:
|
|
38
|
+
lines.extend(("", "### Diagnostics", ""))
|
|
39
|
+
for diagnostic in result.diagnostics:
|
|
40
|
+
kind = html.escape(diagnostic.kind.value)
|
|
41
|
+
message = html.escape(diagnostic.message)
|
|
42
|
+
lines.append(f"- **{kind}:** {message}")
|
|
43
|
+
if diagnostic.detail:
|
|
44
|
+
lines.extend(("", "```text", _code(diagnostic.detail), "```"))
|
|
45
|
+
if result.notes:
|
|
46
|
+
lines.extend(("", "### Notes", ""))
|
|
47
|
+
lines.extend(f"- {html.escape(note)}" for note in result.notes)
|
|
48
|
+
return _bounded("\n".join(lines).strip() + "\n")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def append_job_summary(path: Path, result: Result) -> None:
|
|
52
|
+
"""Append one rendered result to an explicit summary sink."""
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
with path.open("a") as summary:
|
|
55
|
+
summary.write(render_job_summary(result))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _finding_line(finding: Finding) -> str:
|
|
59
|
+
location = ""
|
|
60
|
+
if finding.location is not None:
|
|
61
|
+
location = f" — `{html.escape(finding.location.path)}:{finding.location.start_line}`"
|
|
62
|
+
rule = f" `{html.escape(finding.rule_id)}`" if finding.rule_id else ""
|
|
63
|
+
severity = html.escape(finding.severity.value)
|
|
64
|
+
message = html.escape(finding.message)
|
|
65
|
+
return f"- **{severity}**{rule}: {message}{location}"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _status_icon(status: ResultStatus) -> str:
|
|
69
|
+
return {
|
|
70
|
+
ResultStatus.WAITING: "⏳",
|
|
71
|
+
ResultStatus.IN_PROGRESS: "🚀",
|
|
72
|
+
ResultStatus.PASSED: "✅",
|
|
73
|
+
ResultStatus.FAILED: "❌",
|
|
74
|
+
ResultStatus.SKIPPED: "⏭️",
|
|
75
|
+
ResultStatus.CANCELLED: "🚫",
|
|
76
|
+
}[status]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _table(value: str) -> str:
|
|
80
|
+
return html.escape(value).replace("|", "|").replace("\n", "<br>")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _code(value: str) -> str:
|
|
84
|
+
return value.replace("```", "` ` `")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _bounded(value: str) -> str:
|
|
88
|
+
if len(value) <= MAX_JOB_SUMMARY_CHARACTERS:
|
|
89
|
+
return value
|
|
90
|
+
omitted = len(value) - MAX_JOB_SUMMARY_CHARACTERS
|
|
91
|
+
while True:
|
|
92
|
+
notice = f"\n\n_Job Summary truncated; {omitted} characters omitted._\n"
|
|
93
|
+
prefix = MAX_JOB_SUMMARY_CHARACTERS - len(notice)
|
|
94
|
+
updated = len(value) - prefix
|
|
95
|
+
if updated == omitted:
|
|
96
|
+
return value[:prefix] + notice
|
|
97
|
+
omitted = updated
|
qg_github/runtime.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Execute the pinned GitHub Action runtime behind generated workflows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, cast
|
|
11
|
+
|
|
12
|
+
from qg_github.annotations import escape_data, publish_annotations
|
|
13
|
+
from qg_github.commands import handle_command
|
|
14
|
+
from qg_github.github import HttpGitHubPort
|
|
15
|
+
from qg_github.publication import publish_workflow_run, read_event_json
|
|
16
|
+
from qg_github.reporting import append_job_summary
|
|
17
|
+
from quality_graph_core.adapters import (
|
|
18
|
+
AdapterContext,
|
|
19
|
+
AdapterError,
|
|
20
|
+
adapt_exit,
|
|
21
|
+
adapt_junit,
|
|
22
|
+
adapt_native,
|
|
23
|
+
adapt_sarif,
|
|
24
|
+
adapter_failure,
|
|
25
|
+
read_report,
|
|
26
|
+
)
|
|
27
|
+
from quality_graph_core.graph import AdapterKind
|
|
28
|
+
from quality_graph_core.result import FailureKind, JsonValue, Provenance, Result, ResultStatus
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from collections.abc import Mapping, Sequence
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class CollectionRequest:
|
|
36
|
+
"""Carry trusted workflow context and declared adapter inputs."""
|
|
37
|
+
|
|
38
|
+
context: AdapterContext
|
|
39
|
+
adapter: AdapterKind
|
|
40
|
+
report_path: str | None
|
|
41
|
+
workspace: Path
|
|
42
|
+
result_path: Path
|
|
43
|
+
summary_path: Path | None
|
|
44
|
+
output_path: Path
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_environment(
|
|
48
|
+
cls,
|
|
49
|
+
environment: Mapping[str, str],
|
|
50
|
+
event: Mapping[str, JsonValue],
|
|
51
|
+
) -> CollectionRequest:
|
|
52
|
+
"""Build a request from explicit GitHub Action environment values."""
|
|
53
|
+
adapter = AdapterKind(_required(environment, "QG_ADAPTER"))
|
|
54
|
+
report = environment.get("QG_REPORT_PATH") or None
|
|
55
|
+
workspace = Path(_required(environment, "GITHUB_WORKSPACE"))
|
|
56
|
+
node_id = _required(environment, "QG_NODE_ID")
|
|
57
|
+
result_path = (
|
|
58
|
+
Path(_required(environment, "RUNNER_TEMP")) / "quality-graph" / f"{node_id}.json"
|
|
59
|
+
)
|
|
60
|
+
summary = environment.get("GITHUB_STEP_SUMMARY")
|
|
61
|
+
provenance = _provenance(environment, event)
|
|
62
|
+
context = AdapterContext(
|
|
63
|
+
node_id,
|
|
64
|
+
_required(environment, "QG_TITLE"),
|
|
65
|
+
environment.get("QG_COMMAND_OUTCOME", "success") == "success",
|
|
66
|
+
provenance,
|
|
67
|
+
)
|
|
68
|
+
return cls(
|
|
69
|
+
context,
|
|
70
|
+
adapter,
|
|
71
|
+
report,
|
|
72
|
+
workspace,
|
|
73
|
+
result_path,
|
|
74
|
+
Path(summary) if summary else None,
|
|
75
|
+
Path(_required(environment, "GITHUB_OUTPUT")),
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def collect(request: CollectionRequest) -> Result:
|
|
80
|
+
"""Collect one command outcome through its selected adapter."""
|
|
81
|
+
try:
|
|
82
|
+
if request.adapter is AdapterKind.EXIT_CODE:
|
|
83
|
+
state = "passed" if request.context.command_succeeded else "failed"
|
|
84
|
+
return adapt_exit(request.context, f"The declared command {state}.")
|
|
85
|
+
report = _structured_report(request)
|
|
86
|
+
if request.adapter is AdapterKind.NATIVE:
|
|
87
|
+
return adapt_native(request.context, report)
|
|
88
|
+
if request.adapter is AdapterKind.SARIF:
|
|
89
|
+
return adapt_sarif(request.context, report)
|
|
90
|
+
return adapt_junit(request.context, report)
|
|
91
|
+
except AdapterError as error:
|
|
92
|
+
return adapter_failure(request.context, error)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _structured_report(request: CollectionRequest) -> bytes:
|
|
96
|
+
if request.report_path is None:
|
|
97
|
+
message = f"{request.adapter.value} adapter requires a report path"
|
|
98
|
+
raise AdapterError(message)
|
|
99
|
+
return read_report(request.workspace, request.report_path)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def publish_collection(request: CollectionRequest, result: Result) -> int:
|
|
103
|
+
"""Write result, summary, annotations, and Action outputs."""
|
|
104
|
+
request.result_path.parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
request.result_path.write_text(result.to_json())
|
|
106
|
+
if request.summary_path is not None:
|
|
107
|
+
append_job_summary(request.summary_path, result)
|
|
108
|
+
publish_annotations(result.annotations)
|
|
109
|
+
exit_code = _result_exit_code(result)
|
|
110
|
+
request.output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
with request.output_path.open("a") as output:
|
|
112
|
+
output.write(f"result-path={request.result_path}\n")
|
|
113
|
+
output.write(f"exit-code={exit_code}\n")
|
|
114
|
+
return exit_code
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(arguments: Sequence[str] | None = None) -> int:
|
|
118
|
+
"""Run one generated-workflow runtime operation."""
|
|
119
|
+
operation = list(arguments if arguments is not None else sys.argv[1:])
|
|
120
|
+
if operation == ["collect"]:
|
|
121
|
+
event = _read_event(Path(os.environ["GITHUB_EVENT_PATH"]))
|
|
122
|
+
request = CollectionRequest.from_environment(os.environ, event)
|
|
123
|
+
publish_collection(request, collect(request))
|
|
124
|
+
return 0
|
|
125
|
+
if operation == ["publish"]:
|
|
126
|
+
event = read_event_json(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
|
|
127
|
+
publish_workflow_run(HttpGitHubPort.from_environment(), event)
|
|
128
|
+
return 0
|
|
129
|
+
if operation == ["command"]:
|
|
130
|
+
event = read_event_json(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
|
|
131
|
+
handle_command(HttpGitHubPort.from_environment(), event)
|
|
132
|
+
return 0
|
|
133
|
+
message = f"Unsupported Quality Graph runtime operation: {' '.join(operation)}"
|
|
134
|
+
raise SystemExit(message)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def entrypoint(arguments: Sequence[str] | None = None) -> int:
|
|
138
|
+
"""Expose runtime failures as safe public workflow annotations."""
|
|
139
|
+
try:
|
|
140
|
+
return main(arguments)
|
|
141
|
+
except Exception as error:
|
|
142
|
+
name = type(error).__name__
|
|
143
|
+
detail = escape_data(str(error))
|
|
144
|
+
sys.stderr.write(f"::error title=Quality Graph runtime::{name}: {detail}\n")
|
|
145
|
+
raise
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _provenance(
|
|
149
|
+
environment: Mapping[str, str],
|
|
150
|
+
event: Mapping[str, JsonValue],
|
|
151
|
+
) -> Provenance:
|
|
152
|
+
pull = event.get("pull_request")
|
|
153
|
+
pull_number: int | None = None
|
|
154
|
+
head_sha = _required(environment, "GITHUB_SHA")
|
|
155
|
+
if isinstance(pull, dict):
|
|
156
|
+
number = pull.get("number")
|
|
157
|
+
head = pull.get("head")
|
|
158
|
+
if isinstance(number, int) and not isinstance(number, bool):
|
|
159
|
+
pull_number = number
|
|
160
|
+
if isinstance(head, dict) and isinstance(head.get("sha"), str):
|
|
161
|
+
head_sha = cast("str", head["sha"])
|
|
162
|
+
return Provenance(
|
|
163
|
+
_required(environment, "GITHUB_REPOSITORY"),
|
|
164
|
+
head_sha,
|
|
165
|
+
int(_required(environment, "GITHUB_RUN_ID")),
|
|
166
|
+
int(_required(environment, "GITHUB_RUN_ATTEMPT")),
|
|
167
|
+
_required(environment, "QG_GRAPH_DIGEST"),
|
|
168
|
+
pull_number,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _read_event(path: Path) -> dict[str, JsonValue]:
|
|
173
|
+
value = cast("JsonValue", json.loads(path.read_text()))
|
|
174
|
+
if not isinstance(value, dict):
|
|
175
|
+
message = "GitHub event payload must be an object"
|
|
176
|
+
raise TypeError(message)
|
|
177
|
+
return value
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _required(environment: Mapping[str, str], name: str) -> str:
|
|
181
|
+
value = environment.get(name)
|
|
182
|
+
if not value:
|
|
183
|
+
message = f"Required environment variable is missing: {name}"
|
|
184
|
+
raise ValueError(message)
|
|
185
|
+
return value
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _result_exit_code(result: Result) -> int:
|
|
189
|
+
if result.status not in {ResultStatus.FAILED, ResultStatus.CANCELLED}:
|
|
190
|
+
return 0
|
|
191
|
+
return 1 if result.failure_kind in {FailureKind.QUALITY, FailureKind.COMMAND} else 2
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
raise SystemExit(entrypoint())
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quality-graph-github
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: GitHub provider and Action runtime for Quality Graph
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Requires-Dist: httpx>=0.28.1
|
|
8
|
+
Requires-Dist: jinja2>=3.1.6
|
|
9
|
+
Requires-Dist: pyyaml>=6.0.2
|
|
10
|
+
Requires-Dist: quality-graph-core==0.1.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# Quality Graph GitHub Provider
|
|
14
|
+
|
|
15
|
+
GitHub workflow generation, trusted publication, and Action runtime for Quality Graph.
|
|
16
|
+
|
|
17
|
+
The distribution registers `github` in the `qg.providers` entry-point group.
|
|
18
|
+
`quality-graph-core` is its only Quality Graph workspace dependency; third-party runtime
|
|
19
|
+
dependencies remain private implementation details. The provider never imports the CLI.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
qg_github/__init__.py,sha256=ud6DP1C10Vk64U_0T9SZ3f2YpMtJCzsbCGQ5BOtKhG4,106
|
|
2
|
+
qg_github/annotations.py,sha256=TwcYcY2g0tT__uVoSmEZuxFTkYrt3llf3mBt0VnG_ss,3217
|
|
3
|
+
qg_github/approvals.py,sha256=v4EDiSXVUgm93bvsH2ka6Olza4cPA8xSa2POf1ktOOM,6052
|
|
4
|
+
qg_github/artifacts.py,sha256=qo3sJ4bPcSU5m5uTPqNZwpodS7Y2BneJ2tsI10bnHUs,7802
|
|
5
|
+
qg_github/commands.py,sha256=gD-gioCmdLuzMVGI0jXYxJi6z0elceCDksC0XEZLdGA,12013
|
|
6
|
+
qg_github/comments.py,sha256=-Ag7b0BtieK-v-1ovtTsPJwKnH2P1b5pSwSwAzQU9tc,3357
|
|
7
|
+
qg_github/compiler.py,sha256=PBg3Z4tbyEibCSQu-2L3r0UGkhpwiUPoeNhhVMzXqc0,13582
|
|
8
|
+
qg_github/controls.py,sha256=kDTOp1tNglmCM3ZgdJzL8KYtA0GQ0LTZMPxvaft6B-0,2233
|
|
9
|
+
qg_github/dashboard.py,sha256=MsnWDlBeoJwGIyiQ3AgS3Usy8B70dLOnjNuBGrY-pYo,8854
|
|
10
|
+
qg_github/github.py,sha256=vx7_YhRd_XCCYpC_IvW0hk-tm-nmzGGcZONqQrx4f3A,6979
|
|
11
|
+
qg_github/labels.py,sha256=PT8MnIQZsu896dipMO2880KgUGVcyXH4IJNVQ1oG1zo,4720
|
|
12
|
+
qg_github/provider.py,sha256=9vlC-YrcCYNNaz_CEjFmbQdqfnM8iCYQrcfBBUTn-_Q,578
|
|
13
|
+
qg_github/publication.py,sha256=7T7rE9THUNiKfq7Zt56Fx_sjiuD8zNsIZdsW3N9duKI,10790
|
|
14
|
+
qg_github/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
15
|
+
qg_github/reporting.py,sha256=hf5FA0_mjmqHr53NwpuCYMvUAU1hoUg08m8c1melapQ,3478
|
|
16
|
+
qg_github/runtime.py,sha256=LmBD9MgFMvFrAgvdAxH3MtvB8U-8yDtc5PsYsEZQYKA,7085
|
|
17
|
+
quality_graph_github-0.1.0.dist-info/METADATA,sha256=1KCuZpz_576EdWJCCnzHZVJx6E_vP0_wn9mFZwWQbIs,718
|
|
18
|
+
quality_graph_github-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
19
|
+
quality_graph_github-0.1.0.dist-info/entry_points.txt,sha256=cSP-mOVXpvGL9nCA7EEfxdrIafFMHwKJEq-wc7DOEyo,43
|
|
20
|
+
quality_graph_github-0.1.0.dist-info/RECORD,,
|