Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions .github/workflows/pr-review.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ on:
description: "low | medium | high | xhigh | max"
type: string
default: medium
exclude:
description: "Extra glob patterns to leave out of the review (comma or newline separated), on top of lock files and minified output"
type: string
default: ""
tools_ref:
description: "Fallback ref of fraymio/.github to load the review script from (only used if job.workflow_sha is unavailable)"
type: string
Expand Down Expand Up @@ -54,21 +58,22 @@ jobs:
with:
repository: ${{ job.workflow_repository || 'fraymio/.github' }}
ref: ${{ job.workflow_sha || inputs.tools_ref }}
# Cone mode always includes root files, so pyproject.toml and uv.lock come along.
sparse-checkout: pr_review
persist-credentials: false

- uses: actions/setup-python@v7
# setup-uv publishes no floating major tag, so pin the release commit.
- uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
with:
python-version: "3.14"

- run: pip install -r pr_review/requirements.txt

- name: Review PR
run: python pr_review/review.py
run: uv run --frozen --no-dev pr_review/review.py
env:
GITHUB_TOKEN: ${{ github.token }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
OPENAI_MODEL: ${{ inputs.model }}
REASONING_EFFORT: ${{ inputs.reasoning_effort }}
EXTRA_EXCLUDE: ${{ inputs.exclude }}
REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,28 @@ jobs:
# with:
# model: gpt-6-astra
# reasoning_effort: medium # low | medium | high | xhigh | max
# exclude: "frontend/src/api_service/**, *.ipynb" # on top of lock files + minified output
```

**Secret:** `OPENAI_API_KEY` as an org secret (Org settings → Secrets → Actions), shared with the opted-in repos. No other token is needed: each repo's built-in `GITHUB_TOKEN` posts the review.

**Local dry run:**

```sh
pip install -r pr_review/requirements.txt
GITHUB_TOKEN=... OPENAI_API_KEY=... REPOSITORY=fraymio/tessera PR_NUMBER=123 DRY_RUN=true \
python pr_review/review.py
uv run pr_review/review.py
```

## Stale PR report

`stale_prs/pr_tracker.py` writes a CSV of PRs that have been open past the review SLA.

## Development

```sh
uv sync # creates .venv with runtime + dev deps from uv.lock
uv run pytest # unit tests
uv run pytest --int # + integration tests
```

Dependencies are in `pyproject.toml` (dev tools in the `dev` group) and pinned in `uv.lock`; add one with `uv add <pkg>` or `uv add --dev <pkg>`. Tests live in `tests/`; `pytest.ini` puts `pr_review/` on the import path. Integration tests (`@pytest.mark.int`, e.g. the one that runs the real `git` binary) are skipped by default; run them with `pytest --int`. End to end tests (`@pytest.mark.e2e`) need `pytest --e2e`.
1 change: 0 additions & 1 deletion pr_review/requirements.txt

This file was deleted.

123 changes: 123 additions & 0 deletions pr_review/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,39 @@
PR_NUMBER pull request number (required)
OPENAI_MODEL model ID (default: gpt-6-astra)
REASONING_EFFORT low | medium | high | xhigh | max (default: medium)
EXTRA_EXCLUDE extra glob patterns to drop from the diff, comma or newline separated
DRY_RUN if "true", print the review instead of posting it
"""

import codecs
import os
import re
from fnmatch import fnmatchcase

import requests

MAX_DIFF_CHARS = 400_000

# Files that are generated or carry no reviewable logic. Patterns without a "/"
# match the file name anywhere in the tree; patterns with one match the full path.
DEFAULT_EXCLUDE = [
# Lock files
"*.lock", # yarn, poetry, uv, pdm, pixi, Cargo, Gemfile, composer, flake, Podfile
Comment thread
jamie-sgro marked this conversation as resolved.
Resolved
"terraform.lock.hcl", # Terraform lock file
"package-lock.json",
"npm-shrinkwrap.json",
"pnpm-lock.yaml",
"bun.lockb",
"packages.lock.json",
"conda-lock.yml",
"*.conda-lock.yml",
"go.sum",
# Minified / build output
"*.min.js",
"*.min.css",
"*.map",
]

GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
REPOSITORY = os.environ.get("REPOSITORY")
Expand Down Expand Up @@ -61,14 +85,113 @@ def get_diff(pr_url: str) -> str:
return resp.text


def exclude_patterns() -> list[str]:
extra = os.environ.get("EXTRA_EXCLUDE") or ""
return DEFAULT_EXCLUDE + [p.strip() for p in re.split(r"[,\n]", extra) if p.strip()]


def is_excluded(path: str, patterns: list[str]) -> bool:
name = path.rsplit("/", 1)[-1]
return any(fnmatchcase(path if "/" in p else name, p) for p in patterns)


_QUOTED = re.compile(r'"((?:[^"\\]|\\.)*)"')


def _read_quoted(s: str, i: int) -> tuple[str, int]:
"""Decode a Git C-style quoted string starting at s[i] == '"'.

Returns (text, index just past the closing quote).
"""
m = _QUOTED.match(s, i)
if not m:
raise ValueError(f"unterminated quoted path: {s!r}")
# Git escapes \\ \" and control chars, and writes non-ASCII bytes as \ooo
# octal. unicode_escape decodes those same escapes but yields each byte as
# a Latin-1 char, so round-trip through Latin-1 to get the raw bytes back.
latin1 = codecs.decode(m.group(1).encode("utf-8"), "unicode_escape")
return latin1.encode("latin-1").decode("utf-8", errors="replace"), m.end()


def _unquote_path(raw: str) -> str:
"""Decode one path field from a ---/+++/rename/copy header line."""
if raw.startswith('"'):
return _read_quoted(raw, 0)[0]
# Git appends a TAB after unquoted names that contain a space.
return raw.rstrip("\t")


def _strip_prefix(path: str) -> str:
return path[2:] if path[:2] in ("a/", "b/") else path


def section_path(section: str) -> str | None:
"""Return the file path a per-file diff section applies to.

Prefers the unambiguous header lines (+++, ---, rename to, copy to) over
the 'diff --git' line, whose two paths can't always be split apart.
"""
first, *lines = section.split("\n")
new_path = old_path = moved_to = None
for line in lines:
if line.startswith(("@@", "Binary files ", "GIT binary patch")):
break # end of the header block; content follows
if line.startswith("+++ "):
raw = line[4:]
if raw != "/dev/null":
new_path = _strip_prefix(_unquote_path(raw))
elif line.startswith("--- "):
raw = line[4:]
if raw != "/dev/null":
old_path = _strip_prefix(_unquote_path(raw))
elif line.startswith(("rename to ", "copy to ")):
moved_to = _unquote_path(line.split(" to ", 1)[1])
if new_path or old_path or moved_to:
return new_path or moved_to or old_path
# Renames/copies have explicit headers above. Otherwise Git names the same
# path twice, so split equal-length fields even when the names contain spaces.
rest = first[len("diff --git ") :]
half = len(rest) // 2
if rest[half : half + 1] != " ":
return None
old_path = _strip_prefix(_unquote_path(rest[:half]))
new_path = _strip_prefix(_unquote_path(rest[half + 1 :]))
return new_path if old_path == new_path else None


def filter_diff(diff: str, patterns: list[str] | None = None) -> tuple[str, list[str]]:
"""Drop per-file sections whose path matches an exclude pattern."""
if patterns is None:
patterns = exclude_patterns()
kept, skipped = [], []
# Each file's section starts with a "diff --git" line.
for section in re.split(r"(?m)^(?=diff --git )", diff):
path = section_path(section) if section.startswith("diff --git ") else None
if path is not None and is_excluded(path, patterns):
skipped.append(path)
else:
kept.append(section)
return "".join(kept), skipped


def ask_model(pr: dict, diff: str) -> str:
diff, skipped = filter_diff(diff)
if skipped:
print(f"Excluded from review: {', '.join(skipped)}")
truncated = len(diff) > MAX_DIFF_CHARS
if truncated:
diff = diff[:MAX_DIFF_CHARS]
skipped_note = (
"Files changed but omitted from the diff (generated/lock files, do not "
f"review): {', '.join(skipped)}\n\n"
if skipped
else ""
)
user_input = (
f"Repository: {REPOSITORY}\n"
f"Title: {pr['title']}\n\n"
f"Description:\n{pr.get('body') or '(none)'}\n\n"
f"{skipped_note}"
f"Diff{' (truncated)' if truncated else ''}:\n```diff\n{diff}\n```"
)
resp = requests.post(
Expand Down
17 changes: 17 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[project]
name = "fraymio-github"
version = "0.1.0"
description = "Org-wide GitHub tooling for fraymio (AI PR review, stale PR report)"
requires-python = ">=3.12"
dependencies = [
"requests>=2.31",
]

[dependency-groups]
dev = [
"pytest>=8",
]

[tool.uv]
# Scripts, not an installable package.
package = false
13 changes: 13 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[pytest]
markers =
int: integration tests skipped by default, (only evaluate with 'pytest --int')
e2e: end to end tests skipped by default, (only evaluate with 'pytest --e2e')

testpaths =
tests

# Lets tests `import review` without packaging pr_review/.
pythonpath =
pr_review

addopts = -ra --strict-markers --strict-config
71 changes: 71 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import os
import shutil
import subprocess
from pathlib import Path

import pytest


def pytest_addoption(parser):
parser.addoption(
"--e2e",
action="store_true",
help="also run end to end tests (marked @pytest.mark.e2e)",
)
parser.addoption(
"--int",
action="store_true",
help="also run integration tests (marked @pytest.mark.int)",
)


def pytest_runtest_setup(item):
if "e2e" in item.keywords and not item.config.getoption("--e2e"):
pytest.skip("need --e2e option to run this test")
if "int" in item.keywords and not item.config.getoption("--int"):
pytest.skip("need --int option to run this test")


@pytest.fixture(autouse=True)
def _clean_env(monkeypatch):
"""Keep the developer's shell env from leaking into review.py config."""
for name in ("EXTRA_EXCLUDE", "OPENAI_MODEL", "REASONING_EFFORT", "DRY_RUN"):
monkeypatch.delenv(name, raising=False)


@pytest.fixture
def lock_patterns() -> list[str]:
return ["*.lock", "package-lock.json", "go.sum"]


class GitRepo:
def __init__(self, path: Path):
self.path = path

def git(self, *args: str) -> str:
return subprocess.run(
["git", "-C", str(self.path), "-c", "core.quotePath=true", *args],
check=True,
capture_output=True,
text=True,
).stdout

def write(self, rel: str, data: bytes = b"a\n") -> None:
p = self.path / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)


@pytest.fixture
def git_repo(tmp_path, monkeypatch) -> GitRepo:
"""An empty git repo, isolated from the user's global/system git config
(e.g. diff.noprefix or diff.mnemonicPrefix would change the headers)."""
if not shutil.which("git"):
pytest.skip("git not installed")
monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
repo = GitRepo(tmp_path)
repo.git("init", "-q")
repo.git("config", "user.email", "test@example.com")
repo.git("config", "user.name", "test")
return repo
Loading