pr-preflight 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.
@@ -0,0 +1,3 @@
1
+ """Check a repository's contribution rules before you open a pull request."""
2
+
3
+ __version__ = "0.1.0"
pr_preflight/checks.py ADDED
@@ -0,0 +1,298 @@
1
+ """Check a contribution (commits, diff, PR text) against extracted rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+
8
+ from .context import Context
9
+ from .rules import Rule
10
+
11
+ PASS, FAIL, WARN, MANUAL = "pass", "fail", "warn", "manual"
12
+
13
+ CONVENTIONAL = re.compile(
14
+ r"^(feat|fix|docs|style|refactor|perf|test|tests|build|ci|chore|revert|deps)"
15
+ r"(\([\w ./,-]+\))?!?: \S"
16
+ )
17
+ TEST_PATH = re.compile(
18
+ r"(^|/)(tests?|testing|spec|__tests__|test_?data)(/|$)|(^|/)test_[^/]+$"
19
+ r"|_test\.\w+$|\.test\.\w+$|\.spec\.\w+$|Tests?\.\w+$",
20
+ re.I,
21
+ )
22
+ CHANGELOG_PATH = re.compile(
23
+ r"change[-_]?log|(^|/)news(/|$)|newsfragments|\.changeset/|(^|/)changes?(/|\.)"
24
+ r"|release[-_]?notes|whatsnew|unreleased",
25
+ re.I,
26
+ )
27
+ DOCS_PATH = re.compile(r"(^|/)docs?/|\.(md|rst|mdx|qmd|adoc|txt)$", re.I)
28
+ # Tool names inside identifiers (llm-toolcall-check, openai_client) don't count.
29
+ AI_MENTION = re.compile(
30
+ r"(?<![\w/.-])(?:ai|llms?|copilot|claude|chatgpt|gpt-?\d[\w.]*|gemini|cursor|"
31
+ r"codex|language models?)(?![\w/.-])|\bassisted-by:",
32
+ re.I,
33
+ )
34
+ SIGNOFF = re.compile(r"^Signed-off-by: .+ <.+@.+>\s*$", re.M)
35
+ HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$", re.M)
36
+
37
+
38
+ @dataclass
39
+ class Result:
40
+ rule: Rule
41
+ status: str
42
+ detail: str
43
+
44
+ @property
45
+ def blocking(self) -> bool:
46
+ return self.status == FAIL and self.rule.level == "required"
47
+
48
+ def to_dict(self) -> dict:
49
+ return {**self.rule.to_dict(), "status": self.status, "detail": self.detail}
50
+
51
+
52
+ def _soft(rule: Rule) -> str:
53
+ return FAIL if rule.level == "required" else WARN
54
+
55
+
56
+ def _code_files(files: list[str]) -> list[str]:
57
+ return [f for f in files if not DOCS_PATH.search(f)]
58
+
59
+
60
+ def check_ai_banned(rule: Rule, ctx: Context) -> Result:
61
+ if ctx.used_ai is True or ctx.agent:
62
+ return Result(rule, _soft(rule), "You used AI for this change.")
63
+ if ctx.used_ai is False:
64
+ return Result(rule, PASS, "You said no AI was used.")
65
+ return Result(rule, MANUAL, "Pass --ai or --no-ai to check.")
66
+
67
+
68
+ def check_ai_disclosure(rule: Rule, ctx: Context) -> Result:
69
+ if ctx.used_ai is False:
70
+ return Result(rule, PASS, "You said no AI was used.")
71
+ if ctx.body is None:
72
+ return Result(
73
+ rule, MANUAL, "Say in the PR description which AI tools you used."
74
+ )
75
+ if AI_MENTION.search(ctx.body):
76
+ return Result(rule, PASS, "The PR description mentions AI use.")
77
+ return Result(rule, _soft(rule), "The PR description doesn't mention AI use.")
78
+
79
+
80
+ def check_agent(rule: Rule, ctx: Context) -> Result:
81
+ if ctx.agent:
82
+ return Result(
83
+ rule,
84
+ FAIL if rule.level == "required" else WARN,
85
+ "You are running as an AI agent: stop and let the human do what this "
86
+ "rule reserves for them.",
87
+ )
88
+ return Result(rule, MANUAL, "Applies if an AI agent is preparing this PR.")
89
+
90
+
91
+ def check_issue_first(rule: Rule, ctx: Context) -> Result:
92
+ if ctx.issues:
93
+ refs = ", ".join(f"#{i.number}" for i in ctx.issues if i.found)
94
+ if refs:
95
+ return Result(rule, PASS, f"The PR links {refs}.")
96
+ return Result(rule, _soft(rule), "The linked issue was not found.")
97
+ if ctx.body is None:
98
+ return Result(
99
+ rule, MANUAL, "Link the issue in the PR description (Fixes #123)."
100
+ )
101
+ return Result(rule, _soft(rule), "The PR description doesn't link an issue.")
102
+
103
+
104
+ def check_issue_approval(rule: Rule, ctx: Context) -> Result:
105
+ issues = [i for i in ctx.issues if i.found and not i.is_pr]
106
+ if not issues:
107
+ if ctx.body is None:
108
+ return Result(rule, MANUAL, "Make sure the linked issue is approved.")
109
+ return Result(rule, _soft(rule), "No linked issue to check.")
110
+ label = rule.params.get("label")
111
+ for issue in issues:
112
+ if label and label.lower() in (x.lower() for x in issue.labels):
113
+ return Result(rule, PASS, f"#{issue.number} is labeled '{label}'.")
114
+ if ctx.user and ctx.user in issue.assignees:
115
+ return Result(rule, PASS, f"#{issue.number} is assigned to you.")
116
+ summary = "; ".join(
117
+ f"#{i.number} labels: {', '.join(i.labels) or 'none'}" for i in issues
118
+ )
119
+ if label:
120
+ return Result(rule, _soft(rule), f"Needs label '{label}' ({summary}).")
121
+ return Result(rule, MANUAL, f"Check for maintainer approval ({summary}).")
122
+
123
+
124
+ def check_cla(rule: Rule, ctx: Context) -> Result:
125
+ if ctx.merged_prs:
126
+ return Result(
127
+ rule,
128
+ PASS,
129
+ f"You have {ctx.merged_prs} merged PRs here, so it's likely signed.",
130
+ )
131
+ return Result(rule, MANUAL, "Sign it before or right after opening the PR.")
132
+
133
+
134
+ def check_dco(rule: Rule, ctx: Context) -> Result:
135
+ if not ctx.commits:
136
+ return Result(rule, MANUAL, "Use `git commit -s`.")
137
+ missing = [c.sha[:7] for c in ctx.commits if not SIGNOFF.search(c.body)]
138
+ if missing:
139
+ return Result(
140
+ rule,
141
+ _soft(rule),
142
+ f"{len(missing)} commit(s) without Signed-off-by: {', '.join(missing)}. "
143
+ "Fix: git rebase --signoff <base>.",
144
+ )
145
+ return Result(rule, PASS, f"All {len(ctx.commits)} commits are signed off.")
146
+
147
+
148
+ def check_commit_format(rule: Rule, ctx: Context) -> Result:
149
+ if rule.params.get("style") != "conventional commits" or not ctx.commits:
150
+ return Result(
151
+ rule, MANUAL, "Compare your commit messages with the quoted rule."
152
+ )
153
+ bad = [c.subject for c in ctx.commits if not CONVENTIONAL.match(c.subject)]
154
+ if bad:
155
+ return Result(rule, _soft(rule), f"Not Conventional Commits: {bad[0]!r}.")
156
+ return Result(rule, PASS, "All commit subjects follow Conventional Commits.")
157
+
158
+
159
+ def check_pr_title(rule: Rule, ctx: Context) -> Result:
160
+ if rule.params.get("style") != "conventional commits" or not ctx.title:
161
+ return Result(rule, MANUAL, "Compare your PR title with the quoted rule.")
162
+ if CONVENTIONAL.match(ctx.title):
163
+ return Result(rule, PASS, "The title follows Conventional Commits.")
164
+ return Result(
165
+ rule, _soft(rule), f"The title is not Conventional Commits: {ctx.title!r}."
166
+ )
167
+
168
+
169
+ def check_tests(rule: Rule, ctx: Context) -> Result:
170
+ if not ctx.files:
171
+ return Result(rule, MANUAL, "Add tests for your change.")
172
+ if not _code_files(ctx.files):
173
+ return Result(rule, PASS, "Docs-only change.")
174
+ tests = [f for f in ctx.files if TEST_PATH.search(f)]
175
+ if tests:
176
+ return Result(rule, PASS, f"Touches {len(tests)} test file(s).")
177
+ return Result(rule, _soft(rule), "No test files changed.")
178
+
179
+
180
+ def check_changelog(rule: Rule, ctx: Context) -> Result:
181
+ if not ctx.files:
182
+ return Result(rule, MANUAL, "Add a changelog entry or news fragment.")
183
+ hits = [f for f in ctx.files if CHANGELOG_PATH.search(f)]
184
+ if hits:
185
+ return Result(rule, PASS, f"Changes {hits[0]}.")
186
+ return Result(rule, WARN, "No changelog or news file changed.")
187
+
188
+
189
+ def check_docs(rule: Rule, ctx: Context) -> Result:
190
+ if not ctx.files:
191
+ return Result(rule, MANUAL, "Update docs if behavior changes.")
192
+ if any(DOCS_PATH.search(f) for f in ctx.files):
193
+ return Result(rule, PASS, "Touches documentation.")
194
+ return Result(rule, MANUAL, "No docs changed; update them if behavior changes.")
195
+
196
+
197
+ def check_template(rule: Rule, ctx: Context, template: str | None) -> Result:
198
+ if ctx.body is None:
199
+ return Result(rule, MANUAL, f"Use the PR template ({rule.file}).")
200
+ if not template:
201
+ return Result(rule, MANUAL, "Fill in the PR template.")
202
+ wanted = [h.strip().lower() for h in HEADING.findall(template)]
203
+ body = ctx.body.lower()
204
+ missing = [h for h in wanted if h not in body]
205
+ if missing:
206
+ return Result(
207
+ rule,
208
+ _soft(rule),
209
+ f"Missing template sections: {', '.join(missing[:4])}"
210
+ + ("…" if len(missing) > 4 else ""),
211
+ )
212
+ return Result(rule, PASS, "All template sections are present.")
213
+
214
+
215
+ def check_run(rule: Rule, ctx: Context) -> Result:
216
+ command = rule.params.get("command") or _guess_command(ctx)
217
+ hint = f"Run `{command}`." if command else "Run the checks named in the quote."
218
+ return Result(rule, MANUAL, hint)
219
+
220
+
221
+ def _guess_command(ctx: Context) -> str | None:
222
+ if ctx.root is None:
223
+ return None
224
+ if (ctx.root / ".pre-commit-config.yaml").exists():
225
+ return "pre-commit run --all-files"
226
+ makefile = ctx.root / "Makefile"
227
+ if makefile.exists():
228
+ targets = re.findall(r"^(check|lint|test)\s*:", makefile.read_text(), re.M)
229
+ if targets:
230
+ return " && ".join(f"make {t}" for t in dict.fromkeys(targets))
231
+ return None
232
+
233
+
234
+ def check_focused(rule: Rule, ctx: Context) -> Result:
235
+ if not ctx.files:
236
+ return Result(rule, MANUAL, "Keep the PR to one logical change.")
237
+ areas = {f.split("/")[0] for f in _code_files(ctx.files)}
238
+ detail = f"{len(ctx.files)} files across {len(areas)} top-level area(s)."
239
+ if len(ctx.files) > 30 or len(areas) > 4:
240
+ return Result(rule, WARN, detail + " Consider splitting.")
241
+ return Result(rule, PASS, detail)
242
+
243
+
244
+ def check_branch(rule: Rule, ctx: Context) -> Result:
245
+ branch = rule.params.get("branch")
246
+ if not branch or not ctx.base:
247
+ return Result(rule, MANUAL, "Check which branch the PR should target.")
248
+ if ctx.base.split("/")[-1] == branch:
249
+ return Result(rule, PASS, f"Based on {branch}.")
250
+ return Result(
251
+ rule, _soft(rule), f"Should target '{branch}', you are on '{ctx.base}'."
252
+ )
253
+
254
+
255
+ def check_hygiene(rule: Rule, ctx: Context) -> Result:
256
+ merges = [c.sha[:7] for c in ctx.commits if c.parents > 1]
257
+ if merges:
258
+ return Result(rule, _soft(rule), f"Merge commit(s): {', '.join(merges)}.")
259
+ if not ctx.commits:
260
+ return Result(rule, MANUAL, "Avoid merge commits; rebase instead.")
261
+ return Result(rule, PASS, f"{len(ctx.commits)} commit(s), no merge commits.")
262
+
263
+
264
+ def check_manual(rule: Rule, ctx: Context) -> Result:
265
+ return Result(rule, MANUAL, "Confirm this yourself.")
266
+
267
+
268
+ CHECKS = {
269
+ "ai_banned": check_ai_banned,
270
+ "ai_disclosure": check_ai_disclosure,
271
+ "ai_accountability": check_manual,
272
+ "agent_restrictions": check_agent,
273
+ "issue_first": check_issue_first,
274
+ "issue_approval": check_issue_approval,
275
+ "cla": check_cla,
276
+ "dco": check_dco,
277
+ "commit_format": check_commit_format,
278
+ "pr_title_format": check_pr_title,
279
+ "tests_required": check_tests,
280
+ "changelog_entry": check_changelog,
281
+ "docs_update": check_docs,
282
+ "run_checks": check_run,
283
+ "focused_pr": check_focused,
284
+ "target_branch": check_branch,
285
+ "commit_hygiene": check_hygiene,
286
+ }
287
+
288
+
289
+ def run_checks(
290
+ rules: list[Rule], ctx: Context, template: str | None = None
291
+ ) -> list[Result]:
292
+ results = []
293
+ for rule in rules:
294
+ if rule.id == "pr_template":
295
+ results.append(check_template(rule, ctx, template))
296
+ else:
297
+ results.append(CHECKS.get(rule.id, check_manual)(rule, ctx))
298
+ return results
pr_preflight/cli.py ADDED
@@ -0,0 +1,180 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__
10
+ from .checks import run_checks
11
+ from .context import (
12
+ Context,
13
+ _base_ref,
14
+ current_user,
15
+ fetch_issue,
16
+ git,
17
+ issue_refs,
18
+ local_changes,
19
+ merged_pr_count,
20
+ remote_slug,
21
+ )
22
+ from .report import render_results, render_rules, to_json, use_color
23
+ from .rules import LEVELS, RULE_IDS, Rule, extract
24
+ from .sources import Document, GitHub, local_documents
25
+
26
+
27
+ def load_rules(docs: list[Document], use_llm: bool) -> list[Rule]:
28
+ rules = {r.id: r for r in extract(docs)}
29
+ if use_llm:
30
+ from .llm import extract_llm
31
+
32
+ for rule in extract_llm(docs):
33
+ current = rules.get(rule.id)
34
+ if current is None or LEVELS.index(rule.level) > LEVELS.index(
35
+ current.level
36
+ ):
37
+ if current and not rule.params:
38
+ rule.params = current.params
39
+ rules[rule.id] = rule
40
+ return [rules[i] for i in RULE_IDS if i in rules]
41
+
42
+
43
+ def _template(docs: list[Document]) -> str | None:
44
+ templates = [d for d in docs if d.kind == "pr_template"]
45
+ templates.sort(key=lambda d: "/pull_request_template/" in d.path.lower())
46
+ return templates[0].text if templates else None
47
+
48
+
49
+ def cmd_rules(args: argparse.Namespace) -> int:
50
+ if args.repo and "/" in args.repo and not Path(args.repo).exists():
51
+ repo, docs = args.repo, GitHub().documents(args.repo, args.ref)
52
+ else:
53
+ root = Path(args.repo or ".").resolve()
54
+ repo, docs = root.name, local_documents(root)
55
+ rules = load_rules(docs, args.llm)
56
+ if args.json:
57
+ print(to_json(repo, rules, documents=[d.path for d in docs]))
58
+ else:
59
+ print(render_rules(repo, rules, use_color()), end="")
60
+ return 0
61
+
62
+
63
+ def cmd_check(args: argparse.Namespace) -> int:
64
+ gh = GitHub()
65
+ root = Path(git(Path(args.path), "rev-parse", "--show-toplevel").strip())
66
+ found = remote_slug(root)
67
+ remote, repo = found if found else (None, None)
68
+ repo = args.repo or repo
69
+ if not repo:
70
+ print(
71
+ "Could not find a GitHub remote; pass --repo owner/name.", file=sys.stderr
72
+ )
73
+ return 2
74
+
75
+ default = gh.default_branch(repo)
76
+ docs = gh.documents(repo, default) or local_documents(root)
77
+ rules = load_rules(docs, args.llm)
78
+
79
+ ctx = Context(repo=repo, root=root, agent=args.agent, used_ai=args.ai)
80
+ pr = gh.get(f"repos/{repo}/pulls/{args.pr}") if args.pr else None
81
+ if pr:
82
+ ctx.title, ctx.body = pr["title"], pr.get("body") or ""
83
+ ctx.base = pr["base"]["ref"]
84
+ base_ref = _base_ref(root, remote, args.base or ctx.base or default)
85
+ ctx.base = args.base or ctx.base or default
86
+ if base_ref:
87
+ ctx.commits, ctx.files = local_changes(root, base_ref)
88
+ if args.title:
89
+ ctx.title = args.title
90
+ if args.body_file:
91
+ ctx.body = Path(args.body_file).read_text()
92
+ if ctx.title is None and ctx.commits:
93
+ ctx.title = ctx.commits[-1].subject
94
+ if ctx.body is not None:
95
+ ctx.issues = [fetch_issue(gh, r, n) for r, n in issue_refs(ctx.body, repo)[:5]]
96
+ if any(r.id in ("cla", "issue_approval") for r in rules):
97
+ ctx.user = current_user(gh)
98
+ if ctx.user and any(r.id == "cla" for r in rules):
99
+ ctx.merged_prs = merged_pr_count(gh, repo, ctx.user)
100
+
101
+ results = run_checks(rules, ctx, _template(docs))
102
+ branch = git(root, "rev-parse", "--abbrev-ref", "HEAD").strip()
103
+ if args.json:
104
+ print(to_json(repo, results, branch=branch, base=ctx.base))
105
+ else:
106
+ header = (
107
+ f"pr-preflight · {repo} · {branch} → {ctx.base} "
108
+ f"({len(ctx.commits)} commits, {len(ctx.files)} files)"
109
+ )
110
+ print(render_results(header, results, use_color()), end="")
111
+ return 1 if any(r.blocking for r in results) else 0
112
+
113
+
114
+ def build_parser() -> argparse.ArgumentParser:
115
+ ap = argparse.ArgumentParser(
116
+ prog="pr-preflight",
117
+ description="Check a repository's contribution rules before you open a PR.",
118
+ )
119
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
120
+ sub = ap.add_subparsers(dest="command")
121
+
122
+ rules = sub.add_parser("rules", help="List the contribution rules of a repository.")
123
+ rules.add_argument(
124
+ "repo", nargs="?", help="owner/name or a local path (default: .)"
125
+ )
126
+ rules.add_argument("--ref", help="Branch, tag or commit to read (GitHub only).")
127
+
128
+ check = sub.add_parser("check", help="Check your branch against the rules.")
129
+ check.add_argument("--path", default=".", help="Local clone (default: .)")
130
+ check.add_argument(
131
+ "--repo", help="Target repository owner/name (default: upstream remote)"
132
+ )
133
+ check.add_argument(
134
+ "--base", help="Target branch (default: the repository's default)"
135
+ )
136
+ check.add_argument(
137
+ "--pr", type=int, help="Check an existing pull request's title and body."
138
+ )
139
+ check.add_argument("--title", help="Planned PR title.")
140
+ check.add_argument("--body-file", help="File with the planned PR description.")
141
+ ai = check.add_mutually_exclusive_group()
142
+ ai.add_argument(
143
+ "--ai",
144
+ dest="ai",
145
+ action="store_true",
146
+ default=None,
147
+ help="AI tools helped with this change.",
148
+ )
149
+ ai.add_argument(
150
+ "--no-ai", dest="ai", action="store_false", help="No AI tools were used."
151
+ )
152
+ check.add_argument(
153
+ "--agent", action="store_true", help="An AI agent is running this check."
154
+ )
155
+
156
+ for p in (rules, check):
157
+ p.add_argument(
158
+ "--llm",
159
+ action="store_true",
160
+ help="Also extract rules with an LLM (PR_PREFLIGHT_LLM_URL, "
161
+ "PR_PREFLIGHT_LLM_MODEL, PR_PREFLIGHT_LLM_API_KEY).",
162
+ )
163
+ p.add_argument("--json", action="store_true", help="Print JSON.")
164
+ return ap
165
+
166
+
167
+ def main(argv: list[str] | None = None) -> int:
168
+ argv = sys.argv[1:] if argv is None else argv
169
+ if not argv or argv[0] not in ("rules", "check", "-h", "--help", "--version"):
170
+ argv = ["check", *argv]
171
+ args = build_parser().parse_args(argv)
172
+ try:
173
+ return {"rules": cmd_rules, "check": cmd_check}[args.command](args)
174
+ except (RuntimeError, LookupError, OSError) as exc:
175
+ print(f"pr-preflight: {exc}", file=sys.stderr)
176
+ return 2
177
+
178
+
179
+ if __name__ == "__main__":
180
+ raise SystemExit(main())
@@ -0,0 +1,152 @@
1
+ """Collect facts about the contribution being prepared: commits, diff, PR text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+
10
+ from .sources import GitHub
11
+
12
+ GITHUB_REMOTE = re.compile(r"github\.com[:/](?P<slug>[\w.-]+/[\w.-]+?)(?:\.git)?/?$")
13
+ ISSUE_REF = re.compile(
14
+ r"(?:(?P<owner>[\w.-]+)/(?P<name>[\w.-]+))?#(?P<num>\d+)\b"
15
+ r"|https://github\.com/(?P<o2>[\w.-]+)/(?P<n2>[\w.-]+)/issues/(?P<num2>\d+)"
16
+ )
17
+
18
+
19
+ @dataclass
20
+ class Commit:
21
+ sha: str
22
+ subject: str
23
+ body: str
24
+ parents: int
25
+
26
+ @property
27
+ def message(self) -> str:
28
+ return f"{self.subject}\n\n{self.body}".strip()
29
+
30
+
31
+ @dataclass
32
+ class Issue:
33
+ repo: str
34
+ number: int
35
+ title: str = ""
36
+ state: str = ""
37
+ labels: list[str] = field(default_factory=list)
38
+ assignees: list[str] = field(default_factory=list)
39
+ is_pr: bool = False
40
+ found: bool = True
41
+
42
+
43
+ @dataclass
44
+ class Context:
45
+ repo: str
46
+ base: str | None = None
47
+ commits: list[Commit] = field(default_factory=list)
48
+ files: list[str] = field(default_factory=list)
49
+ title: str | None = None
50
+ body: str | None = None
51
+ issues: list[Issue] = field(default_factory=list)
52
+ user: str | None = None
53
+ agent: bool = False
54
+ used_ai: bool | None = None
55
+ merged_prs: int | None = None
56
+ root: Path | None = None
57
+ notes: list[str] = field(default_factory=list)
58
+
59
+
60
+ def git(root: Path, *args: str) -> str:
61
+ out = subprocess.run(
62
+ ["git", "-C", str(root), *args], capture_output=True, text=True
63
+ )
64
+ if out.returncode != 0:
65
+ raise RuntimeError(out.stderr.strip() or f"git {' '.join(args)} failed")
66
+ return out.stdout
67
+
68
+
69
+ def remote_slug(root: Path) -> tuple[str, str] | None:
70
+ """Return (remote, owner/repo), preferring `upstream` over `origin`."""
71
+ try:
72
+ remotes = git(root, "remote").split()
73
+ except RuntimeError:
74
+ return None
75
+ for name in ("upstream", "origin", *remotes):
76
+ if name not in remotes:
77
+ continue
78
+ url = git(root, "remote", "get-url", name).strip()
79
+ match = GITHUB_REMOTE.search(url)
80
+ if match:
81
+ return name, match.group("slug")
82
+ return None
83
+
84
+
85
+ def _base_ref(root: Path, remote: str | None, branch: str) -> str | None:
86
+ candidates = [f"{remote}/{branch}"] if remote else []
87
+ candidates += [f"origin/{branch}", branch]
88
+ for ref in candidates:
89
+ try:
90
+ git(root, "rev-parse", "--verify", "--quiet", ref)
91
+ except RuntimeError:
92
+ continue
93
+ return ref
94
+ return None
95
+
96
+
97
+ def local_changes(root: Path, base_ref: str) -> tuple[list[Commit], list[str]]:
98
+ merge_base = git(root, "merge-base", base_ref, "HEAD").strip()
99
+ raw = git(root, "log", "--format=%H%x1f%P%x1f%s%x1f%b%x1e", f"{merge_base}..HEAD")
100
+ commits = []
101
+ for entry in raw.split("\x1e"):
102
+ entry = entry.strip("\n")
103
+ if not entry:
104
+ continue
105
+ sha, parents, subject, body = (entry.split("\x1f") + ["", "", ""])[:4]
106
+ commits.append(Commit(sha[:12], subject, body.strip(), len(parents.split())))
107
+ files = [
108
+ f for f in git(root, "diff", "--name-only", f"{merge_base}...HEAD").split() if f
109
+ ]
110
+ return commits, files
111
+
112
+
113
+ def issue_refs(text: str, repo: str) -> list[tuple[str, int]]:
114
+ refs = []
115
+ for m in ISSUE_REF.finditer(text or ""):
116
+ if m.group("num"):
117
+ owner, name = m.group("owner"), m.group("name")
118
+ slug = f"{owner}/{name}" if owner else repo
119
+ refs.append((slug, int(m.group("num"))))
120
+ else:
121
+ refs.append((f"{m.group('o2')}/{m.group('n2')}", int(m.group("num2"))))
122
+ return list(dict.fromkeys(refs))
123
+
124
+
125
+ def fetch_issue(gh: GitHub, repo: str, number: int) -> Issue:
126
+ data = gh.get(f"repos/{repo}/issues/{number}")
127
+ if not data:
128
+ return Issue(repo, number, found=False)
129
+ return Issue(
130
+ repo,
131
+ number,
132
+ data.get("title", ""),
133
+ data.get("state", ""),
134
+ [label["name"] for label in data.get("labels", [])],
135
+ [a["login"] for a in data.get("assignees", [])],
136
+ "pull_request" in data,
137
+ )
138
+
139
+
140
+ def merged_pr_count(gh: GitHub, repo: str, user: str) -> int | None:
141
+ from urllib.parse import quote
142
+
143
+ query = quote(f"repo:{repo} is:pr is:merged author:{user}")
144
+ data = gh.get(f"search/issues?q={query}&per_page=1")
145
+ return None if data is None else data.get("total_count")
146
+
147
+
148
+ def current_user(gh: GitHub) -> str | None:
149
+ if not gh.token:
150
+ return None
151
+ data = gh.get("user")
152
+ return data.get("login") if data else None