added preflight check
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
"""Local release tooling: preflight gate and per-wheel audit.
|
||||
|
||||
Entry point is ``python build/run.py release <command>``; see
|
||||
:mod:`release.preflight` for the gate steps and :mod:`release.cli` for the CLI.
|
||||
Imports are intentionally not re-exported here so importing a submodule never
|
||||
triggers the whole subsystem.
|
||||
"""
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Command line for ``python build/run.py release``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_BUILD_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_BUILD_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_BUILD_ROOT))
|
||||
|
||||
from common.paths import REPO_ROOT # noqa: E402
|
||||
from common.verify.wheel import ( # noqa: E402
|
||||
DEFAULT_RUNTIME_CONFIG,
|
||||
default_verification_video,
|
||||
verify_wheel_assets,
|
||||
verify_wheel_runtime,
|
||||
)
|
||||
from common.verify.wheel_contents import inspect_wheel # noqa: E402
|
||||
from release.preflight import PreflightOptions, run_preflight # noqa: E402
|
||||
|
||||
|
||||
def _cmd_preflight(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="build/run.py release preflight",
|
||||
description="Gate a release locally: version, tests, wheel content, runtime.",
|
||||
)
|
||||
parser.add_argument("--version", help="release version (default: pyproject's dynamic version)")
|
||||
parser.add_argument("--wheel-dir", type=Path, help="directory to inspect (default: SDK/<version>)")
|
||||
parser.add_argument("--video", type=Path, help="clip for the end-to-end runtime check")
|
||||
parser.add_argument("--config", default=DEFAULT_RUNTIME_CONFIG, help="config name for that check")
|
||||
parser.add_argument("--frames", type=int, default=40, help="frames to process (default: 40)")
|
||||
parser.add_argument("--skip-tests", action="store_true", help="skip pytest (recorded in the report)")
|
||||
parser.add_argument("--longrun", action="store_true", help="include the slow long-run stability test")
|
||||
parser.add_argument("--allow-dirty", action="store_true", help="allow a dirty working tree")
|
||||
parser.add_argument("--force", action="store_true", help="allow re-staging an existing SDK/<version>")
|
||||
parser.add_argument("--check-pypi", action="store_true", help="read PyPI and fail if the version exists")
|
||||
parser.add_argument(
|
||||
"--all-wheel-pythons",
|
||||
action="store_true",
|
||||
help="verify cp310/cp311/cp312 wheels, each in its own conda env",
|
||||
)
|
||||
parser.add_argument("--offline", action="store_true", help="reuse parent-env deps instead of PyPI")
|
||||
parser.add_argument("--no-runtime", action="store_true", help="skip the isolated runtime check")
|
||||
parser.add_argument("--no-assets", action="store_true", help="skip the bundled-asset check")
|
||||
parser.add_argument("--keep-going", action="store_true", help="collect every failure instead of stopping")
|
||||
parser.add_argument("--report-dir", type=Path, help="override build/release/reports")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
options = PreflightOptions(
|
||||
version=args.version,
|
||||
wheel_dir=args.wheel_dir,
|
||||
video=args.video,
|
||||
config_name=args.config,
|
||||
frames=args.frames,
|
||||
skip_tests=args.skip_tests,
|
||||
longrun=args.longrun,
|
||||
allow_dirty=args.allow_dirty,
|
||||
force=args.force,
|
||||
check_pypi=args.check_pypi,
|
||||
all_wheel_pythons=args.all_wheel_pythons,
|
||||
offline=args.offline,
|
||||
keep_going=args.keep_going,
|
||||
report_dir=args.report_dir,
|
||||
no_runtime=args.no_runtime,
|
||||
no_assets=args.no_assets,
|
||||
)
|
||||
return run_preflight(options, repo_root=REPO_ROOT)
|
||||
|
||||
|
||||
def _cmd_audit(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="build/run.py release audit",
|
||||
description="Inspect one built wheel without a release context.",
|
||||
)
|
||||
parser.add_argument("wheel", type=Path, help="path to an .whl")
|
||||
parser.add_argument("--expected-version", help="assert the wheel reports this version")
|
||||
parser.add_argument(
|
||||
"--strict-bundle",
|
||||
action="store_true",
|
||||
help="treat bundled-file drift from the current source tree as a failure",
|
||||
)
|
||||
parser.add_argument("--runtime", action="store_true", help="also install and run the wheel")
|
||||
parser.add_argument("--assets", action="store_true", help="also assert bundled assets load")
|
||||
parser.add_argument("--video", type=Path, help="clip for --runtime")
|
||||
parser.add_argument("--config", default=DEFAULT_RUNTIME_CONFIG)
|
||||
parser.add_argument("--frames", type=int, default=40)
|
||||
parser.add_argument("--offline", action="store_true")
|
||||
parser.add_argument(
|
||||
"--python",
|
||||
type=Path,
|
||||
default=None,
|
||||
help="interpreter to build the verification venv from (default: the running one)",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
wheel = args.wheel
|
||||
if not wheel.is_file():
|
||||
print(f"[ERROR] wheel not found: {wheel}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
exit_code = 0
|
||||
|
||||
result = inspect_wheel(
|
||||
wheel,
|
||||
expected_version=args.expected_version,
|
||||
repo_root=REPO_ROOT,
|
||||
strict_bundle=args.strict_bundle,
|
||||
)
|
||||
print(result.render())
|
||||
if not result.ok:
|
||||
exit_code = 1
|
||||
|
||||
if args.assets or args.runtime:
|
||||
try:
|
||||
print(verify_wheel_assets(wheel, python_executable=args.python))
|
||||
except Exception as exc:
|
||||
print(f"[FAIL] bundled assets: {type(exc).__name__}: {exc}")
|
||||
exit_code = 1
|
||||
|
||||
if args.runtime:
|
||||
video = args.video or default_verification_video(REPO_ROOT)
|
||||
if video is None:
|
||||
print("[FAIL] runtime: no verification clip; pass --video or set ORISYS_VERIFY_VIDEO")
|
||||
return 1
|
||||
try:
|
||||
info = verify_wheel_runtime(
|
||||
wheel,
|
||||
video=video,
|
||||
config_name=args.config,
|
||||
frames=args.frames,
|
||||
python_executable=args.python,
|
||||
offline=args.offline,
|
||||
)
|
||||
print(f"[ok ] runtime: {info}")
|
||||
except Exception as exc:
|
||||
print(f"[FAIL] runtime: {type(exc).__name__}: {exc}")
|
||||
exit_code = 1
|
||||
|
||||
return exit_code
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
if not argv or argv[0] in ("-h", "--help"):
|
||||
print(__doc__)
|
||||
print("Commands: preflight | audit")
|
||||
return 0
|
||||
|
||||
command, rest = argv[0], argv[1:]
|
||||
if command == "preflight":
|
||||
return _cmd_preflight(rest)
|
||||
if command == "audit":
|
||||
return _cmd_audit(rest)
|
||||
|
||||
print(f"Unknown release command: {command!r}", file=sys.stderr)
|
||||
print("Choose from: preflight, audit", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,515 @@
|
||||
"""Local release gate: everything that must hold before publishing a wheel.
|
||||
|
||||
``release preflight`` answers one question with an exit code: is this checkout,
|
||||
this version and these wheels safe to publish? It never publishes anything, and
|
||||
by default it makes no network calls.
|
||||
|
||||
Steps, in order:
|
||||
|
||||
1. ``repo-state`` - git repository, clean working tree, recorded commit
|
||||
2. ``version-consistency`` - __version__ == pyproject dynamic attr == wheel names
|
||||
3. ``duplicate-guard`` - SDK/<version>/ already populated; optionally PyPI
|
||||
4. ``tests`` - pytest (slow/hardware markers excluded)
|
||||
5. ``bundle-precheck`` - every bundle item resolves; required assets present
|
||||
6. ``wheel-inspection`` - static metadata/content assertions per wheel
|
||||
7. ``wheel-runtime`` - isolated venv: bundled assets load and real frames
|
||||
flow through the public pipeline
|
||||
|
||||
Output lands in ``build/release/reports/<version>/preflight.{json,txt}``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
_BUILD_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_BUILD_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_BUILD_ROOT))
|
||||
|
||||
from common.paths import REPO_ROOT # noqa: E402
|
||||
from common.pyproject_utils import bundle_items, get_version # noqa: E402
|
||||
from common.verify.wheel import ( # noqa: E402
|
||||
DEFAULT_RUNTIME_CONFIG,
|
||||
default_verification_video,
|
||||
verify_wheel_assets,
|
||||
verify_wheel_runtime,
|
||||
)
|
||||
from common.verify.wheel_contents import inspect_wheel # noqa: E402
|
||||
from release import report as report_mod # noqa: E402
|
||||
from release import version as version_mod # noqa: E402
|
||||
from wheel.layout import resolve_bundle_source_files, verify_required_assets # noqa: E402
|
||||
|
||||
|
||||
@dataclass
|
||||
class Step:
|
||||
name: str
|
||||
ok: bool
|
||||
detail: str = ""
|
||||
duration_s: float = 0.0
|
||||
data: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreflightOptions:
|
||||
version: str | None = None
|
||||
wheel_dir: Path | None = None
|
||||
video: Path | None = None
|
||||
config_name: str = DEFAULT_RUNTIME_CONFIG
|
||||
frames: int = 40
|
||||
skip_tests: bool = False
|
||||
longrun: bool = False
|
||||
allow_dirty: bool = False
|
||||
force: bool = False
|
||||
check_pypi: bool = False
|
||||
all_wheel_pythons: bool = False
|
||||
offline: bool = False
|
||||
keep_going: bool = False
|
||||
report_dir: Path | None = None
|
||||
no_runtime: bool = False
|
||||
no_assets: bool = False
|
||||
|
||||
|
||||
def _sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
class Preflight:
|
||||
def __init__(self, options: PreflightOptions, repo_root: Path | None = None) -> None:
|
||||
self.options = options
|
||||
self.repo_root = Path(repo_root or REPO_ROOT)
|
||||
self.steps: list[Step] = []
|
||||
self.git: dict = {"commit": None, "branch": None, "dirty": None}
|
||||
self.wheels: list[Path] = []
|
||||
self.wheel_dir: Path | None = None
|
||||
self.runtime_records: list[dict] = []
|
||||
self.aborted = False
|
||||
self.ok = False
|
||||
|
||||
if options.version:
|
||||
self.version = options.version
|
||||
self.version_source = "explicit --version"
|
||||
elif (self.repo_root / "pyproject.toml").is_file():
|
||||
self.version = get_version(self.repo_root)
|
||||
self.version_source = "pyproject.toml dynamic attr"
|
||||
else:
|
||||
self.version = "0.0.0"
|
||||
self.version_source = "unresolved"
|
||||
|
||||
self.report_dir = report_mod.reports_root(self.repo_root, options.report_dir) / self.version
|
||||
|
||||
# -- helpers ---------------------------------------------------------
|
||||
|
||||
def _git(self, *args: str) -> str:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=self.repo_root,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except OSError:
|
||||
return ""
|
||||
return (completed.stdout or "").strip()
|
||||
|
||||
def _execute(self, step_fn) -> None:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
step = step_fn()
|
||||
except Exception as exc: # a crashed step is a failed step, never a silent pass
|
||||
step = Step(name=getattr(step_fn, "__name__", "step").lstrip("_").replace("_", "-"),
|
||||
ok=False, detail=f"crashed: {type(exc).__name__}: {exc}")
|
||||
step.duration_s = round(time.perf_counter() - started, 3)
|
||||
self.steps.append(step)
|
||||
|
||||
flag = "ok " if step.ok else "FAIL"
|
||||
print(f"[{flag}] {step.name} ({step.duration_s:.2f}s)")
|
||||
for line in str(step.detail).splitlines():
|
||||
print(f" {line}")
|
||||
|
||||
if not step.ok and not self.options.keep_going:
|
||||
self.aborted = True
|
||||
print(" stopping: pass --keep-going to collect every failure")
|
||||
|
||||
# -- steps -----------------------------------------------------------
|
||||
|
||||
def _repo_state(self) -> Step:
|
||||
if not (self.repo_root / ".git").exists():
|
||||
return Step("repo-state", False, f"{self.repo_root} is not a git repository")
|
||||
|
||||
commit = self._git("rev-parse", "HEAD")
|
||||
branch = self._git("rev-parse", "--abbrev-ref", "HEAD")
|
||||
porcelain = self._git("status", "--porcelain")
|
||||
dirty = bool(porcelain)
|
||||
self.git = {"commit": commit, "branch": branch, "dirty": dirty}
|
||||
|
||||
if dirty and not self.options.allow_dirty:
|
||||
preview = "\n".join(porcelain.splitlines()[:20])
|
||||
return Step(
|
||||
"repo-state",
|
||||
False,
|
||||
f"working tree is dirty; commit, stash or pass --allow-dirty:\n{preview}",
|
||||
data=self.git,
|
||||
)
|
||||
|
||||
detail = f"{branch} @ {commit[:12]} dirty={dirty} version={self.version} ({self.version_source})"
|
||||
if dirty:
|
||||
detail += " (accepted via --allow-dirty)"
|
||||
return Step("repo-state", True, detail, data=self.git)
|
||||
|
||||
def _version_consistency(self) -> Step:
|
||||
problems: list[str] = []
|
||||
data: dict = {"version": self.version, "source": self.version_source}
|
||||
|
||||
attr = version_mod.dynamic_version_attr(self.repo_root)
|
||||
data["dynamic_attr"] = attr
|
||||
if attr is None:
|
||||
problems.append(
|
||||
"pyproject.toml no longer declares tool.setuptools.dynamic.version.attr"
|
||||
)
|
||||
|
||||
if (self.repo_root / "pyproject.toml").is_file():
|
||||
resolved = get_version(self.repo_root)
|
||||
data["resolved_version"] = resolved
|
||||
if resolved != self.version:
|
||||
problems.append(
|
||||
f"src/orisys/__init__.py __version__ is {resolved!r} but the release "
|
||||
f"version is {self.version!r}"
|
||||
)
|
||||
|
||||
sdk_dirs = version_mod.sdk_versions(self.repo_root)
|
||||
data["sdk_versions"] = sdk_dirs
|
||||
for wheel in version_mod.sdk_wheels(self.repo_root, self.version):
|
||||
found = version_mod.wheel_version(wheel)
|
||||
if found != self.version:
|
||||
problems.append(f"{wheel.name} carries version {found!r}, expected {self.version!r}")
|
||||
|
||||
detail = (
|
||||
f"version={self.version} ({self.version_source}) dynamic_attr={attr}\n"
|
||||
f"SDK/ versions present: {sdk_dirs or 'none'}"
|
||||
)
|
||||
if problems:
|
||||
detail += "\n" + "\n".join(problems)
|
||||
return Step("version-consistency", not problems, detail, data=data)
|
||||
|
||||
def _duplicate_guard(self) -> Step:
|
||||
problems: list[str] = []
|
||||
lines: list[str] = []
|
||||
|
||||
existing = version_mod.sdk_wheels(self.repo_root, self.version)
|
||||
if existing:
|
||||
if self.options.force:
|
||||
lines.append(
|
||||
f"SDK/{self.version}/ already holds {len(existing)} wheel(s); "
|
||||
"overwriting because --force was passed"
|
||||
)
|
||||
else:
|
||||
problems.append(
|
||||
f"SDK/{self.version}/ already holds {len(existing)} wheel(s): "
|
||||
f"{[w.name for w in existing]}. Pass --force to rebuild over them."
|
||||
)
|
||||
else:
|
||||
lines.append(f"SDK/{self.version}/ is empty (no wheel has been staged yet)")
|
||||
|
||||
if self.options.check_pypi:
|
||||
versions, error = version_mod.pypi_released_versions()
|
||||
if error:
|
||||
problems.append(f"PyPI lookup failed: {error}")
|
||||
elif versions is None:
|
||||
problems.append("PyPI lookup returned no version list")
|
||||
elif self.version in versions:
|
||||
problems.append(
|
||||
f"orisys {self.version} is already published on PyPI; a PyPI upload "
|
||||
"cannot be undone. Published: " + ", ".join(versions)
|
||||
)
|
||||
else:
|
||||
lines.append(
|
||||
f"PyPI has no {self.version}; published versions: " + (", ".join(versions) or "none")
|
||||
)
|
||||
else:
|
||||
lines.append("PyPI existence check skipped (pass --check-pypi to enable)")
|
||||
|
||||
detail = "\n".join(lines)
|
||||
if problems:
|
||||
detail += "\n" + "\n".join(problems)
|
||||
return Step("duplicate-guard", not problems, detail)
|
||||
|
||||
def _tests(self) -> Step:
|
||||
if self.options.skip_tests:
|
||||
return Step(
|
||||
"tests",
|
||||
True,
|
||||
"WARNING: test gate SKIPPED via --skip-tests; this run cannot certify a release",
|
||||
data={"status": "skipped"},
|
||||
)
|
||||
|
||||
marker = "not hardware" if self.options.longrun else "not slow and not hardware"
|
||||
self.report_dir.mkdir(parents=True, exist_ok=True)
|
||||
junit = self.report_dir / "junit.xml"
|
||||
command = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"pytest",
|
||||
"-q",
|
||||
"-m",
|
||||
marker,
|
||||
f"--junitxml={junit}",
|
||||
]
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
command, cwd=self.repo_root, capture_output=True, text=True, check=False
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
return Step("tests", False, f"cannot run pytest: {exc}")
|
||||
|
||||
ok = completed.returncode == 0
|
||||
tail = ((completed.stdout or "") + (completed.stderr or "")).strip().splitlines()[-12:]
|
||||
detail = f"pytest -m {marker!r} in {sys.executable}\nexit code {completed.returncode}"
|
||||
if tail:
|
||||
detail += "\n" + "\n".join(tail)
|
||||
return Step("tests", ok, detail, data={"marker": marker, "junit": str(junit)})
|
||||
|
||||
def _bundle_precheck(self) -> Step:
|
||||
if not (self.repo_root / "pyproject.toml").is_file():
|
||||
return Step("bundle-precheck", False, "pyproject.toml not found")
|
||||
|
||||
items = bundle_items(self.repo_root)
|
||||
problems: list[str] = []
|
||||
counts: dict[str, int] = {}
|
||||
for item in items:
|
||||
files = resolve_bundle_source_files(self.repo_root, item)
|
||||
counts[str(item.get("name"))] = len(files)
|
||||
if not files:
|
||||
problems.append(
|
||||
f"bundle item {item.get('name')!r} resolved 0 files; its patterns match nothing"
|
||||
)
|
||||
|
||||
try:
|
||||
verify_required_assets(self.repo_root, items)
|
||||
except FileNotFoundError as exc:
|
||||
problems.append(str(exc))
|
||||
|
||||
detail = "resolved files per bundle item: " + json.dumps(counts)
|
||||
if problems:
|
||||
detail += "\n" + "\n".join(problems)
|
||||
return Step("bundle-precheck", not problems, detail, data={"counts": counts})
|
||||
|
||||
def _discover_wheels(self) -> str | None:
|
||||
"""Populate self.wheels; return an error message when nothing was found."""
|
||||
directory = (
|
||||
Path(self.options.wheel_dir)
|
||||
if self.options.wheel_dir
|
||||
else self.repo_root / "SDK" / self.version
|
||||
)
|
||||
self.wheel_dir = directory
|
||||
if not directory.is_dir():
|
||||
return (
|
||||
f"{directory} does not exist. Build first "
|
||||
"(`python build/run.py wheel`) or pass --wheel-dir."
|
||||
)
|
||||
|
||||
self.wheels = sorted(directory.glob("*.whl"))
|
||||
if not self.wheels:
|
||||
return f"no *.whl found in {directory}. Build first or pass --wheel-dir."
|
||||
return None
|
||||
|
||||
def _wheel_inspection(self) -> Step:
|
||||
problem = self._discover_wheels()
|
||||
if problem:
|
||||
return Step("wheel-inspection", False, problem)
|
||||
|
||||
problems: list[str] = []
|
||||
blocks: list[str] = []
|
||||
for wheel in self.wheels:
|
||||
result = inspect_wheel(
|
||||
wheel,
|
||||
expected_version=self.version,
|
||||
repo_root=self.repo_root,
|
||||
strict_bundle=True,
|
||||
)
|
||||
blocks.append(result.render())
|
||||
if not result.ok:
|
||||
problems.append(
|
||||
f"{wheel.name}: " + ", ".join(check.name for check in result.failures)
|
||||
)
|
||||
|
||||
detail = f"{len(self.wheels)} wheel(s) in {self.wheel_dir}\n" + "\n".join(blocks)
|
||||
if problems:
|
||||
detail += "\nfailed checks:\n" + "\n".join(problems)
|
||||
return Step("wheel-inspection", not problems, detail, data={"count": len(self.wheels)})
|
||||
|
||||
def _platform_token(self) -> str:
|
||||
return "win_amd64" if sys.platform == "win32" else "manylinux"
|
||||
|
||||
def _runtime_targets(self) -> list[tuple[str, Path, Path | None]]:
|
||||
token = self._platform_token()
|
||||
if self.options.all_wheel_pythons:
|
||||
targets: list[tuple[str, Path, Path | None]] = []
|
||||
for tag in ("cp310", "cp311", "cp312"):
|
||||
match = next(
|
||||
(w for w in self.wheels if f"-{tag}-" in w.name and token in w.name), None
|
||||
)
|
||||
if match is None:
|
||||
raise RuntimeError(
|
||||
f"no {tag} {token} wheel among {[w.name for w in self.wheels]}"
|
||||
)
|
||||
executable = version_mod.python_for_tag(tag)
|
||||
if executable is None:
|
||||
raise RuntimeError(
|
||||
f"cannot resolve an interpreter for {tag}; create the conda env "
|
||||
f"py{tag[2:]} or set CONDA_ENVS_ROOT"
|
||||
)
|
||||
targets.append((tag, match, executable))
|
||||
return targets
|
||||
|
||||
tag = f"cp{sys.version_info.major}{sys.version_info.minor}"
|
||||
match = next((w for w in self.wheels if f"-{tag}-" in w.name and token in w.name), None)
|
||||
if match is None:
|
||||
raise RuntimeError(
|
||||
f"no {tag} {token} wheel among {[w.name for w in self.wheels]}; pass "
|
||||
"--all-wheel-pythons to verify every ABI in its own environment, or run from "
|
||||
"a matching interpreter"
|
||||
)
|
||||
return [(tag, match, None)]
|
||||
|
||||
def _wheel_runtime(self) -> Step:
|
||||
if self.options.no_runtime:
|
||||
return Step(
|
||||
"wheel-runtime",
|
||||
True,
|
||||
"WARNING: runtime verification SKIPPED via --no-runtime",
|
||||
data={"status": "skipped"},
|
||||
)
|
||||
|
||||
video = self.options.video or default_verification_video(self.repo_root)
|
||||
if video is None:
|
||||
return Step(
|
||||
"wheel-runtime",
|
||||
False,
|
||||
"no verification clip found. Pass --video, set ORISYS_VERIFY_VIDEO, or commit a "
|
||||
"clip under data/sample/. The runtime check is never silently skipped.",
|
||||
)
|
||||
video = Path(video)
|
||||
if not video.is_file():
|
||||
return Step("wheel-runtime", False, f"verification clip not found: {video}")
|
||||
|
||||
try:
|
||||
targets = self._runtime_targets()
|
||||
except RuntimeError as exc:
|
||||
return Step("wheel-runtime", False, str(exc))
|
||||
|
||||
problems: list[str] = []
|
||||
lines: list[str] = [f"clip: {video}", f"config: {self.options.config_name}"]
|
||||
for tag, wheel, executable in targets:
|
||||
label = f"{tag} {wheel.name}"
|
||||
try:
|
||||
if self.options.no_assets:
|
||||
assets_out = "asset check skipped (--no-assets)"
|
||||
else:
|
||||
assets_out = verify_wheel_assets(wheel, python_executable=executable)
|
||||
runtime_out = verify_wheel_runtime(
|
||||
wheel,
|
||||
video=video,
|
||||
config_name=self.options.config_name,
|
||||
frames=self.options.frames,
|
||||
python_executable=executable,
|
||||
offline=self.options.offline,
|
||||
)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
problems.append(f"{label}: command failed ({exc})")
|
||||
continue
|
||||
except Exception as exc:
|
||||
problems.append(f"{label}: {type(exc).__name__}: {exc}")
|
||||
continue
|
||||
|
||||
lines.append(f"{label}: {assets_out} | frames={runtime_out['frames']} flow={runtime_out['flow_shape']}")
|
||||
self.runtime_records.append({"tag": tag, "wheel": wheel.name, **runtime_out})
|
||||
|
||||
detail = "\n".join(lines)
|
||||
if problems:
|
||||
detail += "\nfailures:\n" + "\n".join(problems)
|
||||
return Step("wheel-runtime", not problems, detail, data={"records": self.runtime_records})
|
||||
|
||||
# -- driver ----------------------------------------------------------
|
||||
|
||||
def run(self) -> int:
|
||||
started_at = _now()
|
||||
started = time.perf_counter()
|
||||
print(f"=== orisys release preflight: version {self.version} ({self.version_source}) ===")
|
||||
print(f"repo: {self.repo_root}")
|
||||
print(f"report: {self.report_dir}")
|
||||
print()
|
||||
|
||||
try:
|
||||
for step_fn in (
|
||||
self._repo_state,
|
||||
self._version_consistency,
|
||||
self._duplicate_guard,
|
||||
self._tests,
|
||||
self._bundle_precheck,
|
||||
self._wheel_inspection,
|
||||
self._wheel_runtime,
|
||||
):
|
||||
self._execute(step_fn)
|
||||
if self.aborted:
|
||||
break
|
||||
finally:
|
||||
self.ok = bool(self.steps) and all(step.ok for step in self.steps) and not self.aborted
|
||||
duration = round(time.perf_counter() - started, 3)
|
||||
payload = {
|
||||
"version": self.version,
|
||||
"version_source": self.version_source,
|
||||
"ok": self.ok,
|
||||
"aborted": self.aborted,
|
||||
"started_at": started_at,
|
||||
"finished_at": _now(),
|
||||
"duration_s": duration,
|
||||
"git": self.git,
|
||||
"interpreter": {
|
||||
"executable": sys.executable,
|
||||
"version": platform.python_version(),
|
||||
"platform": sys.platform,
|
||||
},
|
||||
"options": {key: value for key, value in asdict(self.options).items()
|
||||
if not isinstance(value, Path)},
|
||||
"steps": [asdict(step) for step in self.steps],
|
||||
"wheels": [
|
||||
{
|
||||
"name": wheel.name,
|
||||
"size": wheel.stat().st_size,
|
||||
"sha256": _sha256_file(wheel),
|
||||
}
|
||||
for wheel in self.wheels
|
||||
],
|
||||
}
|
||||
payload["options"]["wheel_dir"] = str(self.options.wheel_dir) if self.options.wheel_dir else None
|
||||
payload["options"]["video"] = str(self.options.video) if self.options.video else None
|
||||
|
||||
json_path, text_path = report_mod.write_report(payload, self.report_dir)
|
||||
print()
|
||||
print(f"report: {json_path}")
|
||||
print(f"report: {text_path}")
|
||||
|
||||
print()
|
||||
print(f"=== preflight {'PASSED' if self.ok else 'FAILED'} ({duration}s) ===")
|
||||
return 0 if self.ok else 1
|
||||
|
||||
|
||||
def run_preflight(options: PreflightOptions, repo_root: Path | None = None) -> int:
|
||||
return Preflight(options, repo_root=repo_root).run()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Structured preflight reports.
|
||||
|
||||
A preflight run writes both a machine-readable ``preflight.json`` (the contract a
|
||||
future publish step will consume and re-verify) and a human ``preflight.txt``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPORTS_RELPATH = Path("build") / "release" / "reports"
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def reports_root(repo_root: Path, override: Path | None = None) -> Path:
|
||||
return Path(override) if override else Path(repo_root) / REPORTS_RELPATH
|
||||
|
||||
|
||||
def render_text(payload: dict) -> str:
|
||||
git = payload.get("git") or {}
|
||||
interpreter = payload.get("interpreter") or {}
|
||||
lines = [
|
||||
f"orisys release preflight :: version {payload.get('version')}",
|
||||
f" result: {'PASS' if payload.get('ok') else 'FAIL'}",
|
||||
f" git: {git.get('branch')} @ {git.get('commit')} (dirty={git.get('dirty')})",
|
||||
f" interpreter: {interpreter.get('version')} at {interpreter.get('executable')}",
|
||||
f" duration: {payload.get('duration_s')}s",
|
||||
"",
|
||||
]
|
||||
|
||||
for step in payload.get("steps", []):
|
||||
flag = "ok " if step.get("ok") else "FAIL"
|
||||
lines.append(f"[{flag}] {step.get('name')} ({step.get('duration_s')}s)")
|
||||
for detail_line in str(step.get("detail") or "").splitlines():
|
||||
lines.append(f" {detail_line}")
|
||||
lines.append("")
|
||||
|
||||
wheels = payload.get("wheels") or []
|
||||
if wheels:
|
||||
lines.append("wheels:")
|
||||
for wheel in wheels:
|
||||
lines.append(
|
||||
f" {wheel.get('name')} {wheel.get('size')} bytes sha256={wheel.get('sha256')}"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
options = payload.get("options") or {}
|
||||
waived = [
|
||||
key
|
||||
for key, value in options.items()
|
||||
if value and key in {"skip_tests", "allow_dirty", "force", "no_runtime", "no_assets"}
|
||||
]
|
||||
if waived:
|
||||
lines.append(f"waived guards: {', '.join(sorted(waived))}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
def write_report(payload: dict, out_dir: Path) -> tuple[Path, Path]:
|
||||
out_dir = Path(out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
payload = {**payload, "schema": SCHEMA_VERSION}
|
||||
json_path = out_dir / "preflight.json"
|
||||
text_path = out_dir / "preflight.txt"
|
||||
|
||||
json_path.write_text(json.dumps(payload, indent=2, sort_keys=False), encoding="utf-8")
|
||||
text_path.write_text(render_text(payload), encoding="utf-8")
|
||||
return json_path, text_path
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Version consistency and duplicate-release guards for the release gate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PYPI_JSON_URL = "https://pypi.org/pypi/orisys/json"
|
||||
|
||||
# orisys-<version>-<pytag>-<abitag>-<platformtag>.whl
|
||||
_WHEEL_NAME_RE = re.compile(r"^orisys-(?P<version>[^-]+)-[^-]+-[^-]+-.+\.whl$")
|
||||
|
||||
|
||||
def wheel_version(wheel_path: Path) -> str | None:
|
||||
match = _WHEEL_NAME_RE.match(Path(wheel_path).name)
|
||||
return match.group("version") if match else None
|
||||
|
||||
|
||||
def sdk_versions(repo_root: Path) -> list[str]:
|
||||
"""Version directory names present under ``SDK/``, in ascending order.
|
||||
|
||||
Only digit-leading names count as versions, so stray directories (``tmp``,
|
||||
``latest``) never appear as releases.
|
||||
"""
|
||||
sdk_root = Path(repo_root) / "SDK"
|
||||
if not sdk_root.is_dir():
|
||||
return []
|
||||
|
||||
return sorted(
|
||||
(
|
||||
entry.name
|
||||
for entry in sdk_root.iterdir()
|
||||
if entry.is_dir() and entry.name[:1].isdigit()
|
||||
),
|
||||
key=_version_sort_key,
|
||||
)
|
||||
|
||||
|
||||
def sdk_wheels(repo_root: Path, version: str) -> list[Path]:
|
||||
"""Wheels already published into ``SDK/<version>/``."""
|
||||
version_dir = Path(repo_root) / "SDK" / version
|
||||
if not version_dir.is_dir():
|
||||
return []
|
||||
return sorted(version_dir.glob("*.whl"))
|
||||
|
||||
|
||||
def dynamic_version_attr(repo_root: Path) -> str | None:
|
||||
"""Return pyproject's configured dynamic version attr (e.g. orisys.__version__)."""
|
||||
from common.pyproject_utils import load_pyproject
|
||||
|
||||
config = (
|
||||
load_pyproject(Path(repo_root))
|
||||
.get("tool", {})
|
||||
.get("setuptools", {})
|
||||
.get("dynamic", {})
|
||||
.get("version")
|
||||
)
|
||||
if isinstance(config, dict):
|
||||
attr = config.get("attr")
|
||||
if isinstance(attr, str):
|
||||
return attr
|
||||
return None
|
||||
|
||||
|
||||
def pypi_released_versions(timeout: float = 20.0) -> tuple[list[str] | None, str | None]:
|
||||
"""Read the published version list from PyPI.
|
||||
|
||||
Returns ``(versions, error)``; ``versions`` is ``None`` when the lookup
|
||||
failed. This is the only network call in the release gate and it is
|
||||
read-only, so it is safe to run before an irreversible upload.
|
||||
"""
|
||||
request = urllib.request.Request(
|
||||
PYPI_JSON_URL,
|
||||
headers={"User-Agent": "orisys-release-preflight", "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
payload = json.load(response)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return [], None
|
||||
return None, f"PyPI returned HTTP {exc.code}"
|
||||
except Exception as exc: # network, DNS, TLS, JSON
|
||||
return None, f"{type(exc).__name__}: {exc}"
|
||||
|
||||
releases = payload.get("releases")
|
||||
if not isinstance(releases, dict):
|
||||
return None, "unexpected PyPI response shape (no 'releases' mapping)"
|
||||
listed = [
|
||||
str(version)
|
||||
for version, files in releases.items()
|
||||
if isinstance(files, list) and files
|
||||
]
|
||||
return sorted(listed, key=_version_sort_key), None
|
||||
|
||||
|
||||
def _version_sort_key(name: str):
|
||||
parts = re.findall(r"\d+", name)
|
||||
return ([int(part) for part in parts] or [0], name)
|
||||
|
||||
|
||||
def conda_envs_root() -> Path | None:
|
||||
"""Locate the conda envs directory the same way build/wheel/win.bat does."""
|
||||
override = os.getenv("CONDA_ENVS_ROOT")
|
||||
if override:
|
||||
path = Path(override)
|
||||
return path if path.is_dir() else None
|
||||
|
||||
home = Path.home()
|
||||
candidates = (
|
||||
home / "anaconda3" / "envs",
|
||||
home / "miniconda3" / "envs",
|
||||
Path(os.getenv("LOCALAPPDATA", "")) / "anaconda3" / "envs",
|
||||
Path(os.getenv("LOCALAPPDATA", "")) / "miniconda3" / "envs",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.is_dir():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def python_for_tag(tag: str, envs_root: Path | None = None) -> Path | None:
|
||||
"""Resolve an interpreter for a wheel tag like ``cp310`` (env ``py310``)."""
|
||||
digits = tag[2:] if tag.startswith("cp") else tag
|
||||
env_name = f"py{digits}"
|
||||
root = envs_root or conda_envs_root()
|
||||
if root is None:
|
||||
return None
|
||||
|
||||
for relative in (
|
||||
Path(env_name) / "python.exe",
|
||||
Path(env_name) / "bin" / "python",
|
||||
):
|
||||
candidate = root / relative
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
Reference in New Issue
Block a user