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/dashboard.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Aggregate portable node results into one bounded pull-request dashboard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from qg_github.comments import GITHUB_COMMENT_BODY_LIMIT, marker
|
|
11
|
+
from qg_github.controls import render_control
|
|
12
|
+
from qg_github.labels import configured_label_names, label_state_marker
|
|
13
|
+
from quality_graph_core.result import Control, Result, ResultStatus
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from collections.abc import Iterable, Mapping
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from quality_graph_core.graph import Graph
|
|
20
|
+
|
|
21
|
+
ARTIFACT_ATTEMPT_RE = re.compile(r"-(?P<attempt>[1-9][0-9]*)$")
|
|
22
|
+
DASHBOARD_MARKER = "dashboard"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class DashboardRow:
|
|
27
|
+
"""Represent one stable compact graph node row."""
|
|
28
|
+
|
|
29
|
+
node_id: str
|
|
30
|
+
title: str
|
|
31
|
+
status: ResultStatus
|
|
32
|
+
metric: str
|
|
33
|
+
summary_url: str
|
|
34
|
+
logs_url: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class DashboardControlGroup:
|
|
39
|
+
"""Group semantic administrator controls for one node."""
|
|
40
|
+
|
|
41
|
+
node_id: str
|
|
42
|
+
title: str
|
|
43
|
+
controls: tuple[Control, ...]
|
|
44
|
+
notes: tuple[str, ...] = ()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class DashboardModel:
|
|
49
|
+
"""Carry all deterministic data rendered in a managed dashboard."""
|
|
50
|
+
|
|
51
|
+
status: ResultStatus
|
|
52
|
+
message: str
|
|
53
|
+
run_id: int
|
|
54
|
+
run_attempt: int
|
|
55
|
+
head_sha: str
|
|
56
|
+
rows: tuple[DashboardRow, ...]
|
|
57
|
+
control_groups: tuple[DashboardControlGroup, ...] = ()
|
|
58
|
+
managed_labels: tuple[str, ...] = ()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class DashboardRun:
|
|
63
|
+
"""Identify one workflow attempt and its public URL."""
|
|
64
|
+
|
|
65
|
+
id: int
|
|
66
|
+
attempt: int
|
|
67
|
+
head_sha: str
|
|
68
|
+
url: str
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_results(directory: Path) -> dict[str, Result]:
|
|
72
|
+
"""Load the newest artifact attempt for every node."""
|
|
73
|
+
results: dict[str, Result] = {}
|
|
74
|
+
attempts: dict[str, int] = {}
|
|
75
|
+
if not directory.exists():
|
|
76
|
+
return results
|
|
77
|
+
for path in sorted(directory.rglob("*.json")):
|
|
78
|
+
result = Result.from_json(path.read_text())
|
|
79
|
+
relative = path.relative_to(directory)
|
|
80
|
+
artifact_name = relative.parts[0] if len(relative.parts) > 1 else ""
|
|
81
|
+
match = ARTIFACT_ATTEMPT_RE.search(artifact_name)
|
|
82
|
+
attempt = int(match.group("attempt")) if match is not None else 0
|
|
83
|
+
if attempt >= attempts.get(result.node_id, -1):
|
|
84
|
+
results[result.node_id] = result
|
|
85
|
+
attempts[result.node_id] = attempt
|
|
86
|
+
return results
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def aggregate_status(statuses: Iterable[ResultStatus]) -> ResultStatus:
|
|
90
|
+
"""Derive graph status with pending state taking precedence over failure."""
|
|
91
|
+
observed = set(statuses)
|
|
92
|
+
if ResultStatus.IN_PROGRESS in observed or ResultStatus.WAITING in observed:
|
|
93
|
+
return ResultStatus.IN_PROGRESS
|
|
94
|
+
if ResultStatus.FAILED in observed or ResultStatus.CANCELLED in observed:
|
|
95
|
+
return ResultStatus.FAILED
|
|
96
|
+
return ResultStatus.PASSED
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def final_dashboard(
|
|
100
|
+
graph: Graph,
|
|
101
|
+
results: Mapping[str, Result],
|
|
102
|
+
run: DashboardRun,
|
|
103
|
+
) -> DashboardModel:
|
|
104
|
+
"""Build a final dashboard in declaration order."""
|
|
105
|
+
rows: list[DashboardRow] = []
|
|
106
|
+
groups: list[DashboardControlGroup] = []
|
|
107
|
+
for node in graph.nodes:
|
|
108
|
+
result = results.get(node.id)
|
|
109
|
+
status = result.status if result is not None else ResultStatus.SKIPPED
|
|
110
|
+
rows.append(
|
|
111
|
+
DashboardRow(
|
|
112
|
+
node.id,
|
|
113
|
+
node.title,
|
|
114
|
+
status,
|
|
115
|
+
dashboard_metric(result),
|
|
116
|
+
f"{run.url}#quality-graph-{node.id}",
|
|
117
|
+
run.url,
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
if result is not None and (result.controls or result.notes):
|
|
121
|
+
groups.append(
|
|
122
|
+
DashboardControlGroup(
|
|
123
|
+
node.id,
|
|
124
|
+
node.title,
|
|
125
|
+
result.controls,
|
|
126
|
+
result.notes,
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
return DashboardModel(
|
|
130
|
+
aggregate_status(
|
|
131
|
+
row.status for node, row in zip(graph.nodes, rows, strict=True) if node.policy.blocking
|
|
132
|
+
),
|
|
133
|
+
"Detailed diagnostics and metrics are available in each Job Summary.",
|
|
134
|
+
run.id,
|
|
135
|
+
run.attempt,
|
|
136
|
+
run.head_sha,
|
|
137
|
+
tuple(rows),
|
|
138
|
+
tuple(groups),
|
|
139
|
+
configured_label_names(graph),
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def pending_dashboard(
|
|
144
|
+
graph: Graph,
|
|
145
|
+
run: DashboardRun,
|
|
146
|
+
) -> DashboardModel:
|
|
147
|
+
"""Build an early dashboard before portable results are available."""
|
|
148
|
+
rows = tuple(
|
|
149
|
+
DashboardRow(
|
|
150
|
+
node.id,
|
|
151
|
+
node.title,
|
|
152
|
+
ResultStatus.WAITING,
|
|
153
|
+
"—",
|
|
154
|
+
f"{run.url}#quality-graph-{node.id}",
|
|
155
|
+
run.url,
|
|
156
|
+
)
|
|
157
|
+
for node in graph.nodes
|
|
158
|
+
)
|
|
159
|
+
return DashboardModel(
|
|
160
|
+
ResultStatus.IN_PROGRESS,
|
|
161
|
+
"The current Quality Graph run is in progress.",
|
|
162
|
+
run.id,
|
|
163
|
+
run.attempt,
|
|
164
|
+
run.head_sha,
|
|
165
|
+
rows,
|
|
166
|
+
managed_labels=configured_label_names(graph),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def render_dashboard(model: DashboardModel) -> str:
|
|
171
|
+
"""Render a complete dashboard while retaining high-value controls."""
|
|
172
|
+
rendered = _render(model)
|
|
173
|
+
if _fits(rendered):
|
|
174
|
+
return rendered
|
|
175
|
+
selected: dict[int, set[int]] = {index: set() for index, _ in enumerate(model.control_groups)}
|
|
176
|
+
candidates = sorted(
|
|
177
|
+
(
|
|
178
|
+
(control.kind.value == "file", group_index, control_index)
|
|
179
|
+
for group_index, group in enumerate(model.control_groups)
|
|
180
|
+
for control_index, control in enumerate(group.controls)
|
|
181
|
+
),
|
|
182
|
+
key=lambda candidate: candidate[0],
|
|
183
|
+
)
|
|
184
|
+
for _, group_index, control_index in candidates:
|
|
185
|
+
proposed = {index: set(indices) for index, indices in selected.items()}
|
|
186
|
+
proposed[group_index].add(control_index)
|
|
187
|
+
groups = _selected_groups(model, proposed)
|
|
188
|
+
candidate = _render(replace(model, control_groups=groups))
|
|
189
|
+
if _fits(candidate):
|
|
190
|
+
selected = proposed
|
|
191
|
+
return _render(replace(model, control_groups=_selected_groups(model, selected)))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def dashboard_metric(result: Result | None) -> str:
|
|
195
|
+
"""Render at most two Markdown-safe metrics for one row."""
|
|
196
|
+
if result is None or not result.metrics:
|
|
197
|
+
return "—"
|
|
198
|
+
return " · ".join(
|
|
199
|
+
f"{_table(metric.label)}: {_table(metric.value)}" for metric in result.metrics[:2]
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _render(model: DashboardModel) -> str:
|
|
204
|
+
lines = [
|
|
205
|
+
label_state_marker(model.managed_labels),
|
|
206
|
+
f"## {_status_icon(model.status)} Quality Graph",
|
|
207
|
+
"",
|
|
208
|
+
model.message,
|
|
209
|
+
"",
|
|
210
|
+
"| Check | Status | Metrics | Details |",
|
|
211
|
+
"| --- | --- | --- | --- |",
|
|
212
|
+
]
|
|
213
|
+
lines.extend(
|
|
214
|
+
f"| {_table(row.title)} | {_status_icon(row.status)} {row.status.value} | "
|
|
215
|
+
f"{row.metric} | [Summary]({row.summary_url}) · [Logs]({row.logs_url}) |"
|
|
216
|
+
for row in model.rows
|
|
217
|
+
)
|
|
218
|
+
if model.control_groups:
|
|
219
|
+
lines.extend(("", "<details><summary>For repository administrators</summary>", ""))
|
|
220
|
+
for group in model.control_groups:
|
|
221
|
+
lines.extend((f"#### {html.escape(group.title)}", ""))
|
|
222
|
+
lines.extend(render_control(control) for control in group.controls)
|
|
223
|
+
lines.extend(html.escape(note) for note in group.notes)
|
|
224
|
+
lines.extend(("", "</details>"))
|
|
225
|
+
head = html.escape(model.head_sha)
|
|
226
|
+
lines.extend(("", f"Run `{model.run_id}` attempt `{model.run_attempt}` · head `{head}`"))
|
|
227
|
+
return "\n".join(lines).strip() + "\n"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _selected_groups(
|
|
231
|
+
model: DashboardModel,
|
|
232
|
+
selected: Mapping[int, set[int]],
|
|
233
|
+
) -> tuple[DashboardControlGroup, ...]:
|
|
234
|
+
summary_urls = {row.node_id: row.summary_url for row in model.rows}
|
|
235
|
+
groups: list[DashboardControlGroup] = []
|
|
236
|
+
for group_index, group in enumerate(model.control_groups):
|
|
237
|
+
indices = selected[group_index]
|
|
238
|
+
controls = tuple(
|
|
239
|
+
control for index, control in enumerate(group.controls) if index in indices
|
|
240
|
+
)
|
|
241
|
+
omitted = len(group.controls) - len(controls)
|
|
242
|
+
notes = group.notes
|
|
243
|
+
if omitted:
|
|
244
|
+
summary = summary_urls.get(group.node_id)
|
|
245
|
+
details = f"[{group.title} Job Summary]({summary})" if summary else "the Job Summary"
|
|
246
|
+
notes = (*notes, f"{omitted} additional actions are available in {details}.")
|
|
247
|
+
groups.append(DashboardControlGroup(group.node_id, group.title, controls, notes))
|
|
248
|
+
return tuple(groups)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _status_icon(status: ResultStatus) -> str:
|
|
252
|
+
return {
|
|
253
|
+
ResultStatus.WAITING: "⏳",
|
|
254
|
+
ResultStatus.IN_PROGRESS: "🚀",
|
|
255
|
+
ResultStatus.PASSED: "✅",
|
|
256
|
+
ResultStatus.FAILED: "❌",
|
|
257
|
+
ResultStatus.SKIPPED: "⏭️",
|
|
258
|
+
ResultStatus.CANCELLED: "🚫",
|
|
259
|
+
}[status]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _table(value: str) -> str:
|
|
263
|
+
return html.escape(value).replace("|", "|").replace("\n", "<br>")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _fits(body: str) -> bool:
|
|
267
|
+
return len(f"{marker(DASHBOARD_MARKER)}\n\n{body}") <= GITHUB_COMMENT_BODY_LIMIT
|
qg_github/github.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Provide the narrow injected GitHub transport seam."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from http import HTTPStatus
|
|
9
|
+
from typing import TYPE_CHECKING, Protocol, cast
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
|
|
16
|
+
from quality_graph_core.result import JsonValue
|
|
17
|
+
|
|
18
|
+
REQUEST_TIMEOUT_SECONDS = 30.0
|
|
19
|
+
GITHUB_PAGE_SIZE = 100
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GitHubPort(Protocol):
|
|
23
|
+
"""Describe the single request interface required by GitHub modules."""
|
|
24
|
+
|
|
25
|
+
repository: str
|
|
26
|
+
|
|
27
|
+
def request(self, method: str, path: str, payload: JsonValue = None) -> JsonValue:
|
|
28
|
+
"""Execute one GitHub request and return decoded JSON."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def download(self, path: str) -> bytes:
|
|
32
|
+
"""Download one authenticated binary response."""
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class GitHubError(RuntimeError):
|
|
37
|
+
"""Represent a failed GitHub transport request."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, method: str, path: str, status_code: int) -> None:
|
|
40
|
+
"""Create an error without exposing response or credential content."""
|
|
41
|
+
super().__init__(f"GitHub {method} {path} failed: HTTP {status_code}")
|
|
42
|
+
self.status_code = status_code
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class HttpGitHubPort:
|
|
46
|
+
"""Send repository-scoped requests through GitHub's HTTP interface."""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
repository: str,
|
|
51
|
+
token: str,
|
|
52
|
+
*,
|
|
53
|
+
base_url: str = "https://api.github.com",
|
|
54
|
+
client: httpx.Client | None = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Configure an explicit repository, token, URL, and optional client."""
|
|
57
|
+
self.repository = repository
|
|
58
|
+
self.token = token
|
|
59
|
+
self.base_url = base_url.rstrip("/")
|
|
60
|
+
self.client = client or httpx.Client(timeout=REQUEST_TIMEOUT_SECONDS)
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_environment(cls, environment: Mapping[str, str] | None = None) -> HttpGitHubPort:
|
|
64
|
+
"""Create the production adapter from GitHub Action environment values."""
|
|
65
|
+
values = environment if environment is not None else os.environ
|
|
66
|
+
return cls(
|
|
67
|
+
values["GITHUB_REPOSITORY"],
|
|
68
|
+
values["GITHUB_TOKEN"],
|
|
69
|
+
base_url=values.get("GITHUB_API_URL", "https://api.github.com"),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def request(self, method: str, path: str, payload: JsonValue = None) -> JsonValue:
|
|
73
|
+
"""Execute one bounded request and decode its JSON response."""
|
|
74
|
+
api_path = path if path == "/user" else f"/repos/{self.repository}{path}"
|
|
75
|
+
try:
|
|
76
|
+
response = self.client.request(
|
|
77
|
+
method,
|
|
78
|
+
f"{self.base_url}{api_path}",
|
|
79
|
+
content=None if payload is None else json.dumps(payload).encode(),
|
|
80
|
+
headers={
|
|
81
|
+
"Accept": "application/vnd.github+json",
|
|
82
|
+
"Authorization": f"Bearer {self.token}",
|
|
83
|
+
"Content-Type": "application/json",
|
|
84
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
85
|
+
},
|
|
86
|
+
)
|
|
87
|
+
except httpx.RequestError as error:
|
|
88
|
+
message = f"GitHub {method} {path} transport failed: {type(error).__name__}"
|
|
89
|
+
raise RuntimeError(message) from error
|
|
90
|
+
if response.status_code == HTTPStatus.NO_CONTENT:
|
|
91
|
+
return None
|
|
92
|
+
if response.status_code == HTTPStatus.NOT_FOUND and method in {"GET", "DELETE"}:
|
|
93
|
+
return None
|
|
94
|
+
if response.is_error:
|
|
95
|
+
raise GitHubError(method, path, response.status_code)
|
|
96
|
+
try:
|
|
97
|
+
return cast("JsonValue", response.json())
|
|
98
|
+
except json.JSONDecodeError as error:
|
|
99
|
+
message = f"GitHub {method} {path} returned invalid JSON"
|
|
100
|
+
raise RuntimeError(message) from error
|
|
101
|
+
|
|
102
|
+
def download(self, path: str) -> bytes:
|
|
103
|
+
"""Download one repository-scoped binary response with redirects."""
|
|
104
|
+
api_path = f"/repos/{self.repository}{path}"
|
|
105
|
+
try:
|
|
106
|
+
response = self.client.get(
|
|
107
|
+
f"{self.base_url}{api_path}",
|
|
108
|
+
headers={
|
|
109
|
+
"Accept": "application/vnd.github+json",
|
|
110
|
+
"Authorization": f"Bearer {self.token}",
|
|
111
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
112
|
+
},
|
|
113
|
+
follow_redirects=True,
|
|
114
|
+
)
|
|
115
|
+
except httpx.RequestError as error:
|
|
116
|
+
message = f"GitHub download {path} transport failed: {type(error).__name__}"
|
|
117
|
+
raise RuntimeError(message) from error
|
|
118
|
+
if response.is_error:
|
|
119
|
+
method = "GET"
|
|
120
|
+
raise GitHubError(method, path, response.status_code)
|
|
121
|
+
return response.content
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass
|
|
125
|
+
class MemoryGitHubPort:
|
|
126
|
+
"""Provide deterministic queued responses for pure lifecycle tests."""
|
|
127
|
+
|
|
128
|
+
responses: dict[tuple[str, str], list[JsonValue]] = field(default_factory=dict)
|
|
129
|
+
downloads: dict[str, bytes] = field(default_factory=dict)
|
|
130
|
+
requests: list[tuple[str, str, JsonValue]] = field(default_factory=list)
|
|
131
|
+
downloaded: list[str] = field(default_factory=list)
|
|
132
|
+
repository: str = "owner/repository"
|
|
133
|
+
|
|
134
|
+
def enqueue(self, method: str, path: str, *responses: JsonValue) -> None:
|
|
135
|
+
"""Queue one or more responses for an exact request."""
|
|
136
|
+
self.responses.setdefault((method, path), []).extend(responses)
|
|
137
|
+
|
|
138
|
+
def request(self, method: str, path: str, payload: JsonValue = None) -> JsonValue:
|
|
139
|
+
"""Record a request and return its next configured response."""
|
|
140
|
+
self.requests.append((method, path, payload))
|
|
141
|
+
queued = self.responses.get((method, path))
|
|
142
|
+
if not queued:
|
|
143
|
+
message = f"Unexpected GitHub request: {method} {path}"
|
|
144
|
+
raise AssertionError(message)
|
|
145
|
+
if len(queued) == 1:
|
|
146
|
+
return queued[0]
|
|
147
|
+
return queued.pop(0)
|
|
148
|
+
|
|
149
|
+
def download(self, path: str) -> bytes:
|
|
150
|
+
"""Record and return one configured binary download."""
|
|
151
|
+
self.downloaded.append(path)
|
|
152
|
+
if path not in self.downloads:
|
|
153
|
+
message = f"Unexpected GitHub download: {path}"
|
|
154
|
+
raise AssertionError(message)
|
|
155
|
+
return self.downloads[path]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def paged(port: GitHubPort, path: str) -> tuple[dict[str, JsonValue], ...]:
|
|
159
|
+
"""Read all pages from one GitHub list endpoint."""
|
|
160
|
+
result: list[dict[str, JsonValue]] = []
|
|
161
|
+
page = 1
|
|
162
|
+
while True:
|
|
163
|
+
separator = "&" if "?" in path else "?"
|
|
164
|
+
page_path = f"{path}{separator}per_page={GITHUB_PAGE_SIZE}&page={page}"
|
|
165
|
+
items = _array(port.request("GET", page_path), page_path)
|
|
166
|
+
result.extend(_object(item, page_path) for item in items)
|
|
167
|
+
if len(items) < GITHUB_PAGE_SIZE:
|
|
168
|
+
return tuple(result)
|
|
169
|
+
page += 1
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
|
|
173
|
+
if not isinstance(value, dict):
|
|
174
|
+
message = f"{context} must return an object"
|
|
175
|
+
raise TypeError(message)
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _array(value: JsonValue, context: str) -> list[JsonValue]:
|
|
180
|
+
if not isinstance(value, list):
|
|
181
|
+
message = f"{context} must return an array"
|
|
182
|
+
raise TypeError(message)
|
|
183
|
+
return value
|
qg_github/labels.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Reconcile Quality Graph-owned pull-request labels from effective state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import urllib.parse
|
|
9
|
+
from typing import TYPE_CHECKING, cast
|
|
10
|
+
|
|
11
|
+
from qg_github.github import GitHubPort, paged
|
|
12
|
+
from quality_graph_core.graph import Graph, LabelSpec
|
|
13
|
+
from quality_graph_core.result import JsonValue, Result, ResultStatus
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from collections.abc import Iterable, Mapping
|
|
17
|
+
|
|
18
|
+
LABEL_STATE_RE = re.compile(r"<!-- quality-graph:labels:(?P<payload>[A-Za-z0-9_-]+) -->")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def configured_label_names(graph: Graph) -> tuple[str, ...]:
|
|
22
|
+
"""Return every currently configured Quality Graph-owned label."""
|
|
23
|
+
if not graph.labels.enabled:
|
|
24
|
+
return ()
|
|
25
|
+
aggregate = cast("LabelSpec", graph.labels.failing)
|
|
26
|
+
names: list[str] = [aggregate.name]
|
|
27
|
+
names.extend(
|
|
28
|
+
node.failing_label.name for node in graph.nodes if isinstance(node.failing_label, LabelSpec)
|
|
29
|
+
)
|
|
30
|
+
return tuple(dict.fromkeys(names))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def label_state_marker(names: Iterable[str]) -> str:
|
|
34
|
+
"""Encode owned label names in the managed dashboard."""
|
|
35
|
+
value = json.dumps(sorted(set(names)), separators=(",", ":")).encode()
|
|
36
|
+
encoded = base64.urlsafe_b64encode(value).decode().rstrip("=")
|
|
37
|
+
return f"<!-- quality-graph:labels:{encoded} -->"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_label_state(body: str) -> frozenset[str]:
|
|
41
|
+
"""Decode owned label names from a managed dashboard."""
|
|
42
|
+
match = LABEL_STATE_RE.search(body)
|
|
43
|
+
if match is None:
|
|
44
|
+
return frozenset()
|
|
45
|
+
encoded = match.group("payload")
|
|
46
|
+
try:
|
|
47
|
+
value = cast(
|
|
48
|
+
"JsonValue",
|
|
49
|
+
json.loads(base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))),
|
|
50
|
+
)
|
|
51
|
+
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
|
52
|
+
return frozenset()
|
|
53
|
+
return frozenset(cast("list[str]", value))
|
|
54
|
+
except (ValueError, json.JSONDecodeError):
|
|
55
|
+
return frozenset()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def reconcile_labels(
|
|
59
|
+
port: GitHubPort,
|
|
60
|
+
number: int,
|
|
61
|
+
graph: Graph,
|
|
62
|
+
results: Mapping[str, Result],
|
|
63
|
+
*,
|
|
64
|
+
previous_owned: Iterable[str] = (),
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Converge only Quality Graph-owned labels without touching unrelated state."""
|
|
67
|
+
if not graph.labels.enabled:
|
|
68
|
+
return
|
|
69
|
+
current = {
|
|
70
|
+
_string(item.get("name"), "pull request label")
|
|
71
|
+
for item in paged(port, f"/issues/{number}/labels")
|
|
72
|
+
}
|
|
73
|
+
desired = _desired_labels(graph, results)
|
|
74
|
+
specifications = _label_specs(graph)
|
|
75
|
+
owned = set(previous_owned) | specifications.keys()
|
|
76
|
+
for name in sorted(owned):
|
|
77
|
+
present = name in desired
|
|
78
|
+
if present and name not in current:
|
|
79
|
+
specification = specifications[name]
|
|
80
|
+
if specification.create:
|
|
81
|
+
_ensure_label(port, specification)
|
|
82
|
+
port.request("POST", f"/issues/{number}/labels", {"labels": [name]})
|
|
83
|
+
elif not present and name in current:
|
|
84
|
+
encoded = urllib.parse.quote(name, safe="")
|
|
85
|
+
port.request("DELETE", f"/issues/{number}/labels/{encoded}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _desired_labels(graph: Graph, results: Mapping[str, Result]) -> set[str]:
|
|
89
|
+
desired: set[str] = set()
|
|
90
|
+
aggregate_failure = False
|
|
91
|
+
for node in graph.nodes:
|
|
92
|
+
result = results.get(node.id)
|
|
93
|
+
failed = (
|
|
94
|
+
node.policy.blocking
|
|
95
|
+
and result is not None
|
|
96
|
+
and result.status in {ResultStatus.FAILED, ResultStatus.CANCELLED}
|
|
97
|
+
)
|
|
98
|
+
aggregate_failure = aggregate_failure or failed
|
|
99
|
+
if failed and isinstance(node.failing_label, LabelSpec):
|
|
100
|
+
desired.add(node.failing_label.name)
|
|
101
|
+
if aggregate_failure and graph.labels.failing is not None:
|
|
102
|
+
desired.add(graph.labels.failing.name)
|
|
103
|
+
return desired
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _label_specs(graph: Graph) -> dict[str, LabelSpec]:
|
|
107
|
+
aggregate = cast("LabelSpec", graph.labels.failing)
|
|
108
|
+
specifications: dict[str, LabelSpec] = {aggregate.name: aggregate}
|
|
109
|
+
for node in graph.nodes:
|
|
110
|
+
if isinstance(node.failing_label, LabelSpec):
|
|
111
|
+
specifications[node.failing_label.name] = node.failing_label
|
|
112
|
+
return specifications
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _ensure_label(port: GitHubPort, specification: LabelSpec) -> None:
|
|
116
|
+
encoded = urllib.parse.quote(specification.name, safe="")
|
|
117
|
+
if port.request("GET", f"/labels/{encoded}") is None:
|
|
118
|
+
port.request(
|
|
119
|
+
"POST",
|
|
120
|
+
"/labels",
|
|
121
|
+
{
|
|
122
|
+
"name": specification.name,
|
|
123
|
+
"color": specification.color.lower(),
|
|
124
|
+
"description": specification.description,
|
|
125
|
+
},
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _string(value: JsonValue, context: str) -> str:
|
|
130
|
+
if not isinstance(value, str):
|
|
131
|
+
message = f"{context} must be a string"
|
|
132
|
+
raise TypeError(message)
|
|
133
|
+
return value
|
qg_github/provider.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Expose GitHub workflow generation through the core provider seam."""
|
|
2
|
+
|
|
3
|
+
from qg_github.compiler import compile_graph
|
|
4
|
+
from quality_graph_core.graph import Graph
|
|
5
|
+
from quality_graph_core.provider import GeneratedProject
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class GitHubProvider:
|
|
9
|
+
"""Generate the complete GitHub representation of a Quality Graph."""
|
|
10
|
+
|
|
11
|
+
name = "github"
|
|
12
|
+
|
|
13
|
+
def generate(self, graph: Graph) -> GeneratedProject:
|
|
14
|
+
"""Compile a graph into GitHub workflows and trusted metadata."""
|
|
15
|
+
return compile_graph(graph)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
provider = GitHubProvider()
|
|
19
|
+
|
|
20
|
+
__all__ = ["GitHubProvider", "provider"]
|