190 lines
5.7 KiB
Python
190 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Canonicalize, hash, classify, and version Echoion module contracts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import sys
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
SEMVER = re.compile(
|
|
r"^(?P<major>0|[1-9][0-9]*)\."
|
|
r"(?P<minor>0|[1-9][0-9]*)\."
|
|
r"(?P<patch>0|[1-9][0-9]*)$"
|
|
)
|
|
|
|
|
|
def load_contract(path: Path) -> Any:
|
|
with path.open(encoding="utf-8") as source:
|
|
contract = json.load(source)
|
|
if not isinstance(contract, dict) or contract.get("schemaVersion") != 1:
|
|
raise ValueError(f"{path}: unsupported ABI contract schema")
|
|
return contract
|
|
|
|
|
|
def canonical_bytes(contract: Any) -> bytes:
|
|
return (
|
|
json.dumps(
|
|
contract,
|
|
ensure_ascii=False,
|
|
sort_keys=True,
|
|
separators=(",", ":"),
|
|
)
|
|
+ "\n"
|
|
).encode()
|
|
|
|
|
|
def contract_hash(contract: Any) -> str:
|
|
return "sha256:" + hashlib.sha256(canonical_bytes(contract)).hexdigest()
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Compatibility:
|
|
compatible: bool
|
|
changed: bool
|
|
|
|
|
|
def compare_contract(old: Any, new: Any) -> Compatibility:
|
|
"""Return whether new is an append-only superset of old."""
|
|
if type(old) is not type(new):
|
|
return Compatibility(False, True)
|
|
if isinstance(old, dict):
|
|
changed = len(old) != len(new)
|
|
for key, old_value in old.items():
|
|
if key not in new:
|
|
return Compatibility(False, True)
|
|
result = compare_contract(old_value, new[key])
|
|
if not result.compatible:
|
|
return result
|
|
changed = changed or result.changed
|
|
return Compatibility(True, changed)
|
|
if isinstance(old, list):
|
|
if len(new) < len(old):
|
|
return Compatibility(False, True)
|
|
changed = len(new) != len(old)
|
|
for index, old_value in enumerate(old):
|
|
result = compare_contract(old_value, new[index])
|
|
if not result.compatible:
|
|
return result
|
|
changed = changed or result.changed
|
|
return Compatibility(True, changed)
|
|
return Compatibility(old == new, old != new)
|
|
|
|
|
|
def classify(
|
|
old_contract: Any,
|
|
new_contract: Any,
|
|
old_source_sha: str,
|
|
new_source_sha: str,
|
|
kind: str,
|
|
) -> str:
|
|
if old_source_sha == new_source_sha:
|
|
if canonical_bytes(old_contract) != canonical_bytes(new_contract):
|
|
raise ValueError("ABI contract changed without a source SHA change")
|
|
return "unchanged"
|
|
if kind in {"executable", "assets"}:
|
|
return "patch"
|
|
|
|
comparison = compare_contract(old_contract, new_contract)
|
|
if not comparison.compatible:
|
|
return "major"
|
|
return "minor" if comparison.changed else "patch"
|
|
|
|
|
|
def derive_version(current: str, change: str) -> str:
|
|
match = SEMVER.fullmatch(current)
|
|
if match is None:
|
|
raise ValueError(f"component version is not stable SemVer: {current}")
|
|
major, minor, patch = (
|
|
int(match.group("major")),
|
|
int(match.group("minor")),
|
|
int(match.group("patch")),
|
|
)
|
|
if change == "unchanged":
|
|
return current
|
|
if change == "patch":
|
|
return f"{major}.{minor}.{patch + 1}"
|
|
if change == "minor":
|
|
return f"{major}.{minor + 1}.0"
|
|
if change == "major":
|
|
return f"{major + 1}.0.0"
|
|
raise ValueError(f"unsupported change classification: {change}")
|
|
|
|
|
|
def write_or_print(payload: bytes, output: Path | None) -> None:
|
|
if output is None:
|
|
sys.stdout.buffer.write(payload)
|
|
return
|
|
temporary = output.with_name(output.name + ".tmp")
|
|
temporary.write_bytes(payload)
|
|
temporary.replace(output)
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser()
|
|
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
|
|
canonical = subparsers.add_parser("canonicalize")
|
|
canonical.add_argument("contract", type=Path)
|
|
canonical.add_argument("--output", type=Path)
|
|
|
|
digest = subparsers.add_parser("hash")
|
|
digest.add_argument("contract", type=Path)
|
|
|
|
classify_parser = subparsers.add_parser("classify")
|
|
classify_parser.add_argument("old_contract", type=Path)
|
|
classify_parser.add_argument("new_contract", type=Path)
|
|
classify_parser.add_argument("--old-source-sha", required=True)
|
|
classify_parser.add_argument("--new-source-sha", required=True)
|
|
classify_parser.add_argument(
|
|
"--kind",
|
|
choices=("module", "library", "executable", "assets"),
|
|
default="module",
|
|
)
|
|
|
|
derive = subparsers.add_parser("derive-version")
|
|
derive.add_argument("current")
|
|
derive.add_argument(
|
|
"change", choices=("unchanged", "patch", "minor", "major")
|
|
)
|
|
return parser
|
|
|
|
|
|
def main() -> int:
|
|
args = build_parser().parse_args()
|
|
try:
|
|
if args.command == "canonicalize":
|
|
write_or_print(
|
|
canonical_bytes(load_contract(args.contract)), args.output
|
|
)
|
|
elif args.command == "hash":
|
|
print(contract_hash(load_contract(args.contract)))
|
|
elif args.command == "classify":
|
|
print(
|
|
classify(
|
|
load_contract(args.old_contract),
|
|
load_contract(args.new_contract),
|
|
args.old_source_sha,
|
|
args.new_source_sha,
|
|
args.kind,
|
|
)
|
|
)
|
|
elif args.command == "derive-version":
|
|
print(derive_version(args.current, args.change))
|
|
else:
|
|
raise AssertionError(args.command)
|
|
except (OSError, json.JSONDecodeError, ValueError) as error:
|
|
print(f"abi-contract: {error}", file=sys.stderr)
|
|
return 2
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|