codeveto 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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,330 @@
1
+ """CI steps around ``review`` and ``publish``: the composite action's entry point (SPEC 10.4, 10.5).
2
+
3
+ The action runs CodeVeto from its own source with one fixed bootstrap,
4
+ :data:`BOOTSTRAP`, as ``python -I -c "$BOOTSTRAP" <action>/src <command> ...``:
5
+ ``-I`` keeps the environment, the user site and the working directory off
6
+ ``sys.path``, and the bootstrap puts only the action's ``src`` first. Commands:
7
+
8
+ - ``cli <args>``: ``codeveto <args>`` (the CLI, for ``review`` and ``publish``);
9
+ - ``prepare --forge github|forgejo``: work out what to review from the event
10
+ and make the head's Git objects available, writing step outputs.
11
+
12
+ The Forgejo workflow runs the installed package the same way with
13
+ ``python -I -m codeveto.publish.action prepare --forge forgejo``.
14
+
15
+ ``prepare`` (outputs to ``$GITHUB_OUTPUT``: ``status``, ``message``, ``base``,
16
+ ``head``, ``comparison``, ``ai``):
17
+
18
+ - ``pull_request_target``: fetches ``refs/pull/<n>/head`` from the base
19
+ repository into the private ref ``refs/codeveto/head`` (data only: nothing
20
+ is checked out or run), verifies it equals ``pull_request.head.sha`` and that
21
+ the base commit is present; merge-base comparison.
22
+ - ``merge_group``: ``base_sha..head_sha``, direct; both commits must be present
23
+ (fetched by ID if not).
24
+ - ``push``: ``before..after``, direct. A zero ``before`` (new branch) compares
25
+ with the merge base with the default branch (a first push to the default
26
+ branch has nothing to compare with: incomplete); ``deleted`` → ``skip``
27
+ (exit 0); a ``before`` that cannot be fetched (rewritten history) →
28
+ incomplete.
29
+ - Anything else: ``unsupported event``, incomplete. A shallow repository is
30
+ incomplete with the fix (``fetch-depth: 0``).
31
+ - ``ai``: the ``CODEVETO_AI`` input, or ``none`` for a pull request from a fork
32
+ unless ``CODEVETO_AI_ON_FORKS`` is ``true`` (cost control).
33
+
34
+ ``status`` is ``review``, ``skip`` or ``fail``; on ``fail`` the job summary says
35
+ why and the action's last step exits 2. Git runs with no system or global
36
+ config, no hooks, no prompts, no redirects, HTTPS only, and the token only in
37
+ the fetch's environment (``http.<url>.extraheader`` via ``GIT_CONFIG_*``),
38
+ never on a command line or in ``.git/config``.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import argparse
44
+ import base64
45
+ import os
46
+ import re
47
+ import subprocess
48
+ import sys
49
+ from collections.abc import Mapping, Sequence
50
+ from dataclasses import dataclass, field
51
+
52
+ from codeveto.publish import PublishError
53
+ from codeveto.publish.common import DID_NOT_COMPLETE
54
+ from codeveto.publish.event import Event, is_oid, read_event
55
+
56
+ __all__ = ["BOOTSTRAP", "Prepared", "main", "prepare", "write_outputs"]
57
+
58
+ BOOTSTRAP = (
59
+ "import sys; sys.path.insert(0, sys.argv.pop(1)); "
60
+ "from codeveto.publish.action import main; sys.exit(main(sys.argv[1:]))"
61
+ )
62
+ HEAD_REF = "refs/codeveto/head"
63
+ BASE_REF = "refs/codeveto/base"
64
+ DEFAULT_REF = "refs/codeveto/default"
65
+ FETCH_TIMEOUT = 600
66
+ _BRANCH = re.compile(r"[A-Za-z0-9._/-]{1,255}")
67
+ _AI = frozenset({"none", "claude", "openai"})
68
+ SHALLOW_FIX = (
69
+ "the repository is shallow, so the change cannot be compared: "
70
+ "set fetch-depth: 0 on actions/checkout"
71
+ )
72
+
73
+
74
+ @dataclass(slots=True)
75
+ class Prepared:
76
+ """The outcome of ``prepare``: what the next steps read from the step outputs."""
77
+
78
+ status: str
79
+ message: str = ""
80
+ base: str = ""
81
+ head: str = ""
82
+ comparison: str = ""
83
+ ai: str = "none"
84
+ notes: list[str] = field(default_factory=list)
85
+
86
+ def outputs(self) -> dict[str, str]:
87
+ return {
88
+ "status": self.status,
89
+ "message": self.message,
90
+ "base": self.base,
91
+ "head": self.head,
92
+ "comparison": self.comparison,
93
+ "ai": self.ai,
94
+ }
95
+
96
+
97
+ class _Git:
98
+ def __init__(self, workspace: str, environ: Mapping[str, str], allow: str) -> None:
99
+ self.workspace = workspace
100
+ self.env = {
101
+ "PATH": environ.get("PATH", os.defpath),
102
+ "HOME": environ.get("RUNNER_TEMP") or environ.get("HOME", "/"),
103
+ "LC_ALL": "C",
104
+ "GIT_CONFIG_NOSYSTEM": "1",
105
+ "GIT_CONFIG_GLOBAL": os.devnull,
106
+ "GIT_TERMINAL_PROMPT": "0",
107
+ "GIT_ALLOW_PROTOCOL": allow,
108
+ "GIT_NO_REPLACE_OBJECTS": "1",
109
+ "GIT_LFS_SKIP_SMUDGE": "1",
110
+ "GIT_ASKPASS": "",
111
+ "SSH_ASKPASS": "",
112
+ }
113
+ self.prefix = [
114
+ "git",
115
+ "-c",
116
+ f"safe.directory={workspace}",
117
+ "-c",
118
+ f"core.hooksPath={os.devnull}",
119
+ "-c",
120
+ "core.fsmonitor=false",
121
+ "-c",
122
+ "gc.auto=0",
123
+ "-c",
124
+ "http.followRedirects=false",
125
+ ]
126
+
127
+ def run(
128
+ self, *args: str, extra: Mapping[str, str] | None = None, timeout: float = 60
129
+ ) -> tuple[int, str]:
130
+ try:
131
+ done = subprocess.run( # noqa: S603 - fixed git argv, no shell
132
+ [*self.prefix, *args],
133
+ cwd=self.workspace,
134
+ env={**self.env, **(extra or {})},
135
+ stdin=subprocess.DEVNULL,
136
+ stdout=subprocess.PIPE,
137
+ stderr=subprocess.DEVNULL,
138
+ timeout=timeout,
139
+ check=False,
140
+ )
141
+ except (OSError, subprocess.SubprocessError):
142
+ return 1, ""
143
+ return done.returncode, done.stdout.decode("ascii", "replace").strip()
144
+
145
+ def commit(self, rev: str) -> str | None:
146
+ code, out = self.run(
147
+ "rev-parse", "--verify", "--quiet", "--end-of-options", f"{rev}^{{commit}}"
148
+ )
149
+ return out if code == 0 and is_oid(out) else None
150
+
151
+ def shallow(self) -> bool:
152
+ code, out = self.run("rev-parse", "--is-shallow-repository")
153
+ return code != 0 or out != "false"
154
+
155
+
156
+ def _auth(url: str, token: str) -> dict[str, str]:
157
+ if not token:
158
+ return {}
159
+ basic = base64.b64encode(f"x-access-token:{token}".encode()).decode("ascii")
160
+ return {
161
+ "GIT_CONFIG_COUNT": "1",
162
+ "GIT_CONFIG_KEY_0": f"http.{url}.extraheader",
163
+ "GIT_CONFIG_VALUE_0": f"AUTHORIZATION: basic {basic}",
164
+ }
165
+
166
+
167
+ def _fetch(git: _Git, url: str, token: str, *refspecs: str) -> bool:
168
+ code, _ = git.run(
169
+ "fetch",
170
+ "--quiet",
171
+ "--no-tags",
172
+ "--no-recurse-submodules",
173
+ "--no-write-fetch-head",
174
+ "--end-of-options",
175
+ url,
176
+ *refspecs,
177
+ extra=_auth(url, token),
178
+ timeout=FETCH_TIMEOUT,
179
+ )
180
+ return code == 0
181
+
182
+
183
+ def _ensure(git: _Git, url: str, token: str, oid: str, ref: str) -> bool:
184
+ """Is commit ``oid`` present, fetching it by ID into ``ref`` if not?"""
185
+ if git.commit(oid) == oid:
186
+ return True
187
+ _fetch(git, url, token, f"+{oid}:{ref}")
188
+ return git.commit(oid) == oid
189
+
190
+
191
+ def _effective_ai(environ: Mapping[str, str], event: Event, notes: list[str]) -> str:
192
+ ai = environ.get("CODEVETO_AI", "none").strip() or "none"
193
+ if ai not in _AI:
194
+ raise PublishError(f"invalid ai input {ai!r} (none, claude or openai)")
195
+ on_forks = environ.get("CODEVETO_AI_ON_FORKS", "false").strip().lower() == "true"
196
+ if ai != "none" and event.fork and not on_forks:
197
+ notes.append("AI review is off for pull requests from forks (ai-on-forks: false)")
198
+ return "none"
199
+ return ai
200
+
201
+
202
+ def prepare(
203
+ environ: Mapping[str, str],
204
+ forge: str,
205
+ *,
206
+ remote: str | None = None,
207
+ allow_protocols: str = "https",
208
+ ) -> Prepared:
209
+ """Decide what to review and make its objects available (see the module docstring).
210
+
211
+ ``remote`` overrides the fetch URL (tests use a local repository).
212
+ """
213
+ try:
214
+ event = read_event(environ, forge)
215
+ except PublishError as exc:
216
+ return Prepared("fail", str(exc))
217
+ workspace = environ.get("GITHUB_WORKSPACE") or os.getcwd()
218
+ git = _Git(workspace, environ, allow_protocols)
219
+ url = remote or f"{event.server_url}/{event.repo}.git"
220
+ token = environ.get("GITHUB_TOKEN", "")
221
+ notes: list[str] = []
222
+ try:
223
+ ai = _effective_ai(environ, event, notes)
224
+ except PublishError as exc:
225
+ return Prepared("fail", str(exc))
226
+ if event.deleted:
227
+ return Prepared("skip", "the branch was deleted: nothing to review")
228
+ if git.commit("HEAD") is None:
229
+ return Prepared("fail", "no Git repository in the workspace: run actions/checkout first")
230
+ if git.shallow():
231
+ return Prepared("fail", SHALLOW_FIX)
232
+ if event.name == "pull_request_target":
233
+ if not _fetch(git, url, token, f"+refs/pull/{event.number}/head:{HEAD_REF}"):
234
+ return Prepared("fail", "could not fetch the pull request's head")
235
+ if git.commit(HEAD_REF) != event.head:
236
+ return Prepared(
237
+ "fail",
238
+ "the fetched head is not pull_request.head.sha "
239
+ "(the pull request moved; a newer run reviews it)",
240
+ )
241
+ if event.base is None or not _ensure(git, url, token, event.base, BASE_REF):
242
+ return Prepared("fail", "the pull request's base commit is not available")
243
+ base = event.base
244
+ elif event.name == "merge_group":
245
+ base = event.base or "" # merge_group events always name both commits
246
+ for oid, ref in ((event.head, HEAD_REF), (base, BASE_REF)):
247
+ if not oid or not _ensure(git, url, token, oid, ref):
248
+ return Prepared("fail", "the merge group's commits are not available")
249
+ else: # push
250
+ if not _ensure(git, url, token, event.head, HEAD_REF):
251
+ return Prepared("fail", "the pushed commit is not available")
252
+ if event.base is None:
253
+ branch = event.default_branch or ""
254
+ if not _BRANCH.fullmatch(branch) or ".." in branch:
255
+ return Prepared("fail", "the event names no usable default branch")
256
+ if event.ref == f"refs/heads/{branch}":
257
+ return Prepared(
258
+ "fail", "the first push to the default branch has no base to compare with"
259
+ )
260
+ resolved = git.commit(f"refs/remotes/origin/{branch}")
261
+ if resolved is None:
262
+ _fetch(git, url, token, f"+refs/heads/{branch}:{DEFAULT_REF}")
263
+ resolved = git.commit(DEFAULT_REF)
264
+ if resolved is None:
265
+ return Prepared("fail", "the default branch could not be fetched")
266
+ base = resolved
267
+ else:
268
+ if not _ensure(git, url, token, event.base, BASE_REF):
269
+ return Prepared(
270
+ "fail",
271
+ "the push's before commit is not reachable (rewritten or missing history), "
272
+ "so the change cannot be compared",
273
+ )
274
+ base = event.base
275
+ return Prepared(
276
+ "review",
277
+ "; ".join(notes),
278
+ base=base,
279
+ head=event.head,
280
+ comparison=event.comparison,
281
+ ai=ai,
282
+ notes=notes,
283
+ )
284
+
285
+
286
+ def write_outputs(environ: Mapping[str, str], prepared: Prepared) -> None:
287
+ """Append the step outputs (and, on ``fail``, the job summary)."""
288
+ lines = []
289
+ for key, value in prepared.outputs().items():
290
+ single = " ".join(str(value).split()) # never a line break in an output value
291
+ lines.append(f"{key}={single}\n")
292
+ output = environ.get("GITHUB_OUTPUT")
293
+ if output:
294
+ with open(output, "a", encoding="utf-8") as stream:
295
+ stream.writelines(lines)
296
+ else:
297
+ sys.stdout.writelines(lines)
298
+ summary = environ.get("GITHUB_STEP_SUMMARY")
299
+ if prepared.status == "fail" and summary:
300
+ with open(summary, "a", encoding="utf-8") as stream:
301
+ stream.write(f"### {DID_NOT_COMPLETE}\n\n{prepared.message}.\n")
302
+
303
+
304
+ def _parser() -> argparse.ArgumentParser:
305
+ parser = argparse.ArgumentParser(prog="codeveto-action")
306
+ sub = parser.add_subparsers(dest="command", required=True)
307
+ step = sub.add_parser("prepare")
308
+ step.add_argument("--forge", choices=("github", "forgejo"), required=True)
309
+ return parser
310
+
311
+
312
+ def main(argv: Sequence[str] | None = None) -> int:
313
+ """Entry point of :data:`BOOTSTRAP` and ``python -m codeveto.publish.action``."""
314
+ args = list(sys.argv[1:] if argv is None else argv)
315
+ if args[:1] == ["cli"]:
316
+ from codeveto.cli import main as cli_main
317
+
318
+ return cli_main(args[1:])
319
+ try:
320
+ parsed = _parser().parse_args(args)
321
+ except SystemExit as exc:
322
+ return 0 if exc.code == 0 else 2
323
+ prepared = prepare(os.environ, parsed.forge)
324
+ write_outputs(os.environ, prepared)
325
+ print(f"codeveto: prepare: {prepared.status} {prepared.message}".rstrip(), file=sys.stderr)
326
+ return 0
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())
@@ -0,0 +1,84 @@
1
+ """What both publishers share: the job log, the job summary and the warnings.
2
+
3
+ - :class:`Output` collects publishing warnings and writes the job summary
4
+ (``$GITHUB_STEP_SUMMARY``) once at the end, with a **Publishing warnings**
5
+ section; without a summary file the warnings go to stderr.
6
+ - :meth:`Output.log_report` prints the text rendering of the report to the
7
+ job log between ``::stop-commands::<random token>`` and the resume
8
+ command, so no line of it (a path, a snippet) can act as a workflow
9
+ command; only the publisher's own annotation commands run.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import secrets
15
+ import sys
16
+ from collections.abc import Mapping
17
+ from typing import Any, TextIO
18
+
19
+ from codeveto.render import RenderOptions, safe
20
+ from codeveto.render import text as text_renderer
21
+
22
+ __all__ = ["DID_NOT_COMPLETE", "Output"]
23
+
24
+ DID_NOT_COMPLETE = "CodeVeto did not complete"
25
+
26
+
27
+ class Output:
28
+ """The job summary, the job log and the warnings of one ``publish`` run."""
29
+
30
+ def __init__(
31
+ self,
32
+ environ: Mapping[str, str],
33
+ *,
34
+ stdout: TextIO | None = None,
35
+ stderr: TextIO | None = None,
36
+ ) -> None:
37
+ self.summary_path = environ.get("GITHUB_STEP_SUMMARY") or None
38
+ self.stdout = stdout or sys.stdout
39
+ self.stderr = stderr or sys.stderr
40
+ self.warnings: list[str] = []
41
+ self.body: str | None = None
42
+ # False when an earlier step already wrote ``body``'s message to the job summary.
43
+ self.body_in_summary = True
44
+
45
+ def warn(self, message: str) -> None:
46
+ """Record a publishing warning (trusted text; it is escaped when written)."""
47
+ self.warnings.append(message)
48
+
49
+ def command(self, line: str) -> None:
50
+ """Print one workflow command the publisher built (already escaped)."""
51
+ self.stdout.write(line + "\n")
52
+
53
+ def log_report(self, report: Mapping[str, Any]) -> None:
54
+ """Print the text rendering to the log with workflow commands stopped."""
55
+ token = secrets.token_hex(16)
56
+ body = text_renderer.render(report, RenderOptions(color=False, unicode=True))
57
+ self.stdout.write(f"::stop-commands::{token}\n{body}::{token}::\n")
58
+ self.stdout.flush()
59
+
60
+ def _summary_text(self) -> str:
61
+ parts: list[str] = []
62
+ if self.body and self.body_in_summary:
63
+ parts.append(self.body.rstrip("\n"))
64
+ if self.warnings:
65
+ parts += ["", "**Publishing warnings**", ""]
66
+ parts += [f"- {safe.md_code(w)}" for w in self.warnings]
67
+ return "\n".join(parts).lstrip("\n") + "\n"
68
+
69
+ def finish(self) -> None:
70
+ """Write the job summary (or the warnings to stderr) and warning annotations."""
71
+ for warning in self.warnings:
72
+ self.command(f"::warning title=codeveto publish::{safe.workflow_data(warning)}")
73
+ if self.summary_path is None:
74
+ for warning in self.warnings:
75
+ self.stderr.write(f"codeveto: publish: {safe.text(warning)}\n")
76
+ return
77
+ try:
78
+ with open(self.summary_path, "a", encoding="utf-8") as stream:
79
+ stream.write(self._summary_text())
80
+ except OSError:
81
+ self.stderr.write("codeveto: publish: cannot write the job summary\n")
82
+ for warning in self.warnings:
83
+ self.stderr.write(f"codeveto: publish: {safe.text(warning)}\n")
84
+ self.stdout.flush()
@@ -0,0 +1,208 @@
1
+ """Changed lines of a pull request, from the forge's own diff (SPEC 10.4).
2
+
3
+ ``publish`` keeps only findings on lines the pull request changes, as the
4
+ forge sees the change: added lines (new side) and removed lines (old side)
5
+ per file. A file the forge lists without a patch (binary, or too large for
6
+ the API) is ``known = False``: its findings stay in the summary and the
7
+ annotations but never become inline comments, since no line of it can be
8
+ checked. A file the forge does not list at all drops every finding on it.
9
+
10
+ Two sources: the ``patch`` field of GitHub's ``GET /pulls/{n}/files``
11
+ entries (:func:`from_github_files`), and a whole unified diff such as
12
+ Forgejo's ``GET /pulls/{n}.diff`` (:func:`parse_unified`). Hunks are read by
13
+ their line counts, so a removed line that starts with ``--`` is never taken
14
+ for a file header.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from collections.abc import Iterable, Mapping
21
+ from dataclasses import dataclass, field
22
+ from typing import Any
23
+
24
+ __all__ = ["FileLines", "from_github_files", "parse_hunks", "parse_unified", "placement"]
25
+
26
+ _HUNK = re.compile(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
27
+ _ESCAPES = {"a": 7, "b": 8, "t": 9, "n": 10, "v": 11, "f": 12, "r": 13, '"': 34, "\\": 92}
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class FileLines:
32
+ """The changed lines of one file of a pull request."""
33
+
34
+ path: str
35
+ added: set[int] = field(default_factory=set)
36
+ deleted: set[int] = field(default_factory=set)
37
+ known: bool = True
38
+
39
+
40
+ def _hunk_lines(lines: list[str], start: int, header: re.Match[str], out: FileLines) -> int:
41
+ old, new = int(header.group(1)), int(header.group(3))
42
+ old_left = int(header.group(2)) if header.group(2) is not None else 1
43
+ new_left = int(header.group(4)) if header.group(4) is not None else 1
44
+ i = start
45
+ while i < len(lines) and (old_left > 0 or new_left > 0):
46
+ line = lines[i]
47
+ i += 1
48
+ if line.startswith("\\"):
49
+ continue # ""
50
+ tag = line[:1]
51
+ if tag == "+":
52
+ out.added.add(new)
53
+ new += 1
54
+ new_left -= 1
55
+ elif tag == "-":
56
+ out.deleted.add(old)
57
+ old += 1
58
+ old_left -= 1
59
+ else: # context (" " or an empty line some tools strip to "")
60
+ old += 1
61
+ new += 1
62
+ old_left -= 1
63
+ new_left -= 1
64
+ while i < len(lines) and lines[i].startswith("\\"):
65
+ i += 1
66
+ return i
67
+
68
+
69
+ def parse_hunks(patch: str, path: str = "") -> FileLines:
70
+ """The changed lines of one file's hunks (a GitHub ``patch`` field)."""
71
+ out = FileLines(path)
72
+ lines = patch.replace("\r\n", "\n").split("\n")
73
+ i = 0
74
+ while i < len(lines):
75
+ match = _HUNK.match(lines[i])
76
+ if match is None:
77
+ i += 1
78
+ continue
79
+ i = _hunk_lines(lines, i + 1, match, out)
80
+ return out
81
+
82
+
83
+ def from_github_files(entries: Iterable[Any]) -> dict[str, FileLines]:
84
+ """``path -> FileLines`` from ``GET /pulls/{n}/files`` entries (bad entries are skipped)."""
85
+ files: dict[str, FileLines] = {}
86
+ for entry in entries:
87
+ if not isinstance(entry, Mapping):
88
+ continue
89
+ path = entry.get("filename")
90
+ if not isinstance(path, str) or not path:
91
+ continue
92
+ patch = entry.get("patch")
93
+ if isinstance(patch, str) and patch:
94
+ files[path] = parse_hunks(patch, path)
95
+ else:
96
+ files[path] = FileLines(path, known=False)
97
+ return files
98
+
99
+
100
+ def _unquote(raw: str) -> str:
101
+ """A path as Git prints it: C-quoted (``"a\\303\\251"``) or plain."""
102
+ if len(raw) < 2 or raw[0] != '"' or raw[-1] != '"':
103
+ return raw
104
+ body = raw[1:-1]
105
+ out = bytearray()
106
+ i = 0
107
+ while i < len(body):
108
+ ch = body[i]
109
+ if ch != "\\" or i + 1 == len(body):
110
+ out += ch.encode("utf-8", "surrogateescape")
111
+ i += 1
112
+ continue
113
+ nxt = body[i + 1]
114
+ if nxt in _ESCAPES:
115
+ out.append(_ESCAPES[nxt])
116
+ i += 2
117
+ elif re.fullmatch(r"[0-7]{3}", body[i + 1 : i + 4]):
118
+ out.append(int(body[i + 1 : i + 4], 8) & 0xFF)
119
+ i += 4
120
+ else:
121
+ out += nxt.encode("utf-8", "surrogateescape")
122
+ i += 2
123
+ return out.decode("utf-8", "surrogateescape")
124
+
125
+
126
+ def _strip_prefix(raw: str) -> str | None:
127
+ path = _unquote(raw.split("\t", 1)[0] if not raw.startswith('"') else raw)
128
+ if path == "/dev/null":
129
+ return None
130
+ return path[2:] if path[:2] in ("a/", "b/") else path
131
+
132
+
133
+ def _header_path(header: str) -> str | None:
134
+ rest = header[len("diff --git ") :]
135
+ if rest.startswith('"'):
136
+ end = rest.find('" ', 1)
137
+ while end != -1 and rest[end - 1] == "\\":
138
+ end = rest.find('" ', end + 1)
139
+ new = rest[end + 2 :] if end != -1 else ""
140
+ return _strip_prefix(new) if new else None
141
+ # "a/<p> b/<p>": the two halves are equal for anything but a rename.
142
+ half = (len(rest) - 1) // 2
143
+ if len(rest) % 2 == 1 and rest[half] == " " and rest[:half][2:] == rest[half + 1 :][2:]:
144
+ return rest[half + 1 :][2:]
145
+ return None
146
+
147
+
148
+ def parse_unified(text: str) -> dict[str, FileLines]:
149
+ """``path -> FileLines`` from a whole unified Git diff (``diff --git`` sections)."""
150
+ files: dict[str, FileLines] = {}
151
+ lines = text.replace("\r\n", "\n").split("\n")
152
+ current: FileLines | None = None
153
+ old_path: str | None = None
154
+ i = 0
155
+ while i < len(lines):
156
+ line = lines[i]
157
+ if line.startswith("diff --git "):
158
+ path = _header_path(line)
159
+ current = FileLines(path or "", known=False)
160
+ if path:
161
+ files[path] = current
162
+ old_path = None
163
+ i += 1
164
+ continue
165
+ if current is None:
166
+ i += 1
167
+ continue
168
+ if line.startswith("rename to "):
169
+ path = _unquote(line[len("rename to ") :])
170
+ files.pop(current.path, None)
171
+ current.path = path
172
+ files[path] = current
173
+ elif line.startswith("--- "):
174
+ old_path = _strip_prefix(line[4:])
175
+ elif line.startswith("+++ "):
176
+ path = _strip_prefix(line[4:]) or old_path
177
+ if path and path != current.path:
178
+ files.pop(current.path, None)
179
+ current.path = path
180
+ files[path] = current
181
+ current.known = True
182
+ else:
183
+ match = _HUNK.match(line)
184
+ if match is not None:
185
+ current.known = True
186
+ i = _hunk_lines(lines, i + 1, match, current)
187
+ continue
188
+ i += 1
189
+ files.pop("", None)
190
+ return files
191
+
192
+
193
+ def placement(finding: Mapping[str, Any], files: Mapping[str, FileLines]) -> str | None:
194
+ """Where a finding may be published: ``"inline"``, ``"summary"`` or ``None`` (dropped).
195
+
196
+ ``inline``: on a changed line of a file whose patch is known; ``summary``:
197
+ a whole-file finding on a listed file, or any finding on a listed file
198
+ without a patch; ``None``: the file is not in the pull request, or the
199
+ line is not one it changes.
200
+ """
201
+ entry = files.get(finding["path"])
202
+ if entry is None:
203
+ return None
204
+ line = finding["line"]
205
+ if line is None or not entry.known:
206
+ return "summary"
207
+ lines = entry.deleted if finding["side"] == "old" else entry.added
208
+ return "inline" if line in lines else None