diff --git a/README.md b/README.md index 3c7a6ca9..53a28b5c 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,20 @@ with ProoflineClient() as client: 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. +To upload report files straight from disk, use `upload_coverage_files`. It reads each file as UTF-8 text and names it by its path relative to `root`, which defaults to the working directory. Pass `CoverageFile(path, name)` to choose a different report name. Every check runs before a request is sent: a short or non-hexadecimal SHA, a report count outside 1 to 50, a duplicate name, a file outside `root`, a name containing `..`, non-UTF-8 content and a body over 30 MiB all raise `ValueError`. A missing file raises the usual `OSError`. The async client has the same method as a coroutine. + +```python +from proofline import CoverageFile, ProoflineClient + +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", CoverageFile("go/cover.out", "go/coverage.out")], + ) +``` + ## MCP organization selection With an MCP OAuth credential approved for several organizations, discover its currently authorized targets with `client.mcp.list_organizations()`. It returns a `KnowledgeResult`; inspect `isError` before reading `structuredContent["data"]["organizations"]`. Each entry contains `organization_id`, `github_login`, and `scopes`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 5704485b..eab1cbb5 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,6 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .coverage import CoverageFile from .exports import ExportDataset, ExportFormat, ExportPage from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -45,6 +46,7 @@ "CheckGap", "CommitReviewRequest", "CommitReviewResponse", + "CoverageFile", "CoverageUploadRequest", "CoverageUploadResponse", "CustomerAssessmentDetail", diff --git a/proofline/client.py b/proofline/client.py index 0a68a55c..a1482b81 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,9 +2,11 @@ from __future__ import annotations +import asyncio import math +import os from asyncio import sleep as async_sleep -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Sequence from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -72,6 +74,7 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .coverage import CoverageFileSpec, build_coverage_request from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -478,6 +481,18 @@ def upload_coverage_reports( body=body, ) + def upload_coverage_files( + self, + organization_id: UUID, + repository_id: UUID, + *, + tested_sha: str, + files: Sequence[CoverageFileSpec], + root: str | os.PathLike[str] | None = None, + ) -> CoverageUploadResponse: + body = build_coverage_request(tested_sha, files, root=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: @@ -869,6 +884,18 @@ async def upload_coverage_reports( body=body, ) + async def upload_coverage_files( + self, + organization_id: UUID, + repository_id: UUID, + *, + tested_sha: str, + files: Sequence[CoverageFileSpec], + root: str | os.PathLike[str] | None = None, + ) -> CoverageUploadResponse: + body = await asyncio.to_thread(build_coverage_request, tested_sha, files, root=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: diff --git a/proofline/coverage.py b/proofline/coverage.py new file mode 100644 index 00000000..627678cc --- /dev/null +++ b/proofline/coverage.py @@ -0,0 +1,90 @@ +"""Build coverage upload requests from report files on disk.""" + +from __future__ import annotations + +import json +import os +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from string import hexdigits + +from ._generated.models.coverage_upload_request import CoverageUploadRequest +from ._generated.models.uploaded_report import UploadedReport + +MAX_REPORTS = 50 +MAX_BODY_BYTES = 30 * 1024 * 1024 + + +@dataclass(frozen=True, slots=True) +class CoverageFile: + """A report file and, optionally, the name the server records for it.""" + + path: str | os.PathLike[str] + name: str | None = None + + +CoverageFileSpec = str | os.PathLike[str] | CoverageFile + + +def _tested_sha(value: str) -> None: + if ( + not isinstance(value, str) + or len(value) != 40 + or any(character not in hexdigits for character in value) + ): + raise ValueError("tested_sha must be a full 40 character hexadecimal commit SHA.") + + +def _explicit_name(name: str) -> str: + parts = PurePosixPath(name.replace("\\", "/")).parts + if not parts or PurePosixPath(name).is_absolute() or ".." in parts: + raise ValueError(f"Report name {name!r} must be a relative path without '..'.") + return "/".join(part for part in parts if part != ".") + + +def _relative_name(path: Path, root: Path) -> str: + try: + relative = path.relative_to(root) + except ValueError: + raise ValueError(f"Report {str(path)!r} is outside the root {str(root)!r}.") from None + return relative.as_posix() + + +def build_coverage_request( + tested_sha: str, + files: Sequence[CoverageFileSpec], + *, + root: str | os.PathLike[str] | None = None, +) -> CoverageUploadRequest: + """Read report files as UTF-8 text and return the upload request for them. + + Each report is named by its path relative to ``root`` (default: the working + directory) unless a :class:`CoverageFile` gives a name. Nothing is sent: every + problem is raised as ``ValueError`` before a request exists. Missing files raise + the usual ``OSError``. + """ + _tested_sha(tested_sha) + if isinstance(files, str | os.PathLike) or not 1 <= len(files) <= MAX_REPORTS: + raise ValueError(f"Upload 1 to {MAX_REPORTS} report files.") + base = Path(root if root is not None else Path.cwd()).resolve() + reports: list[UploadedReport] = [] + seen: set[str] = set() + for spec in files: + item = spec if isinstance(spec, CoverageFile) else CoverageFile(spec) + path = Path(item.path) + resolved = (path if path.is_absolute() else base / path).resolve() + relative = _relative_name(resolved, base) + name = _explicit_name(item.name) if item.name is not None else relative + if name in seen: + raise ValueError(f"Report name {name!r} is used twice.") + seen.add(name) + try: + content = resolved.read_bytes().decode("utf-8") + except UnicodeDecodeError: + raise ValueError(f"Report {name!r} is not UTF-8 text.") from None + reports.append(UploadedReport(name=name, content=content)) + request = CoverageUploadRequest(tested_sha=tested_sha, reports=reports) + if len(json.dumps(request.to_dict()).encode()) > MAX_BODY_BYTES: + raise ValueError("The coverage upload body would exceed 30 MiB.") + return request diff --git a/tests/test_coverage_files.py b/tests/test_coverage_files.py new file mode 100644 index 00000000..79f423d0 --- /dev/null +++ b/tests/test_coverage_files.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from proofline import CoverageFile, CoverageUploadResponse +from proofline.coverage import MAX_BODY_BYTES, build_coverage_request + +from .fixtures import ORG, REPOSITORY, REVIEW +from .http_server import Reply, Request, Server +from .test_http import MODES, call, session + +SHA = "a" * 40 +LCOV = "SF:src/main.py\nDA:1,1\nDA:2,0\nend_of_record\n" + + +def write(path: Path, text: str = LCOV) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + +def names(request: Any) -> list[str]: + return [report.name for report in request.reports] + + +def test_reports_are_named_by_path_relative_to_root(tmp_path: Path) -> None: + write(tmp_path / "coverage/lcov.info") + write(tmp_path / "go/cover.out", "mode: set\n") + request = build_coverage_request( + SHA, ["coverage/lcov.info", tmp_path / "go/cover.out"], root=tmp_path + ) + assert request.tested_sha == SHA + assert names(request) == ["coverage/lcov.info", "go/cover.out"] + assert request.reports[0].content == LCOV + + +def test_default_root_is_the_working_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + write(tmp_path / "lcov.info") + monkeypatch.chdir(tmp_path) + assert names(build_coverage_request(SHA, ["lcov.info"])) == ["lcov.info"] + + +def test_explicit_name_overrides_the_path(tmp_path: Path) -> None: + write(tmp_path / "go/cover.out") + request = build_coverage_request( + SHA, [CoverageFile(tmp_path / "go/cover.out", "./go/coverage.out")], root=tmp_path + ) + assert names(request) == ["go/coverage.out"] + + +@pytest.mark.parametrize("sha", ["a" * 7, "a" * 39, "A" * 41, "main", "g" * 40, ""]) +def test_abbreviated_or_malformed_sha_is_refused(tmp_path: Path, sha: str) -> None: + write(tmp_path / "lcov.info") + with pytest.raises(ValueError, match="40 character"): + build_coverage_request(sha, ["lcov.info"], root=tmp_path) + + +def test_report_count_must_be_one_to_fifty(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="1 to 50"): + build_coverage_request(SHA, [], root=tmp_path) + with pytest.raises(ValueError, match="1 to 50"): + build_coverage_request(SHA, "lcov.info", root=tmp_path) + files = [write(tmp_path / f"r{index}.info").name for index in range(51)] + with pytest.raises(ValueError, match="1 to 50"): + build_coverage_request(SHA, files, root=tmp_path) + fifty = build_coverage_request(SHA, files[:50], root=tmp_path) + assert len(fifty.reports) == 50 + + +def test_duplicate_names_are_refused(tmp_path: Path) -> None: + write(tmp_path / "a/lcov.info") + write(tmp_path / "b/lcov.info") + with pytest.raises(ValueError, match="used twice"): + build_coverage_request( + SHA, + [ + "a/lcov.info", + CoverageFile("b/lcov.info", "a/lcov.info"), + ], + root=tmp_path, + ) + + +def test_names_cannot_escape_the_root(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + write(tmp_path / "outside.info") + write(root / "inside.info") + with pytest.raises(ValueError, match="outside the root"): + build_coverage_request(SHA, ["../outside.info"], root=root) + with pytest.raises(ValueError, match="outside the root"): + build_coverage_request(SHA, [tmp_path / "outside.info"], root=root) + for name in ("../x.info", "/abs/x.info", "a/../../x.info", ""): + with pytest.raises(ValueError, match="relative path"): + build_coverage_request(SHA, [CoverageFile("inside.info", name)], root=root) + + +def test_a_symlink_out_of_the_root_is_refused(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + target = write(tmp_path / "secret.txt", "token\n") + (root / "lcov.info").symlink_to(target) + with pytest.raises(ValueError, match="outside the root"): + build_coverage_request(SHA, ["lcov.info"], root=root) + + +def test_explicit_name_does_not_bypass_the_root(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + outside = write(tmp_path / "secret.txt", "token\n") + target = write(tmp_path / "other.txt", "token\n") + (root / "link.info").symlink_to(target) + with pytest.raises(ValueError, match="outside the root"): + build_coverage_request(SHA, [CoverageFile(outside, "ok.info")], root=root) + with pytest.raises(ValueError, match="outside the root"): + build_coverage_request(SHA, [CoverageFile("link.info", "ok.info")], root=root) + + +def test_non_utf8_report_is_refused(tmp_path: Path) -> None: + (tmp_path / "lcov.info").write_bytes(b"SF:\xff\xfe\n") + with pytest.raises(ValueError, match="not UTF-8"): + build_coverage_request(SHA, ["lcov.info"], root=tmp_path) + + +def test_missing_file_raises_the_file_system_error(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError): + build_coverage_request(SHA, ["missing.info"], root=tmp_path) + + +def test_body_over_thirty_mebibytes_is_refused(tmp_path: Path) -> None: + write(tmp_path / "big.info", "x" * (MAX_BODY_BYTES + 1)) + with pytest.raises(ValueError, match="30 MiB"): + build_coverage_request(SHA, ["big.info"], root=tmp_path) + + +def test_size_limit_counts_the_serialized_body(tmp_path: Path) -> None: + # Every newline becomes two bytes of JSON, so the raw content fits but the body does not. + write(tmp_path / "escaped.info", "\n" * (MAX_BODY_BYTES // 2)) + with pytest.raises(ValueError, match="30 MiB"): + build_coverage_request(SHA, ["escaped.info"], root=tmp_path) + + +def test_body_just_under_the_limit_is_accepted(tmp_path: Path) -> None: + write(tmp_path / "large.info", "x" * (MAX_BODY_BYTES - 1024)) + request = build_coverage_request(SHA, ["large.info"], root=tmp_path) + assert len(request.reports) == 1 + + +@MODES +async def test_upload_coverage_files_sends_the_named_reports(mode: str, tmp_path: Path) -> None: + write(tmp_path / "python/lcov.info") + + 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": "python/lcov.info", "content": LCOV}], + } + return Reply( + status=201, + body={ + "report_id": str(REVIEW), + "tested_sha": SHA, + "created": True, + "formats": ["LCOV"], + "instrumented_lines": 2, + "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=["python/lcov.info"], + root=tmp_path, + ) + assert isinstance(result, CoverageUploadResponse) + assert (result.created, result.covered_lines, result.instrumented_lines) == ( + True, + 1, + 2, + ) + assert len(server.requests) == 1 + + +@MODES +async def test_invalid_files_send_nothing(mode: str, tmp_path: Path) -> None: + with Server(lambda request, index: Reply(status=500, body={})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError, match="40 character"): + await call( + client, + "upload_coverage_files", + ORG, + REPOSITORY, + tested_sha="main", + files=["lcov.info"], + root=tmp_path, + ) + assert server.requests == []