213 lines
8.1 KiB
Python
Executable File
213 lines
8.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Create one deterministic, product-independent Echoion component package."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
from types import ModuleType
|
|
from typing import Any, NoReturn
|
|
|
|
|
|
GIT_SHA = re.compile(r"^[0-9a-f]{40}$")
|
|
HASH = re.compile(r"^(?:sha256:[0-9a-f]{64}|git-sha1:[0-9a-f]{40})$")
|
|
SEMVER = re.compile(
|
|
r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
|
r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
|
|
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$"
|
|
)
|
|
TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$")
|
|
RELEASE_BUILD_TYPE = "RelWithDebInfo"
|
|
|
|
|
|
def fail(message: str) -> NoReturn:
|
|
raise SystemExit(f"package-component: {message}")
|
|
|
|
|
|
def load_packaging_helpers() -> ModuleType:
|
|
path = Path(__file__).with_name("package-components.py")
|
|
specification = importlib.util.spec_from_file_location(
|
|
"echoion_package_components", path
|
|
)
|
|
if specification is None or specification.loader is None:
|
|
fail(f"cannot load shared packaging helpers from {path}")
|
|
module = importlib.util.module_from_spec(specification)
|
|
specification.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def load_json_object(path: Path, label: str) -> dict[str, Any]:
|
|
try:
|
|
value = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
|
fail(f"cannot read {label} {path}: {error}")
|
|
if not isinstance(value, dict):
|
|
fail(f"{label} must be a JSON object")
|
|
return value
|
|
|
|
|
|
def require_debug_information(root: Path) -> None:
|
|
readelf = shutil.which("readelf")
|
|
if readelf is None:
|
|
fail("readelf is required to verify RelWithDebInfo artifacts")
|
|
for path in sorted(root.rglob("*")):
|
|
if path.is_symlink() or not path.is_file():
|
|
continue
|
|
try:
|
|
with path.open("rb") as stream:
|
|
is_elf = stream.read(4) == b"\x7fELF"
|
|
except OSError as error:
|
|
fail(f"cannot inspect {path}: {error}")
|
|
if not is_elf:
|
|
continue
|
|
completed = subprocess.run(
|
|
[readelf, "-SW", os.fspath(path)],
|
|
check=False,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
env={**os.environ, "LC_ALL": "C"},
|
|
)
|
|
if completed.returncode != 0:
|
|
message = completed.stderr.strip() or completed.stdout.strip()
|
|
fail(f"readelf failed for {path.relative_to(root)}: {message}")
|
|
if re.search(r"\]\s+\.(?:z)?debug_info\s", completed.stdout) is None:
|
|
fail(
|
|
f"ELF {path.relative_to(root)} has no debug information; "
|
|
f"expected a {RELEASE_BUILD_TYPE} artifact"
|
|
)
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--registry", type=Path, default=Path("components.json"))
|
|
parser.add_argument("--component", required=True)
|
|
parser.add_argument("--package-root", type=Path, required=True)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
parser.add_argument("--component-version", required=True)
|
|
parser.add_argument(
|
|
"--product-compatibility", default=">=2.0.0 <3.0.0"
|
|
)
|
|
parser.add_argument("--source-sha", required=True)
|
|
parser.add_argument("--source-tree-hash", required=True)
|
|
parser.add_argument("--abi-hash")
|
|
parser.add_argument("--build-dependencies", type=Path)
|
|
parser.add_argument(
|
|
"--build-type", choices=(RELEASE_BUILD_TYPE,), required=True
|
|
)
|
|
parser.add_argument("--platform", default="linux")
|
|
parser.add_argument("--architecture", default="x86_64")
|
|
parser.add_argument(
|
|
"--toolchain-contract",
|
|
default="linux-x86_64-glibc-2.35-cxx26",
|
|
)
|
|
arguments = parser.parse_args()
|
|
|
|
if not TOKEN.fullmatch(arguments.component):
|
|
fail("invalid component ID")
|
|
if not SEMVER.fullmatch(arguments.component_version):
|
|
fail("--component-version must be canonical SemVer")
|
|
if (
|
|
not arguments.product_compatibility
|
|
or len(arguments.product_compatibility) > 256
|
|
or any(
|
|
character in arguments.product_compatibility
|
|
for character in "\r\n\0"
|
|
)
|
|
):
|
|
fail("--product-compatibility is invalid")
|
|
if not GIT_SHA.fullmatch(arguments.source_sha):
|
|
fail("--source-sha must be a full lowercase Git SHA")
|
|
if not HASH.fullmatch(arguments.source_tree_hash):
|
|
fail("--source-tree-hash must be a supported content hash")
|
|
if arguments.abi_hash is not None and not re.fullmatch(
|
|
r"sha256:[0-9a-f]{64}", arguments.abi_hash
|
|
):
|
|
fail("--abi-hash must be a SHA-256 hash")
|
|
for label, value in (
|
|
("--platform", arguments.platform),
|
|
("--architecture", arguments.architecture),
|
|
("--toolchain-contract", arguments.toolchain_contract),
|
|
):
|
|
if not TOKEN.fullmatch(value):
|
|
fail(f"{label} is invalid")
|
|
|
|
registry = load_json_object(arguments.registry, "component registry")
|
|
definitions = registry.get("components")
|
|
if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict):
|
|
fail("unsupported component registry schema")
|
|
definition = definitions.get(arguments.component)
|
|
if not isinstance(definition, dict):
|
|
fail(f"component is not registered: {arguments.component}")
|
|
package_id = definition.get("packageId")
|
|
if not isinstance(package_id, str) or not TOKEN.fullmatch(package_id):
|
|
fail("registered packageId is invalid")
|
|
|
|
build_dependencies: dict[str, Any] = {}
|
|
if arguments.build_dependencies is not None:
|
|
build_dependencies = load_json_object(
|
|
arguments.build_dependencies, "build dependency provenance"
|
|
)
|
|
|
|
package_root = arguments.package_root.resolve(strict=True)
|
|
if package_root.is_symlink() or not package_root.is_dir():
|
|
fail("--package-root must be a real directory")
|
|
require_debug_information(package_root)
|
|
output = arguments.output.resolve()
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
epoch_value = os.environ.get("SOURCE_DATE_EPOCH", "0")
|
|
if not epoch_value.isdigit():
|
|
fail("SOURCE_DATE_EPOCH must be a non-negative integer")
|
|
|
|
helpers = load_packaging_helpers()
|
|
artifact_identity = (
|
|
f"{package_id}-{arguments.component_version}-"
|
|
f"{arguments.platform}-{arguments.architecture}"
|
|
)
|
|
with tempfile.TemporaryDirectory(
|
|
prefix=".component-package.", dir=output
|
|
) as temporary:
|
|
staged = Path(temporary) / artifact_identity
|
|
shutil.copytree(package_root, staged, symlinks=True)
|
|
files = helpers.validate_tree(staged)
|
|
manifest = {
|
|
"schemaVersion": 3,
|
|
"componentId": arguments.component,
|
|
"packageId": package_id,
|
|
"kind": definition["kind"],
|
|
"productCompatibility": arguments.product_compatibility,
|
|
"componentVersion": arguments.component_version,
|
|
"sourceSha": arguments.source_sha,
|
|
"sourceTreeHash": arguments.source_tree_hash,
|
|
"abiHash": arguments.abi_hash,
|
|
"activation": definition["activation"],
|
|
"dependencies": definition["dependencies"],
|
|
"buildDependencies": build_dependencies,
|
|
"buildType": arguments.build_type,
|
|
"platform": arguments.platform,
|
|
"architecture": arguments.architecture,
|
|
"toolchainContract": arguments.toolchain_contract,
|
|
"artifactIdentity": artifact_identity,
|
|
"privateLibraries": helpers.private_libraries(staged),
|
|
"files": files,
|
|
}
|
|
manifest_bytes = helpers.canonical(manifest)
|
|
(staged / "manifest.json").write_bytes(manifest_bytes)
|
|
archive = output / f"{artifact_identity}.tar.zst"
|
|
helpers.create_archive(staged, archive, int(epoch_value))
|
|
manifest_path = output / f"{artifact_identity}.manifest.json"
|
|
manifest_path.write_bytes(manifest_bytes)
|
|
|
|
print(f"packaged {arguments.component}: {archive.name}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|