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/commands.py ADDED
@@ -0,0 +1,333 @@
1
+ """Authenticate and dispatch pull-request Quality Graph commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import re
7
+ import urllib.parse
8
+ from dataclasses import dataclass
9
+ from enum import StrEnum
10
+
11
+ from qg_github.approvals import ApprovalRecord, append_approval_record
12
+ from qg_github.artifacts import ArtifactExpectation, download_results
13
+ from qg_github.compiler import compile_graph
14
+ from qg_github.controls import control_states, decode_control_marker
15
+ from qg_github.github import GITHUB_PAGE_SIZE, GitHubPort
16
+ from quality_graph_core.graph import Graph
17
+ from quality_graph_core.policy import ApprovalTarget, effective_graph
18
+ from quality_graph_core.result import ControlKind, JsonValue
19
+
20
+ COMMAND_RE = re.compile(
21
+ r"^/qg(?:\s+(help|status|ignore|remove-ignore|ignore-file|remove-ignore-file)"
22
+ r"(?:\s+(\S+))?)?$"
23
+ )
24
+ DEFAULT_BOT_LOGIN = "github-actions[bot]"
25
+
26
+
27
+ class CommandName(StrEnum):
28
+ """Represent the supported administrator command surface."""
29
+
30
+ HELP = "help"
31
+ STATUS = "status"
32
+ IGNORE = "ignore"
33
+ REMOVE_IGNORE = "remove-ignore"
34
+ IGNORE_FILE = "ignore-file"
35
+ REMOVE_IGNORE_FILE = "remove-ignore-file"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Command:
40
+ """Carry one parsed canonical command."""
41
+
42
+ name: CommandName
43
+ arguments: tuple[str, ...] = ()
44
+
45
+ @property
46
+ def text(self) -> str:
47
+ """Render the canonical command text."""
48
+ suffix = f" {','.join(self.arguments)}" if self.arguments else ""
49
+ return f"/qg {self.name.value}{suffix}"
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class CommandRequest:
54
+ """Carry one command candidate extracted from an issue-comment event."""
55
+
56
+ comment_id: int
57
+ body: str
58
+ actor: str | None
59
+ pull_request: int | None
60
+ previous_dashboard_body: str | None = None
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class CommandOutcome:
65
+ """Describe whether a command was handled and changed approval state."""
66
+
67
+ handled: bool
68
+ authorized: bool = False
69
+ changed: bool = False
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class CommandContext:
74
+ """Carry the latest graph, run, and active semantic targets."""
75
+
76
+ graph: Graph
77
+ run_id: int
78
+ targets: frozenset[ApprovalTarget]
79
+
80
+
81
+ def parse_command(value: str) -> Command | None:
82
+ """Parse one complete canonical `/qg` comment."""
83
+ match = COMMAND_RE.fullmatch(value.strip())
84
+ if match is None:
85
+ return None
86
+ name = CommandName(match.group(1) or "status")
87
+ raw = match.group(2)
88
+ if name in {CommandName.HELP, CommandName.STATUS}:
89
+ return Command(name) if raw is None else None
90
+ if raw is None:
91
+ return None
92
+ arguments = tuple(item.strip() for item in raw.split(","))
93
+ if not all(arguments) or "all" in arguments:
94
+ return None
95
+ return Command(name, arguments)
96
+
97
+
98
+ def command_request(
99
+ event_value: JsonValue,
100
+ *,
101
+ bot_logins: tuple[str, ...] = (DEFAULT_BOT_LOGIN,),
102
+ ) -> CommandRequest | None:
103
+ """Extract a direct command or one canonical checkbox transition."""
104
+ event = _object(event_value, "issue comment event")
105
+ comment = _object(event.get("comment"), "issue comment")
106
+ comment_id = _integer(comment.get("id"), "comment id")
107
+ body = _string(comment.get("body"), "comment body").strip()
108
+ issue = _object(event.get("issue"), "issue")
109
+ number = _optional_integer(issue.get("number"), "issue number")
110
+ pull_request = number if issue.get("pull_request") is not None else None
111
+ author = comment.get("user")
112
+ author_login = (
113
+ _optional_string(author.get("login"), "comment author")
114
+ if isinstance(author, dict)
115
+ else None
116
+ )
117
+ if body == "/qg" or body.startswith("/qg "):
118
+ return CommandRequest(comment_id, body, author_login, pull_request)
119
+ if event.get("action") != "edited" or author_login not in bot_logins:
120
+ return None
121
+ changes = _object(event.get("changes"), "comment changes")
122
+ body_change = _object(changes.get("body"), "comment body change")
123
+ previous = _string(body_change.get("from"), "previous comment body")
124
+ before = control_states(previous)
125
+ after = control_states(body)
126
+ changed = [marker for marker in before.keys() & after.keys() if before[marker] != after[marker]]
127
+ if len(changed) != 1:
128
+ return None
129
+ commands = decode_control_marker(changed[0])
130
+ if commands is None:
131
+ return None
132
+ apply, reverse = commands
133
+ sender = _object(event.get("sender"), "event sender")
134
+ actor = _optional_string(sender.get("login"), "event sender login")
135
+ selected = apply if after[changed[0]] else reverse
136
+ return CommandRequest(comment_id, selected, actor, pull_request, previous)
137
+
138
+
139
+ def handle_command(port: GitHubPort, event_value: JsonValue) -> CommandOutcome:
140
+ """Authenticate, record, and trigger one Quality Graph command."""
141
+ request = command_request(event_value)
142
+ if request is None:
143
+ return CommandOutcome(handled=False)
144
+ if request.previous_dashboard_body is not None:
145
+ port.request(
146
+ "PATCH",
147
+ f"/issues/comments/{request.comment_id}",
148
+ {"body": request.previous_dashboard_body},
149
+ )
150
+ command = parse_command(request.body)
151
+ if command is None or request.pull_request is None or request.actor is None:
152
+ _react(port, request.comment_id, "x")
153
+ return CommandOutcome(handled=True)
154
+ if command.name in {CommandName.HELP, CommandName.STATUS}:
155
+ reply = (
156
+ _help_body()
157
+ if command.name is CommandName.HELP
158
+ else "Quality Graph command handling is available."
159
+ )
160
+ _reply(port, request.pull_request, reply)
161
+ _react(port, request.comment_id, "+1")
162
+ return CommandOutcome(handled=True, authorized=True)
163
+ context = _command_context(port, request.pull_request)
164
+ if not _authorized(port, request.actor, context.graph.administrator_roles):
165
+ _react(port, request.comment_id, "confused")
166
+ return CommandOutcome(handled=True)
167
+ targets = _command_targets(command, context.targets)
168
+ _react(port, request.comment_id, "eyes")
169
+ record = ApprovalRecord(
170
+ command.name in {CommandName.IGNORE, CommandName.IGNORE_FILE},
171
+ targets,
172
+ request.actor,
173
+ request.comment_id,
174
+ )
175
+ append_approval_record(port, request.pull_request, record)
176
+ port.request("POST", f"/actions/runs/{context.run_id}/rerun-failed-jobs")
177
+ _react(port, request.comment_id, "hooray")
178
+ return CommandOutcome(handled=True, authorized=True, changed=True)
179
+
180
+
181
+ # pragma: no mutate start
182
+ def _command_context(port: GitHubPort, number: int) -> CommandContext:
183
+ pull = _object(port.request("GET", f"/pulls/{number}"), "pull request")
184
+ head = _object(pull.get("head"), "pull request head")
185
+ base = _object(pull.get("base"), "pull request base")
186
+ head_sha = _string(head.get("sha"), "pull request head SHA")
187
+ base_sha = _string(base.get("sha"), "pull request base SHA")
188
+ graph = Graph.from_yaml(_repository_file(port, "quality-graph.yml", base_sha))
189
+ compiled = compile_graph(graph)
190
+ run = _latest_run(port, number)
191
+ run_id = _integer(run.get("id"), "workflow run id")
192
+ attempt = _integer(run.get("run_attempt", 1), "workflow run attempt")
193
+ expectation = ArtifactExpectation(
194
+ port.repository,
195
+ number,
196
+ head_sha,
197
+ run_id,
198
+ compiled.graph_digest,
199
+ frozenset(node.id for node in graph.nodes),
200
+ )
201
+ results = download_results(port, expectation)
202
+ if any(result.provenance.run_attempt > attempt for result in results.values()):
203
+ message = "result artifact attempt exceeds the latest workflow attempt"
204
+ raise ValueError(message)
205
+ state = effective_graph(graph, results, set())
206
+ return CommandContext(graph, run_id, state.targets)
207
+
208
+
209
+ def _latest_run(port: GitHubPort, number: int) -> dict[str, JsonValue]:
210
+ path = (
211
+ "/actions/workflows/quality-graph.yml/runs?event=pull_request"
212
+ f"&per_page={GITHUB_PAGE_SIZE}&page=1"
213
+ )
214
+ response = _object(port.request("GET", path), "workflow runs")
215
+ runs = [
216
+ run
217
+ for value in _array(response.get("workflow_runs", []), "workflow runs")
218
+ for run in (_object(value, "workflow run"),)
219
+ if any(
220
+ _object(pull, "workflow pull request").get("number") == number
221
+ for pull in _array(run.get("pull_requests", []), "workflow pull requests")
222
+ )
223
+ ]
224
+ if not runs:
225
+ message = f"no Quality Graph workflow run found for PR #{number}"
226
+ raise ValueError(message)
227
+ return max(runs, key=lambda run: _integer(run.get("id"), "workflow run id"))
228
+
229
+
230
+ # pragma: no mutate end
231
+ def _authorized(port: GitHubPort, actor: str, roles: tuple[str, ...]) -> bool:
232
+ login = urllib.parse.quote(actor, safe="")
233
+ try:
234
+ response = port.request("GET", f"/collaborators/{login}/permission")
235
+ except RuntimeError:
236
+ return False
237
+ data = _object(response, "collaborator permission")
238
+ permission = _optional_string(data.get("permission"), "collaborator permission")
239
+ return permission in roles
240
+
241
+
242
+ def _command_targets(
243
+ command: Command,
244
+ active: frozenset[ApprovalTarget],
245
+ ) -> tuple[ApprovalTarget, ...]:
246
+ targets: list[ApprovalTarget] = []
247
+ for argument in command.arguments:
248
+ if command.name in {CommandName.IGNORE_FILE, CommandName.REMOVE_IGNORE_FILE}:
249
+ candidates: tuple[ApprovalTarget, ...] = (ApprovalTarget(ControlKind.FILE, argument),)
250
+ else:
251
+ candidates = (
252
+ ApprovalTarget(ControlKind.FINDING, argument),
253
+ ApprovalTarget(ControlKind.NODE, argument),
254
+ )
255
+ selected = next((candidate for candidate in candidates if candidate in active), None)
256
+ if selected is None:
257
+ message = f"unknown or non-approvable Quality Graph target: {argument}"
258
+ raise ValueError(message)
259
+ targets.append(selected)
260
+ return tuple(dict.fromkeys(targets))
261
+
262
+
263
+ # pragma: no mutate start
264
+ def _repository_file(port: GitHubPort, path: str, ref: str) -> str:
265
+ encoded_path = urllib.parse.quote(path, safe="")
266
+ encoded_ref = urllib.parse.quote(ref, safe="")
267
+ response = _object(
268
+ port.request("GET", f"/contents/{encoded_path}?ref={encoded_ref}"),
269
+ "repository file",
270
+ )
271
+ content = _string(response.get("content"), "repository file content")
272
+ return base64.b64decode(content.replace("\n", ""), validate=True).decode()
273
+
274
+
275
+ def _react(port: GitHubPort, comment_id: int, content: str) -> None:
276
+ port.request(
277
+ "POST",
278
+ f"/issues/comments/{comment_id}/reactions",
279
+ {"content": content},
280
+ )
281
+
282
+
283
+ def _reply(port: GitHubPort, number: int, body: str) -> None:
284
+ port.request("POST", f"/issues/{number}/comments", {"body": body})
285
+
286
+
287
+ def _help_body() -> str:
288
+ return """Quality Graph commands:
289
+
290
+ - `/qg status`
291
+ - `/qg ignore <finding-or-node>`
292
+ - `/qg remove-ignore <finding-or-node>`
293
+ - `/qg ignore-file <path>`
294
+ - `/qg remove-ignore-file <path>`"""
295
+
296
+
297
+ def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
298
+ if not isinstance(value, dict):
299
+ message = f"{context} must be an object"
300
+ raise TypeError(message)
301
+ return value
302
+
303
+
304
+ def _array(value: JsonValue, context: str) -> list[JsonValue]:
305
+ if not isinstance(value, list):
306
+ message = f"{context} must be an array"
307
+ raise TypeError(message)
308
+ return value
309
+
310
+
311
+ def _string(value: JsonValue, context: str) -> str:
312
+ if not isinstance(value, str):
313
+ message = f"{context} must be a string"
314
+ raise TypeError(message)
315
+ return value
316
+
317
+
318
+ def _optional_string(value: JsonValue, context: str) -> str | None:
319
+ return None if value is None else _string(value, context)
320
+
321
+
322
+ def _integer(value: JsonValue, context: str) -> int:
323
+ if not isinstance(value, int) or isinstance(value, bool):
324
+ message = f"{context} must be an integer"
325
+ raise TypeError(message)
326
+ return value
327
+
328
+
329
+ def _optional_integer(value: JsonValue, context: str) -> int | None:
330
+ return None if value is None else _integer(value, context)
331
+
332
+
333
+ # pragma: no mutate end
qg_github/comments.py ADDED
@@ -0,0 +1,104 @@
1
+ """Manage one bounded bot-owned Quality Graph pull-request comment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING
7
+
8
+ from qg_github.github import GitHubPort, paged
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Iterable
12
+
13
+ from quality_graph_core.result import JsonValue
14
+
15
+ GITHUB_COMMENT_BODY_LIMIT = 65_536
16
+ DEFAULT_BOT_LOGIN = "github-actions[bot]"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ManagedComment:
21
+ """Carry the identity and body of one trusted managed comment."""
22
+
23
+ id: int
24
+ body: str
25
+
26
+
27
+ def marker(name: str) -> str:
28
+ """Render one stable Quality Graph hidden marker."""
29
+ return f"<!-- quality-graph:{name} -->"
30
+
31
+
32
+ def bounded_comment(name: str, body: str) -> str:
33
+ """Wrap and bound one managed comment with an exact omission notice."""
34
+ value = f"{marker(name)}\n\n{body.rstrip()}\n"
35
+ if len(value) <= GITHUB_COMMENT_BODY_LIMIT:
36
+ return value
37
+ omitted = len(value) - GITHUB_COMMENT_BODY_LIMIT
38
+ while True:
39
+ notice = f"\n\n_Report truncated; {omitted} characters omitted._\n"
40
+ prefix = GITHUB_COMMENT_BODY_LIMIT - len(notice)
41
+ updated = len(value) - prefix
42
+ if updated == omitted:
43
+ return value[:prefix] + notice
44
+ omitted = updated
45
+
46
+
47
+ def find_managed_comment(
48
+ port: GitHubPort,
49
+ number: int,
50
+ name: str,
51
+ *,
52
+ bot_logins: Iterable[str] = (DEFAULT_BOT_LOGIN,),
53
+ ) -> ManagedComment | None:
54
+ """Return the bot-owned comment carrying the requested marker."""
55
+ expected = marker(name)
56
+ trusted = set(bot_logins)
57
+ for item in paged(port, f"/issues/{number}/comments"):
58
+ body = item.get("body")
59
+ author = item.get("user")
60
+ comment_id = item.get("id")
61
+ login = author.get("login") if isinstance(author, dict) else None
62
+ if (
63
+ isinstance(body, str)
64
+ and expected in body
65
+ and login in trusted
66
+ and isinstance(comment_id, int)
67
+ and not isinstance(comment_id, bool)
68
+ ):
69
+ return ManagedComment(comment_id, body)
70
+ return None
71
+
72
+
73
+ def upsert_managed_comment(
74
+ port: GitHubPort,
75
+ number: int,
76
+ name: str,
77
+ body: str,
78
+ *,
79
+ bot_logins: Iterable[str] = (DEFAULT_BOT_LOGIN,),
80
+ ) -> ManagedComment:
81
+ """Create or replace one trusted managed comment."""
82
+ rendered = bounded_comment(name, body)
83
+ existing = find_managed_comment(port, number, name, bot_logins=bot_logins)
84
+ if existing is None:
85
+ response = port.request("POST", f"/issues/{number}/comments", {"body": rendered})
86
+ else:
87
+ response = port.request("PATCH", f"/issues/comments/{existing.id}", {"body": rendered})
88
+ data = _object(response, "managed comment")
89
+ comment_id = data.get("id")
90
+ response_body = data.get("body")
91
+ if not isinstance(comment_id, int) or isinstance(comment_id, bool):
92
+ message = "managed comment response has no numeric id"
93
+ raise TypeError(message)
94
+ if not isinstance(response_body, str):
95
+ message = "managed comment response has no body"
96
+ raise TypeError(message)
97
+ return ManagedComment(comment_id, response_body)
98
+
99
+
100
+ def _object(value: JsonValue, context: str) -> dict[str, JsonValue]:
101
+ if not isinstance(value, dict):
102
+ message = f"{context} must be an object"
103
+ raise TypeError(message)
104
+ return value