The wheelhouse's own folder holds the candidate's wheels of invisible-core and invisible-playwright, built from core_ref and wrapper_ref; at an equal version they have the file names of the published ones. With real pip, two --find-links and --require-hashes take the first local file of a name and fail on a hash mismatch, they do not choose by hash. - install: the gate lock's dependencies from the wheelhouse, then the two published wheels from <house>/published ONLY (one --find-links per pip call, --no-deps, by the hashes of ci/py-lock/published.txt), then pip check over the venv with the set's python: red, with what pip reports, when a requirement of the published wheels is not met. The wheel of each package is chosen by the sha256 the lock holds (a file with the name and another hash is refused, naming both) and recorded with the digest of its package files in <venv>/published-set.json. - verify: reads that record and the disk. It names the file installed (wheel name, sha256), is red when that sha256 is not one the lock holds (naming both), and when a file of the package on disk is not, byte for byte, the wheel's. A version says nothing of which file is installed. - tests (real pip, offline, wheels made with zipfile): the same name and version in the house root (the candidate's) and in published/ installs the published one and verify is green; a venv holding the candidate's wheels is red naming the file, its sha256 and the lock's; a record that says published over candidate bytes is red; a lock naming neither is red; a published wheel requiring what the house lacks is red at pip check, the normal house green. 42 tests in the file (+6), the rows of the whole unit suite raised by 6. Red on the old install: the real-pip same-name test fails with pip's "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE" on the candidate's wheel of the same name (8 of the 42 fail on the previous script).
443 lines
25 KiB
Python
443 lines
25 KiB
Python
#!/usr/bin/env python3
|
|
"""The PUBLISHED SET: the control side of every A/B oracle, exactly as a user installs it.
|
|
|
|
An A/B oracle holds a candidate against the engine published before it. That engine is not a binary alone: it is launched by the core that declares the prefs it
|
|
requires (the engine refuses a launch whose declarations are not the ones it was built for), and that core is the one the published wrapper pins. So the control
|
|
side is a SET, and nothing in it is chosen by hand: the last published `invisible-playwright` on PyPI pins its core exactly, and that core's seal pins its engine.
|
|
|
|
ci/py-lock/published.txt the set as a lock (ci-03): the wrapper and the core it pins, each at an exact version with the sha256 of EVERY file of that
|
|
version on the index, and the requirements each declares (the headers), which the gate's own lock must satisfy.
|
|
python scripts/ci_published_set.py resolve [--write] reads PyPI (the only command that does), prints the lock, or writes it
|
|
python scripts/ci_published_set.py check PyPI's last release against the committed lock: red when they differ (.github/workflows/published-set.yml)
|
|
python scripts/ci_published_set.py install --house DIR --venv DIR [--lock FILE]
|
|
OFFLINE and hash-checked: a venv of its own with the gate's third-party lock (DIR/lock.txt), then the two wheels of the set by their hashes
|
|
(`--no-deps`, from DIR/published: the wheelhouse of the run, whose job downloaded the files this lock names there). Prints the venv's python.
|
|
DIR itself holds the candidate's wheels of the same two packages (built from core_ref and wrapper_ref, and at an equal version with the SAME
|
|
file names): the set never takes a file of invisible-core or invisible-playwright from DIR, only from DIR/published.
|
|
python scripts/ci_published_set.py verify --python PY what that python imports is the lock's set, from its own venv and from nowhere else
|
|
python scripts/ci_published_set.py fetch --work DIR (run BY the set's python) fetches the engine the way a user's core does: its own seal
|
|
python scripts/ci_published_set.py tag (run BY the set's python) the tag its seal names
|
|
|
|
Exit codes: 0 green, 1 red (a finding), 2 the command could not run.
|
|
|
|
The candidate's side is untouched: its core is core_ref's, its wrapper is wrapper_ref's, its engine is the candidate.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import urllib.request
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
LOCK_PATH = ROOT / "ci" / "py-lock" / "published.txt"
|
|
GATE_LOCK_PATH = ROOT / "ci" / "py-lock" / "gate.txt"
|
|
#: Where the wheelhouse of the run keeps the two wheels of the published set (the wheelhouse's own folder holds the candidate's wheels of the same names).
|
|
PUBLISHED_DIR = "published"
|
|
#: What install writes in the venv: which wheel of each package it installed (file name, sha256) and the digest of every file of the package as that wheel holds it. verify reads it
|
|
#: and holds it to the lock and to the disk: the lock and the candidate's lock can name the same package at the same version, so a version says nothing of WHICH file is installed.
|
|
RECORD_FILE = "published-set.json"
|
|
RECORD_FORMAT = "published-set-installed/1"
|
|
|
|
WRAPPER = "invisible-playwright"
|
|
CORE = "invisible-core"
|
|
INDEX = "https://pypi.org/pypi"
|
|
|
|
HASH_RE = re.compile(r"^--hash=sha256:([0-9a-f]{64})$")
|
|
PIN_RE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==([0-9][A-Za-z0-9.!+_-]*)$")
|
|
HEADER = ("The PUBLISHED SET, the control side of the A/B oracles (scripts/ci_published_set.py): the last published invisible-playwright and the invisible-core it pins "
|
|
"(its seal pins the engine). Written by `python scripts/ci_published_set.py resolve --write`; .github/workflows/published-set.yml keeps it equal to the index.")
|
|
|
|
#: What a process of the published set must not inherit from the candidate's job: anything that makes its python import another wrapper or another core, or run
|
|
#: another engine's seal. The set is what its venv holds, as it is on a user's machine.
|
|
SET_LEAKS = ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONUSERBASE", "VIRTUAL_ENV", "INVISIBLE_SEAL_FILE", "INVISIBLE_CORE_PIN", "INVISIBLE_CORE_AUTOFIX",
|
|
"INVISIBLE_PLAYWRIGHT_ENGINE_DIR")
|
|
|
|
|
|
def norm(name: str) -> str:
|
|
return re.sub(r"[-_.]+", "-", name).lower()
|
|
|
|
|
|
# -
|
|
# The lock: text <-> parts (pure, no network)
|
|
|
|
def _release_parts(release: dict, name: str) -> tuple:
|
|
"""(version, [sha256 of every file], [requirements without extras]) of a PyPI release document (`/pypi/<name>/<version>/json`)."""
|
|
info = release.get("info") or {}
|
|
if norm(info.get("name") or "") != norm(name):
|
|
raise ValueError("the document is of %r, not %s" % (info.get("name"), name))
|
|
files = [f for f in release.get("urls") or [] if not f.get("yanked")]
|
|
hashes = sorted({(f.get("digests") or {}).get("sha256", "") for f in files})
|
|
if not files or not all(re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes):
|
|
raise ValueError("%s %s has no file with a sha256 on the index" % (name, info.get("version")))
|
|
if not any(f.get("packagetype") == "bdist_wheel" for f in files):
|
|
raise ValueError("%s %s has no wheel on the index" % (name, info.get("version")))
|
|
requires = [r for r in (info.get("requires_dist") or []) if "extra ==" not in r]
|
|
return info["version"], hashes, requires
|
|
|
|
|
|
def core_pin_of(requires: list) -> str:
|
|
"""The version of `invisible-core==X` among the requirements of the wrapper; ValueError when there is not exactly one exact pin."""
|
|
pins = []
|
|
for r in requires:
|
|
m = re.fullmatch(r"\s*invisible[-_.]core\s*==\s*([0-9][A-Za-z0-9.!+_-]*)\s*(?:;.*)?", r)
|
|
if m:
|
|
pins.append(m.group(1))
|
|
if len(pins) != 1:
|
|
raise ValueError("the published wrapper does not pin invisible-core exactly once with `==` (it declares %s)" % (requires or "nothing"))
|
|
return pins[0]
|
|
|
|
|
|
def lock_text(wrapper_release: dict, core_release: dict) -> str:
|
|
version, hashes, requires = _release_parts(wrapper_release, WRAPPER)
|
|
core_version, core_hashes, core_requires = _release_parts(core_release, CORE)
|
|
pin = core_pin_of(requires)
|
|
if pin != core_version:
|
|
raise ValueError("%s %s pins invisible-core==%s but the core document is of %s" % (WRAPPER, version, pin, core_version))
|
|
others = [r for r in requires if not re.match(r"\s*invisible[-_.]core\b", r, re.I)]
|
|
out = ["# " + HEADER,
|
|
"# wrapper-requires: " + " | ".join(sorted(others)),
|
|
"# core-requires: " + " | ".join(sorted(core_requires))]
|
|
for name, v, hs in ((CORE, core_version, core_hashes), (WRAPPER, version, hashes)):
|
|
out.append("%s==%s \\" % (name, v))
|
|
out.append(" \\\n".join(" --hash=sha256:" + h for h in hs))
|
|
return "\n".join(out) + "\n"
|
|
|
|
|
|
def parse_lock(text: str) -> dict:
|
|
"""{"wrapper": (version, hashes), "core": (version, hashes), "wrapper_requires": [...], "core_requires": [...]}; ValueError names what is wrong.
|
|
Every entry is `name==version` with at least one sha256: no range, no URL, no entry without a hash."""
|
|
meta, entries, current = {}, {}, None
|
|
joined = text.replace("\\\n", " ")
|
|
for raw in joined.splitlines():
|
|
line = raw.strip()
|
|
if not line:
|
|
continue
|
|
m = re.match(r"^#\s*(wrapper-requires|core-requires):\s*(.*)$", line)
|
|
if m:
|
|
meta[m.group(1)] = [r.strip() for r in m.group(2).split(" | ") if r.strip()]
|
|
continue
|
|
if line.startswith("#"):
|
|
continue
|
|
parts = line.split()
|
|
pin = PIN_RE.match(parts[0])
|
|
if not pin:
|
|
raise ValueError("a line that is not `name==version --hash=sha256:...`: %r" % line[:80])
|
|
hashes = []
|
|
for p in parts[1:]:
|
|
h = HASH_RE.match(p)
|
|
if not h:
|
|
raise ValueError("%s: %r is not a --hash=sha256:<64 hex>" % (parts[0], p[:40]))
|
|
hashes.append(h.group(1))
|
|
if not hashes:
|
|
raise ValueError("%s has no hash: an entry without a hash is an unchecked install" % parts[0])
|
|
current = norm(pin.group(1))
|
|
if current in entries:
|
|
raise ValueError("%s is listed twice" % current)
|
|
entries[current] = (pin.group(2), sorted(hashes))
|
|
if sorted(entries) != sorted([CORE, WRAPPER]):
|
|
raise ValueError("the lock holds %s, it must hold exactly %s and %s" % (sorted(entries), CORE, WRAPPER))
|
|
for key in ("wrapper-requires", "core-requires"):
|
|
if key not in meta:
|
|
raise ValueError("the header line `# %s:` is missing" % key)
|
|
return {"wrapper": entries[WRAPPER], "core": entries[CORE], "wrapper_requires": meta["wrapper-requires"], "core_requires": meta["core-requires"]}
|
|
|
|
|
|
def locked_versions(gate_text: str) -> dict:
|
|
"""{normalized name: version} of the pinned entries of a lock (ci/py-lock/gate.txt)."""
|
|
out = {}
|
|
for line in gate_text.replace("\\\n", " ").splitlines():
|
|
m = PIN_RE.match(line.split()[0]) if line.strip() and not line.lstrip().startswith("#") else None
|
|
if m:
|
|
out[norm(re.sub(r"\[.*\]", "", m.group(1)))] = m.group(2)
|
|
return out
|
|
|
|
|
|
def problems_of_lock(parsed: dict, gate_text: str) -> list:
|
|
"""What makes the set not installable, offline, over the gate's lock: the wrapper's pin of the core is not the core in the lock, or a requirement of either is
|
|
not met by the third-party package the gate's lock holds (the venv of the set is the gate's lock plus these two wheels, `--no-deps`)."""
|
|
from packaging.requirements import Requirement # the gate lock installs it (pytest needs it); resolve/check do not come here
|
|
|
|
problems = []
|
|
try:
|
|
pin = core_pin_of(parsed["wrapper_requires"] + ["%s==%s" % (CORE, parsed["core"][0])])
|
|
if pin != parsed["core"][0]:
|
|
problems.append("the lock names core %s" % parsed["core"][0])
|
|
except ValueError as e:
|
|
problems.append(str(e))
|
|
held = locked_versions(gate_text)
|
|
for owner, requires in (("the published wrapper", parsed["wrapper_requires"]), ("the published core", parsed["core_requires"])):
|
|
for text in requires:
|
|
req = Requirement(text)
|
|
if req.marker is not None and not req.marker.evaluate({"extra": ""}):
|
|
continue
|
|
version = held.get(norm(req.name))
|
|
if version is None:
|
|
problems.append("%s requires %s: the gate's lock (ci/py-lock/gate.txt) does not hold it, so the set cannot be installed offline" % (owner, text))
|
|
elif not req.specifier.contains(version, prereleases=True):
|
|
problems.append("%s requires %s: the gate's lock holds %s==%s" % (owner, text, req.name, version))
|
|
return problems
|
|
|
|
|
|
# -
|
|
# The index (the only network here)
|
|
|
|
def fetch_json(url: str) -> dict:
|
|
request = urllib.request.Request(url, headers={"User-Agent": "ci-published-set"})
|
|
with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - the index of the package, https
|
|
return json.loads(response.read().decode("utf-8"))
|
|
|
|
|
|
def resolve(get=fetch_json) -> str:
|
|
"""The lock of the last published set: PyPI's latest release of the wrapper, and the core that wrapper pins."""
|
|
latest = get("%s/%s/json" % (INDEX, WRAPPER))
|
|
version = (latest.get("info") or {}).get("version")
|
|
if not version:
|
|
raise ValueError("the index names no latest version of %s" % WRAPPER)
|
|
wrapper = get("%s/%s/%s/json" % (INDEX, WRAPPER, version))
|
|
pin = core_pin_of(_release_parts(wrapper, WRAPPER)[2])
|
|
return lock_text(wrapper, get("%s/%s/%s/json" % (INDEX, CORE, pin)))
|
|
|
|
|
|
def check(get=fetch_json, path: Path = LOCK_PATH) -> list:
|
|
"""[] when the committed lock is the index's last release; else the lines that say how it differs (and how to fix it)."""
|
|
committed = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
try:
|
|
wanted = resolve(get)
|
|
except (ValueError, OSError) as e:
|
|
return ["the index could not be read or is not what a release is: %s" % e]
|
|
if committed == wanted:
|
|
return []
|
|
old = parse_lock(committed) if committed else None
|
|
new = parse_lock(wanted)
|
|
now = "%s %s + %s %s" % (WRAPPER, new["wrapper"][0], CORE, new["core"][0])
|
|
was = "%s %s + %s %s" % (WRAPPER, old["wrapper"][0], CORE, old["core"][0]) if old else "nothing"
|
|
return ["%s holds %s but the index's last release is %s. Fix: python scripts/ci_published_set.py resolve --write, and commit it. "
|
|
"Rule: the control side of an A/B is the last published set" % (path.name, was, now)]
|
|
|
|
|
|
# -
|
|
# The venv of the set (offline) and what it must be
|
|
|
|
def venv_python(venv: Path) -> Path:
|
|
return venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
|
|
|
|
|
def clean_env(extra: dict | None = None) -> dict:
|
|
env = {k: v for k, v in os.environ.items() if k not in SET_LEAKS}
|
|
env.update(extra or {})
|
|
return env
|
|
|
|
|
|
def install(house: Path, venv: Path, lock: Path = LOCK_PATH, run=subprocess.run) -> Path:
|
|
"""A venv of its own: the gate's third-party lock from the wheelhouse (`house/lock.txt`, the lock of the run), then the two wheels of the set by their hashes, from
|
|
`house/published` ONLY. Offline: `--no-index` and `--require-hashes` on both; the two are installed `--no-deps` because the first step holds everything they need.
|
|
|
|
The wheelhouse's own folder holds the candidate's wheels of invisible-core and invisible-playwright, built from core_ref and wrapper_ref; at an equal version they have
|
|
the file names of the published ones, so the published ones live in their own folder and are the only place the second step looks: a wheel of ours taken from the wheelhouse
|
|
would be the candidate's core in the control's venv, or a hash refused. pip never sees the wheelhouse's folder and `published/` in one call: with two `--find-links` it takes
|
|
the first local file of a name and fails on a hash mismatch, it does not choose by hash. Then `pip check` over the venv: red, with what pip reports, when a requirement of
|
|
the two wheels is not met."""
|
|
parse_lock(lock.read_text(encoding="utf-8")) # a lock that does not read is no install
|
|
house_lock = house / "lock.txt"
|
|
if not house_lock.is_file():
|
|
raise FileNotFoundError("the wheelhouse %s has no lock.txt (the gate's lock): it is not a py-deps wheelhouse" % house)
|
|
published = house / PUBLISHED_DIR
|
|
if not published.is_dir():
|
|
raise FileNotFoundError("the wheelhouse %s has no %s/ folder: the two wheels of the published set (the files ci/py-lock/published.txt names) are kept there, "
|
|
"apart from the candidate's wheels of the same names" % (house, PUBLISHED_DIR))
|
|
parsed = parse_lock(lock.read_text(encoding="utf-8"))
|
|
chosen = {name: published_wheel(published, name, *parsed[key]) for key, name in (("core", CORE), ("wrapper", WRAPPER))}
|
|
run([sys.executable, "-m", "venv", str(venv)], check=True)
|
|
python = str(venv_python(venv))
|
|
base = [python, "-m", "pip", "install", "--quiet", "--no-index", "--require-hashes"]
|
|
run(base + ["--find-links", str(house), "-r", str(house_lock)], check=True, env=clean_env())
|
|
run(base + ["--find-links", str(published), "--no-deps", "-r", str(lock)], check=True, env=clean_env())
|
|
# `--no-deps` installs the two wheels without looking at what they declare: pip check does, over the whole venv (the third-party lock and the two wheels).
|
|
checked = run([python, "-m", "pip", "check"], capture_output=True, text=True, env=clean_env())
|
|
if checked.returncode != 0:
|
|
raise RuntimeError("pip check of the published set's venv %s is red (the requirements of the published wheels are not met by the wheelhouse's dependencies): %s"
|
|
% (venv, (checked.stdout + checked.stderr).strip()[-1500:]))
|
|
write_record(venv, chosen)
|
|
return venv_python(venv)
|
|
|
|
|
|
def file_digest(data: bytes) -> str:
|
|
"""The digest of a file as a wheel's RECORD writes it: `sha256=<urlsafe base64, no padding>`."""
|
|
return "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
|
|
|
|
|
|
def published_wheel(published: Path, name: str, version: str, hashes: list) -> tuple:
|
|
"""(path, sha256) of the wheel of `name` `version` in `published` whose sha256 is one the lock holds. FileNotFoundError names what was there and what the lock holds."""
|
|
stem = name.replace("-", "_").lower() + "-" + version + "-"
|
|
seen = []
|
|
for path in sorted(published.glob("*.whl")):
|
|
if path.name.lower().startswith(stem):
|
|
sha = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
if sha in hashes:
|
|
return path, sha
|
|
seen.append("%s sha256 %s" % (path.name, sha))
|
|
raise FileNotFoundError("%s %s: no wheel in %s has a sha256 the lock (ci/py-lock/published.txt) holds (%s); there %s"
|
|
% (name, version, published, ", ".join(hashes), "is " + "; ".join(seen) if seen else "is none of that name"))
|
|
|
|
|
|
def package_digests(wheel: Path, package: str) -> dict:
|
|
"""{path: digest} of every file of the package `package` in the wheel, taken from the bytes of the wheel (its RECORD is not believed)."""
|
|
with zipfile.ZipFile(wheel) as z:
|
|
return {n: file_digest(z.read(n)) for n in sorted(z.namelist()) if n.startswith(package + "/") and not n.endswith("/")}
|
|
|
|
|
|
def write_record(venv: Path, chosen: dict) -> Path:
|
|
"""`chosen` is {distribution: (wheel path, sha256)}: what was installed into `venv`, written where verify reads it."""
|
|
packages = {name: {"wheel": path.name, "sha256": sha, "files": package_digests(path, name.replace("-", "_"))} for name, (path, sha) in chosen.items()}
|
|
target = Path(venv) / RECORD_FILE
|
|
Path(venv).mkdir(parents=True, exist_ok=True)
|
|
target.write_text(json.dumps({"format": RECORD_FORMAT, "packages": packages}, sort_keys=True, indent=1) + "\n", encoding="utf-8", newline="\n")
|
|
return target
|
|
|
|
|
|
def installed_problems(prefix: str, parsed: dict, site_files: dict) -> list:
|
|
"""What the record of the venv `prefix` says was installed, against the lock and against the disk. `site_files` is {distribution: the folder that holds its package}.
|
|
A package the record names with a sha256 the lock does not hold is red, naming the file and both hashes; so is a file of the package that is not, byte for byte, the wheel's."""
|
|
path = Path(prefix) / RECORD_FILE
|
|
if not path.is_file():
|
|
return ["%s has no %s: nothing says which wheel of invisible-core and invisible-playwright was installed (install writes it); the same version can be a "
|
|
"different file (the candidate's wheels have the names of the published ones)" % (prefix, RECORD_FILE)]
|
|
record = json.loads(path.read_text(encoding="utf-8"))
|
|
problems = []
|
|
for key, name in (("core", CORE), ("wrapper", WRAPPER)):
|
|
entry = (record.get("packages") or {}).get(name)
|
|
if not entry:
|
|
problems.append("%s: the record of the venv does not name the wheel it installed" % name)
|
|
continue
|
|
lock_hashes = parsed[key][1]
|
|
if entry["sha256"] not in lock_hashes:
|
|
problems.append("%s: the file installed is %s with sha256 %s, and ci/py-lock/published.txt holds %s (the published set is %s %s)"
|
|
% (name, entry["wheel"], entry["sha256"], ", ".join(lock_hashes), name, parsed[key][0]))
|
|
for rel, digest in sorted(entry["files"].items()):
|
|
target = Path(site_files[name]) / rel
|
|
actual = file_digest(target.read_bytes()) if target.is_file() else "missing"
|
|
if actual != digest:
|
|
problems.append("%s: %s on disk is %s, the wheel %s (sha256 %s) holds %s" % (name, rel, actual, entry["wheel"], entry["sha256"], digest))
|
|
break
|
|
return problems
|
|
|
|
|
|
IDENTITY_CODE = """
|
|
import importlib.metadata as md, json, sys
|
|
import invisible_core, invisible_playwright
|
|
from invisible_core.seal import active_seal
|
|
seal = active_seal()
|
|
print(json.dumps({"prefix": sys.prefix, "core": md.version("invisible-core"), "core_version": invisible_core.__version__, "core_file": invisible_core.__file__,
|
|
"wrapper": md.version("invisible-playwright"), "wrapper_file": invisible_playwright.__file__, "seal_tag": seal.tag, "seal_local": seal.is_local}))
|
|
"""
|
|
|
|
|
|
def identity(python: str, run=subprocess.run) -> dict:
|
|
"""What `python` is when it imports the set: versions, files and the tag of the seal its core carries (read in isolated mode, with no variable of the job)."""
|
|
done = run([python, "-I", "-c", IDENTITY_CODE], capture_output=True, text=True, env=clean_env(), timeout=120)
|
|
if done.returncode != 0:
|
|
raise RuntimeError("%s could not import the published set (exit %s): %s" % (python, done.returncode, (done.stderr or done.stdout)[-800:]))
|
|
return json.loads(done.stdout.strip().splitlines()[-1])
|
|
|
|
|
|
def verify(python: str, lock: Path = LOCK_PATH, run=subprocess.run) -> list:
|
|
"""[] when `python` runs the lock's wrapper and the lock's core, both from its own prefix, under the seal its core was published with, and the files they are made of
|
|
are the wheels the lock's sha256 name (read from the record install wrote and from the disk, never assumed from the version)."""
|
|
parsed = parse_lock(lock.read_text(encoding="utf-8"))
|
|
ident = identity(python, run)
|
|
problems = []
|
|
if ident["wrapper"] != parsed["wrapper"][0] or not ident["wrapper_file"].startswith(ident["prefix"]):
|
|
problems.append("the wrapper it runs is %s from %s, the set says %s from its own venv" % (ident["wrapper"], ident["wrapper_file"], parsed["wrapper"][0]))
|
|
if ident["core"] != parsed["core"][0] or ident["core_version"] != parsed["core"][0] or not ident["core_file"].startswith(ident["prefix"]):
|
|
problems.append("the core it runs is %s (reports %s) from %s, the set says %s from its own venv"
|
|
% (ident["core"], ident["core_version"], ident["core_file"], parsed["core"][0]))
|
|
if ident["seal_local"]:
|
|
problems.append("its core runs under a local seal: a published core carries a release seal")
|
|
problems += installed_problems(ident["prefix"], parsed, {CORE: str(Path(ident["core_file"]).parent.parent), WRAPPER: str(Path(ident["wrapper_file"]).parent.parent)})
|
|
return problems
|
|
|
|
|
|
# -
|
|
# What the set's own python does (the commands below are run BY it: they import the published core)
|
|
|
|
def fetch(work: Path) -> dict:
|
|
"""The engine of the core this python has, fetched the way a user's core fetches it: its own seal, its own download, its own verification."""
|
|
from invisible_core import download
|
|
from invisible_core.seal import active_seal
|
|
|
|
work = Path(work)
|
|
os.environ[download.ENGINE_DIR_ENV] = str(work / "engines")
|
|
seal = active_seal()
|
|
binary = download.ensure_binary()
|
|
return {"binary": str(binary), "tag": seal.tag, "describe": seal.describe()}
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
|
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
r = sub.add_parser("resolve")
|
|
r.add_argument("--write", action="store_true")
|
|
sub.add_parser("check")
|
|
i = sub.add_parser("install")
|
|
i.add_argument("--house", type=Path, required=True)
|
|
i.add_argument("--venv", type=Path, required=True)
|
|
i.add_argument("--lock", type=Path, default=LOCK_PATH)
|
|
v = sub.add_parser("verify")
|
|
v.add_argument("--python", required=True)
|
|
v.add_argument("--lock", type=Path, default=LOCK_PATH)
|
|
f = sub.add_parser("fetch")
|
|
f.add_argument("--work", type=Path, required=True)
|
|
sub.add_parser("tag")
|
|
args = ap.parse_args(argv)
|
|
try:
|
|
if args.cmd == "resolve":
|
|
text = resolve()
|
|
if args.write:
|
|
LOCK_PATH.write_text(text, encoding="utf-8", newline="\n")
|
|
print("wrote %s" % LOCK_PATH)
|
|
else:
|
|
sys.stdout.write(text)
|
|
return 0
|
|
if args.cmd == "check":
|
|
problems = check()
|
|
print("\n".join("FAIL " + p for p in problems) if problems else "OK the committed published set is the index's last release")
|
|
return 1 if problems else 0
|
|
if args.cmd == "install":
|
|
python = install(args.house, args.venv, args.lock)
|
|
problems = verify(str(python), args.lock)
|
|
for name, entry in sorted(json.loads((args.venv / RECORD_FILE).read_text(encoding="utf-8"))["packages"].items()):
|
|
print("installed %s: %s sha256 %s" % (name, entry["wheel"], entry["sha256"]), file=sys.stderr)
|
|
if problems:
|
|
print("\n".join("FAIL " + p for p in problems))
|
|
return 1
|
|
print(python)
|
|
return 0
|
|
if args.cmd == "verify":
|
|
problems = verify(args.python, args.lock)
|
|
print("\n".join("FAIL " + p for p in problems) if problems else "OK")
|
|
return 1 if problems else 0
|
|
if args.cmd == "fetch":
|
|
print(json.dumps(fetch(args.work)))
|
|
return 0
|
|
if args.cmd == "tag":
|
|
from invisible_core.seal import active_seal
|
|
|
|
print(active_seal().tag)
|
|
return 0
|
|
except (ValueError, OSError, RuntimeError, subprocess.CalledProcessError) as e:
|
|
print("ERROR %s: %s" % (type(e).__name__, e))
|
|
return 2
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|