rd0-fence 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rd0_fence-0.1.0/LICENSE +9 -0
- rd0_fence-0.1.0/MANIFEST.in +3 -0
- rd0_fence-0.1.0/PKG-INFO +41 -0
- rd0_fence-0.1.0/README.md +20 -0
- rd0_fence-0.1.0/examples/issue.md +4 -0
- rd0_fence-0.1.0/examples/pr.diff +50 -0
- rd0_fence-0.1.0/pyproject.toml +37 -0
- rd0_fence-0.1.0/setup.cfg +4 -0
- rd0_fence-0.1.0/src/rd0_fence/__init__.py +8 -0
- rd0_fence-0.1.0/src/rd0_fence/__main__.py +5 -0
- rd0_fence-0.1.0/src/rd0_fence/action.py +71 -0
- rd0_fence-0.1.0/src/rd0_fence/cli.py +112 -0
- rd0_fence-0.1.0/src/rd0_fence/diff.py +179 -0
- rd0_fence-0.1.0/src/rd0_fence/github.py +66 -0
- rd0_fence-0.1.0/src/rd0_fence/issue.py +118 -0
- rd0_fence-0.1.0/src/rd0_fence/py.typed +0 -0
- rd0_fence-0.1.0/src/rd0_fence/render.py +42 -0
- rd0_fence-0.1.0/src/rd0_fence/scope.py +326 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/PKG-INFO +41 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/SOURCES.txt +33 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/dependency_links.txt +1 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/entry_points.txt +2 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/requires.txt +4 -0
- rd0_fence-0.1.0/src/rd0_fence.egg-info/top_level.txt +1 -0
- rd0_fence-0.1.0/tests/fixtures/README.md +3 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4078493051/issue.json +6 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4078493051/meta.json +9 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4078493051/pr.diff +262 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4087484391/issue.json +6 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4087484391/meta.json +9 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4087484391/pr.diff +62 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4164885376/issue.json +6 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4164885376/meta.json +9 -0
- rd0_fence-0.1.0/tests/fixtures/aidev_4164885376/pr.diff +96 -0
- rd0_fence-0.1.0/tests/test_fence.py +263 -0
rd0_fence-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Harshul Jain
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
rd0_fence-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rd0-fence
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fence: flags the parts of an agent PR that go beyond what its issue asked for. The third tool in rd0, a toolkit for review debt.
|
|
5
|
+
Author: Harshul Jain
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://rd0-fence.netlify.app
|
|
8
|
+
Project-URL: Source, https://github.com/ReviewDebtZero/rd0-fence
|
|
9
|
+
Project-URL: Issues, https://github.com/ReviewDebtZero/rd0-fence/issues
|
|
10
|
+
Keywords: code-review,pull-requests,coding-agents,scope-creep,github-action,review-debt
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
19
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# rd0-fence
|
|
23
|
+
|
|
24
|
+
Fence flags the parts of a coding-agent pull request that go beyond what its linked issue asked for, with a
|
|
25
|
+
reason for each part. Pure Python standard library, CPU only, no LLM and no API key.
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install rd0-fence
|
|
29
|
+
fence check --issue issue.md --diff pr.diff # local diff vs issue (Markdown or JSON)
|
|
30
|
+
fence github owner/repo#123 # a GitHub PR vs the issue it closes
|
|
31
|
+
fence check --issue issue.json --diff pr.diff --format json --fail-over 0.3
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from rd0_fence import Issue, check, parse_diff
|
|
36
|
+
|
|
37
|
+
rep = check(Issue.from_text(title, body), parse_diff(diff_text))
|
|
38
|
+
print(rep.out_fraction, [(p.path, p.reason) for p in rep.flagged])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Part of rd0 (review debt, to zero): https://github.com/ReviewDebtZero/rd0-fence
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# rd0-fence
|
|
2
|
+
|
|
3
|
+
Fence flags the parts of a coding-agent pull request that go beyond what its linked issue asked for, with a
|
|
4
|
+
reason for each part. Pure Python standard library, CPU only, no LLM and no API key.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install rd0-fence
|
|
8
|
+
fence check --issue issue.md --diff pr.diff # local diff vs issue (Markdown or JSON)
|
|
9
|
+
fence github owner/repo#123 # a GitHub PR vs the issue it closes
|
|
10
|
+
fence check --issue issue.json --diff pr.diff --format json --fail-over 0.3
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from rd0_fence import Issue, check, parse_diff
|
|
15
|
+
|
|
16
|
+
rep = check(Issue.from_text(title, body), parse_diff(diff_text))
|
|
17
|
+
print(rep.out_fraction, [(p.path, p.reason) for p in rep.flagged])
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Part of rd0 (review debt, to zero): https://github.com/ReviewDebtZero/rd0-fence
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
diff --git a/utils/text.py b/utils/text.py
|
|
2
|
+
--- a/utils/text.py
|
|
3
|
+
+++ b/utils/text.py
|
|
4
|
+
@@ -1,6 +1,9 @@ import re
|
|
5
|
+
import re
|
|
6
|
+
+import unicodedata
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def slugify(value):
|
|
10
|
+
- value = re.sub(r"[^a-z0-9]+", "-", value.lower())
|
|
11
|
+
+ value = unicodedata.normalize("NFKD", value)
|
|
12
|
+
+ value = value.encode("ascii", "ignore").decode("ascii")
|
|
13
|
+
+ value = re.sub(r"[^a-z0-9]+", "-", value.lower())
|
|
14
|
+
return value.strip("-")
|
|
15
|
+
@@ -20,2 +23,2 @@ def truncate(value, n):
|
|
16
|
+
-def truncate(value,n):
|
|
17
|
+
- return value[:n]
|
|
18
|
+
+def truncate(value, n):
|
|
19
|
+
+ return value[: n]
|
|
20
|
+
diff --git a/tests/test_text.py b/tests/test_text.py
|
|
21
|
+
--- a/tests/test_text.py
|
|
22
|
+
+++ b/tests/test_text.py
|
|
23
|
+
@@ -1,1 +1,5 @@ from utils.text import slugify
|
|
24
|
+
from utils.text import slugify
|
|
25
|
+
+
|
|
26
|
+
+
|
|
27
|
+
+def test_slugify_non_ascii():
|
|
28
|
+
+ assert slugify("Café au lait") == "cafe-au-lait"
|
|
29
|
+
diff --git a/utils/dates.py b/utils/dates.py
|
|
30
|
+
--- a/utils/dates.py
|
|
31
|
+
+++ b/utils/dates.py
|
|
32
|
+
@@ -5,2 +5,4 @@ from datetime import datetime
|
|
33
|
+
-def parse(s):
|
|
34
|
+
- return datetime.strptime(s, "%Y-%m-%d")
|
|
35
|
+
+def parse(s, fmt="%Y-%m-%d"):
|
|
36
|
+
+ if not s:
|
|
37
|
+
+ return None
|
|
38
|
+
+ return datetime.strptime(s.strip(), fmt)
|
|
39
|
+
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
|
|
40
|
+
--- a/.github/workflows/ci.yml
|
|
41
|
+
+++ b/.github/workflows/ci.yml
|
|
42
|
+
@@ -10,1 +10,1 @@ jobs:
|
|
43
|
+
- python-version: ["3.9"]
|
|
44
|
+
+ python-version: ["3.9", "3.12"]
|
|
45
|
+
diff --git a/requirements.txt b/requirements.txt
|
|
46
|
+
--- a/requirements.txt
|
|
47
|
+
+++ b/requirements.txt
|
|
48
|
+
@@ -1,1 +1,2 @@
|
|
49
|
+
requests
|
|
50
|
+
+python-dateutil
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rd0-fence"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Fence: flags the parts of an agent PR that go beyond what its issue asked for. The third tool in rd0, a toolkit for review debt."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Harshul Jain" }]
|
|
14
|
+
keywords = ["code-review", "pull-requests", "coding-agents", "scope-creep", "github-action", "review-debt"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
19
|
+
]
|
|
20
|
+
dependencies = []
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
dev = ["pytest>=8", "ruff>=0.6"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://rd0-fence.netlify.app"
|
|
27
|
+
Source = "https://github.com/ReviewDebtZero/rd0-fence"
|
|
28
|
+
Issues = "https://github.com/ReviewDebtZero/rd0-fence/issues"
|
|
29
|
+
|
|
30
|
+
[project.scripts]
|
|
31
|
+
fence = "rd0_fence.cli:main"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
where = ["src"]
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.package-data]
|
|
37
|
+
rd0_fence = ["py.typed"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Fence: flags the parts of an agent PR that go beyond what its issue asked for."""
|
|
2
|
+
|
|
3
|
+
from .diff import FileChange, Hunk, parse_diff
|
|
4
|
+
from .issue import Issue
|
|
5
|
+
from .scope import Part, Report, check
|
|
6
|
+
|
|
7
|
+
__all__ = ["FileChange", "Hunk", "Issue", "Part", "Report", "check", "parse_diff"]
|
|
8
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""GitHub Action entry point: comment on a PR with the parts that go beyond its linked issue.
|
|
2
|
+
|
|
3
|
+
Uses only the GitHub REST API with the workflow's GITHUB_TOKEN. No LLM or paid API calls."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import urllib.error
|
|
11
|
+
|
|
12
|
+
from .github import GitHub, linked_issues
|
|
13
|
+
from .issue import Issue
|
|
14
|
+
from .render import MARKER, markdown
|
|
15
|
+
from .scope import check
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def upsert_comment(gh: GitHub, number: int, body: str | None) -> None:
|
|
19
|
+
"""Edit Fence's own marker comment (newest first); anyone can paste the marker, so skip comments we cannot edit."""
|
|
20
|
+
comments = gh.pages(f"/issues/{number}/comments", 300)
|
|
21
|
+
ours = [c for c in reversed(comments) if (c.get("body") or "").startswith(MARKER)]
|
|
22
|
+
clearing = not body
|
|
23
|
+
if clearing:
|
|
24
|
+
if not ours:
|
|
25
|
+
return
|
|
26
|
+
body = MARKER + "\n**Fence:** no out-of-scope parts now."
|
|
27
|
+
for c in ours:
|
|
28
|
+
try:
|
|
29
|
+
gh.call("PATCH", f"/issues/comments/{c['id']}", {"body": body})
|
|
30
|
+
return
|
|
31
|
+
except urllib.error.HTTPError as e:
|
|
32
|
+
if e.code not in (403, 404):
|
|
33
|
+
raise
|
|
34
|
+
if not clearing:
|
|
35
|
+
gh.call("POST", f"/issues/{number}/comments", {"body": body})
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def run(event: dict, gh: GitHub, issue_number: int | None = None, min_lines: int = 1) -> str | None:
|
|
39
|
+
pr = event["pull_request"]
|
|
40
|
+
refs = [(gh.repo, issue_number)] if issue_number else linked_issues(pr.get("body") or "", gh.repo)
|
|
41
|
+
# The PR author picks these references; reading other repositories' issues could leak private issue text.
|
|
42
|
+
refs = [(r, n) for r, n in refs if r.lower() == gh.repo.lower()]
|
|
43
|
+
if not refs:
|
|
44
|
+
print("rd0_fence: PR links no issue (use 'Fixes #N' in the description); skipping")
|
|
45
|
+
return None
|
|
46
|
+
issue = Issue.merge([gh.issue(n, repo=r) for r, n in refs])
|
|
47
|
+
rep = check(issue, gh.pr_files(pr["number"]))
|
|
48
|
+
shown = ", ".join(f"#{n}" if r == gh.repo else f"{r}#{n}" for r, n in refs)
|
|
49
|
+
if rep.out_lines < min_lines or not rep.flagged:
|
|
50
|
+
upsert_comment(gh, pr["number"], None)
|
|
51
|
+
return None
|
|
52
|
+
body = markdown(rep, f"issue {shown}")
|
|
53
|
+
upsert_comment(gh, pr["number"], body)
|
|
54
|
+
return body
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def main() -> int:
|
|
58
|
+
with open(os.environ["GITHUB_EVENT_PATH"]) as fh:
|
|
59
|
+
event = json.load(fh)
|
|
60
|
+
if "pull_request" not in event:
|
|
61
|
+
print("rd0_fence: not a pull_request event, skipping")
|
|
62
|
+
return 0
|
|
63
|
+
gh = GitHub(os.environ["INPUT_GITHUB_TOKEN"], os.environ["GITHUB_REPOSITORY"])
|
|
64
|
+
issue = os.environ.get("INPUT_ISSUE") or ""
|
|
65
|
+
body = run(event, gh, int(issue) if issue.strip() else None, int(os.environ.get("INPUT_MIN_LINES") or "1"))
|
|
66
|
+
print(body or "rd0_fence: nothing out of scope")
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
if __name__ == "__main__":
|
|
71
|
+
sys.exit(main())
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""`fence` command line: check a diff against the issue it should resolve."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .diff import files_from_patches, parse_diff
|
|
13
|
+
from .issue import Issue
|
|
14
|
+
from .render import markdown, text
|
|
15
|
+
from .scope import check
|
|
16
|
+
|
|
17
|
+
PR_REF = re.compile(r"^(?:https://github\.com/)?([\w.-]+/[\w.-]+)(?:#|/pull/)(\d+)$")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read(path: str) -> str:
|
|
21
|
+
if path == "-":
|
|
22
|
+
return sys.stdin.read()
|
|
23
|
+
with open(path, encoding="utf-8") as fh:
|
|
24
|
+
return fh.read()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _issue(a) -> Issue:
|
|
28
|
+
if a.issue:
|
|
29
|
+
raw = _read(a.issue)
|
|
30
|
+
if a.issue.endswith(".json"):
|
|
31
|
+
d = json.loads(raw)
|
|
32
|
+
return Issue.from_text(d.get("title", ""), d.get("body", ""), d.get("number"))
|
|
33
|
+
first, _, rest = raw.partition("\n")
|
|
34
|
+
return Issue.from_text(first.lstrip("# ").strip(), rest)
|
|
35
|
+
return Issue.from_text(a.title or "", a.body or "")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _emit(rep, a) -> int:
|
|
39
|
+
if a.format == "json":
|
|
40
|
+
print(json.dumps(rep.to_dict(), indent=2))
|
|
41
|
+
elif a.format == "markdown":
|
|
42
|
+
print(markdown(rep))
|
|
43
|
+
else:
|
|
44
|
+
print(text(rep))
|
|
45
|
+
if a.fail_over is not None and rep.out_fraction > a.fail_over:
|
|
46
|
+
return 1
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_check(a) -> int:
|
|
51
|
+
if not (a.issue or a.title or a.body):
|
|
52
|
+
sys.exit("fence: give the issue with --issue FILE or --title/--body")
|
|
53
|
+
raw = _read(a.diff)
|
|
54
|
+
if a.diff.endswith(".json"):
|
|
55
|
+
d = json.loads(raw)
|
|
56
|
+
files = files_from_patches(d["files"]) if "files" in d else parse_diff(d.get("diff", ""))
|
|
57
|
+
else:
|
|
58
|
+
files = parse_diff(raw)
|
|
59
|
+
return _emit(check(_issue(a), files), a)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def cmd_github(a) -> int:
|
|
63
|
+
from .github import GitHub, linked_issues
|
|
64
|
+
|
|
65
|
+
m = PR_REF.match(a.pr)
|
|
66
|
+
if not m:
|
|
67
|
+
sys.exit("fence: PR must look like owner/repo#123 or a pull URL")
|
|
68
|
+
repo, num = m.group(1), int(m.group(2))
|
|
69
|
+
gh = GitHub(os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN"), repo)
|
|
70
|
+
pr = gh.call("GET", f"/pulls/{num}")
|
|
71
|
+
refs = [(repo, a.issue_number)] if a.issue_number else linked_issues(pr.get("body") or "", repo)
|
|
72
|
+
if not refs:
|
|
73
|
+
sys.exit(f"fence: {a.pr} links no issue; pass --issue-number N")
|
|
74
|
+
issue = Issue.merge([gh.issue(n, repo=r) for r, n in refs])
|
|
75
|
+
return _emit(check(issue, gh.pr_files(num)), a)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main(argv=None) -> int:
|
|
79
|
+
ap = argparse.ArgumentParser(
|
|
80
|
+
prog="fence", description="Fence: flag the parts of a pull request that go beyond what its issue asked for."
|
|
81
|
+
)
|
|
82
|
+
ap.add_argument("--version", action="version", version=f"fence {__version__}")
|
|
83
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
84
|
+
|
|
85
|
+
def outputs(p):
|
|
86
|
+
p.add_argument("--format", choices=["text", "json", "markdown"], default="text")
|
|
87
|
+
p.add_argument(
|
|
88
|
+
"--fail-over", type=float, default=None, help="exit 1 if the out-of-scope fraction is above this"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
c = sub.add_parser("check", help="check a local diff against an issue")
|
|
92
|
+
c.add_argument(
|
|
93
|
+
"--diff", required=True, help="unified diff file, or JSON with files[{filename,patch}] ('-' = stdin)"
|
|
94
|
+
)
|
|
95
|
+
c.add_argument("--issue", help="issue as JSON {title, body} or Markdown (first line = title)")
|
|
96
|
+
c.add_argument("--title", help="issue title (instead of --issue)")
|
|
97
|
+
c.add_argument("--body", help="issue body (instead of --issue)")
|
|
98
|
+
outputs(c)
|
|
99
|
+
c.set_defaults(func=cmd_check)
|
|
100
|
+
|
|
101
|
+
g = sub.add_parser("github", help="check a GitHub PR against the issue it closes (GITHUB_TOKEN optional)")
|
|
102
|
+
g.add_argument("pr", help="owner/repo#123 or https://github.com/owner/repo/pull/123")
|
|
103
|
+
g.add_argument("--issue-number", type=int, help="issue to compare against (default: the ones the PR closes)")
|
|
104
|
+
outputs(g)
|
|
105
|
+
g.set_defaults(func=cmd_github)
|
|
106
|
+
|
|
107
|
+
a = ap.parse_args(argv)
|
|
108
|
+
return a.func(a)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == "__main__":
|
|
112
|
+
sys.exit(main())
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Parse a unified diff into files and hunks, and pull out the code names each hunk touches."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$")
|
|
10
|
+
IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]{2,}")
|
|
11
|
+
DEF = re.compile(
|
|
12
|
+
r"^\s*(?:export\s+)?(?:async\s+)?(?:def|class|function|func|fn|interface|type|struct|enum|trait|impl"
|
|
13
|
+
r"|(?:public|private|protected|static|final|abstract)\s[\w<>\[\], ]*?)\s*\(?\s*([A-Za-z_][\w]*)"
|
|
14
|
+
)
|
|
15
|
+
CODE_TOKEN = re.compile(r"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'|`[^`]*`|\S")
|
|
16
|
+
ASSIGN_DEF = re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_]\w*)\s*=")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Hunk:
|
|
21
|
+
old_start: int
|
|
22
|
+
new_start: int
|
|
23
|
+
header: str = ""
|
|
24
|
+
added: list[str] = field(default_factory=list)
|
|
25
|
+
removed: list[str] = field(default_factory=list)
|
|
26
|
+
context: list[str] = field(default_factory=list)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def changed(self) -> int:
|
|
30
|
+
return len(self.added) + len(self.removed)
|
|
31
|
+
|
|
32
|
+
def whitespace_only(self) -> bool:
|
|
33
|
+
"""True when the hunk only re-indents or re-wraps lines (same tokens before and after)."""
|
|
34
|
+
if not self.added and not self.removed:
|
|
35
|
+
return False
|
|
36
|
+
toks = lambda xs: [t for x in xs for t in CODE_TOKEN.findall(x)] # noqa: E731
|
|
37
|
+
return toks(self.added) == toks(self.removed)
|
|
38
|
+
|
|
39
|
+
def symbols(self) -> set[str]:
|
|
40
|
+
"""Names defined in or enclosing this hunk: the @@ header, plus def/class lines (changed or context)."""
|
|
41
|
+
out: set[str] = set()
|
|
42
|
+
for line in [self.header, *self.context, *self.added, *self.removed]:
|
|
43
|
+
m = DEF.match(line) or ASSIGN_DEF.match(line)
|
|
44
|
+
if m:
|
|
45
|
+
out.add(m.group(1))
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
def identifiers(self) -> set[str]:
|
|
49
|
+
out: set[str] = set()
|
|
50
|
+
for line in self.added + self.removed:
|
|
51
|
+
out.update(IDENT.findall(line))
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class FileChange:
|
|
57
|
+
path: str
|
|
58
|
+
status: str = "modified" # added | removed | modified | renamed
|
|
59
|
+
old_path: str | None = None
|
|
60
|
+
hunks: list[Hunk] = field(default_factory=list)
|
|
61
|
+
binary: bool = False
|
|
62
|
+
counted: int = 0 # line count reported by GitHub when it omits the patch
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def added(self) -> int:
|
|
66
|
+
return sum(len(h.added) for h in self.hunks)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def removed(self) -> int:
|
|
70
|
+
return sum(len(h.removed) for h in self.hunks)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def changed(self) -> int:
|
|
74
|
+
return (self.added + self.removed) or self.counted
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parse_diff(diff: str) -> list[FileChange]:
|
|
78
|
+
"""Parse `git diff` output, or plain `diff -u` output with only ---/+++ headers."""
|
|
79
|
+
files: list[FileChange] = []
|
|
80
|
+
cur: FileChange | None = None
|
|
81
|
+
h: Hunk | None = None
|
|
82
|
+
old_left = new_left = 0
|
|
83
|
+
git_header = False
|
|
84
|
+
lines = diff.splitlines()
|
|
85
|
+
for i, raw in enumerate(lines):
|
|
86
|
+
if raw.startswith(("diff --git ", "@@ ")):
|
|
87
|
+
old_left = new_left = 0
|
|
88
|
+
if h is not None and (old_left > 0 or new_left > 0):
|
|
89
|
+
if raw.startswith("+"):
|
|
90
|
+
h.added.append(raw[1:])
|
|
91
|
+
new_left -= 1
|
|
92
|
+
elif raw.startswith("-"):
|
|
93
|
+
h.removed.append(raw[1:])
|
|
94
|
+
old_left -= 1
|
|
95
|
+
elif not raw.startswith("\\"):
|
|
96
|
+
h.context.append(raw[1:])
|
|
97
|
+
old_left -= 1
|
|
98
|
+
new_left -= 1
|
|
99
|
+
continue
|
|
100
|
+
if raw.startswith("diff --git "):
|
|
101
|
+
parts = raw[len("diff --git ") :].split(" b/", 1)
|
|
102
|
+
path = parts[1].strip() if len(parts) == 2 else parts[0].strip()
|
|
103
|
+
old = parts[0][2:].strip() if parts[0].startswith("a/") else None
|
|
104
|
+
cur = FileChange(path=path, old_path=old if old and old != path else None)
|
|
105
|
+
if cur.old_path:
|
|
106
|
+
cur.status = "renamed"
|
|
107
|
+
files.append(cur)
|
|
108
|
+
h, git_header = None, True
|
|
109
|
+
elif raw.startswith("--- ") and i + 1 < len(lines) and lines[i + 1].startswith("+++ "):
|
|
110
|
+
if git_header:
|
|
111
|
+
continue
|
|
112
|
+
old = _header_path(raw[4:])
|
|
113
|
+
new = _header_path(lines[i + 1][4:])
|
|
114
|
+
if (old or "a/").startswith("a/") and (new or "b/").startswith("b/"):
|
|
115
|
+
old, new = old and old[2:], new and new[2:]
|
|
116
|
+
cur = FileChange(path=new or old or "", old_path=old if old and new and old != new else None)
|
|
117
|
+
if new is None:
|
|
118
|
+
cur.status = "removed"
|
|
119
|
+
elif old is None:
|
|
120
|
+
cur.status = "added"
|
|
121
|
+
elif cur.old_path:
|
|
122
|
+
cur.status = "renamed"
|
|
123
|
+
files.append(cur)
|
|
124
|
+
h = None
|
|
125
|
+
elif cur is None or raw.startswith("+++ "):
|
|
126
|
+
continue
|
|
127
|
+
elif raw.startswith("new file mode"):
|
|
128
|
+
cur.status = "added"
|
|
129
|
+
elif raw.startswith("deleted file mode"):
|
|
130
|
+
cur.status = "removed"
|
|
131
|
+
elif raw.startswith(("Binary files", "GIT binary patch")):
|
|
132
|
+
cur.binary = True
|
|
133
|
+
elif raw.startswith("@@"):
|
|
134
|
+
m = HUNK.match(raw)
|
|
135
|
+
if m:
|
|
136
|
+
h = Hunk(int(m.group(1)), int(m.group(3)), (m.group(5) or "").strip())
|
|
137
|
+
old_left = int(m.group(2)) if m.group(2) is not None else 1
|
|
138
|
+
new_left = int(m.group(4)) if m.group(4) is not None else 1
|
|
139
|
+
cur.hunks.append(h)
|
|
140
|
+
elif h is not None and raw.startswith("+"):
|
|
141
|
+
h.added.append(raw[1:])
|
|
142
|
+
elif h is not None and raw.startswith("-"):
|
|
143
|
+
h.removed.append(raw[1:])
|
|
144
|
+
elif h is not None and raw.startswith(" "):
|
|
145
|
+
h.context.append(raw[1:])
|
|
146
|
+
return files
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _header_path(v: str) -> str | None:
|
|
150
|
+
p = v.split("\t", 1)[0].strip()
|
|
151
|
+
if p == "/dev/null":
|
|
152
|
+
return None
|
|
153
|
+
return p
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def files_from_patches(items) -> list[FileChange]:
|
|
157
|
+
"""Build FileChanges from GitHub API style dicts: {filename, status, patch, previous_filename}."""
|
|
158
|
+
out = []
|
|
159
|
+
for it in items:
|
|
160
|
+
name = it.get("filename") or it.get("path")
|
|
161
|
+
patch = it.get("patch") or ""
|
|
162
|
+
fc = parse_diff(f"diff --git a/{name} b/{name}\n{patch}\n")[0]
|
|
163
|
+
st = it.get("status") or "modified"
|
|
164
|
+
fc.status = {"deleted": "removed"}.get(st, st)
|
|
165
|
+
fc.old_path = it.get("previous_filename")
|
|
166
|
+
fc.binary = not patch and (it.get("changes") or 0) == 0
|
|
167
|
+
if not patch:
|
|
168
|
+
fc.counted = (it.get("additions") or 0) + (it.get("deletions") or 0) or (it.get("changes") or 0)
|
|
169
|
+
out.append(fc)
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def python_symbols(source: str) -> set[str]:
|
|
174
|
+
"""Function and class names defined in a Python source file (used when the full file is available)."""
|
|
175
|
+
try:
|
|
176
|
+
tree = ast.parse(source)
|
|
177
|
+
except (SyntaxError, ValueError):
|
|
178
|
+
return set()
|
|
179
|
+
return {n.name for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Small GitHub REST client (stdlib only) and helpers to load an issue and a PR's files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import urllib.request
|
|
9
|
+
|
|
10
|
+
from .diff import FileChange, files_from_patches
|
|
11
|
+
from .issue import Issue
|
|
12
|
+
|
|
13
|
+
API = os.environ.get("GITHUB_API_URL", "https://api.github.com")
|
|
14
|
+
CLOSING = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+(?:([\w.-]+/[\w.-]+))?#(\d+)", re.IGNORECASE)
|
|
15
|
+
ISSUE_URL = re.compile(r"github\.com/([\w.-]+/[\w.-]+)/issues/(\d+)")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GitHub:
|
|
19
|
+
def __init__(self, token: str | None, repo: str):
|
|
20
|
+
self.token, self.repo = token, repo
|
|
21
|
+
|
|
22
|
+
def call(self, method: str, path: str, body: dict | None = None, repo: str | None = None):
|
|
23
|
+
req = urllib.request.Request(
|
|
24
|
+
f"{API}/repos/{repo or self.repo}{path}",
|
|
25
|
+
method=method,
|
|
26
|
+
data=json.dumps(body).encode() if body is not None else None,
|
|
27
|
+
)
|
|
28
|
+
if self.token:
|
|
29
|
+
req.add_header("Authorization", f"Bearer {self.token}")
|
|
30
|
+
req.add_header("Accept", "application/vnd.github+json")
|
|
31
|
+
req.add_header("X-GitHub-Api-Version", "2022-11-28")
|
|
32
|
+
with urllib.request.urlopen(req, timeout=30) as r:
|
|
33
|
+
return json.loads(r.read() or b"null")
|
|
34
|
+
|
|
35
|
+
def pages(self, path: str, limit: int):
|
|
36
|
+
out, page = [], 1
|
|
37
|
+
while len(out) < limit:
|
|
38
|
+
sep = "&" if "?" in path else "?"
|
|
39
|
+
batch = self.call("GET", f"{path}{sep}per_page=100&page={page}")
|
|
40
|
+
if not batch:
|
|
41
|
+
break
|
|
42
|
+
out.extend(batch)
|
|
43
|
+
page += 1
|
|
44
|
+
return out[:limit]
|
|
45
|
+
|
|
46
|
+
def pr_files(self, number: int) -> list[FileChange]:
|
|
47
|
+
return files_from_patches(self.pages(f"/pulls/{number}/files", 3000))
|
|
48
|
+
|
|
49
|
+
def issue(self, number: int, repo: str | None = None) -> Issue:
|
|
50
|
+
d = self.call("GET", f"/issues/{number}", repo=repo)
|
|
51
|
+
return Issue.from_text(d.get("title") or "", d.get("body") or "", d.get("number"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def linked_issues(body: str, repo: str) -> list[tuple[str, int]]:
|
|
55
|
+
"""Issues a PR body closes (`Fixes #12`, `Closes owner/repo#3`, or a full issue URL)."""
|
|
56
|
+
out = []
|
|
57
|
+
for r, n in CLOSING.findall(body or ""):
|
|
58
|
+
out.append((r or repo, int(n)))
|
|
59
|
+
for r, n in ISSUE_URL.findall(body or ""):
|
|
60
|
+
out.append((r, int(n)))
|
|
61
|
+
seen, uniq = set(), []
|
|
62
|
+
for x in out:
|
|
63
|
+
if x not in seen:
|
|
64
|
+
seen.add(x)
|
|
65
|
+
uniq.append(x)
|
|
66
|
+
return uniq
|