diff --git a/README.md b/README.md index 3c7a6ca9..8bdf1de5 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,22 @@ except ProoflineError as error: print(error.detail) ``` +## Finding a repository by name + +Review requests and coverage uploads take the repository's stable Proofline ID. When you only have the provider's `owner/name`, such as `GITHUB_REPOSITORY` in a GitHub Actions job, `find_repository` resolves it with one `list_repositories` read. + +```python +import os +from uuid import UUID + +with ProoflineClient() as client: + organization_id = UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]) + repository = client.find_repository(organization_id, os.environ["GITHUB_REPOSITORY"]) + requested = client.request_review(organization_id, repository.id, 12) +``` + +The match ignores ASCII case, as GitHub does, and a repository spelled exactly as you wrote it wins over one that differs only in case. A name that is not exactly `owner/name` raises `ValueError` before a request. A name the token cannot see raises `ProoflineError` with type `urn:proofline:sdk:repository-not-found`; a repository-restricted token sees only its allowlist, and a renamed repository is listed under its new name. More than one match raises `urn:proofline:sdk:ambiguous-repository`. Both carry the name you passed in `repository_name`. Store `repository.id` rather than the name, since the name can change on a rename. Use `await` with `AsyncProoflineClient`. + ## Holding a wait to a commit `request_review` names a pull request, and its response names no commit: the review belongs to the head the pull request has when the request arrives. To accept a result only for the commit you hold, pass that commit to `wait_for_review`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 5704485b..85925d19 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -19,6 +19,7 @@ PatchReviewResponse, PatchTriggerSource, RepositoryGuidance, + RepositoryName, RepositoryNames, RerunResponse, ReviewPage, @@ -61,6 +62,7 @@ "ProoflineClient", "ProoflineError", "RepositoryGuidance", + "RepositoryName", "RepositoryNames", "RerunResponse", "ReviewFilters", diff --git a/proofline/client.py b/proofline/client.py index dd5106f6..139c86c1 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,7 +5,7 @@ import math from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator -from string import hexdigits +from string import ascii_lowercase, ascii_uppercase, hexdigits from time import monotonic, sleep from types import TracebackType from typing import Any, Self, TypedDict, TypeVar, Unpack, cast @@ -58,6 +58,7 @@ from ._generated.models.patch_review_request import PatchReviewRequest from ._generated.models.patch_review_response import PatchReviewResponse from ._generated.models.repository_guidance import RepositoryGuidance +from ._generated.models.repository_name import RepositoryName from ._generated.models.repository_names import RepositoryNames from ._generated.models.rerun_response import RerunResponse from ._generated.models.review_page import ReviewPage @@ -207,6 +208,47 @@ def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: return cursor +_ASCII_LOWER = str.maketrans(ascii_uppercase, ascii_lowercase) + + +def _repository_full_name(full_name: str) -> str: + # A provider name is exactly owner/name; anything else cannot name one repository. + if not isinstance(full_name, str) or full_name.count("/") != 1: + raise ValueError("The repository name must be owner/name, such as octo-org/api.") + owner, name = full_name.split("/") + if not owner or not name or owner != owner.strip() or name != name.strip(): + raise ValueError("The repository name must be owner/name, such as octo-org/api.") + return full_name + + +def _matching_repository(names: RepositoryNames, full_name: str) -> RepositoryName: + # GitHub compares owner/name without regard to ASCII case, so the lookup does too; + # a name spelled exactly as the caller wrote it still wins over a case-only variant. + exact = [item for item in names.repositories if item.full_name == full_name] + folded = full_name.translate(_ASCII_LOWER) + similar = [ + item for item in names.repositories if item.full_name.translate(_ASCII_LOWER) == folded + ] + matches = exact or similar + if len(matches) == 1: + return matches[0] + if not matches: + raise ProoflineError( + 0, + "urn:proofline:sdk:repository-not-found", + f"No repository named {full_name} is visible to this token. A repository-restricted " + "token sees only its allowlist, and a renamed repository is listed under its new name.", + repository_name=full_name, + ) + raise ProoflineError( + 0, + "urn:proofline:sdk:ambiguous-repository", + f"More than one repository matches {full_name}; pass the exact owner/name spelling " + "or use the repository ID.", + repository_name=full_name, + ) + + class ProoflineClient(Operations): """Synchronous typed HTTP operations. @@ -439,6 +481,16 @@ def get_review_guidance(self, organization_id: UUID, repository_id: UUID) -> Rep def list_repositories(self, organization_id: UUID) -> RepositoryNames: return self._call(list_repositories.sync_detailed, RepositoryNames, organization_id) + def find_repository(self, organization_id: UUID, full_name: str) -> RepositoryName: + """Resolve a provider owner/name, such as GITHUB_REPOSITORY, to its repository. + + The match ignores ASCII case, as GitHub does, and an exact spelling wins. + Keep the returned id: the name can change on a rename. A malformed name + raises ValueError before any request. + """ + full_name = _repository_full_name(full_name) + return _matching_repository(self.list_repositories(organization_id), full_name) + def request_review( self, organization_id: UUID, @@ -830,6 +882,16 @@ async def list_repositories(self, organization_id: UUID) -> RepositoryNames: list_repositories.asyncio_detailed, RepositoryNames, organization_id ) + async def find_repository(self, organization_id: UUID, full_name: str) -> RepositoryName: + """Resolve a provider owner/name, such as GITHUB_REPOSITORY, to its repository. + + The match ignores ASCII case, as GitHub does, and an exact spelling wins. + Keep the returned id: the name can change on a rename. A malformed name + raises ValueError before any request. + """ + full_name = _repository_full_name(full_name) + return _matching_repository(await self.list_repositories(organization_id), full_name) + async def request_review( self, organization_id: UUID, diff --git a/scripts/contracts.py b/scripts/contracts.py index e8e4e73a..a86d5b62 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -31,7 +31,14 @@ def main() -> None: from proofline import AsyncProoflineClient, ProoflineClient for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "find_repository", + "iter_export_pages", + "iter_reviews", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_http.py b/tests/test_http.py index 7b922c34..5506e814 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -42,6 +42,7 @@ ProoflineClient, ProoflineError, RepositoryGuidance, + RepositoryName, RepositoryNames, RerunResponse, ReviewPage, @@ -1734,6 +1735,143 @@ def respond(request: Request, index: int) -> Reply: assert raised.value.type == "urn:proofline:sdk:pagination-limit" +SIBLING = UUID("00000000-0000-4000-8000-000000000007") +OTHER_OWNER = UUID("00000000-0000-4000-8000-000000000008") + + +def repository_names(*entries: tuple[UUID, str]) -> dict[str, Any]: + return { + "repositories": [ + {"id": str(identifier), "full_name": full_name} for identifier, full_name in entries + ] + } + + +@MODES +async def test_find_repository_resolves_owner_name_to_its_stable_id(mode: str) -> None: + listed = repository_names( + (SIBLING, "octo-org/api-docs"), + (REPOSITORY, "octo-org/api"), + (OTHER_OWNER, "other-org/api"), + ) + + def respond(request: Request, index: int) -> Reply: + assert request.method == "GET" + assert urlsplit(request.path).path == f"/api/v1/organizations/{ORG}/repository-names" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + return Reply(body=listed) + + with Server(respond) as server: + async with session(mode, server.url) as client: + found = await call(client, "find_repository", ORG, "octo-org/api") + assert isinstance(found, RepositoryName) + assert (found.id, found.full_name) == (REPOSITORY, "octo-org/api") + # GitHub owner/name comparisons ignore case, e.g. GITHUB_REPOSITORY spellings. + found = await call(client, "find_repository", ORG, "Octo-Org/API") + assert (found.id, found.full_name) == (REPOSITORY, "octo-org/api") + found = await call(client, "find_repository", ORG, "other-org/api") + assert found.id == OTHER_OWNER + assert len(server.requests) == 3 + + +@MODES +async def test_find_repository_prefers_the_exact_spelling_and_refuses_ambiguity( + mode: str, +) -> None: + listed = repository_names((SIBLING, "acme/Tool"), (REPOSITORY, "acme/tool")) + with Server(lambda request, index: Reply(body=listed)) as server: + async with session(mode, server.url) as client: + assert (await call(client, "find_repository", ORG, "acme/tool")).id == REPOSITORY + assert (await call(client, "find_repository", ORG, "acme/Tool")).id == SIBLING + with pytest.raises(ProoflineError) as raised: + await call(client, "find_repository", ORG, "ACME/TOOL") + assert raised.value.status == 0 + assert raised.value.type == "urn:proofline:sdk:ambiguous-repository" + assert raised.value.repository_name == "ACME/TOOL" + duplicated = repository_names((SIBLING, "acme/tool"), (REPOSITORY, "acme/tool")) + with Server(lambda request, index: Reply(body=duplicated)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "find_repository", ORG, "acme/tool") + assert raised.value.type == "urn:proofline:sdk:ambiguous-repository" + + +@MODES +async def test_find_repository_reports_a_name_the_token_cannot_see(mode: str) -> None: + listed = repository_names((REPOSITORY, "octo-org/api"), (SIBLING, "octo-org/kit")) + with Server(lambda request, index: Reply(body=listed)) as server: + async with session(mode, server.url) as client: + # Only ASCII letters fold; the Kelvin sign U+212A lowercases to k in Unicode. + assert "\u212ait".lower() == "kit" + for missing in [ + "octo-org/web", + "octo-org/ap", + "octo-org/api-v2", + "octo/api", + "octo-org/\u212ait", + ]: + with pytest.raises(ProoflineError) as raised: + await call(client, "find_repository", ORG, missing) + assert raised.value.status == 0 + assert raised.value.type == "urn:proofline:sdk:repository-not-found" + assert raised.value.repository_name == missing + assert missing in raised.value.detail + assert TOKEN not in raised.value.detail + assert repr(raised.value) == "ProoflineError(status=0)" + with Server(lambda request, index: Reply(body=repository_names())) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "find_repository", ORG, "octo-org/api") + assert raised.value.type == "urn:proofline:sdk:repository-not-found" + + +@MODES +async def test_find_repository_keeps_the_server_problem(mode: str) -> None: + problem = { + "type": "https://proofline.sh/problems/forbidden", + "title": "Forbidden", + "status": 403, + "detail": "The token lacks reviews:read.", + } + with Server( + lambda request, index: Reply( + status=403, body=problem, headers={"Content-Type": "application/problem+json"} + ) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "find_repository", ORG, "octo-org/api") + assert raised.value.status == 403 + assert raised.value.type == problem["type"] + assert len(server.requests) == 1 + + +@MODES +async def test_find_repository_validates_the_name_before_any_request(mode: str) -> None: + refused: list[Any] = [ + "", + "api", + "/api", + "octo-org/", + "/", + "octo-org/api/extra", + " octo-org/api", + "octo-org/api ", + "octo-org /api", + "octo-org/api\n", + None, + 7, + b"octo-org/api", + ] + listed = repository_names((REPOSITORY, "octo-org/api")) + with Server(lambda request, index: Reply(body=listed)) as server: + async with session(mode, server.url) as client: + for value in refused: + with pytest.raises(ValueError, match="owner/name"): + await call(client, "find_repository", ORG, value) + assert server.requests == [] + + def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN) with ProoflineClient() as client: