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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 2 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
from .exports import ExportDataset, ExportFormat, ExportPage
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome

Expand All @@ -45,6 +46,7 @@
"CheckGap",
"CommitReviewRequest",
"CommitReviewResponse",
"CoverageFile",
"CoverageUploadRequest",
"CoverageUploadResponse",
"CustomerAssessmentDetail",
Expand Down
29 changes: 28 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
90 changes: 90 additions & 0 deletions proofline/coverage.py
Original file line number Diff line number Diff line change
@@ -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
Loading