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
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The process's GitHub session (#767) sends its own REST requests through gidgethu

- `gidgethub` and its one new dependency, `uritemplate`, are pinned in `pyproject.toml` and `uv.lock`. `PyJWT[crypto]` was already locked. `cachetools`, locked before only through `py-key-value-aio`, is declared for the ETag store.
- gidgethub is async only. Every synchronous caller goes through the session's portal, and no caller creates an event loop of its own.
- `GitHubClient.get_pr_diff` and SSH key registration (the authentication key and the signing key) are session requests. Neither builds its own client or reads a `Location` header. A redirect to github.com, which the old diff code followed with the token copied onto it, is now refused.
- Every `GitHubClient` call (a pull request, its files and diff, a file at a commit, a merge base, an organization's repositories and an issue comment) and SSH key registration (the authentication key and the signing key) are session requests. None builds its own client or reads a `Location` header. A redirect to github.com, which the old diff code followed with the token copied onto it, is now refused.
- Tests fake the session through the repository's existing httpx2 client seam, the one `stub_web` uses. The `github_api` fixture puts `GitHubApiFake` (`tests/support/fakes/github.py`), a fake GitHub API on `httpx2.MockTransport`, in place of the transport the factory built, and its contract suite holds it to GitHub's recorded answers. The factory, its timeouts, the redirect handling and the origin hook stay real, and every request is still vetted at the egress level the factory was asked for. The plan gave the session constructor a `transport=` argument instead. That was dropped: it needed a path around egress vetting in product code, used only by tests.
- `run_gh` no longer pages. The project's own listings (a pull request's files, reviews, timeline and check runs, the reconcile listings, and the roadmap store's REST listings) read through `paginate()`; the roadmap store keeps gh for its board commands. `devops gh api --paginate` is the only `--paginate` left, and `run_gh` hands gh that flag with `--slurp`, `--jq` and `--template` as given, since gh follows `Link` itself. gh walks the pages in one process, so the whole walk runs under one timeout (`DEFAULT_GH_API_PAGINATE_TIMEOUT_SECONDS`), and a rate-limited walk is retried from page 1. `run_gh_async` and its `aiolimiter` limiter are gone.
- A failed gh command is classified in the same module, `classify_gh_failure`, from gh's exit status (4 is "requires authentication") and the gh-output table in `config/constants.py`, matched against what gh wrote to stderr, never GitHub's answer on stdout. The table is the one place gh's failures are classified by gh's text; `_is_branch_unprotected_error`, `create_repository_issue`, `_report_create_failure` and `extract_retry_after` still match gh's text of their own. Its errors carry the status gh names as an int, like an HTTP failure's. `graphql()` waits for the first item that moves a GraphQL call off gh.

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ dependencies = [
"typer==0.27.2",
"rich==15.0.0",
"pydantic==2.13.5",
"PyGithub==2.10.0",
"gitpython==3.2.1",
"cryptography==50.0.2",
"httpx2==2.13.1",
Expand Down
5 changes: 4 additions & 1 deletion src/devops_cli/ai/analyze/symbols.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
@dataclass(frozen=True)
class BaseRevision:
"""The revision a reviewed diff starts from: the files the diff changed, and `read`, which
returns a file's text there by its path at that revision, or None when it cannot.
returns a file's text there by its path at that revision, or None when there is none.

A revision read from GitHub raises the error of the GitHub session when GitHub cannot answer,
so a failed read is never taken for a file that is not there.

`read_head` does the same where the diff ends, when that is a commit rather than the files
on disk: a branch that is not checked out, or one whose checkout has uncommitted edits the
Expand Down
14 changes: 6 additions & 8 deletions src/devops_cli/ai/review/path_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,13 @@


def _read_config_content(base_revision: BaseRevision | None, repo_root: Path | None) -> str | None:
"""Read .devops/review.toml content from the base revision or workspace root."""
"""Read .devops/review.toml content from the base revision or workspace root.

A base revision whose read fails raises its error: a configuration that could not be read
is not an absent one, and the default would classify the files differently.
"""
if base_revision is not None and base_revision.read is not None:
try:
content = base_revision.read(CONST_REVIEW_CONFIG_FILE)
if content:
return content
except Exception as exc:
logger.debug("Failed reading %s from base revision: %s", CONST_REVIEW_CONFIG_FILE, exc)
return None
return base_revision.read(CONST_REVIEW_CONFIG_FILE) or None

if repo_root is not None:
cfg_file = repo_root / CONST_REVIEW_CONFIG_FILE
Expand Down
51 changes: 23 additions & 28 deletions src/devops_cli/ai/review/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@

if TYPE_CHECKING:
from devops_cli.ai.review.pipeline import ReviewPipelineOrchestrator
from devops_cli.github.client import GitHubClient, PullRequest, PullRequestFile

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -783,7 +784,7 @@ def _prepare_pr_content(
number: int,
repo_arg: str | None = None,
**kwargs: Any,
) -> tuple[list[str], str, Any, str, BaseRevision | None]:
) -> tuple[list[str], str, PullRequest, str, BaseRevision | None]:
"""Fetch PR details, diff blocks, and title for PR review target.

With `head_dir`, the PR head's changed files are written under it, and the base revision
Expand Down Expand Up @@ -813,56 +814,54 @@ def _prepare_pr_content(
head_dir: Path | None = kwargs.get("head_dir")
base_revision: BaseRevision | None = None
if head_dir is not None:
pr_files = list(pull.get_files())
pr_files = gh.get_pull_files(repo, number)
_materialize_pr_head(gh, repo, pull, head_dir, pr_files)
base_revision = _pr_base_revision(gh, repo, pull, pr_files)
path_classes = load_path_classes(base_revision=base_revision)
pages = [redact_text(p) for p in diff_blocks(diff, path_classes=path_classes)]
return pages, title, pull, repo, base_revision


def _pr_changed_file(pr_file: Any) -> ChangedFile:
def _pr_changed_file(pr_file: PullRequestFile) -> ChangedFile:
"""A pull request file as a change: its status, head path and, if renamed, its old path."""
return ChangedFile(
change_type=CONST_GITHUB_PR_FILE_CHANGE_TYPES.get(str(pr_file.status), "unknown"),
change_type=CONST_GITHUB_PR_FILE_CHANGE_TYPES.get(pr_file.status, "unknown"),
path=pr_file.filename,
old_path=getattr(pr_file, "previous_filename", None) or None,
old_path=pr_file.previous_filename or None,
)


def _pr_base_revision(gh: Any, repo: str, pull: Any, pr_files: Sequence[Any]) -> BaseRevision:
def _pr_base_revision(
gh: GitHubClient, repo: str, pull: PullRequest, pr_files: Sequence[PullRequestFile]
) -> BaseRevision:
"""The PR's changed files, and a reader for their text at its merge base in the base repo.

`pull.base.sha` is the base branch's tip, which can be ahead of the merge base: read there,
a PR branched earlier would list symbols added on the base since as removed. When the merge
base cannot be read, nothing is read, and a modified file's delta stays unknown.
a PR branched earlier would list symbols added on the base since as removed. When GitHub has
no merge base for the two commits, nothing is read, and a modified file's delta stays
unknown; a comparison that fails to be read raises.
"""
base_obj = getattr(pull, "base", None)
base_repo = getattr(getattr(base_obj, "repo", None), "full_name", None) or repo
base_sha = getattr(base_obj, "sha", None)
head_sha = getattr(getattr(pull, "head", None), "sha", None)
merge_base = gh.get_merge_base(base_repo, base_sha, head_sha) if base_sha and head_sha else None
base_repo = pull.base.repository or repo
merge_base = gh.get_merge_base(base_repo, pull.base.sha, pull.head.sha)
if merge_base is None:
logger.debug("No merge base for %s...%s in %s", base_sha, head_sha, base_repo)
logger.debug("No merge base for %s...%s in %s", pull.base.sha, pull.head.sha, base_repo)

def read(path: str) -> str | None:
return gh.get_file_at(base_repo, path, merge_base) if merge_base else None

return BaseRevision(changes=tuple(_pr_changed_file(f) for f in pr_files), read=read)


def _materialize_pr_head(gh: Any, repo: str, pull: Any, dest: Path, pr_files: Sequence[Any]) -> int:
def _materialize_pr_head(
gh: GitHubClient, repo: str, pull: PullRequest, dest: Path, pr_files: Sequence[PullRequestFile]
) -> int:
"""Write PR head's version of changed files, and base conventions, under `dest`."""
from devops_cli.ai.review.review_environment import _TARGET_CONVENTIONS_CANDIDATES
from devops_cli.config.constants import CONST_REVIEW_CONVENTIONS_FILE

head_obj = getattr(pull, "head", None)
base_obj = getattr(pull, "base", None)
head_repo = getattr(getattr(head_obj, "repo", None), "full_name", None) or repo
base_repo = getattr(getattr(base_obj, "repo", None), "full_name", None) or repo
base_ref = getattr(base_obj, "sha", None) or getattr(base_obj, "ref", None) or "main"
head_sha = getattr(head_obj, "sha", None) or "HEAD"
changed = [f.filename for f in pr_files if getattr(f, "status", "") != "removed"]
head_repo = pull.head.repository or repo
base_repo = pull.base.repository or repo
changed = [f.filename for f in pr_files if f.status != "removed"]
convention_files = set(_TARGET_CONVENTIONS_CANDIDATES) | {CONST_REVIEW_CONVENTIONS_FILE}
root = dest.resolve()
written = 0
Expand All @@ -871,11 +870,7 @@ def _materialize_pr_head(gh: Any, repo: str, pull: Any, dest: Path, pr_files: Se
target = (root / rel).resolve()
if not target.is_relative_to(root):
continue
text = gh.get_file_at(base_repo, rel, base_ref) if gh else None
if text is None and (gh is None or not base_repo):
local_conv = Path.cwd() / rel
if local_conv.exists() and local_conv.is_file():
text = local_conv.read_text(encoding="utf-8")
text = gh.get_file_at(base_repo, rel, pull.base.sha)
if text is not None:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
Expand All @@ -887,7 +882,7 @@ def _materialize_pr_head(gh: Any, repo: str, pull: Any, dest: Path, pr_files: Se
target = (root / rel).resolve()
if not target.is_relative_to(root):
continue
text = gh.get_file_at(head_repo, rel, head_sha)
text = gh.get_file_at(head_repo, rel, pull.head.sha)
if text is None:
continue
target.parent.mkdir(parents=True, exist_ok=True)
Expand Down
15 changes: 8 additions & 7 deletions src/devops_cli/commands/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,11 +519,12 @@ def analyze_pr( # noqa: C901
print_error(MESSAGES.analyze.github_origin_failed, prefix=False)
raise typer.Exit(1)

gh_client = session.client
pull = gh_client.get_pull(repo_name, pr_number)
with exit_on_error(GitHubOperationError):
pull = session.client.get_pull(repo_name, pr_number)
pull_files = session.client.get_pull_files(repo_name, pr_number)
file_metas: list[FileAnalysisMeta] = []

for f_file in pull.get_files():
for f_file in pull_files:
path = f_file.filename
if not path or ".." in path or path.startswith(("/", "\\")):
continue
Expand All @@ -533,7 +534,7 @@ def analyze_pr( # noqa: C901
file_path = safe_resolve_subpath(repo, path)
except Exception:
continue
status = str(f_file.status)
status = f_file.status
if file_path.exists() and status != "removed":
try:
content = file_path.read_text(encoding="utf-8", errors="replace")
Expand All @@ -556,9 +557,9 @@ def analyze_pr( # noqa: C901
file_metas.append(
FileAnalysisMeta(
path=path,
size_bytes=int(f_file.changes),
line_count=int(f_file.additions),
char_count=int(f_file.changes),
size_bytes=f_file.changes,
line_count=f_file.additions,
char_count=f_file.changes,
language=detect_language(path),
primary_purpose=f"PR file {Path(path).name}",
key_symbols=[],
Expand Down
28 changes: 5 additions & 23 deletions src/devops_cli/commands/gh.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
load_branch_protection_policies,
sync_branch_protection,
)
from devops_cli.github.client import GhCliClient, GitHubClient
from devops_cli.github.client import GhCliClient
from devops_cli.github.issues import (
audit_issues_triage,
create_repository_issue,
Expand Down Expand Up @@ -86,7 +86,6 @@
list_repository_secrets,
sync_repository_secrets,
)
from devops_cli.github.session import get_github_session
from devops_cli.lang import HELP, MESSAGES
from devops_cli.output import (
print,
Expand Down Expand Up @@ -143,19 +142,8 @@ def _resolve_repo(repo: str | None = None) -> str:
return target or "unknown/repo"


def _get_github_client() -> GitHubClient | None:
"""The session's PyGithub client; None when PyGithub cannot be set up."""
session = get_github_session()
try:
return session.client
except Exception as exc:
logger.warning("Failed to initialize GitHubClient: %s", exc)
return None


def _get_repo_labels(repo: str | None = None) -> list[dict[str, Any]]:
"""Retrieve repository labels via gh CLI or GitHubClient."""
target_repo = _resolve_repo(repo)
"""Retrieve repository labels via the gh CLI; none when gh cannot list them."""
cmd = ["label", "list", "--json", "name,color,description"]
cmd += ["--limit", str(DEFAULT_GH_LABEL_LIST_LIMIT)]
if repo:
Expand All @@ -166,13 +154,6 @@ def _get_repo_labels(repo: str | None = None) -> list[dict[str, Any]]:
return json.loads(res.stdout) # type: ignore[no-any-return]
except json.JSONDecodeError as exc:
logger.debug("Failed to decode JSON from gh label list: %s", exc)

client = _get_github_client()
if client and target_repo != "unknown/repo":
try:
return client.get_labels(target_repo)
except Exception as exc:
logger.warning("Failed to fetch labels via GitHubClient for %s: %s", target_repo, exc)
return []


Expand Down Expand Up @@ -246,9 +227,10 @@ def sync_labels(
print_error(f"Failed to load labels schema: {exc}")
raise typer.Exit(1) from exc

client = _get_github_client() or GhCliClient(target_repo)
try:
result = sync_repository_labels(client, target_repo, desired, dry_run=dry_run)
result = sync_repository_labels(
GhCliClient(target_repo), target_repo, desired, dry_run=dry_run
)
except GitHubOperationError as exc:
print_error(f"Label sync failed for {target_repo}: {exc}", safe=True)
raise typer.Exit(1) from exc
Expand Down
15 changes: 8 additions & 7 deletions src/devops_cli/commands/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def _github_https_url(full_name: str) -> str:


def _require_client() -> GitHubClient:
"""The session's PyGithub client, exiting with the unauthenticated error when gh has no token."""
"""The session's client, exiting with the unauthenticated error when gh has no token."""
from devops_cli.github.session import get_github_session

with exit_on_error(GitHubOperationError):
Expand Down Expand Up @@ -180,12 +180,13 @@ def clone_org(
org_dir = _resolve_safe_org_dir(root, org_name)
client = _require_client()

repos = client.get_org_repos(
org_name,
include_private=private,
include_forks=forks,
include_archived=False,
)
with exit_on_error(GitHubOperationError):
repos = client.get_org_repos(
org_name,
include_private=private,
include_forks=forks,
include_archived=False,
)
org_dir.mkdir(parents=True, exist_ok=True)

print_info(
Expand Down
Loading
Loading