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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ with ProoflineClient() as client:
)
```

To upload reports straight from disk, pass their paths to `upload_coverage_files`. Relative paths resolve against `root` (the current directory by default), every report must stay inside `root`, and each report is named by its path relative to it. The files are read as UTF-8 and sent exactly as written. The SDK checks the SHA, the file count, and the paths before it sends anything. `AsyncProoflineClient` reads the files in a worker thread.

```python
with ProoflineClient() as client:
report = client.upload_coverage_files(
UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]),
UUID(os.environ["PROOFLINE_REPOSITORY_ID"]),
tested_sha=os.environ["TESTED_SHA"],
files=["coverage/lcov.info", "coverage/coverage.xml"],
)
```

The response names the recorded report and its covered and instrumented line counts. An identical upload returns that report with `created=False`. Refused reports raise `ProoflineError`. Uploading a report does not establish a check verdict.

## MCP organization selection
Expand Down
87 changes: 86 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from __future__ import annotations

import math
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Iterator
from pathlib import Path
from string import hexdigits
from time import sleep
from types import TracebackType
Expand All @@ -13,6 +14,7 @@

import httpx2
from anyio import sleep as async_sleep
from anyio import to_thread
from pydantic import SecretStr

from . import _transport
Expand Down Expand Up @@ -69,6 +71,7 @@
from ._generated.models.run_now_response import RunNowResponse
from ._generated.models.start_session import StartSession
from ._generated.models.stop_response import StopResponse
from ._generated.models.uploaded_report import UploadedReport
from ._generated.types import UNSET, Response, Unset
from ._mcp import AsyncMcpClient, McpClient
from ._transport import ProoflineError
Expand Down Expand Up @@ -208,6 +211,53 @@ def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None:
return cursor


def _coverage_upload_request(
tested_sha: str, files: Iterable[str | Path], root: str | Path
) -> CoverageUploadRequest:
"""Read coverage reports from disk into one upload request.

Each report is named by its path relative to ``root``, and its text is sent
byte for byte as the coverage tool wrote it, line endings included.
"""
if (
not isinstance(tested_sha, str)
or len(tested_sha) != 40
or any(character not in hexdigits for character in tested_sha)
):
raise ValueError("The tested SHA must be a full 40 character hexadecimal commit SHA.")
if isinstance(files, (str, bytes, Path)):
raise TypeError("files must be a collection of report paths, not a single path.")
root_path = Path(root).expanduser().resolve(strict=True)
if not root_path.is_dir():
raise ValueError("The coverage report root must be a directory.")
file_paths = list(files)
if not 1 <= len(file_paths) <= 50:
raise ValueError("Coverage uploads require between 1 and 50 report files.")

reports: list[UploadedReport] = []
names: set[str] = set()
for file_path in file_paths:
path = Path(file_path).expanduser()
if not path.is_absolute():
path = root_path / path
# Resolving first means a symlink that leaves the root is refused too.
resolved = path.resolve(strict=True)
try:
name = resolved.relative_to(root_path).as_posix()
except ValueError:
raise ValueError(
f"Coverage report must be inside the configured root: {file_path}"
) from None
if not resolved.is_file():
raise ValueError(f"Coverage report is not a file: {file_path}")
if name in names:
raise ValueError(f"Duplicate coverage report name: {name}")
names.add(name)
# read_text would translate CRLF; the contract wants the report verbatim.
reports.append(UploadedReport(name=name, content=resolved.read_bytes().decode("utf-8")))
return CoverageUploadRequest(tested_sha=tested_sha, reports=reports)


class ProoflineClient(Operations):
"""Synchronous typed HTTP operations.

Expand Down Expand Up @@ -479,6 +529,23 @@ def upload_coverage_reports(
body=body,
)

def upload_coverage_files(
self,
organization_id: UUID,
repository_id: UUID,
*,
tested_sha: str,
files: Iterable[str | Path],
root: str | Path = ".",
) -> CoverageUploadResponse:
"""Read coverage reports under ``root`` and upload them for ``tested_sha``.

Relative paths in ``files`` resolve against ``root`` and every report must
stay inside it. Reports are named by their path relative to ``root``.
"""
body = _coverage_upload_request(tested_sha, files, root)
return self.upload_coverage_reports(organization_id, repository_id, body=body)

def request_file_review(
self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest
) -> FileReviewResponse:
Expand Down Expand Up @@ -872,6 +939,24 @@ async def upload_coverage_reports(
body=body,
)

async def upload_coverage_files(
self,
organization_id: UUID,
repository_id: UUID,
*,
tested_sha: str,
files: Iterable[str | Path],
root: str | Path = ".",
) -> CoverageUploadResponse:
"""Read coverage reports under ``root`` and upload them for ``tested_sha``.

Relative paths in ``files`` resolve against ``root`` and every report must
stay inside it. Reports are named by their path relative to ``root``. The
files are read in a worker thread so the event loop is not blocked.
"""
body = await to_thread.run_sync(_coverage_upload_request, tested_sha, files, root)
return await self.upload_coverage_reports(organization_id, repository_id, body=body)

async def request_file_review(
self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest
) -> FileReviewResponse:
Expand Down
9 changes: 8 additions & 1 deletion scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,14 @@ def main() -> None:
raise SystemExit("ReviewFilters differs from the list_reviews query parameters.")

for client in (ProoflineClient, AsyncProoflineClient):
helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"}
helpers = {
"aclose",
"close",
"iter_export_pages",
"iter_reviews",
"upload_coverage_files",
"wait_for_review",
}
exposed = {
name
for name in dir(client)
Expand Down
130 changes: 130 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -2732,3 +2732,133 @@ def respond(request: Request, index: int) -> Reply:
assert len(exported.rows) == 1
assert exported.rows[0]["claim"] == row["claim"]
assert exported.next_cursor == "next-page"


SHA = "a" * 40


@MODES
async def test_upload_coverage_files_reads_reports_under_root(mode: str, tmp_path: Path) -> None:
coverage = tmp_path / "coverage"
coverage.mkdir()
lcov = "SF:src/main.py\r\nDA:1,1\r\nend_of_record\r\n"
(coverage / "lcov.info").write_bytes(lcov.encode())
(coverage / "coverage.xml").write_text("<coverage />", encoding="utf-8")

def respond(request: Request, index: int) -> Reply:
assert request.method == "POST"
assert request.path == (
f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/coverage-reports"
)
assert json.loads(request.body) == {
"tested_sha": SHA,
"reports": [
{"name": "coverage/lcov.info", "content": lcov},
{"name": "coverage/coverage.xml", "content": "<coverage />"},
],
}
return Reply(
status=201,
body={
"report_id": str(REVIEW),
"tested_sha": SHA,
"created": True,
"formats": ["LCOV", "COBERTURA"],
"instrumented_lines": 1,
"covered_lines": 1,
},
)

with Server(respond) as server:
async with session(mode, server.url) as client:
result = await call(
client,
"upload_coverage_files",
ORG,
REPOSITORY,
tested_sha=SHA,
files=["coverage/lcov.info", coverage / "coverage.xml"],
root=tmp_path,
)
assert isinstance(result, CoverageUploadResponse)
assert (result.report_id, result.created) == (REVIEW, True)
assert len(server.requests) == 1


@MODES
async def test_upload_coverage_files_refuses_before_sending(mode: str, tmp_path: Path) -> None:
(tmp_path / "lcov.info").write_text("data", encoding="utf-8")
with Server(lambda request, index: Reply(status=500, body={})) as server:
async with session(mode, server.url) as client:
with pytest.raises(ValueError, match="tested SHA"):
await call(
client,
"upload_coverage_files",
ORG,
REPOSITORY,
tested_sha="HEAD",
files=["lcov.info"],
root=tmp_path,
)
assert server.requests == []


def build(root: Path, files: Any, tested_sha: str = SHA) -> CoverageUploadRequest:
return client_module._coverage_upload_request(tested_sha, files, root)


def test_coverage_upload_request_rejects_files_outside_root(tmp_path: Path) -> None:
root = tmp_path / "coverage"
root.mkdir()
outside = tmp_path / "outside.info"
outside.write_text("coverage data", encoding="utf-8")
(root / "escape.info").symlink_to(outside)
for files in ([outside], ["../outside.info"], ["escape.info"]):
with pytest.raises(ValueError, match="inside the configured root"):
build(root, files)


def test_coverage_upload_request_rejects_duplicate_report_names(tmp_path: Path) -> None:
report = tmp_path / "lcov.info"
report.write_text("coverage data", encoding="utf-8")
with pytest.raises(ValueError, match="Duplicate coverage report name"):
build(tmp_path, ["lcov.info", report])


@pytest.mark.parametrize("count", [0, 51])
def test_coverage_upload_request_bounds_report_count(tmp_path: Path, count: int) -> None:
for index in range(count):
(tmp_path / f"{index}.info").write_text("data", encoding="utf-8")
with pytest.raises(ValueError, match="between 1 and 50"):
build(tmp_path, [f"{index}.info" for index in range(count)])


@pytest.mark.parametrize("files", ["lcov.info", Path("lcov.info")])
def test_coverage_upload_request_rejects_a_single_path(tmp_path: Path, files: Any) -> None:
(tmp_path / "lcov.info").write_text("data", encoding="utf-8")
with pytest.raises(TypeError, match="not a single path"):
build(tmp_path, files)


@pytest.mark.parametrize("tested_sha", ["HEAD", "a" * 39, "a" * 64, "g" * 40])
def test_coverage_upload_request_requires_full_tested_sha(tmp_path: Path, tested_sha: str) -> None:
(tmp_path / "lcov.info").write_text("data", encoding="utf-8")
with pytest.raises(ValueError, match="tested SHA"):
build(tmp_path, ["lcov.info"], tested_sha)


def test_coverage_upload_request_rejects_directories_and_missing_files(tmp_path: Path) -> None:
(tmp_path / "reports").mkdir()
(tmp_path / "plain.info").write_text("data", encoding="utf-8")
with pytest.raises(ValueError, match="not a file"):
build(tmp_path, ["reports"])
with pytest.raises(FileNotFoundError):
build(tmp_path, ["missing.info"])
with pytest.raises(ValueError, match="root must be a directory"):
build(tmp_path / "plain.info", ["plain.info"])


def test_coverage_upload_request_rejects_invalid_utf8(tmp_path: Path) -> None:
(tmp_path / "lcov.info").write_bytes(b"\xff\xfe")
with pytest.raises(UnicodeDecodeError):
build(tmp_path, ["lcov.info"])
Loading