chessbaseLinux/androidApp/scripts/check_release_notes.py

318 lines
12 KiB
Python

#!/usr/bin/env python3
"""Validate the canonical Android release-notes manifest and classify CI intent."""
from __future__ import annotations
import argparse
import json
import re
import sys
import tomllib
from pathlib import Path
from typing import Any
INT_MAX = 2_147_483_647
LANGUAGES = frozenset({"en", "ru", "de", "fr", "es", "it", "pt", "uz", "kk"})
MANIFEST_PATH = Path("androidApp/app/src/main/assets/android-release-notes.json")
NUMERIC_VERSION = re.compile(r"^([0-9]+)\.([0-9]+)\.([0-9]+)$")
class ReleaseNotesError(Exception):
"""A user-facing manifest or release-version error."""
def _object_without_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise ReleaseNotesError(f"duplicate JSON key {key!r}")
result[key] = value
return result
def load_manifest(path: Path) -> dict[str, Any]:
try:
text = path.read_text(encoding="utf-8")
except OSError as exc:
raise ReleaseNotesError(f"cannot read {path}: {exc}") from exc
except UnicodeError as exc:
raise ReleaseNotesError(f"{path} is not valid UTF-8: {exc}") from exc
try:
manifest = json.loads(text, object_pairs_hook=_object_without_duplicate_keys)
except json.JSONDecodeError as exc:
raise ReleaseNotesError(
f"{path}: malformed JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}"
) from exc
return validate_manifest(manifest)
def _is_int(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool)
def _numeric_version(version_name: str, context: str) -> tuple[int, int, int, int]:
match = NUMERIC_VERSION.fullmatch(version_name)
if match is None:
raise ReleaseNotesError(
f"{context}: versionName {version_name!r} must be numeric major.minor.patch"
)
try:
major, minor, patch = (int(component) for component in match.groups())
except ValueError as exc:
raise ReleaseNotesError(f"{context}: numeric version component is too large") from exc
if minor > 99 or patch > 99:
raise ReleaseNotesError(f"{context}: minor and patch must be in 0..99")
version_code = major * 10_000 + minor * 100 + patch
if version_code <= 0 or version_code > INT_MAX:
raise ReleaseNotesError(
f"{context}: computed versionCode must be in 1..{INT_MAX}"
)
return major, minor, patch, version_code
def validate_manifest(manifest: Any) -> dict[str, Any]:
if not isinstance(manifest, dict):
raise ReleaseNotesError("manifest root must be an object")
if not _is_int(manifest.get("schemaVersion")) or manifest["schemaVersion"] != 1:
raise ReleaseNotesError("schemaVersion must be integer 1")
releases = manifest.get("releases")
if not isinstance(releases, list):
raise ReleaseNotesError("releases must be a list")
expected_codes: list[int] = []
for index, release in enumerate(releases):
context = f"releases[{index}]"
if not isinstance(release, dict):
raise ReleaseNotesError(f"{context} must be an object")
for field in ("versionCode", "versionName", "items"):
if field not in release:
raise ReleaseNotesError(f"{context}: missing required field {field}")
version_code = release["versionCode"]
version_name = release["versionName"]
if not _is_int(version_code):
raise ReleaseNotesError(f"{context}.versionCode must be an integer")
if version_code <= 0 or version_code > INT_MAX:
raise ReleaseNotesError(
f"{context}.versionCode must be in 1..{INT_MAX}"
)
if not isinstance(version_name, str) or not version_name:
raise ReleaseNotesError(f"{context}.versionName must be a non-empty string")
_, _, _, expected_code = _numeric_version(version_name, context)
expected_codes.append(expected_code)
items = release["items"]
if not isinstance(items, dict):
raise ReleaseNotesError(f"{context}.items must be an object")
for language, localized_items in items.items():
if language not in LANGUAGES:
raise ReleaseNotesError(f"{context}.items: unknown language {language!r}")
if not isinstance(localized_items, list):
raise ReleaseNotesError(
f"{context}.items.{language} must be a list of strings"
)
for item_index, item in enumerate(localized_items):
if not isinstance(item, str):
raise ReleaseNotesError(
f"{context}.items.{language}[{item_index}] must be a string"
)
seen_codes: dict[int, int] = {}
seen_names: dict[str, int] = {}
for index, release in enumerate(releases):
version_code = release["versionCode"]
version_name = release["versionName"]
if version_code in seen_codes:
raise ReleaseNotesError(
f"releases[{index}]: duplicate versionCode {version_code} "
f"(first used in releases[{seen_codes[version_code]}])"
)
if version_name in seen_names:
raise ReleaseNotesError(
f"releases[{index}]: duplicate versionName {version_name!r} "
f"(first used in releases[{seen_names[version_name]}])"
)
seen_codes[version_code] = index
seen_names[version_name] = index
previous_code = 0
for index, release in enumerate(releases):
version_code = release["versionCode"]
expected_code = expected_codes[index]
if version_code != expected_code:
raise ReleaseNotesError(
f"releases[{index}]: versionCode {version_code} does not match "
f"{release['versionName']} (expected {expected_code})"
)
if version_code <= previous_code:
raise ReleaseNotesError(
f"releases[{index}]: versionCode regression "
f"{version_code} after {previous_code}"
)
previous_code = version_code
return manifest
def read_current_version(repo_root: Path) -> str:
cargo_toml = repo_root / "Cargo.toml"
try:
with cargo_toml.open("rb") as source:
cargo = tomllib.load(source)
except OSError as exc:
raise ReleaseNotesError(f"cannot read {cargo_toml}: {exc}") from exc
except (tomllib.TOMLDecodeError, UnicodeError) as exc:
raise ReleaseNotesError(f"cannot parse {cargo_toml}: {exc}") from exc
workspace = cargo.get("workspace")
package = workspace.get("package") if isinstance(workspace, dict) else None
version = package.get("version") if isinstance(package, dict) else None
if version is None:
raise ReleaseNotesError("Cargo.toml has no workspace.package.version")
if not isinstance(version, str) or not version:
raise ReleaseNotesError("workspace.package.version must be a non-empty string")
return version
def _current_match(
manifest: dict[str, Any], version_name: str, version_code: int
) -> tuple[int, dict[str, Any]] | None:
for index, release in enumerate(manifest["releases"]):
if release["versionName"] == version_name and release["versionCode"] == version_code:
return index, release
return None
def require_current(manifest: dict[str, Any], version_name: str) -> dict[str, Any]:
_, _, _, version_code = _numeric_version(version_name, "workspace.package.version")
match = _current_match(manifest, version_name, version_code)
releases = manifest["releases"]
if match is not None:
index, release = match
if index != len(releases) - 1:
raise ReleaseNotesError(
f"current release {version_name} must be the last manifest entry"
)
return release
name_match = next(
(release for release in releases if release["versionName"] == version_name), None
)
if name_match is not None:
raise ReleaseNotesError(
f"current release name {version_name} has mismatched versionCode "
f"{name_match['versionCode']}; expected {version_code}"
)
code_match = next(
(release for release in releases if release["versionCode"] == version_code), None
)
if code_match is not None:
raise ReleaseNotesError(
f"current versionCode {version_code} belongs to "
f"{code_match['versionName']}, not {version_name}"
)
raise ReleaseNotesError(
f"current Android release is missing: expected versionName={version_name}, "
f"versionCode={version_code} as the last entry"
)
def classify_ci_intent(
manifest: dict[str, Any], current_version: str
) -> dict[str, str | int | bool]:
"""Classify only after manifest validation; never strip a prerelease suffix."""
version_name = current_version[1:] if current_version.startswith("v") else current_version
result: dict[str, str | int | bool] = {"version": version_name}
if NUMERIC_VERSION.fullmatch(version_name) is None:
if any(
release["versionName"] == version_name for release in manifest["releases"]
):
raise ReleaseNotesError(
f"non-numeric/prerelease current version {version_name!r} "
"has a matching Android entry"
)
result.update(android=False, intent="desktop-only")
return result
_, _, _, version_code = _numeric_version(version_name, "current CI version")
match = _current_match(manifest, version_name, version_code)
if match is not None:
index, _ = match
if index != len(manifest["releases"]) - 1:
raise ReleaseNotesError(
f"current Android release {version_name} must be the last manifest entry"
)
result.update(
version_code=version_code,
android=True,
intent="android",
)
return result
name_match = next(
(
release
for release in manifest["releases"]
if release["versionName"] == version_name
),
None,
)
code_match = next(
(
release
for release in manifest["releases"]
if release["versionCode"] == version_code
),
None,
)
if name_match is not None:
raise ReleaseNotesError(
f"CI name-only match for {version_name}: entry has versionCode "
f"{name_match['versionCode']}, expected {version_code}"
)
if code_match is not None:
raise ReleaseNotesError(
f"CI code-only match for {version_code}: entry has versionName "
f"{code_match['versionName']}, expected {version_name}"
)
result.update(android=False, intent="desktop-only")
return result
def _load_repo_manifest(repo_root: Path) -> dict[str, Any]:
return load_manifest(repo_root / MANIFEST_PATH)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=("check", "require-current", "ci-intent"))
parser.add_argument("--repo-root", required=True, type=Path)
args = parser.parse_args(argv)
try:
manifest = _load_repo_manifest(args.repo_root)
if args.command == "check":
print(f"OK: {args.repo_root / MANIFEST_PATH}")
return 0
version = read_current_version(args.repo_root)
if args.command == "require-current":
release = require_current(manifest, version)
print(
f"OK: current Android release {release['versionName']} "
f"(versionCode={release['versionCode']})"
)
return 0
result = classify_ci_intent(manifest, version)
print(f"version={result['version']}")
if "version_code" in result:
print(f"version_code={result['version_code']}")
print(f"android={str(result['android']).lower()}")
print(f"intent={result['intent']}")
return 0
except ReleaseNotesError as exc:
print(f"FAIL: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())