| 1 | """Order Vinix packages by the dependencies in a signed feed or a native ports tree.""" |
| 2 | import argparse |
| 3 | import csv |
| 4 | import hashlib |
| 5 | import os |
| 6 | import re |
| 7 | import subprocess |
| 8 | from collections import defaultdict |
| 9 | from pathlib import Path |
| 10 | |
| 11 | |
| 12 | def metadata(path, expected, arch): |
| 13 | if Path(path.name).name != expected["archive"] or "/" in expected["archive"]: |
| 14 | raise ValueError(f"invalid archive name {expected['archive']}") |
| 15 | with path.open("rb") as stream: |
| 16 | if hashlib.file_digest(stream, "sha256").hexdigest() != expected["sha256"]: |
| 17 | raise ValueError(f"checksum mismatch for {path}") |
| 18 | raw = subprocess.check_output(["bsdtar", "-xOf", path, ".PKGINFO"], text=True) |
| 19 | values = defaultdict(list) |
| 20 | for line in raw.splitlines(): |
| 21 | if " = " in line: |
| 22 | key, value = line.split(" = ", 1) |
| 23 | values[key].append(value) |
| 24 | if (values["pkgname"] != [expected["name"]] or values["pkgver"] != [expected["version"]] or |
| 25 | values["arch"] not in (["any"], [arch])): |
| 26 | raise ValueError(f"invalid metadata for {path}") |
| 27 | return values |
| 28 | |
| 29 | |
| 30 | def requirement(text): |
| 31 | match = re.fullmatch(r"([^<>=\s]+)(?:(>=|<=|=|<|>)([^<>=\s]+))?", text) |
| 32 | if not match: |
| 33 | raise ValueError(f"invalid dependency expression {text!r}") |
| 34 | return match.groups() |
| 35 | |
| 36 | |
| 37 | def satisfies(version, operator, requested): |
| 38 | if not operator: |
| 39 | return True |
| 40 | if version is None: |
| 41 | return False |
| 42 | result = int(subprocess.check_output(["vercmp", version, requested], text=True)) |
| 43 | return {"=": result == 0, ">=": result >= 0, "<=": result <= 0, |
| 44 | ">": result > 0, "<": result < 0}[operator] |
| 45 | |
| 46 | |
| 47 | def feed_records(directory, arch): |
| 48 | with (directory / "packages.tsv").open() as stream: |
| 49 | for row in csv.DictReader(stream, delimiter="\t"): |
| 50 | yield row["name"], metadata(directory / arch / row["archive"], row, arch) |
| 51 | |
| 52 | |
| 53 | def recipe_records(args): |
| 54 | reader = Path(__file__).resolve().with_name("recipe-metadata.vile") |
| 55 | recipes = sorted(args.source.glob("*/PKGBUILD.vile")) + args.extra_recipe |
| 56 | aliases = {"depends": "depend", "makedepends": "makedepend", "checkdepends": "checkdepend"} |
| 57 | for recipe in recipes: |
| 58 | env = {**os.environ, "VINIX_RECIPE": str(recipe.resolve()), "VPAC_TARGET_ARCH": args.arch} |
| 59 | result = subprocess.run(["vpac", "--recipe-run", reader, "check"], env=env, |
| 60 | text=True, capture_output=True) |
| 61 | if result.returncode: |
| 62 | raise ValueError(f"{recipe}: vpac could not read the metadata:\n{result.stderr}{result.stdout}") |
| 63 | info = defaultdict(list) |
| 64 | for line in result.stdout.splitlines(): |
| 65 | key, value = line.split("\t") |
| 66 | info[aliases.get(key, key)].append(value) |
| 67 | if not info["arch"] or not info["pkgname"]: |
| 68 | raise ValueError(f"missing architecture or package name in {recipe}") |
| 69 | if args.arch not in info["arch"] and "any" not in info["arch"]: |
| 70 | continue |
| 71 | version, = info["pkgver"] |
| 72 | release, = info["pkgrel"] |
| 73 | epoch, = info.get("epoch", ["0"]) |
| 74 | info["pkgver"] = [(epoch + ":" if epoch != "0" else "") + version + "-" + release] |
| 75 | info["source_recipe"] = [recipe.parent.name] |
| 76 | for name in info["pkgname"]: |
| 77 | yield name, info |
| 78 | |
| 79 | |
| 80 | def plan(args): |
| 81 | providers = defaultdict(list) |
| 82 | packages = {} |
| 83 | records = recipe_records(args) if args.recipes else feed_records(args.source, args.arch) |
| 84 | for name, info in records: |
| 85 | if name in packages: |
| 86 | raise ValueError(f"duplicate package {name}") |
| 87 | packages[name] = info |
| 88 | providers[name].append((name, info["pkgver"][0])) |
| 89 | for provide in info["provides"]: |
| 90 | alias, operator, version = requirement(provide) |
| 91 | if operator not in (None, "="): |
| 92 | raise ValueError(f"invalid provides expression {provide!r}") |
| 93 | providers[alias].append((name, version)) |
| 94 | if not packages: |
| 95 | raise ValueError("no target packages") |
| 96 | edges = [] |
| 97 | needs = {name: set() for name in packages} |
| 98 | waiting = set() |
| 99 | for name, info in packages.items(): |
| 100 | for kind in ("depend", "makedepend", "checkdepend"): |
| 101 | for spec in info[kind]: |
| 102 | dependency, operator, requested = requirement(spec) |
| 103 | choices = {pkg for pkg, ver in providers[dependency] if satisfies(ver, operator, requested)} |
| 104 | if dependency in choices: |
| 105 | choices = {dependency} |
| 106 | if len(choices) == 1: |
| 107 | provider, = choices |
| 108 | if provider != name: |
| 109 | needs[name].add(provider) |
| 110 | else: |
| 111 | waiting.add(name) |
| 112 | provider = "missing" if not choices else "choose:" + ",".join(sorted(choices)) |
| 113 | edges.append((name, kind, spec, provider)) |
| 114 | stages = {} |
| 115 | remaining = set(packages) |
| 116 | level = 0 |
| 117 | while ready := {n for n in remaining - waiting if needs[n] <= stages.keys()}: |
| 118 | for name in ready: |
| 119 | stages[name] = level |
| 120 | remaining -= ready |
| 121 | level += 1 |
| 122 | args.output.mkdir() |
| 123 | with (args.output / "edges.tsv").open("x") as stream: |
| 124 | table = csv.writer(stream, delimiter="\t", lineterminator="\n") |
| 125 | table.writerow(["package", "kind", "requirement", "selected_provider"]) |
| 126 | table.writerows(sorted(edges)) |
| 127 | with (args.output / "order.tsv").open("x") as stream: |
| 128 | table = csv.writer(stream, delimiter="\t", lineterminator="\n") |
| 129 | columns = ["stage", "package", "version", "depends_on", "unresolved_packages"] |
| 130 | table.writerow(columns + (["source_recipe"] if args.recipes else [])) |
| 131 | for name in sorted(packages, key=lambda n: (stages.get(n, level), n)): |
| 132 | fields = [stages.get(name, "pending"), name, packages[name]["pkgver"][0], |
| 133 | ",".join(sorted(needs[name])), ",".join(sorted(needs[name] & remaining))] |
| 134 | table.writerow(fields + (packages[name]["source_recipe"] if args.recipes else [])) |
| 135 | print(f"{args.arch}: ordered {len(stages)} of {len(packages)} packages in {level} stages") |
| 136 | if remaining: |
| 137 | raise SystemExit(f"unresolved providers or cycles: {', '.join(sorted(remaining))}; see edges.tsv") |
| 138 | |
| 139 | |
| 140 | if __name__ == "__main__": |
| 141 | parser = argparse.ArgumentParser(description=__doc__) |
| 142 | parser.add_argument("arch", choices=("x86_64", "aarch64")) |
| 143 | parser.add_argument("source", type=Path, help="published feed, or a recipe directory such as ports/ with --recipes") |
| 144 | parser.add_argument("output", type=Path) |
| 145 | parser.add_argument("--recipes", action="store_true", help="read native Vile recipes using vpac") |
| 146 | parser.add_argument("--extra-recipe", type=Path, default=[], action="append", |
| 147 | help="include an externally prepared recipe such as vinix-keyring") |
| 148 | args = parser.parse_args() |
| 149 | if args.extra_recipe and not args.recipes: |
| 150 | parser.error("--extra-recipe requires --recipes") |
| 151 | plan(args) |
| 152 | |