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

To upload reports directly from disk, `upload_coverage_files` reads each file as UTF-8 text and names it by its POSIX path relative to `root`, which defaults to the working directory. Wrap an entry in `CoverageFile` to choose a different report name, or call `read_coverage_files` to build the `CoverageUploadRequest` without sending it.

```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"]),
os.environ["TESTED_SHA"],
[
"coverage/lcov.info",
CoverageFile("go/cover.out", name="go/coverage.out"),
],
)
```

`upload_coverage_files` and `read_coverage_files` raise `ValueError` before sending anything when `tested_sha` is not a full 40-character hexadecimal SHA, the report count is outside 1 to 50, two reports share a name, a report path or name escapes `root`, a report is not a regular UTF-8 file, or the serialized JSON body would exceed 30 MiB. Filesystem errors such as a missing report propagate unchanged as `OSError`.

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
3 changes: 3 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, read_coverage_files
from .exports import ExportDataset, ExportFormat, ExportPage
from .knowledge import KnowledgeResult
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome
Expand All @@ -46,6 +47,7 @@
"CheckGap",
"CommitReviewRequest",
"CommitReviewResponse",
"CoverageFile",
"CoverageUploadRequest",
"CoverageUploadResponse",
"CustomerAssessmentDetail",
Expand Down Expand Up @@ -80,4 +82,5 @@
"UploadedReport",
"__version__",
"models",
"read_coverage_files",
]
37 changes: 36 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@

import math
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
from typing import Any, Self, TypedDict, TypeVar, Unpack, cast
from urllib.parse import quote
from uuid import UUID

import anyio
import httpx2
from pydantic import SecretStr

Expand Down Expand Up @@ -72,6 +73,13 @@
from ._generated.types import UNSET, Response, Unset
from ._mcp import AsyncMcpClient, McpClient
from ._transport import ProoflineError
from .coverage import (
CoverageFileInput,
CoveragePath,
_prepare_coverage_files,
_read_prepared_coverage_files,
read_coverage_files,
)
from .exports import ExportDataset, ExportFormat, ExportPage, decode_export
from .fixes import AsyncFixesClient, FixesClient
from .knowledge import AsyncKnowledgeClient, KnowledgeClient
Expand Down Expand Up @@ -479,6 +487,19 @@ def upload_coverage_reports(
body=body,
)

def upload_coverage_files(
self,
organization_id: UUID,
repository_id: UUID,
tested_sha: str,
files: Sequence[CoverageFileInput],
*,
root: CoveragePath | None = None,
) -> CoverageUploadResponse:
"""Read coverage report files from disk and upload them for one commit."""
body = read_coverage_files(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:
Expand Down Expand Up @@ -870,6 +891,20 @@ async def upload_coverage_reports(
body=body,
)

async def upload_coverage_files(
self,
organization_id: UUID,
repository_id: UUID,
tested_sha: str,
files: Sequence[CoverageFileInput],
*,
root: CoveragePath | None = None,
) -> CoverageUploadResponse:
"""Read coverage report files from disk and upload them for one commit."""
prepared = _prepare_coverage_files(tested_sha, files, root=root)
body = await anyio.to_thread.run_sync(_read_prepared_coverage_files, prepared)
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
224 changes: 224 additions & 0 deletions proofline/coverage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
"""Read coverage report files from disk into a validated upload request."""

from __future__ import annotations

import errno
import json
import os
import stat
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path, PureWindowsPath
from string import hexdigits
from typing import TypeAlias

from ._generated.models.coverage_upload_request import CoverageUploadRequest
from ._generated.models.uploaded_report import UploadedReport

MAX_REPORTS = 50
MAX_BODY_BYTES = 30 * 1024 * 1024

CoveragePath: TypeAlias = str | os.PathLike[str]


@dataclass(frozen=True, slots=True)
class CoverageFile:
"""A coverage report path on disk with an optional server-recorded name."""

path: CoveragePath
name: str | None = None


CoverageFileInput: TypeAlias = CoveragePath | CoverageFile


@dataclass(frozen=True, slots=True)
class _PreparedFile:
raw_path: str
logical_path: Path
name: str


@dataclass(frozen=True, slots=True)
class _PreparedCoverageUpload:
tested_sha: str
logical_root: Path
files: tuple[_PreparedFile, ...]


def _path_text(value: object, label: str) -> str:
if not isinstance(value, (str, os.PathLike)):
raise TypeError(f"{label} must be a str or os.PathLike[str].")
raw = os.fspath(value)
if not isinstance(raw, str):
raise TypeError(f"{label} must be a str path, not bytes.")
if "\x00" in raw:
raise ValueError(f"{label} cannot contain NUL bytes.")
return raw


def _within_root(target: Path, root: Path) -> bool:
return target != root and target.is_relative_to(root)


def _report_name(name: str) -> str:
segments = name.split("/")
windows = PureWindowsPath(name)
if (
not name
or "\x00" in name
or "\\" in name
or os.path.isabs(name)
or windows.is_absolute()
or windows.drive != ""
or any(segment in ("", ".", "..") for segment in segments)
):
raise ValueError(
f"Coverage report name {name!r} must be a relative POSIX path inside root."
)
return name


def _prepare_coverage_files(
tested_sha: str,
files: Sequence[CoverageFileInput],
*,
root: CoveragePath | None = None,
) -> _PreparedCoverageUpload:
if (
not isinstance(tested_sha, str)
or len(tested_sha) != 40
or any(character not in hexdigits for character in tested_sha)
):
raise ValueError("tested_sha must be a full 40-character hexadecimal commit SHA.")
if isinstance(files, (str, bytes, bytearray, memoryview, os.PathLike)) or not isinstance(
files, Sequence
):
raise TypeError("files must be a sequence of report paths or CoverageFile entries.")
entries = tuple(files)
if not 1 <= len(entries) <= MAX_REPORTS:
raise ValueError(f"Upload 1 to {MAX_REPORTS} coverage reports.")

root_text = os.getcwd() if root is None else _path_text(root, "root")
logical_root = Path(os.path.abspath(root_text))

prepared: list[_PreparedFile] = []
seen_names: set[str] = set()
for entry in entries:
if isinstance(entry, CoverageFile):
raw_path = _path_text(entry.path, "CoverageFile.path")
if entry.name is not None and not isinstance(entry.name, str):
raise TypeError("CoverageFile.name must be a str or None.")
explicit_name = entry.name
else:
raw_path = _path_text(entry, "files entry")
explicit_name = None

if not raw_path:
raise ValueError("Coverage report path must be inside root.")
logical_path = Path(os.path.abspath(os.path.join(logical_root, raw_path)))
if not _within_root(logical_path, logical_root):
raise ValueError(f"Coverage report path {raw_path!r} must be inside root.")

default_name = logical_path.relative_to(logical_root).as_posix()
name = _report_name(explicit_name if explicit_name is not None else default_name)
if name in seen_names:
raise ValueError(f"Coverage report names must be unique; {name!r} is duplicated.")
seen_names.add(name)
prepared.append(_PreparedFile(raw_path=raw_path, logical_path=logical_path, name=name))

return _PreparedCoverageUpload(
tested_sha=tested_sha,
logical_root=logical_root,
files=tuple(prepared),
)


def _read_regular_file(path: Path, name: str, remaining_budget: int) -> bytes:
flags = (
os.O_RDONLY
| getattr(os, "O_BINARY", 0)
| getattr(os, "O_NONBLOCK", 0)
| getattr(os, "O_NOFOLLOW", 0)
)
fd = os.open(path, flags)
try:
info = os.fstat(fd)
if stat.S_ISDIR(info.st_mode):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), str(path))
if not stat.S_ISREG(info.st_mode):
raise ValueError(f"Coverage report {name!r} must be a regular file.")
if info.st_size > remaining_budget:
raise ValueError("Coverage reports exceed the 30 MiB upload limit.")
chunks: list[bytes] = []
total = 0
while True:
chunk = os.read(fd, min(65_536, remaining_budget - total + 1))
if not chunk:
break
total += len(chunk)
if total > remaining_budget:
raise ValueError("Coverage reports exceed the 30 MiB upload limit.")
chunks.append(chunk)
return b"".join(chunks)
finally:
os.close(fd)


def _read_prepared_coverage_files(prepared: _PreparedCoverageUpload) -> CoverageUploadRequest:
real_root = Path(os.path.realpath(prepared.logical_root, strict=True))
if not real_root.is_dir():
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), str(prepared.logical_root)
)

resolved_files: list[tuple[_PreparedFile, Path]] = []
for item in prepared.files:
real_path = Path(os.path.realpath(item.logical_path, strict=True))
if not _within_root(real_path, real_root):
raise ValueError(f"Coverage report path {item.raw_path!r} must be inside root.")
resolved_files.append((item, real_path))

# Check size on the open fd first so huge files don't blow up memory.
remaining_budget = MAX_BODY_BYTES
reports: list[UploadedReport] = []
for item, real_path in resolved_files:
raw = _read_regular_file(real_path, item.name, remaining_budget)
remaining_budget -= len(raw)
try:
# Keep leading BOM intact (don't use utf-8-sig).
content = raw.decode("utf-8")
except UnicodeDecodeError:
raise ValueError(f"Coverage report {item.name!r} is not UTF-8 text.") from None
reports.append(UploadedReport(name=item.name, content=content))

request = CoverageUploadRequest(tested_sha=prepared.tested_sha, reports=reports)
# Same compact json encoding httpx2 uses on the wire.
wire = json.dumps(
request.to_dict(),
ensure_ascii=False,
separators=(",", ":"),
allow_nan=False,
).encode("utf-8")
if len(wire) > MAX_BODY_BYTES:
raise ValueError("Coverage reports exceed the 30 MiB upload limit.")
return request


def read_coverage_files(
tested_sha: str,
files: Sequence[CoverageFileInput],
*,
root: CoveragePath | None = None,
) -> CoverageUploadRequest:
"""Read coverage reports from disk into a validated upload request.

Each report defaults its recorded name to its POSIX path relative to ``root``
(the current working directory when omitted), unless wrapped in ``CoverageFile``
with an explicit ``name``. Refuses abbreviated SHAs, counts outside 1..50,
duplicate or escaping paths and names, non-regular or non-UTF-8 files, and
serialized JSON bodies exceeding 30 MiB with ``ValueError`` before any network
call. Filesystem errors such as missing files propagate unchanged as ``OSError``.
"""
prepared = _prepare_coverage_files(tested_sha, files, root=root)
return _read_prepared_coverage_files(prepared)
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 = {
"close",
"aclose",
"iter_export_pages",
"iter_reviews",
"upload_coverage_files",
"wait_for_review",
}
exposed = {
name
for name in dir(client)
Expand Down
Loading