vinix-ports / tests / combined-feed.py
108 lines · 100 sloc · 5.56 KB · e1adb26f890e7ed302a11b152024a0ee601ccbd9
Raw
1"""Install the latest receipted native packages together and audit their complete root."""
2import argparse
3import csv
4import hashlib
5import re
6import subprocess
7from pathlib import Path
8
9
10def archives(location, arch):
11 if location.is_dir() or location.suffix == ".sha256":
12 receipts = sorted(location.glob("*.sha256")) if location.is_dir() else [location]
13 for receipt in receipts:
14 for line in receipt.read_text().splitlines():
15 digest, name = line.split(maxsplit=1)
16 if name.endswith(".pkg.tar.zst"):
17 if Path(name).name != name:
18 raise ValueError(f"expected a package basename in {receipt}")
19 yield receipt.parent / name, digest
20 else:
21 with location.open() as index:
22 for row in csv.DictReader(index, delimiter="\t"):
23 if Path(row["archive"]).name != row["archive"]:
24 raise ValueError(f"invalid package name in {location}")
25 if row["arch"] not in (arch, "any"):
26 continue
27 path = location.parent / arch / row["archive"]
28 if row["arch"] == "any" and not path.is_file():
29 # Data packages in a single-target feed live in its architecture directory.
30 siblings = [directory / row["archive"] for directory in location.parent.iterdir()
31 if directory.is_dir() and (directory / row["archive"]).is_file()]
32 if not siblings:
33 raise ValueError(f"missing architecture-independent package {row['archive']}")
34 for sibling in siblings:
35 yield sibling, row["sha256"]
36 else:
37 yield path, row["sha256"]
38
39
40def collect(sources, arch):
41 selected = {}
42 for source in sources:
43 for archive, expected in archives(source, arch):
44 if not archive.name.endswith((f"-{arch}.pkg.tar.zst", "-any.pkg.tar.zst")):
45 continue
46 with archive.open("rb") as stream:
47 digest = hashlib.file_digest(stream, "sha256").hexdigest()
48 if digest != expected:
49 raise ValueError(f"checksum mismatch for {archive}")
50 metadata = subprocess.check_output(["bsdtar", "-xOf", archive, ".PKGINFO"], text=True)
51 fields = dict(line.split(" = ", 1) for line in metadata.splitlines() if " = " in line)
52 name, version, machine = (fields[k] for k in ("pkgname", "pkgver", "arch"))
53 if machine not in ("any", arch) or not re.fullmatch(r"[A-Za-z0-9@._+][A-Za-z0-9@._+-]*", name):
54 raise ValueError(f"invalid target package metadata: {archive}")
55 if archive.name != f"{name}-{version}-{machine}.pkg.tar.zst":
56 raise ValueError(f"archive filename does not match its metadata: {archive}")
57 if name in selected:
58 old, old_digest, _ = selected[name]
59 newer = int(subprocess.check_output(["vercmp", version, old], text=True))
60 if newer == 0 and digest != old_digest:
61 raise ValueError(f"distinct archives have the same {name} version {version}")
62 if newer <= 0:
63 continue
64 selected[name] = version, digest, archive
65 if not selected:
66 raise ValueError("no packages with checksums for this architecture")
67 return selected
68
69
70def run(args):
71 args.work.mkdir()
72 selected = collect(args.sources, args.arch)
73 names = sorted(selected)
74 with (args.work / "selection.tsv").open("w") as output:
75 table = csv.writer(output, delimiter="\t", lineterminator="\n")
76 table.writerow(["name", "version", "sha256", "archive"])
77 table.writerows((name, *selected[name]) for name in names)
78 repo, client = args.work / "repo", args.work / "client"
79 with (args.work / "publish.log").open("w") as log:
80 subprocess.run(["feed", "publish", args.keys, repo, args.arch, *[selected[n][2] for n in names]],
81 check=True, stdout=log, stderr=subprocess.STDOUT)
82 if args.publish_only:
83 return
84 install_flags = ["--fakeroot"]
85 if args.cross_sdk:
86 install_flags.append("--cross-sdk")
87 for label, command in [
88 ("install", ["feed", "install", args.keys, repo, args.arch, client, *install_flags, *(args.install or names)]),
89 ("audit", [args.auditor, args.arch, client]),
90 ]:
91 with (args.work / (label + ".log")).open("w") as log:
92 subprocess.run(command, check=True, stdout=log, stderr=subprocess.STDOUT)
93 print((args.work / "audit.log").read_text(), end="")
94
95
96if __name__ == "__main__":
97 parser = argparse.ArgumentParser(description=__doc__)
98 parser.add_argument("arch", choices=["x86_64", "aarch64"])
99 for option in ["keys", "auditor", "work"]:
100 parser.add_argument(option, type=lambda x: Path(x).resolve())
101 parser.add_argument("sources", nargs="+", type=lambda x: Path(x).resolve(),
102 help="artifact directory, individual .sha256 receipt, or signed feed's packages.tsv")
103 mode = parser.add_mutually_exclusive_group()
104 mode.add_argument("--install", metavar="NAME", action="append",
105 help="install this root and its dependencies; repeat for additional roots (default: every package)")
106 mode.add_argument("--publish-only", action="store_true", help="publish the signed repository for a separate clean install")
107 parser.add_argument("--cross-sdk", action="store_true", help="emulate the bitmap font hook on a cross-build SDK")
108 run(parser.parse_args())
109