import dataclasses
import gzip
import json
import pathlib
import re
import shutil
import tarfile
import tomllib
import typing as typ
import zlib
import release_digest
import release_digest_files
_COMMIT = re.compile(r"[0-9a-f]{40}")
_SHA256 = re.compile(r"[0-9A-Fa-f]{64}")
_VCS_INFO = ".cargo_vcs_info.json"
_UNREADABLE_ARCHIVE = (
tarfile.TarError,
gzip.BadGzipFile,
zlib.error,
EOFError,
json.JSONDecodeError,
UnicodeError,
)
class CandidateError(ValueError):
@dataclasses.dataclass(frozen=True, slots=True)
class CrateArchive:
name: str
version: str
sha256: str
@property
def filename(self) -> str:
return f"{self.name}-{self.version}.crate"
@dataclasses.dataclass(frozen=True, slots=True)
class Candidate:
commit: str
tag: str
crates: tuple[CrateArchive, ...]
def __post_init__(self) -> None:
if len({crate.version for crate in self.crates}) > 1:
message = "the candidate record names different crate versions"
raise CandidateError(message)
@property
def version(self) -> str:
return self.crates[0].version
@dataclasses.dataclass(frozen=True, slots=True)
class Expectation:
commit: str
tag: str
def _load_toml(path: pathlib.Path) -> dict[str, typ.Any]:
try:
return tomllib.loads(path.read_text(encoding="utf-8"))
except (tomllib.TOMLDecodeError, UnicodeError) as error:
message = f"{path.name} is not valid TOML: {error}"
raise CandidateError(message) from error
def publish_order(workspace_root: pathlib.Path) -> tuple[str, ...]:
publish = _load_toml(workspace_root / "lading.toml").get("publish", {})
order = publish.get("order") if isinstance(publish, dict) else None
if not _is_crate_list(order):
message = "lading.toml must declare publish.order as a list of crate names"
raise CandidateError(message)
return tuple(order)
def _is_crate_list(order: object) -> typ.TypeIs[list[str]]:
return (
isinstance(order, list)
and bool(order)
and all(isinstance(name, str) for name in order)
)
def workspace_version(workspace_root: pathlib.Path) -> str:
manifest = _load_toml(workspace_root / "Cargo.toml")
try:
version = manifest["package"]["version"]
except (KeyError, TypeError) as error:
message = "Cargo.toml declares no package.version"
raise CandidateError(message) from error
if not isinstance(version, str):
message = "Cargo.toml declares package.version as something other than text"
raise CandidateError(message)
return version
def archive_commit(archive: pathlib.Path) -> str:
try:
git = _recorded_git(archive)
except _UNREADABLE_ARCHIVE as error:
message = f"{archive.name} is not a readable package archive: {error}"
raise CandidateError(message) from error
if git.get("dirty"):
message = f"{archive.name} was packaged from uncommitted changes"
raise CandidateError(message)
return str(git.get("sha1", ""))
def _recorded_git(archive: pathlib.Path) -> dict[str, typ.Any]:
member = f"{archive.name.removesuffix('.crate')}/{_VCS_INFO}"
with tarfile.open(archive, "r:gz") as package:
try:
recorded = package.extractfile(member)
except KeyError:
recorded = None
if recorded is None:
message = f"{archive.name} records no commit"
raise CandidateError(message)
record = json.load(recorded)
git = record.get("git", {}) if isinstance(record, dict) else None
if not isinstance(git, dict):
message = f"{archive.name} records no commit"
raise CandidateError(message)
return git
def require_expectation(expected: Expectation, version: str) -> None:
if _COMMIT.fullmatch(expected.commit) is None:
message = "the commit must be a full lowercase SHA-1"
raise CandidateError(message)
if expected.tag not in {"", f"v{version}"}:
message = f"tag {expected.tag!r} does not name version {version}"
raise CandidateError(message)
def record_candidate(
workspace_root: pathlib.Path,
package_directory: pathlib.Path,
expected: Expectation,
) -> Candidate:
version = workspace_version(workspace_root)
require_expectation(expected, version)
crates = []
for name in publish_order(workspace_root):
archive = package_directory / f"{name}-{version}.crate"
if not archive.is_file():
message = f"{archive.name} was not packaged"
raise CandidateError(message)
commit = archive_commit(archive)
if commit != expected.commit:
message = f"{archive.name} was packaged from {commit or 'no commit'}"
raise CandidateError(message)
digest = release_digest_files.digest_of_file(archive)
crates.append(CrateArchive(name, version, digest))
return Candidate(expected.commit, expected.tag, tuple(crates))
def retain_archives(
candidate: Candidate, package_directory: pathlib.Path, destination: pathlib.Path
) -> None:
destination.mkdir(parents=True, exist_ok=True)
for crate in candidate.crates:
shutil.copyfile(
package_directory / crate.filename, destination / crate.filename
)
def check_candidate(
candidate: Candidate, package_directory: pathlib.Path, expected: Expectation
) -> None:
require_expectation(expected, candidate.version)
if (candidate.commit, candidate.tag) != (expected.commit, expected.tag):
message = "the candidate record belongs to another commit or tag"
raise CandidateError(message)
for crate in candidate.crates:
archive = package_directory / crate.filename
if not archive.is_file():
message = f"{crate.filename} is missing"
raise CandidateError(message)
digest = release_digest_files.digest_of_file(archive)
if not release_digest.constant_time_equal(digest, crate.sha256):
message = f"{crate.filename} is {digest}, not the recorded {crate.sha256}"
raise CandidateError(message)
def write_candidate(candidate: Candidate, path: pathlib.Path) -> None:
record = json.dumps(dataclasses.asdict(candidate), indent=2, sort_keys=True)
path.write_text(record + "\n", encoding="utf-8")
def expected_digests(candidate: Candidate) -> str:
return "".join(f"{crate.sha256} {crate.filename}\n" for crate in candidate.crates)
def _decode_crate(entry: object) -> CrateArchive:
match entry:
case {"name": str(name), "version": str(version), "sha256": str(digest)}:
if len(entry) == 3 and _SHA256.fullmatch(digest):
return CrateArchive(name, version, digest)
raise ValueError("invalid candidate crate entry")
def read_candidate(path: pathlib.Path) -> Candidate:
message = f"{path.name} is not a candidate record"
try:
record = json.loads(path.read_text(encoding="utf-8"))
match record:
case {"commit": str(commit), "tag": str(tag), "crates": list(entries)}:
crates = tuple(_decode_crate(crate) for crate in entries)
case _:
raise ValueError("invalid candidate envelope")
except ValueError as error:
raise CandidateError(message) from error
if not crates:
message = f"{path.name} names no crates"
raise CandidateError(message)
return Candidate(commit, tag, crates)