Skip to content
Open
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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 2 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
PatchReviewResponse,
PatchTriggerSource,
RepositoryGuidance,
RepositoryName,
RepositoryNames,
RerunResponse,
ReviewPage,
Expand Down Expand Up @@ -61,6 +62,7 @@
"ProoflineClient",
"ProoflineError",
"RepositoryGuidance",
"RepositoryName",
"RepositoryNames",
"RerunResponse",
"ReviewFilters",
Expand Down
64 changes: 63 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 8 additions & 1 deletion scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
138 changes: 138 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
ProoflineClient,
ProoflineError,
RepositoryGuidance,
RepositoryName,
RepositoryNames,
RerunResponse,
ReviewPage,
Expand Down Expand Up @@ -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:
Expand Down