diff options
Diffstat (limited to '.github/scripts')
37 files changed, 6532 insertions, 223 deletions
diff --git a/.github/scripts/armhf-ci-image-config.sh b/.github/scripts/armhf-ci-image-config.sh index 6e97c2f0..85b95523 100755 --- a/.github/scripts/armhf-ci-image-config.sh +++ b/.github/scripts/armhf-ci-image-config.sh @@ -6,23 +6,14 @@ _armhf_config_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" # shellcheck source=.github/scripts/linux-ci-image-config.sh . "$_armhf_config_dir/linux-ci-image-config.sh" +# shellcheck source=.github/scripts/armhf-toolchain-config.sh +. "$_armhf_config_dir/armhf-toolchain-config.sh" unset _armhf_config_dir ARMHF_CI_IMAGE_SCHEMA=1 -ARMHF_CROSSTOOL_NG_VERSION=1.28.0 -ARMHF_CROSSTOOL_NG_SHA256=5750e29a2bda5cd8d67900592576b1670a1987a4dcd5e4f6beae09138a1f5699 -ARMHF_CROSSTOOL_NG_URL="https://github.com/crosstool-ng/crosstool-ng/releases/download/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}.tar.xz" - -ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf -ARMHF_TOOLCHAIN_PREFIX=/opt/wsjtx/armhf-toolchain ARMHF_SYSROOT=/opt/wsjtx/armhf-sysroot ARMHF_RUNTIME_PREFIX=/opt/wsjtx/armhf-runtime ARMHF_QEMU_EXECUTABLE=/usr/local/bin/qemu-arm-static -ARMHF_GCC_VERSION=13.4.0 -ARMHF_GLIBC_VERSION=2.36 -ARMHF_BINUTILS_VERSION=2.40 -ARMHF_LINUX_HEADERS_VERSION=6.1.147 -ARMHF_MIN_KERNEL_VERSION=3.2.0 ARMHF_SYSROOT_PACKAGES=( libc6-dev libstdc++6 libgfortran5 libgomp1 libatomic1 diff --git a/.github/scripts/armhf-static-ldd.sh b/.github/scripts/armhf-static-ldd.sh index bb85e6f3..50cecc61 100755 --- a/.github/scripts/armhf-static-ldd.sh +++ b/.github/scripts/armhf-static-ldd.sh @@ -1,9 +1,9 @@ #!/usr/bin/env bash set -euo pipefail -# linuxdeploy's ldd probe crashes when an ARM loader is nested under user-mode -# QEMU. Resolve DT_NEEDED entries from the clean ARMHF runtime without executing -# the target; packaged runtime behavior is still proved by the QEMU smoke test. +# Resolve DT_NEEDED entries from the clean ARMHF runtime without executing the +# target, so linuxdeploy sees the runtime prefix first and a libquadmath +# dependency fails; the AppImage startup smoke test proves runtime behavior. if [ "$#" -ne 1 ]; then echo "Usage: armhf-static-ldd.sh ELF" >&2 diff --git a/.github/scripts/armhf-toolchain-config.sh b/.github/scripts/armhf-toolchain-config.sh new file mode 100755 index 00000000..bcd44613 --- /dev/null +++ b/.github/scripts/armhf-toolchain-config.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +# Pinned inputs for the native ARMHF cross-toolchain. +# shellcheck disable=SC2034 + +ARMHF_TOOLCHAIN_REBUILD_REVISION=1 +ARMHF_CROSSTOOL_NG_VERSION=1.28.0 +ARMHF_CROSSTOOL_NG_SHA256=5750e29a2bda5cd8d67900592576b1670a1987a4dcd5e4f6beae09138a1f5699 +ARMHF_CROSSTOOL_NG_URL="https://github.com/crosstool-ng/crosstool-ng/releases/download/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}/crosstool-ng-${ARMHF_CROSSTOOL_NG_VERSION}.tar.xz" + +ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf +ARMHF_TOOLCHAIN_PREFIX=/opt/wsjtx/armhf-toolchain +ARMHF_GCC_VERSION=13.4.0 +ARMHF_GLIBC_VERSION=2.36 +ARMHF_BINUTILS_VERSION=2.40 +ARMHF_LINUX_HEADERS_VERSION=6.1.147 +ARMHF_MIN_KERNEL_VERSION=3.2.0 diff --git a/.github/scripts/audit-staged-dll-imports-windows.sh b/.github/scripts/audit-staged-dll-imports-windows.sh index ca8b75f2..464faf7e 100644 --- a/.github/scripts/audit-staged-dll-imports-windows.sh +++ b/.github/scripts/audit-staged-dll-imports-windows.sh @@ -38,8 +38,14 @@ for exe in "$@"; do fi echo "::group::DLL imports for $exe" + if ! import_metadata=$(objdump -p "$exe"); then + echo "::error::Could not inspect DLL imports for $exe" + echo "::endgroup::" + fail=1 + continue + fi imports=$( - objdump -p "$exe" | + printf '%s\n' "$import_metadata" | awk '/DLL Name:/ {print $3}' | sort -u ) @@ -50,8 +56,16 @@ for exe in "$@"; do echo "(none)" fi + if [ "$(basename "$exe" | tr '[:upper:]' '[:lower:]')" = jt9.exe ]; then + qt_imports=$(printf '%s\n' "$imports" | awk 'tolower($0) ~ /^qt.*\.dll$/') + if [ -n "$qt_imports" ]; then + echo "::error::$exe must not depend on Qt: $qt_imports" + fail=1 + fi + fi + win7_blocked_imports=$( - objdump -p "$exe" | + printf '%s\n' "$import_metadata" | awk ' /DLL Name:/ { dll=tolower($3) } /api-ms-win-core-synch-l1-2-0\.dll/ { print "api-ms-win-core-synch-l1-2-0.dll" } diff --git a/.github/scripts/beta-scheduler.py b/.github/scripts/beta-scheduler.py new file mode 100644 index 00000000..925703ee --- /dev/null +++ b/.github/scripts/beta-scheduler.py @@ -0,0 +1,798 @@ +#!/usr/bin/env python3 +"""Advance the scheduled beta line by one state-machine step per workflow run.""" + +from __future__ import annotations + +import argparse +import base64 +import importlib.util +import io +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import textwrap +import traceback +from typing import Callable, NamedTuple +import urllib.error +import urllib.parse +import urllib.request +import zipfile + + +def load_script(name: str, filename: str): + spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +policy = load_script("release_policy", "release-policy.py") +images = load_script("release_linux_images", "release-linux-images.py") +image_tags = load_script("resolve_linux_ci_image_tag", "resolve-linux-ci-image-tag.py") + +PUBLIC_REPOSITORY = "WSJTX/wsjtx" +ALERT_TITLE = "Scheduled beta alerts" +ALERT_CREATOR = "github-actions[bot]" +STATE_FILE = "release-state.txt" +LOCK_FILE = "release-linux-images.json" +METADATA_FILES = frozenset((STATE_FILE, LOCK_FILE)) +PREPARED_ARTIFACT = "prepared-release-dependencies" +IMAGE_PACKAGES = ( + image_tags.NORMAL_PACKAGE, + image_tags.ARM64_PACKAGE, + image_tags.ARMHF_CROSS_PACKAGE, + image_tags.ARMHF_PACKAGE, +) +CI = "ci.yml" +CANDIDATE = "release-tag-helper.yml" +PROMOTION = "promote-release.yml" +PREPARATION = "prepare-release-dependencies.yml" +WARMER = "warm-dependency-caches.yml" +PUBLISHER = "publish-linux-ci-images.yml" +PUBLICATION = "public-release.yml" +BETA_CUT = "beta-cut.yml" +IMAGE_REFRESH_JOB = "refresh-linux-images" +NORMAL_IMAGES_JOB = "build-normal" +CANDIDATE_TITLE = re.compile(r"Prepare Release Candidate build/v(?P<version>\S+) \((?P<operation>validate|create)\)") +PREPARATION_TITLE = re.compile(r"Prepare Release Dependencies (?P<source>\S+) (?P<generation>\S+)") +GENERATION_TAG = re.compile(r"validated-build-\d{8}-(?P<run>\d+)-(?P<attempt>\d+)") + + +class Skip(Exception): + """Nothing to do now; a later run tries again. Reported in the job summary only.""" + + +class Stop(Exception): + """A person must act. Reported in the job summary and on the tracking issue.""" + + def __init__(self, stage: str, reason: str, link: str | None = None) -> None: + super().__init__(reason) + self.stage = stage + self.link = link + + +class Spent(Exception): + """The candidate failed after its build tag was pushed; build tags never move, so the number is used up.""" + + def __init__(self, reason: str, link: str | None = None) -> None: + super().__init__(reason) + self.link = link + + +class Line(NamedTuple): + branch: str + tip: str + version: str + number: int + + def prerelease(self, number: int | None = None) -> str: + return f"{self.version}-beta{self.number if number is None else number}" + + +class Commit(NamedTuple): + sha: str + author_email: str + files: tuple[str, ...] + + +def candidate_tag(version: str) -> str: + return f"build/v{version}" + + +def in_flight(run: dict) -> bool: + return run.get("status") != "completed" + + +def run_order(run: dict) -> tuple[str, int]: + return run.get("created_at") or "", run.get("id") or 0 + + +def newest(runs: list[dict]) -> dict | None: + return max(runs, key=run_order, default=None) + + +def candidate_of(run: dict) -> tuple[str, str] | None: + match = CANDIDATE_TITLE.fullmatch(run.get("display_title") or "") + return (match["version"], match["operation"]) if match else None + + +def preparation_of(run: dict) -> tuple[str, str] | None: + match = PREPARATION_TITLE.fullmatch(run.get("display_title") or "") + return (match["source"], match["generation"]) if match else None + + +def render_state(version: str, number: int) -> str: + return f"version={version}\nchannel=BETA\nprerelease={number}\nrevision=$Format:%H$\nwindows_signing=unsigned\n" + + +def git_identity(name: str, email: str) -> dict[str, str]: + return {"GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email, + "GIT_COMMITTER_NAME": name, "GIT_COMMITTER_EMAIL": email} + + +def lock_recipes(lock: bytes | None) -> dict[str, str] | None: + try: + selected = json.loads(lock)["images"] + return {key: selected[key]["recipe_sha256"] for key in images.IMAGES} + except (TypeError, ValueError, KeyError): + return None + + +def lock_generation(lock: bytes) -> str | None: + try: + return json.loads(lock).get("generation") + except (ValueError, AttributeError): + return None + + +class Scheduler: + def __init__(self, repository, internal, public=None, packages=None, *, bot_login: str, + bot_email: str | None = None, notes: list[str] | None = None) -> None: + self.repository = repository + self.internal = internal + self.public = public + self.packages = packages + self.bot_login = bot_login + self.bot_email = bot_email + self.notes = [] if notes is None else notes + self.recipe_cache: dict[str, dict[str, str] | None] = {} + + def beta_line(self) -> Line: + lines = [] + for branch, tip in sorted(self.repository.release_heads().items()): + if not policy.RELEASE_BRANCH_RE.fullmatch(branch): + continue + raw = self.repository.read(tip, STATE_FILE) + try: + state = policy.parse_state(raw.decode("utf-8")) + except (AttributeError, UnicodeDecodeError, ValueError) as error: + if raw is not None and b"channel=BETA" in raw.splitlines(): + raise Stop("line", f"{branch}'s {STATE_FILE} says channel=BETA but does not validate: " + f"{error}") from error + continue + if state["channel"] != "BETA": + continue + if policy.classify(state["version"])["release_branch"] != branch: + raise Stop("line", f"{branch} is in BETA state for version {state['version']}, " + "which belongs to another release line.") + lines.append(Line(branch, tip, state["version"], int(state["prerelease"]))) + if not lines: + raise Skip("No release/X.Y branch is in BETA state, as between a freeze and the next line's start; " + "nothing to do.") + if len(lines) > 1: + found = ", ".join(line.branch for line in lines) + raise Stop("line", f"Exactly one release/X.Y branch may be in BETA state; found {found}.") + line = lines[0] + self.notes.append(f"Beta line: {line.branch} at {line.tip}, state BETA {line.number}.") + return line + + def cut(self) -> str: + self.repository.sync() + line = self.beta_line() + tag_sha = self.repository.tag(candidate_tag(line.prerelease())) + if tag_sha is None: + return self.retry(line) + public_tag = f"v{line.prerelease()}" + if self.public.release_published(public_tag): + self.notes.append(f"`{public_tag}` is published, so the next cut is BETA {line.number + 1}.") + return self.advance(line) + outcome = self.unpublished(line, tag_sha) + if not isinstance(outcome, Spent): + raise outcome + self.notes.append(str(outcome)) + return self.advance(line, spent=outcome) + + def retry(self, line: Line) -> str: + version = line.prerelease() + self.notes.append(f"`{candidate_tag(version)}` does not exist, so {version} is retried under the same number.") + self.check_fixes_on_develop(line) + runs = self.internal.runs(CI, head_sha=line.tip) + if any(in_flight(run) for run in runs): + raise self.wait("ci", runs, f"CI for {line.branch} at {line.tip} is still running; {version} waits for it.") + ci = newest(runs) + if ci is None: + raise Stop("ci", f"{line.branch} at {line.tip} has no CI run, so {version} cannot be cut.") + if ci.get("conclusion") != "success": + return self.recut(line, ci) + candidates = self.candidate_runs(line) + if any(in_flight(run) for run in candidates): + raise self.wait("candidate", candidates, f"A candidate run for {version} is still running.") + return self.dispatch_candidate(line) + + def wait(self, stage: str, runs: list[dict], reason: str) -> Exception: + running = [run for run in runs if in_flight(run)] + # The continuation follows only runs the App started, and the weekly cut would otherwise wait a week. + if any((run.get("actor") or {}).get("login") == self.bot_login for run in running): + return Skip(reason) + return Stop(stage, f"{reason} Nothing resumes the cut when that run finishes, so dispatch Scheduled Beta Cut " + "after it does.", running[0].get("html_url")) + + def recut(self, line: Line, ci: dict) -> str: + version = line.prerelease() + failed = f"CI for {line.branch} at {line.tip} concluded {ci.get('conclusion')}" + target = self.newest_green_develop() + if target is None or self.repository.is_ancestor(target, line.tip): + raise Stop("ci", f"{failed}, and develop has no newer green commit to cut {version} from. Re-run the CI " + "if the failure is transient.", ci.get("html_url")) + self.notes.append(f"{failed}, so {version} is cut again from develop {target}.") + lock, lock_note = self.lock_for(line, target) + commit = self.commit_cut(line, line.number, target, lock, lock_note) + return f"Pushed {commit} to {line.branch}: develop {target} as {version} again." + + def candidate_runs(self, line: Line) -> list[dict]: + return [run for run in self.internal.runs(CANDIDATE, branch=line.branch, event="workflow_dispatch") + if candidate_of(run) == (line.prerelease(), "create")] + + def dispatch_candidate(self, line: Line) -> str: + version = line.prerelease() + self.internal.dispatch(CANDIDATE, line.branch, + {"version": version, "expected_sha": line.tip, "operation": "create"}) + return f"Dispatched Prepare Release Candidate for `{candidate_tag(version)}` at {line.tip}." + + def unpublished(self, line: Line, tag_sha: str) -> Exception: + version = line.prerelease() + public_tag = f"v{version}" + stages = { + "CI": self.internal.runs(CI, head_sha=tag_sha), + "candidate": [run for run in self.candidate_runs(line) if run.get("head_sha") == tag_sha], + "promotion": self.internal.runs(PROMOTION, branch=line.branch, event="workflow_dispatch", head_sha=tag_sha), + "public release": self.public.runs(PUBLICATION, branch=public_tag, event="push"), + } + for stage, runs in stages.items(): + if any(in_flight(run) for run in runs): + reason = f"`{public_tag}` is not published yet; its {stage} run is still in progress." + # The public release completes on its own; nothing is due from the cut until it has. + return Skip(reason) if stage == "public release" else self.wait(stage.lower(), runs, reason) + failed = newest(stages["candidate"]) + if failed is None: + return Stop("candidate", f"`{candidate_tag(version)}` exists, but no candidate run for it was found.") + candidate = newest([run for run in stages["candidate"] if run.get("conclusion") == "success"]) + # A run reports only its latest attempt, so a later failed re-run can hide a promoted candidate. + promoted = newest([run for run in stages["promotion"] if run.get("conclusion") == "success"]) + if candidate is None and promoted is None: + return Spent(f"The candidate run for `{candidate_tag(version)}` concluded {failed.get('conclusion')} after " + f"the tag was pushed. Build tags never move, so {version} is spent and the next cut is " + f"BETA {line.number + 1}.", failed.get("html_url")) + promotion = promoted or newest(stages["promotion"]) + if promotion is None: + return Stop("promotion", f"The candidate for {version} succeeded, but Promote Release Source was not " + f"dispatched. Dispatch it with operation=promote and candidate run " + f"{candidate.get('id')}.", candidate.get("html_url")) + if promotion.get("conclusion") != "success": + return Stop("promotion", f"Promote Release Source for {version} concluded {promotion.get('conclusion')}.", + promotion.get("html_url")) + publication = newest(stages["public release"]) + if publication is None: + return Stop("publication", f"`{public_tag}` was promoted, but no public release run started for it.", + promotion.get("html_url")) + if publication.get("conclusion") != "success": + return Stop("publication", f"The public release run for `{public_tag}` concluded " + f"{publication.get('conclusion')}.", publication.get("html_url")) + return Stop("publication", f"The public release run for `{public_tag}` succeeded, but the release is not " + "published.", publication.get("html_url")) + + def advance(self, line: Line, spent: Spent | None = None) -> str: + number = line.number + 1 + target = self.newest_green_develop() + if target is None: + raise Stop("develop", "No commit on develop has a successful push CI run.") + if self.repository.is_ancestor(target, line.tip): + if spent is not None: + raise Stop("candidate", f"{spent} develop has no newer green commit to cut " + f"{line.prerelease(number)} from; land the fix on develop.", spent.link) + raise Skip(f"develop has not moved: its newest green commit {target} is already in {line.branch}.") + self.check_fixes_on_develop(line) + lock, lock_note = self.lock_for(line, target) + commit = self.commit_cut(line, number, target, lock, lock_note) + return f"Pushed {commit} to {line.branch}: develop {target} as {line.prerelease(number)}." + + def newest_green_develop(self) -> str | None: + develop = self.repository.develop() + runs = self.internal.runs(CI, branch="develop", event="push", status="success") + for run in sorted(runs, key=run_order, reverse=True): + sha = run.get("head_sha", "") + if self.repository.contains(sha) and self.repository.is_ancestor(sha, develop): + self.notes.append(f"Newest green develop commit: {sha}.") + return sha + return None + + def check_fixes_on_develop(self, line: Line) -> None: + fixes = [ + commit.sha for commit in self.repository.commits_missing_from_develop(line.tip) + if commit.author_email != self.bot_email and not METADATA_FILES.issuperset(commit.files) + ] + if fixes: + raise Stop("fixes", f"{line.branch} holds commits that are not on develop: {', '.join(fixes)}. " + "Fixes land on develop first.") + + def recipes(self, commit: str) -> dict[str, str] | None: + if commit not in self.recipe_cache: + self.recipe_cache[commit] = self.repository.fingerprints(commit) + return self.recipe_cache[commit] + + def lock_for(self, line: Line, target: str) -> tuple[bytes, str]: + wanted = self.recipes(target) + if wanted is None: + raise RuntimeError(f"develop commit {target} is missing from the checkout") + current = self.repository.read(line.tip, LOCK_FILE) + if current is not None and lock_recipes(current) == wanted: + self.notes.append(f"Linux image lock: kept; develop's recipe fingerprints match {line.branch}'s lock.") + return current, "" + generation = self.generation_for(wanted) + lock, run = self.prepared_lock(generation, wanted) + self.notes.append(f"Linux image lock: replaced with {generation} from {run.get('html_url')}.") + return lock, f"The Linux image lock moves to {generation}, prepared by {run.get('html_url')}." + + def published_generations(self) -> dict[int, str]: + shared: set[str] | None = None + for package in IMAGE_PACKAGES: + tags = {tag for version in self.packages.list_versions(image_tags.OWNER, package) + for tag in version.tags if GENERATION_TAG.fullmatch(tag)} + shared = tags if shared is None else shared & tags + generations: dict[int, str] = {} + for tag in sorted(shared or (), key=lambda item: int(GENERATION_TAG.fullmatch(item)["attempt"])): + generations[int(GENERATION_TAG.fullmatch(tag)["run"])] = tag + return generations + + def generation_for(self, wanted: dict[str, str]) -> str: + published = self.published_generations() + refreshing = None + runs = (self.internal.runs(WARMER, branch="develop") + + self.internal.runs(PUBLISHER, branch="develop", event="workflow_dispatch")) + for run in sorted(runs, key=run_order, reverse=True): + matches = self.recipes(run.get("head_sha", "")) == wanted + # A generation is tagged only by the run's promote job, so it can be used before the run ends. + if matches and run.get("id") in published: + return published[run["id"]] + if refreshing is None and in_flight(run) and matches and self.refreshes_images(run): + refreshing = run + if refreshing is not None: + raise Stop("lock", "The Linux images for develop's recipe fingerprints are still being refreshed. Nothing " + "resumes the cut when that run finishes, so dispatch Scheduled Beta Cut after it does.", + refreshing.get("html_url")) + raise Stop("lock", "No validated Linux image generation matches develop's recipe fingerprints. " + "Refresh the images with Refresh Build Caches (targets: linux-images) on develop.") + + def refreshes_images(self, run: dict) -> bool: + for job in self.internal.jobs(run["id"]): + name = job.get("name") or "" + if name in (NORMAL_IMAGES_JOB, f"{IMAGE_REFRESH_JOB} / {NORMAL_IMAGES_JOB}"): + return job.get("conclusion") != "skipped" + if name == IMAGE_REFRESH_JOB: + return job.get("status") != "completed" + # The run has not yet decided whether it builds the four normal images. + return True + + def prepared_lock(self, generation: str, wanted: dict[str, str]) -> tuple[bytes, dict]: + runs = [run for run in self.internal.runs(PREPARATION, branch="develop", event="workflow_dispatch") + if preparation_of(run) == ("develop", generation)] + if any(in_flight(run) for run in runs): + raise self.wait("lock", runs, f"Prepare Release Dependencies for {generation} is still running; the cut " + "waits for its lock.") + for run in sorted(runs, key=run_order, reverse=True): + if run.get("conclusion") != "success": + continue + lock = self.internal.artifact_file(run["id"], PREPARED_ARTIFACT, LOCK_FILE) + if lock is not None and lock_generation(lock) == generation and lock_recipes(lock) == wanted: + return lock, run + latest = newest(runs) + if latest is not None and latest.get("conclusion") != "success": + raise Stop("lock", f"Prepare Release Dependencies for {generation} concluded {latest.get('conclusion')}. " + "Re-run it to resume the cut.", latest.get("html_url")) + tip = self.repository.develop() + if self.recipes(tip) != wanted: + # The preparation verifies the images against develop's tip, not against the commit being cut. + raise Stop("lock", f"develop's tip {tip} has other Linux image recipes than its newest green commit, so " + f"a preparation of {generation} would fail. Dispatch Scheduled Beta Cut once the tip's " + "CI has passed.") + self.internal.dispatch(PREPARATION, "develop", {"source_branch": "develop", "generation": generation}) + raise Skip(f"Dispatched Prepare Release Dependencies for {generation}; a later run commits its lock " + "in the cut.") + + def commit_cut(self, line: Line, number: int, target: str, lock: bytes, lock_note: str) -> str: + version = line.prerelease(number) + worktree, conflicts = self.repository.start_merge(line.tip, target, self.bot_login, self.bot_email) + try: + unexpected = sorted(set(conflicts) - METADATA_FILES) + if unexpected: + raise Stop("merge", f"Merging develop {target} into {line.branch} conflicts in " + f"{', '.join(unexpected)}.") + self.repository.write(worktree, {STATE_FILE: render_state(line.version, number).encode(), LOCK_FILE: lock}) + try: + self.repository.validate_lock(worktree) + except RuntimeError as error: + raise Stop("lock", f"The Linux image lock for {version} does not validate: {error}") from error + body = textwrap.fill( + f"Merge develop at {target} into {line.branch} with release state BETA {number}. {lock_note}".strip(), + 72, break_long_words=False, break_on_hyphens=False) + commit = self.repository.commit(worktree, self.bot_login, self.bot_email, + f"Cut {version} from develop\n\n{body}\n") + try: + self.repository.push(commit, line.branch) + except RuntimeError as error: + raise Stop("merge", f"Pushing the {version} cut to {line.branch} failed: {error}") from error + return commit + finally: + self.repository.discard(worktree) + + def continue_after(self, run: dict) -> str: + actor = (run.get("actor") or {}).get("login") + if actor != self.bot_login: + raise Skip(f"{run.get('html_url')} was started by {actor}, not {self.bot_login}; nothing to do.") + workflow = (run.get("path"), run.get("event")) + conclusion = run.get("conclusion") + if workflow == (f".github/workflows/{PREPARATION}", "workflow_dispatch"): + return self.after_preparation(run) + self.repository.sync(shallow=True) + line = self.beta_line() + if (run.get("head_branch"), run.get("head_sha")) != (line.branch, line.tip): + raise Skip(f"{run.get('html_url')} ran on {run.get('head_branch')} at {run.get('head_sha')}, not at the " + f"tip of {line.branch}; nothing to do.") + version = line.prerelease() + tag = candidate_tag(version) + if workflow == (f".github/workflows/{CI}", "push"): + if conclusion != "success": + raise Stop("ci", f"CI for the {version} cut concluded {conclusion}. Re-run it if the failure is " + "transient.", run.get("html_url")) + if self.repository.tag(tag) is not None: + raise Skip(f"`{tag}` already exists; nothing to do.") + if any(in_flight(candidate) for candidate in self.candidate_runs(line)): + raise Skip(f"A candidate run for {version} is already running; nothing to do.") + return self.dispatch_candidate(line) + candidate_run = workflow == (f".github/workflows/{CANDIDATE}", "workflow_dispatch") + if candidate_run and candidate_of(run) == (version, "create"): + if conclusion != "success": + if self.repository.tag(tag) is None: + after = f"the next scheduled cut retries {version}" + else: + after = f"the next scheduled cut moves on to BETA {line.number + 1}, because build tags never move" + raise Stop("candidate", f"The candidate run for `{tag}` concluded {conclusion}. Re-run it if the " + f"failure is transient; otherwise {after}.", run.get("html_url")) + tag_sha = self.repository.tag(tag) + if tag_sha != line.tip: + raise Stop("candidate", f"The candidate run succeeded, but `{tag}` resolves to {tag_sha or 'nothing'} " + f"instead of {line.tip}.", run.get("html_url")) + self.internal.dispatch(PROMOTION, line.branch, + {"version": version, "candidate_run_id": str(run["id"]), "operation": "promote"}) + return f"Dispatched Promote Release Source for `v{version}` from candidate run {run['id']}." + if workflow == (f".github/workflows/{PROMOTION}", "workflow_dispatch"): + if conclusion != "success": + raise Stop("promotion", f"Promote Release Source for {version} concluded {conclusion}. Re-running it " + f"resumes {version}.", run.get("html_url")) + raise Skip(f"`v{version}` is promoted; the public repository's release run publishes it.") + raise Skip(f"{run.get('html_url')} is not a CI, candidate or promotion run of the {version} cut; " + "nothing to do.") + + def after_preparation(self, run: dict) -> str: + prepared = preparation_of(run) + if run.get("head_branch") != "develop" or prepared is None or prepared[0] != "develop": + raise Skip(f"{run.get('html_url')} is not a preparation from develop; nothing to do.") + if run.get("conclusion") != "success": + raise Stop("lock", f"Prepare Release Dependencies for {prepared[1]} concluded {run.get('conclusion')}. " + "Re-run it to resume the cut.", run.get("html_url")) + self.internal.dispatch(BETA_CUT, "develop", {}) + return f"Dispatched the beta cut on develop: the lock for {prepared[1]} is prepared." + + +class Repository: + """Git operations on the workflow checkout; remote access authenticates with the release-bot token.""" + + def __init__(self, root: Path, remote: str, token: str | None = None, server: str = "https://github.com") -> None: + self.root = root + self.remote = remote + self.auth: tuple[str, ...] = () + if token: + credential = base64.b64encode(f"x-access-token:{token}".encode()).decode() + self.auth = ("-c", f"http.{server}/.extraheader=AUTHORIZATION: basic {credential}") + + def git(self, *arguments: str, cwd: Path | None = None, check: bool = True, + env: dict[str, str] | None = None) -> subprocess.CompletedProcess: + result = subprocess.run(["git", *self.auth, *arguments], cwd=cwd or self.root, capture_output=True, + env={**os.environ, "GIT_TERMINAL_PROMPT": "0", **(env or {})}) + if check and result.returncode: + detail = (result.stderr or result.stdout).decode(errors="replace").strip() + raise RuntimeError(f"git {' '.join(arguments[:2])} failed: {detail}") + return result + + def output(self, *arguments: str, cwd: Path | None = None) -> str: + return self.git(*arguments, cwd=cwd).stdout.decode().strip() + + def sync(self, *, shallow: bool = False) -> None: + releases = "+refs/heads/release/*:refs/remotes/origin/release/*" + if shallow: + self.git("fetch", "--prune", "--no-tags", "--depth=1", self.remote, releases) + else: + self.git("fetch", "--prune", "--no-tags", self.remote, + "+refs/heads/develop:refs/remotes/origin/develop", releases) + + def release_heads(self) -> dict[str, str]: + listing = self.output("for-each-ref", "--format=%(refname:strip=3) %(objectname)", + "refs/remotes/origin/release/") + return dict(line.split(" ", 1) for line in listing.splitlines()) + + def develop(self) -> str: + return self.output("rev-parse", "--verify", "refs/remotes/origin/develop^{commit}") + + def tag(self, name: str) -> str | None: + listing = self.output("ls-remote", self.remote, f"refs/tags/{name}", f"refs/tags/{name}^{{}}") + refs = {ref: sha for sha, ref in (line.split("\t") for line in listing.splitlines())} + return refs.get(f"refs/tags/{name}^{{}}") or refs.get(f"refs/tags/{name}") + + def contains(self, commit: str) -> bool: + return bool(commit) and self.git("cat-file", "-e", f"{commit}^{{commit}}", check=False).returncode == 0 + + def read(self, commit: str, path: str) -> bytes | None: + self.git("cat-file", "-e", f"{commit}^{{commit}}") + if self.git("cat-file", "-e", f"{commit}:{path}", check=False).returncode: + return None + return self.git("cat-file", "blob", f"{commit}:{path}").stdout + + def is_ancestor(self, ancestor: str, descendant: str) -> bool: + result = self.git("merge-base", "--is-ancestor", ancestor, descendant, check=False) + if result.returncode not in (0, 1): + raise RuntimeError(f"git merge-base failed: {result.stderr.decode(errors='replace').strip()}") + return result.returncode == 0 + + def commits_missing_from_develop(self, tip: str) -> list[Commit]: + commits = [] + for sha in self.output("rev-list", f"refs/remotes/origin/develop..{tip}").split(): + email, _, parents = self.output("show", "-s", "--format=%ae%n%P", sha).partition("\n") + if parents: + files = self.output("diff", "--no-renames", "--name-only", parents.split()[0], sha) + else: + files = self.output("ls-tree", "-r", "--name-only", sha) + commits.append(Commit(sha, email, tuple(files.splitlines()))) + return commits + + def fingerprints(self, commit: str) -> dict[str, str] | None: + if not self.contains(commit): + return None + archive = self.git("archive", "--format=tar", commit, ".github").stdout + with tempfile.TemporaryDirectory() as directory: + subprocess.run(["tar", "-x", "-f", "-", "-C", directory], input=archive, check=True, capture_output=True) + return { + key: subprocess.run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", profile], cwd=directory, + check=True, capture_output=True, text=True).stdout.strip() + for key, (_package, profile, *_rest) in images.IMAGES.items() + } + + def start_merge(self, tip: str, commit: str, name: str, email: str) -> tuple[Path, list[str]]: + worktree = Path(tempfile.mkdtemp(prefix="beta-cut-")) / "tree" + self.git("worktree", "add", "--detach", str(worktree), tip) + merged = self.git("merge", "--no-ff", "--no-commit", commit, cwd=worktree, check=False, + env=git_identity(name, email)) + conflicts = self.output("diff", "--name-only", "--diff-filter=U", cwd=worktree).splitlines() + if merged.returncode and not conflicts: + detail = (merged.stderr or merged.stdout).decode(errors="replace").strip() + self.discard(worktree) + raise RuntimeError(f"git merge failed: {detail}") + return worktree, conflicts + + def write(self, worktree: Path, files: dict[str, bytes]) -> None: + for path, content in files.items(): + (worktree / path).write_bytes(content) + self.git("add", "--", *files, cwd=worktree) + + def validate_lock(self, worktree: Path) -> None: + result = subprocess.run([sys.executable, ".github/scripts/release-linux-images.py", "validate", LOCK_FILE, + "--check-remote"], cwd=worktree, capture_output=True, text=True) + if result.returncode: + raise RuntimeError((result.stderr or result.stdout).strip()) + + def commit(self, worktree: Path, name: str, email: str, message: str) -> str: + self.git("commit", "--no-verify", "--quiet", "--message", message, cwd=worktree, + env=git_identity(name, email)) + return self.output("rev-parse", "HEAD", cwd=worktree) + + def push(self, commit: str, branch: str) -> None: + self.git("push", self.remote, f"{commit}:refs/heads/{branch}") + + def discard(self, worktree: Path) -> None: + self.git("worktree", "remove", "--force", str(worktree), check=False) + shutil.rmtree(worktree.parent, ignore_errors=True) + + +class KeepRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *arguments, **keywords): + return None + + +class GitHub: + def __init__(self, token: str, repository: str, api_url: str = "https://api.github.com") -> None: + self.token = token + self.repository = repository + self.api_url = api_url.rstrip("/") + + def request(self, method: str, path: str, *, params: dict | None = None, + body: object = None) -> urllib.request.Request: + url = self.api_url + path + ("?" + urllib.parse.urlencode(params) if params else "") + data = None if body is None else json.dumps(body).encode() + headers = { + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "wsjtx-beta-scheduler", + } + if data is not None: + headers["Content-Type"] = "application/json" + return urllib.request.Request(url, data=data, method=method, headers=headers) + + def call(self, method: str, path: str, *, params: dict | None = None, body: object = None, + missing_ok: bool = False): + try: + with urllib.request.urlopen(self.request(method, path, params=params, body=body), timeout=60) as response: + payload = response.read() + except urllib.error.HTTPError as error: + if missing_ok and error.code == 404: + return None + raise RuntimeError(f"{method} {path} failed with HTTP {error.code}") from error + return json.loads(payload) if payload else None + + def runs(self, workflow: str, **filters: str) -> list[dict]: + return self.call("GET", f"/repos/{self.repository}/actions/workflows/{workflow}/runs", + params={"per_page": 100, **filters})["workflow_runs"] + + def jobs(self, run_id: int) -> list[dict]: + return self.call("GET", f"/repos/{self.repository}/actions/runs/{run_id}/jobs", + params={"per_page": 100})["jobs"] + + def dispatch(self, workflow: str, ref: str, inputs: dict[str, str]) -> None: + self.call("POST", f"/repos/{self.repository}/actions/workflows/{workflow}/dispatches", + body={"ref": ref, "inputs": inputs}) + + def release_published(self, tag: str) -> bool: + path = f"/repos/{self.repository}/releases/tags/{urllib.parse.quote(tag, safe='')}" + return self.call("GET", path, missing_ok=True) is not None + + def user_id(self, login: str) -> int: + return self.call("GET", f"/users/{urllib.parse.quote(login, safe='')}")["id"] + + def artifact_file(self, run_id: int, name: str, member: str) -> bytes | None: + listing = self.call("GET", f"/repos/{self.repository}/actions/runs/{run_id}/artifacts", + params={"name": name, "per_page": 100}) + live = [item for item in listing["artifacts"] if item.get("name") == name and not item.get("expired")] + if not live: + return None + archive = self.download(f"/repos/{self.repository}/actions/artifacts/{live[0]['id']}/zip") + with zipfile.ZipFile(io.BytesIO(archive)) as bundle: + return bundle.read(member) if member in bundle.namelist() else None + + def download(self, path: str) -> bytes: + try: + with urllib.request.build_opener(KeepRedirect).open(self.request("GET", path), timeout=60) as response: + return response.read() + except urllib.error.HTTPError as redirect: + location = redirect.headers.get("Location") + if redirect.code not in (301, 302, 303, 307, 308) or not location: + raise RuntimeError(f"GET {path} failed with HTTP {redirect.code}") from redirect + # The signed storage URL must not receive the API token. + with urllib.request.urlopen(location, timeout=120) as response: + return response.read() + + +class Alerts: + def __init__(self, github, run_url: str) -> None: + self.github = github + self.run_url = run_url + + def post(self, stage: str, reason: str, link: str | None = None) -> None: + lines = [f"**Stage:** {stage}", f"**Reason:** {reason}", f"**Run:** {link or self.run_url}"] + if link and link != self.run_url: + lines.append(f"**Reported by:** {self.run_url}") + body = "\n\n".join(lines) + issues_path = f"/repos/{self.github.repository}/issues" + issues = self.github.call("GET", issues_path, + params={"state": "open", "creator": ALERT_CREATOR, "per_page": 100}) + tracking = sorted( + issue["number"] for issue in issues + if issue.get("title") == ALERT_TITLE and "pull_request" not in issue + and (issue.get("user") or {}).get("login") == ALERT_CREATOR + ) + if tracking: + self.github.call("POST", f"{issues_path}/{tracking[0]}/comments", body={"body": body}) + else: + self.github.call("POST", issues_path, body={"title": ALERT_TITLE, "body": body}) + + +def run_step(command: str, action: Callable[[], str], + notes: list[str]) -> tuple[int, str, tuple[str, str, str | None] | None]: + alert = None + try: + result, status = action(), 0 + except Skip as skip: + result, status = str(skip), 0 + except Stop as stop: + result, status, alert = f"Stopped at {stop.stage}: {stop}", 1, (stop.stage, str(stop), stop.link) + except Exception as error: # Every unexpected failure also reaches the tracking issue. + traceback.print_exc() + result, status, alert = f"Failed: {error}", 1, (command, f"Unexpected error: {error}", None) + summary = "\n".join([f"## Scheduled beta: {command}", "", *(f"- {note}" for note in notes), "", result, ""]) + return status, summary, alert + + +def build_scheduler(command: str, env, notes: list[str]) -> Scheduler: + repository = env["GITHUB_REPOSITORY"] + server = env.get("GITHUB_SERVER_URL", "https://github.com") + api_url = env.get("GITHUB_API_URL", "https://api.github.com") + token = env["RELEASE_BOT_TOKEN"] + bot_login = f"{env['RELEASE_BOT_SLUG']}[bot]" + internal = GitHub(token, repository, api_url) + git = Repository(Path.cwd(), f"{server}/{repository}.git", token, server) + if command == "continue": + return Scheduler(git, internal, bot_login=bot_login, notes=notes) + return Scheduler( + git, internal, + GitHub(env["PUBLIC_READ_TOKEN"], PUBLIC_REPOSITORY, api_url), + image_tags.GitHubPackagesClient(env["GITHUB_TOKEN"], api_url), + bot_login=bot_login, + bot_email=f"{internal.user_id(bot_login)}+{bot_login}@users.noreply.github.com", + notes=notes, + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("cut", help="apply one step of the beta state machine") + commands.add_parser("continue", help="continue after the workflow run in GITHUB_EVENT_PATH") + alert_parser = commands.add_parser("alert", help="record a failure on the tracking issue") + alert_parser.add_argument("--stage", required=True) + alert_parser.add_argument("--reason", required=True) + args = parser.parse_args(argv) + env = os.environ + repository = env["GITHUB_REPOSITORY"] + run_url = f"{env.get('GITHUB_SERVER_URL', 'https://github.com')}/{repository}/actions/runs/{env['GITHUB_RUN_ID']}" + alerts = Alerts(GitHub(env["GITHUB_TOKEN"], repository, env.get("GITHUB_API_URL", "https://api.github.com")), + run_url) + if args.command == "alert": + alerts.post(args.stage, args.reason) + return 0 + notes: list[str] = [] + + def step() -> str: + scheduler = build_scheduler(args.command, env, notes) + if args.command == "cut": + return scheduler.cut() + event = json.loads(Path(env["GITHUB_EVENT_PATH"]).read_text(encoding="utf-8")) + return scheduler.continue_after(event["workflow_run"]) + + status, summary, alert = run_step(args.command, step, notes) + print(summary) + if env.get("GITHUB_STEP_SUMMARY"): + with open(env["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as stream: + stream.write(summary) + if alert: + alerts.post(*alert) + if env.get("GITHUB_OUTPUT"): + with open(env["GITHUB_OUTPUT"], "a", encoding="utf-8") as stream: + stream.write("alerted=true\n") + return status + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/build-fftw-macos.sh b/.github/scripts/build-fftw-macos.sh index 6ae1505d..cbaf0291 100755 --- a/.github/scripts/build-fftw-macos.sh +++ b/.github/scripts/build-fftw-macos.sh @@ -19,7 +19,7 @@ cd "fftw-${version}" --enable-single \ --enable-threads \ --enable-shared --disable-static \ - CFLAGS="-mmacosx-version-min=${deployment_target}" \ + CFLAGS="-O3 -mmacosx-version-min=${deployment_target}" \ LDFLAGS="-mmacosx-version-min=${deployment_target}" make -j"$(sysctl -n hw.ncpu)" make install diff --git a/.github/scripts/build-linux-armhf-cross.sh b/.github/scripts/build-linux-armhf-cross.sh index cfbb2f03..f8c80dd8 100755 --- a/.github/scripts/build-linux-armhf-cross.sh +++ b/.github/scripts/build-linux-armhf-cross.sh @@ -4,8 +4,13 @@ set -euo pipefail VERSION="${VERSION:?missing}" ARCH="${ARCH:?missing}" HAMLIB_BRANCH="${HAMLIB_BRANCH:?missing}" -WSJT_RELEASE_CHANNEL="${WSJT_RELEASE_CHANNEL:-DEVEL}" -WSJT_RC_NUMBER="${WSJT_RC_NUMBER:-}" +WSJT_RELEASE_CHANNEL="${WSJT_RELEASE_CHANNEL:-}" +WSJT_PRERELEASE_NUMBER="${WSJT_PRERELEASE_NUMBER:-}" +ARMHF_BUILD_ONLY="${ARMHF_BUILD_ONLY:-false}" +case "$ARMHF_BUILD_ONLY" in + true|false) ;; + *) echo "ARMHF_BUILD_ONLY must be true or false" >&2; exit 2 ;; +esac if [ "$ARCH" != armhf ]; then echo "build-linux-armhf-cross.sh supports only arch=armhf" >&2 exit 2 @@ -42,7 +47,7 @@ cmake -S . -B wsjtx-build \ -DWSJT_ENABLE_TESTS=ON \ -DWSJT_FORTRAN_LIBRARY_VARIANTS=OPENMP_ONLY \ -DWSJT_RELEASE_CHANNEL="$WSJT_RELEASE_CHANNEL" \ - -DWSJT_RC_NUMBER="$WSJT_RC_NUMBER" \ + -DWSJT_PRERELEASE_NUMBER="$WSJT_PRERELEASE_NUMBER" \ -Wno-dev cmake --build wsjtx-build --parallel "$(nproc)" ended="$(date +%s)" @@ -55,6 +60,10 @@ ccache --show-stats validate_linux_build_executables wsjtx-build "$ARCH" .github/scripts/audit-armhf-cross-build.sh wsjtx-build +if [ "$ARMHF_BUILD_ONLY" = true ]; then + echo "ARMHF build-only compilation and binary audits complete for version=$VERSION" + exit 0 +fi echo "::group::Prepare ARMHF AppDir" cmake --install wsjtx-build --prefix /work/AppDir/usr validate_linux_application_tree AppDir appdir "$ARCH" diff --git a/.github/scripts/generate-quick-downloads.py b/.github/scripts/generate-quick-downloads.py index 6706292d..0ba21c36 100755 --- a/.github/scripts/generate-quick-downloads.py +++ b/.github/scripts/generate-quick-downloads.py @@ -3,7 +3,7 @@ The release workflow attaches every build artifact to the Release, which makes the assets list long and hard for an end user to navigate (installers sit among -standalone command-line utilities, raw binaries, and source). This emits a +the command-line program tarballs, checksums, the manifest, and source). This emits a short, curated per-platform installer picker to prepend to the auto-generated release notes. @@ -19,9 +19,8 @@ Usage: generate-quick-downloads.py <owner/repo> <tag> <asset-path-or-name>... Only installer-grade assets are listed (.pkg / win64.exe / .deb / .rpm / -.AppImage) plus the source tarball. Per-mode utility tarballs and raw -command-line binaries are intentionally omitted; they remain in the full -assets list below the notes. +.AppImage) plus the source tarball. The command-line program tarballs are +intentionally omitted; they remain in the full assets list below the notes. """ import os import re @@ -66,8 +65,8 @@ def main(argv): appimage[m.group(1)] = n elif (m := re.search(r"\.([A-Za-z0-9_]+)\.rpm$", n)): rpm[m.group(1)] = n - # Anything else (utility tarballs, raw binaries) is intentionally - # excluded; it stays in the full assets list. + # Anything else (program tarballs, checksums, the manifest) is + # intentionally excluded; it stays in the full assets list. def arches(d): known = [a for a in ARCH_ORDER if a in d] @@ -83,7 +82,7 @@ def main(argv): "## Quick Downloads", "", "Choose the installer for your platform. The full assets list below also", - "includes standalone command-line utilities and source code for developers.", + "includes the command-line program tarballs and source code for developers.", ] if macos: diff --git a/.github/scripts/is-linux-ci-image-input.sh b/.github/scripts/is-linux-ci-image-input.sh index 23a76e1b..07437151 100755 --- a/.github/scripts/is-linux-ci-image-input.sh +++ b/.github/scripts/is-linux-ci-image-input.sh @@ -82,6 +82,8 @@ if [ "${1:-}" = "--self-test" ]; then expect_non_input normal-noble ".github/images/linux-ci/install-armhf-runtime-packages.sh" expect_input armhf-cross-bookworm ".github/images/linux-ci/armhf-cross-toolchain.config" expect_non_input armhf-runtime-bookworm ".github/images/linux-ci/armhf-cross-toolchain.config" + expect_input armhf-cross-bookworm ".github/scripts/armhf-toolchain-config.sh" + expect_input armhf-runtime-bookworm ".github/scripts/armhf-toolchain-config.sh" expect_input normal-noble ".github/scripts/build-hamlib-linux.sh" expect_non_input tsan-noble ".github/scripts/build-hamlib-linux.sh" expect_input tsan-noble ".github/scripts/build-qt-tsan-linux.sh" diff --git a/.github/scripts/linux-artifact-validation.sh b/.github/scripts/linux-artifact-validation.sh index 01a607f6..2a7db636 100644 --- a/.github/scripts/linux-artifact-validation.sh +++ b/.github/scripts/linux-artifact-validation.sh @@ -70,6 +70,7 @@ validate_elf_executable() { local file_output local header_output local program_output + local dynamic_output if [ ! -x "$path" ]; then linux_validation_error "Required executable is missing: $path" @@ -80,7 +81,14 @@ validate_elf_executable() { header_output=$(readelf -hW -- "$path") || return program_output=$(readelf -lW -- "$path") || return echo "$file_output" - validate_elf_metadata "$arch" "$path" "$file_output" "$header_output" "$program_output" + validate_elf_metadata "$arch" "$path" "$file_output" "$header_output" "$program_output" || return + if [ "${path##*/}" = jt9 ]; then + dynamic_output=$(readelf -dW -- "$path") || return + if printf '%s\n' "$dynamic_output" | awk '/\(NEEDED\)/ && /\[libQt/ { found=1 } END { exit found ? 0 : 1 }'; then + linux_validation_error "$path must not depend on Qt" + return 1 + fi + fi } validate_linux_build_executables() { diff --git a/.github/scripts/linux-ci-image-inputs.sh b/.github/scripts/linux-ci-image-inputs.sh index bc3e43af..938ad2d7 100644 --- a/.github/scripts/linux-ci-image-inputs.sh +++ b/.github/scripts/linux-ci-image-inputs.sh @@ -33,6 +33,7 @@ linux_ci_image_inputs() { printf '%s\n' \ .github/images/linux-ci/Dockerfile.armhf-cross \ .github/images/linux-ci/armhf-cross-toolchain.config \ + .github/scripts/armhf-toolchain-config.sh \ .github/scripts/armhf-ci-image-config.sh \ .github/scripts/build-armhf-toolchain-smoke.sh \ .github/scripts/build-hamlib-armhf-cross.sh \ @@ -49,6 +50,7 @@ linux_ci_image_inputs() { printf '%s\n' \ .github/images/linux-ci/Dockerfile.armhf-runtime \ .github/images/linux-ci/install-armhf-runtime-packages.sh \ + .github/scripts/armhf-toolchain-config.sh \ .github/scripts/armhf-ci-image-config.sh \ .github/scripts/linux-ci-image-config.sh \ .github/scripts/linux-ci-image-fingerprint.sh \ diff --git a/.github/scripts/linuxdeploy-excludelist.txt b/.github/scripts/linuxdeploy-excludelist.txt new file mode 100644 index 00000000..ee55ae4d --- /dev/null +++ b/.github/scripts/linuxdeploy-excludelist.txt @@ -0,0 +1,55 @@ +# The excludelist compiled into linuxdeploy 1-alpha-20251107-1, identical in +# its x86_64, aarch64 and armhf builds. linuxdeploy leaves these libraries, +# ld-linux* and linux-vdso to the host; update this file with the pin. +ld-linux-x86-64.so.2 +ld-linux.so.2 +libBrokenLocale.so.1 +libEGL.so.1 +libGL.so.1 +libGLX.so.0 +libGLdispatch.so.0 +libICE.so.6 +libOpenGL.so.0 +libSM.so.6 +libX11-xcb.so.1 +libX11.so.6 +libanl.so.1 +libasound.so.2 +libc.so.6 +libcidn.so.1 +libcom_err.so.2 +libdl.so.2 +libdrm.so.2 +libexpat.so.1 +libfontconfig.so.1 +libfreetype.so.6 +libfribidi.so.0 +libgbm.so.1 +libgcc_s.so.1 +libglapi.so.0 +libgmp.so.10 +libgpg-error.so.0 +libharfbuzz.so.0 +libjack.so.0 +libm.so.6 +libmvec.so.1 +libnss_compat.so.2 +libnss_dns.so.2 +libnss_files.so.2 +libnss_hesiod.so.2 +libnss_nis.so.2 +libnss_nisplus.so.2 +libpipewire-0.3.so.0 +libpthread.so.0 +libresolv.so.2 +librt.so.1 +libstdc++.so.6 +libthread_db.so.1 +libusb-1.0.so.0 +libutil.so.1 +libuuid.so.1 +libwayland-client.so.0 +libxcb-dri2.so.0 +libxcb-dri3.so.0 +libxcb.so.1 +libz.so.1 diff --git a/.github/scripts/package-cli-tools.sh b/.github/scripts/package-cli-tools.sh new file mode 100755 index 00000000..e9b7d03d --- /dev/null +++ b/.github/scripts/package-cli-tools.sh @@ -0,0 +1,499 @@ +#!/usr/bin/env bash +# Package the command-line programs into the release tarballs published beside +# the installers: one tarball per line of CMake/release-tarballs.txt. +# +# package-cli-tools.sh --platform macos|linux|windows --version V --arch A \ +# --groups FILE --source DIR --out DIR \ +# [--dll-dir DIR --system-dir DIR] [--linuxdeploy COMMAND] +# +# wsjtx-V-<target>-<tarball>.tar.gz holds one directory of the same name: the +# tarball's programs, every library they load beyond the operating system's, +# README.txt, COPYING and THIRD-PARTY.txt. A missing program, an unresolved +# library or a library third-party-libraries.tsv does not name fails the run, +# and then no tarball is written. +# +# macos: --source is the CLI assets directory: the signed programs and the +# deployed lib/ of dylibs they reference as @rpath/<name>. Each +# tarball gets its programs at the top and, in lib/, the dylibs they +# reach through their LC_RPATH entries. A reference outside /usr/lib +# and /System/Library that does not resolve there, or an absolute +# LC_RPATH, fails the run. +# linux: --source is the CMake build directory. --linuxdeploy is a command +# that runs the pinned linuxdeploy AppImage. It deploys each tarball's +# programs to bin/ and the libraries they load to lib/, except those +# on its excludelist (linuxdeploy-excludelist.txt), with RUNPATH +# $ORIGIN/../lib and $ORIGIN, and the libraries' Debian copyright +# files to share/doc/. A library that resolves neither inside the +# tarball nor to the excludelist, or a RUNPATH entry not relative to +# $ORIGIN, fails the run. +# windows: --source is the CMake build directory, --dll-dir the staged bin/ +# after DLL fixup and --system-dir the Windows system directory. Each +# tarball gets its .exe files and the transitive closure of the DLLs +# they import from --dll-dir; an import found in neither directory +# fails the run. +set -euo pipefail + +PLATFORM=""; VERSION=""; ARCH=""; GROUPS_FILE=""; SOURCE=""; OUT=""; DLL_DIR=""; SYSTEM_DIR=""; LINUXDEPLOY="" +while [ "$#" -gt 0 ]; do + case "$1" in + --platform) PLATFORM="$2"; shift 2 ;; + --version) VERSION="$2"; shift 2 ;; + --arch) ARCH="$2"; shift 2 ;; + --groups) GROUPS_FILE="$2"; shift 2 ;; + --source) SOURCE="$2"; shift 2 ;; + --out) OUT="$2"; shift 2 ;; + --dll-dir) DLL_DIR="$2"; shift 2 ;; + --system-dir) SYSTEM_DIR="$2"; shift 2 ;; + --linuxdeploy) LINUXDEPLOY="$2"; shift 2 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +for option in PLATFORM VERSION ARCH GROUPS_FILE SOURCE OUT; do + if [ -z "${!option}" ]; then echo "missing --$(echo "${option%_FILE}" | tr '[:upper:]' '[:lower:]')" >&2; exit 2; fi +done + +SCRIPTS="$(cd "$(dirname "$0")" && pwd)" +COPYING="${SCRIPTS}/../../COPYING" +NOTICES_TABLE="${SCRIPTS}/third-party-libraries.tsv" +EXCLUDELIST="${SCRIPTS}/linuxdeploy-excludelist.txt" +LICENSE_PAGE="${SCRIPTS}/../../doc/common/license.adoc" + +fail() { echo "::error::$*" >&2; exit 1; } + +case "$PLATFORM" in + macos) TARGET="${ARCH}-macOS"; EXT="" ;; + linux) TARGET="linux-${ARCH}"; EXT="" + [ -n "$LINUXDEPLOY" ] || { echo "::error::--linuxdeploy is required for linux" >&2; exit 2; } ;; + windows) TARGET="windows-${ARCH}"; EXT=".exe" + [ -n "$DLL_DIR" ] && [ -d "$DLL_DIR" ] || { echo "::error::--dll-dir is required for windows" >&2; exit 2; } + [ -n "$SYSTEM_DIR" ] && [ -d "$SYSTEM_DIR" ] || { echo "::error::--system-dir is required for windows" >&2; exit 2; } + ;; + *) echo "unknown platform: $PLATFORM" >&2; exit 2 ;; +esac +[ -d "$SOURCE" ] || fail "source directory not found: $SOURCE" +[ -s "$GROUPS_FILE" ] || fail "release tarball list not found or empty: $GROUPS_FILE" +[ -f "$COPYING" ] || fail "COPYING not found: $COPYING" +[ -f "$NOTICES_TABLE" ] || fail "third-party library table not found: $NOTICES_TABLE" +[ -f "$LICENSE_PAGE" ] || fail "license page not found: $LICENSE_PAGE" +[ "$PLATFORM" != linux ] || [ -f "$EXCLUDELIST" ] || fail "linuxdeploy excludelist not found: $EXCLUDELIST" + +# Plain indexed arrays and lookup files keep this runnable on bash 3.2. +GROUP_NAMES=(); GROUP_PROGRAMS=() +while IFS= read -r line || [ -n "$line" ]; do + line="${line%$'\r'}" # a Windows checkout may have CRLF endings + read -r -a fields <<< "$line" || true + [ "${#fields[@]}" -gt 0 ] || continue + case "${fields[0]}" in '#'*) continue ;; esac + [ "${#fields[@]}" -ge 2 ] || fail "release tarball ${fields[0]} names no programs in ${GROUPS_FILE}" + for name in ${GROUP_NAMES[@]+"${GROUP_NAMES[@]}"}; do + [ "$name" != "${fields[0]}" ] || fail "release tarball ${name} is named twice in ${GROUPS_FILE}" + done + GROUP_NAMES+=("${fields[0]}") + GROUP_PROGRAMS+=("${fields[*]:1}") +done < "$GROUPS_FILE" +[ "${#GROUP_NAMES[@]}" -gt 0 ] || fail "no release tarballs named in ${GROUPS_FILE}" + +missing=() +for programs in "${GROUP_PROGRAMS[@]}"; do + for program in $programs; do + [ -f "${SOURCE}/${program}${EXT}" ] || missing+=("${program}${EXT}") + done +done +[ "${#missing[@]}" -eq 0 ] || fail "programs listed in ${GROUPS_FILE} are missing under ${SOURCE}: ${missing[*]}" + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +mkdir -p "${WORK}/tarballs" + +# --- macOS ----------------------------------------------------------------- + +macho_rpaths() { + otool -l "$1" | awk '$1 == "cmd" && $2 == "LC_RPATH" { getline; getline; print $2 }' +} + +# Copies into $DEST/lib every dylib program $1 reaches. dyld resolves the +# @rpath references of the program, and of each dylib it loads, through that +# file's own LC_RPATH entries and then the program's; @executable_path is the +# program's directory, the top of $SOURCE. +macos_closure() { + local program="$1" rpath entry file id ref candidate directory found + local program_rpaths=() rpaths=() queue=("$1") unresolved=() i=0 visited=$'\n'"$1"$'\n' + while IFS= read -r rpath; do + case "$rpath" in + @loader_path|@executable_path) entry="" ;; + @loader_path/*) entry="${rpath#@loader_path/}" ;; + @executable_path/*) entry="${rpath#@executable_path/}" ;; + /*) fail "${program} has an absolute LC_RPATH: ${rpath}" ;; + *) fail "${program} has an LC_RPATH dyld cannot resolve: ${rpath}" ;; + esac + case "/${entry}/" in */../*) fail "${program} has an LC_RPATH outside its directory: ${rpath}" ;; esac + program_rpaths+=("$entry") + done < <(macho_rpaths "${SOURCE}/${program}") + while [ "$i" -lt "${#queue[@]}" ]; do + file="${queue[$i]}"; i=$((i + 1)) + directory=$(dirname "$file") + [ "$directory" != . ] || directory="" + rpaths=() + if [ "$file" != "$program" ]; then + while IFS= read -r rpath; do + case "$rpath" in + @loader_path) entry="$directory" ;; + @loader_path/*) entry="${directory:+${directory}/}${rpath#@loader_path/}" ;; + @executable_path) entry="" ;; + @executable_path/*) entry="${rpath#@executable_path/}" ;; + /*) fail "${file} has an absolute LC_RPATH: ${rpath}" ;; + *) fail "${file} has an LC_RPATH dyld cannot resolve: ${rpath}" ;; + esac + # QtCore searches ../Frameworks, outside the tarball; nothing may load from there. + case "/${entry}/" in */../*) continue ;; esac + rpaths+=("$entry") + done < <(macho_rpaths "${SOURCE}/${file}") + fi + rpaths+=(${program_rpaths[@]+"${program_rpaths[@]}"}) + id=$(otool -D "${SOURCE}/${file}" | awk 'NR == 2 { print; exit }') + while IFS= read -r ref; do + [ "$ref" != "$id" ] || continue + found="" + case "$ref" in + /usr/lib/*|/System/Library/*) continue ;; + @rpath/*) + for entry in ${rpaths[@]+"${rpaths[@]}"}; do + candidate="${entry:+${entry}/}${ref#@rpath/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; break; fi + done + ;; + @loader_path/*) + candidate="${directory:+${directory}/}${ref#@loader_path/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; fi + ;; + @executable_path/*) + candidate="${ref#@executable_path/}" + if [ -f "${SOURCE}/${candidate}" ]; then found="$candidate"; fi + ;; + esac + case "/${found}/" in */../*) found="" ;; esac + case "$found" in lib/*) ;; *) found="" ;; esac + if [ -z "$found" ]; then + unresolved+=("${ref}(${file})") + continue + fi + case "$visited" in *$'\n'"$found"$'\n'*) continue ;; esac + visited="${visited}${found}"$'\n' + queue+=("$found") + if [ ! -e "${DEST}/${found}" ]; then + mkdir -p "$(dirname "${DEST}/${found}")" + cp -p "${SOURCE}/${found}" "${DEST}/${found}" + fi + done < <(otool -L "${SOURCE}/${file}" | awk 'NR > 1 { print $1 }') + done + [ "${#unresolved[@]}" -eq 0 ] || fail "references that resolve neither to lib/ under ${SOURCE} nor to the system: ${unresolved[*]}" +} + +macos_minimum() { + local file + find "$DEST" -type f ! -name '*.txt' ! -name COPYING | while IFS= read -r file; do + otool -l "$file" | awk ' + $1 == "Load" && $2 == "command" { command = "" } + $1 == "cmd" { command = $2 } + command == "LC_BUILD_VERSION" && $1 == "minos" { print $2 } + command == "LC_VERSION_MIN_MACOSX" && $1 == "version" { print $2 } + ' + done | sort -t . -k 1,1n -k 2,2n -k 3,3n | tail -n 1 +} + +# --- Windows --------------------------------------------------------------- + +windows_setup() { + have="${WORK}/have.tsv" + : > "$have" + for dll in "$DLL_DIR"/*.dll "$DLL_DIR"/*.DLL; do + [ -e "$dll" ] || continue + printf '%s\t%s\n' "$(basename "$dll" | tr '[:upper:]' '[:lower:]')" "$dll" >> "$have" + done + system="${WORK}/system.txt" + for file in "$SYSTEM_DIR"/*; do + printf '%s\n' "${file##*/}" + done | tr '[:upper:]' '[:lower:]' > "$system" +} + +windows_closure() { + local queue=("${DEST}"/*.exe) unresolved=() i=0 bin imports dep lower src target + while [ "$i" -lt "${#queue[@]}" ]; do + bin="${queue[$i]}"; i=$((i + 1)) + imports=$(objdump -p "$bin") || fail "objdump failed on ${bin##*/}" + while read -r dep; do + lower=$(printf '%s' "$dep" | tr '[:upper:]' '[:lower:]') + src=$(awk -F '\t' -v k="$lower" '$1 == k { print $2; exit }' "$have") + if [ -z "$src" ]; then + grep -qxF "$lower" "$system" || unresolved+=("${dep}(${bin##*/})") + continue + fi + target="${DEST}/$(basename "$src")" + [ ! -e "$target" ] || continue + cp "$src" "$target" + queue+=("$target") + done < <(awk '/DLL Name:/ { print $3 }' <<< "$imports") + done + [ "${#unresolved[@]}" -eq 0 ] || fail "DLL imports found in neither ${DLL_DIR} nor ${SYSTEM_DIR}: ${unresolved[*]}" +} + +# --- Linux ----------------------------------------------------------------- + +in_excludelist() { + local library="$1" pattern + case "$library" in ld-linux*|linux-vdso*) return 0 ;; esac + while IFS= read -r pattern; do + pattern="${pattern%%#*}" + pattern="${pattern//[[:space:]]/}" + [ -n "$pattern" ] || continue + # shellcheck disable=SC2254 # entries are glob patterns + case "$library" in $pattern) return 0 ;; esac + done < "$EXCLUDELIST" + return 1 +} + +linux_deploy() { + local appdir="${WORK}/appdir-$1" program arguments=() + shift + for program in "$@"; do + arguments+=(--executable "${SOURCE}/${program}") + done + env -u GITHUB_TOKEN APPIMAGE_EXTRACT_AND_RUN=1 \ + "$LINUXDEPLOY" --appimage-extract-and-run --appdir "$appdir" "${arguments[@]}" || + fail "linuxdeploy failed for ${NAME}" + mkdir -p "${DEST}/bin" "${DEST}/lib" + for program in "$@"; do + [ -f "${appdir}/usr/bin/${program}" ] || fail "linuxdeploy did not deploy ${program}" + cp -p "${appdir}/usr/bin/${program}" "${DEST}/bin/" + done + if [ -d "${appdir}/usr/lib" ]; then + find "${appdir}/usr/lib" -maxdepth 1 -type f -exec cp -p {} "${DEST}/lib/" \; + fi + if [ -d "${appdir}/usr/share/doc" ]; then + mkdir -p "${DEST}/share" + cp -R "${appdir}/usr/share/doc" "${DEST}/share/doc" + fi +} + +# Every library a file needs must resolve inside the tarball through that +# file's own RUNPATH (it is not inherited) or be on the excludelist. Records +# what the host must provide. +linux_check() { + local file relative directory dynamic line entry library found unresolved=() searched + # shellcheck disable=SC2016 # the loader's literal ORIGIN token + local origin='$ORIGIN' braced='${ORIGIN}' + : > "${WORK}/host-libraries.txt" + : > "${WORK}/host-versions.txt" + while IFS= read -r file; do + relative="${file#"${DEST}"/}" + dynamic=$(readelf -dW "$file") || fail "readelf failed on ${relative}" + directory=$(dirname "$file") + searched=() + while IFS= read -r line; do + [[ "$line" =~ \((RUNPATH|RPATH)\).*Library[[:space:]](runpath|rpath):[[:space:]]\[([^]]+)\] ]] || continue + # The loader reads an empty entry as the current directory. + case "${BASH_REMATCH[3]}" in + :*|*:|*::*) fail "${relative} has an empty RUNPATH entry: ${BASH_REMATCH[3]}" ;; + esac + IFS=: read -r -a entries <<< "${BASH_REMATCH[3]}" + for entry in "${entries[@]}"; do + case "$entry" in + "$origin"|"$braced") searched+=("$directory") ;; + "$origin"/*) searched+=("${directory}/${entry#"$origin"/}") ;; + "$braced"/*) searched+=("${directory}/${entry#"$braced"/}") ;; + *) fail "${relative} has a RUNPATH entry not relative to ${origin}: ${entry}" ;; + esac + done + done <<< "$dynamic" + while IFS= read -r line; do + [[ "$line" =~ \(NEEDED\).*Shared[[:space:]]library:[[:space:]]\[([^]]+)\] ]] || continue + library="${BASH_REMATCH[1]}" + if in_excludelist "$library"; then + printf '%s\n' "$library" >> "${WORK}/host-libraries.txt" + continue + fi + found="" + for entry in ${searched[@]+"${searched[@]}"}; do + if [ -f "${entry}/${library}" ]; then found=1; break; fi + done + [ -n "$found" ] || unresolved+=("${library}(${relative})") + done <<< "$dynamic" + readelf -VW "$file" | awk ' + /^Version needs section/ { needs = 1; next } + /^Version (definition|symbols) section/ { needs = 0 } + needs && match($0, /Name: (GLIBC|GLIBCXX)_[0-9.]+/) { print substr($0, RSTART + 6, RLENGTH - 6) } + ' >> "${WORK}/host-versions.txt" || fail "readelf failed on ${relative}" + done < <(find "${DEST}/bin" "${DEST}/lib" -type f) + [ "${#unresolved[@]}" -eq 0 ] || fail "libraries that resolve neither inside ${NAME} nor to linuxdeploy's excludelist: ${unresolved[*]}" +} + +highest_version() { + awk -v prefix="$1_" 'index($0, prefix) == 1 { print substr($0, length(prefix) + 1) }' "${WORK}/host-versions.txt" | + sort -t . -k 1,1n -k 2,2n -k 3,3n | tail -n 1 +} + +# --- Notices and README ---------------------------------------------------- + +bundled_libraries() { + case "$PLATFORM" in + macos) if [ -d "${DEST}/lib" ]; then find "${DEST}/lib" -type f; fi ;; + linux) find "${DEST}/lib" -type f ;; + windows) find "$DEST" -maxdepth 1 -type f -iname '*.dll' ;; + esac +} + +write_notices() { + local file name pattern component license url matched unknown=() + : > "${WORK}/notices.tsv" + shopt -s nocasematch # Windows DLL names vary in case + while IFS= read -r file; do + name="${file##*/}" + matched="" + while IFS=$'\t' read -r pattern component license url; do + case "$pattern" in ''|'#'*) continue ;; esac + # shellcheck disable=SC2254 # table entries are glob patterns + case "$name" in + $pattern) printf '%s\t%s\t%s\t%s\n' "$component" "$license" "$url" "$name" >> "${WORK}/notices.tsv"; matched=1; break ;; + esac + done < "$NOTICES_TABLE" + [ -n "$matched" ] || unknown+=("$name") + done < <(bundled_libraries) + shopt -u nocasematch + while IFS=$'\t' read -r pattern component license url; do + [ "$pattern" != "@${PLATFORM}" ] || printf '%s\t%s\t%s\t(static)\n' "$component" "$license" "$url" >> "${WORK}/notices.tsv" + done < "$NOTICES_TABLE" + [ "${#unknown[@]}" -eq 0 ] || fail "bundled libraries missing from ${NOTICES_TABLE##*/}: ${unknown[*]}" + { + echo "Third-party libraries in ${NAME}" + echo + if [ -s "${WORK}/notices.tsv" ]; then + echo "These libraries are not part of WSJT-X. Each is distributed under its own license, published at the address given." + echo + LC_ALL=C sort -t $'\t' -k 1,1 -k 4,4 "${WORK}/notices.tsv" | awk -F '\t' ' + function flush() { + if (files != "") print " Files:" files + if (static) print " Linked statically into the programs" + } + $1 != last { if (last != "") { flush(); print "" } printf "%s\n License: %s\n %s\n", $1, $2, $3; last = $1; files = ""; static = 0 } + $4 == "(static)" { static = 1; next } + { files = files " " $4 } + END { if (last != "") flush() } + ' + else + echo "This tarball bundles no third-party libraries." + fi + if [ -d "${DEST}/share/doc" ]; then + echo + echo "share/doc/ holds the copyright files of the Debian packages that bundled libraries come from; a library built outside a Debian package has none there." + fi + } > "${DEST}/THIRD-PARTY.txt" +} + +describe() { + local writes="writes working files to its data directory (-a) and its temporary directory (-t), both the current directory by default; run it where it can write, or point -a and -t at writable directories." + case "$1" in + jt9) + echo "jt9 is the decoder the WSJT-X application drives through shared memory (-s). It also decodes WAV files, and framed PCM audio on standard input (--stream). jt9stream, in its own tarball, is the same decoder without Qt or shared memory." + echo "jt9 ${writes}" + ;; + jt9stream) + echo "jt9stream is the decoder of jt9 without Qt or shared memory: it decodes WAV files, and framed PCM audio on standard input (--stream). Its usage text names jt9 and lists -s, which jt9stream does not support." + echo "jt9stream ${writes}" + ;; + wsprd) + echo "wsprd decodes WSPR from WAV files, and from framed PCM audio on standard input (-0)." + echo "wsprd writes working files to its data directory (-a, default the current directory) and stops if it cannot write there." + ;; + utilities) + echo "Utilities for testing decoders: wsprcode and encode77 encode messages; ft4sim, jt4sim, jt65sim, cwsim and sfoxsim write simulated signals to WAV files in the current directory, so run them where they can write." + ;; + *) fail "no README description for release tarball $1" ;; + esac +} + +# The notice doc/common/license.adoc asks anyone using WSJT-X under the GPL to display. +copyright_notice() { + tr -d '\r' < "$LICENSE_PAGE" | + awk '/^\*The algorithms/ { on = 1 } on { printf "%s ", $0 } on && /Development Group\.\*$/ { exit }' | + sed -e 's/_{prog}_/WSJT-X/g' -e 's/^\*//' -e 's/\* *$//' -e 's/ */ /g' -e 's/ *$//' +} + +write_readme() { + local group="$1" programs="$2" floor glibc glibcxx host notice + notice=$(copyright_notice) + [ -n "$notice" ] || fail "no copyright notice found in ${LICENSE_PAGE}" + { + echo "WSJT-X ${VERSION}: ${group} for ${TARGET}" + echo + echo "Programs: ${programs}" + describe "$group" + echo + case "$PLATFORM" in + macos) + floor=$(macos_minimum) + [ -n "$floor" ] || fail "no minimum macOS version recorded in ${NAME}" + echo "Layout: the programs are at the top of this directory and the libraries they load are in lib/. Keep lib/ beside the programs. They require macOS ${floor} or later." + echo + echo "The programs and libraries carry ad-hoc signatures and are not notarized. macOS blocks quarantined programs that are not notarized, so remove the quarantine attribute from the tarball before extracting it (xattr -d com.apple.quarantine <tarball>), or from an extracted directory (xattr -dr com.apple.quarantine <directory>). Changing one of these files, for example with install_name_tool, invalidates its signature; sign it again with codesign --force --sign - <file>." + ;; + linux) + glibc=$(highest_version GLIBC) + glibcxx=$(highest_version GLIBCXX) + host=$(LC_ALL=C sort -u "${WORK}/host-libraries.txt" | paste -sd ' ' -) + echo "Layout: the programs are in bin/ and the libraries they load are in lib/. Keep both directories together." + echo + echo "The system must provide glibc ${glibc:-of any version}${glibc:+ or later}${glibcxx:+, libstdc++ with GLIBCXX_${glibcxx} or later}, and these libraries: ${host}." + echo "LD_LIBRARY_PATH takes precedence over the bundled lib/, so start the programs without it." + ;; + windows) + echo "Layout: the programs and the DLLs they load are in this directory. Keep them together." + echo + echo "The programs and DLLs carry no Authenticode signature." + ;; + esac + echo + echo "WSJT-X is free software under the GNU General Public License version 3 (COPYING). Its source code is wsjtx-${VERSION}-src.tar.gz on the same release page. THIRD-PARTY.txt lists the bundled libraries and their licenses." + echo + echo "$notice" + } > "${DEST}/README.txt" +} + +# --- Package --------------------------------------------------------------- + +[ "$PLATFORM" != windows ] || windows_setup +packaged=() +for index in "${!GROUP_NAMES[@]}"; do + group="${GROUP_NAMES[$index]}" + programs="${GROUP_PROGRAMS[$index]}" + NAME="wsjtx-${VERSION}-${TARGET}-${group}" + DEST="${WORK}/${NAME}" + mkdir -p "$DEST" + # shellcheck disable=SC2086 # program names are single words + case "$PLATFORM" in + macos) + for program in $programs; do + cp -p "${SOURCE}/${program}" "${DEST}/" + macos_closure "$program" + done + ;; + linux) + linux_deploy "$group" $programs + linux_check + ;; + windows) + for program in $programs; do cp "${SOURCE}/${program}.exe" "${DEST}/"; done + windows_closure + ;; + esac + cp "$COPYING" "${DEST}/COPYING" + write_notices + write_readme "$group" "$programs" + COPYFILE_DISABLE=1 tar -czf "${WORK}/tarballs/${NAME}.tar.gz" -C "$WORK" "$NAME" + packaged+=("${NAME}.tar.gz") +done + +mkdir -p "$OUT" +for tarball in "${packaged[@]}"; do + mv "${WORK}/tarballs/${tarball}" "${OUT}/${tarball}" + echo "packaged ${OUT}/${tarball}" +done diff --git a/.github/scripts/package-linux-armhf.sh b/.github/scripts/package-linux-armhf.sh index abef3284..552fea56 100755 --- a/.github/scripts/package-linux-armhf.sh +++ b/.github/scripts/package-linux-armhf.sh @@ -16,8 +16,6 @@ source .github/scripts/armhf-ci-image-config.sh # shellcheck source=.github/scripts/linux-artifact-validation.sh source .github/scripts/linux-artifact-validation.sh export LD_LIBRARY_PATH="$ARMHF_RUNTIME_PREFIX" -export ARMHF_QEMU_EXECUTABLE -export LINUX_APPIMAGE_RUNNER="$ARMHF_QEMU_EXECUTABLE" echo "::group::Package .deb" ( @@ -89,20 +87,14 @@ QT_PLUGIN_ASSET_ID="$( )" curl "${curl_flags[@]}" -o linuxdeploy.AppImage \ "https://github.com/linuxdeploy/linuxdeploy/releases/download/${LINUXDEPLOY_TAG}/linuxdeploy-armhf.AppImage" -mkdir -p wsjtx-build/appimage-tools -github_api_curl -H "Accept: application/octet-stream" \ - -o wsjtx-build/appimage-tools/qt-plugin.AppImage \ +github_api_curl -H "Accept: application/octet-stream" -o linuxdeploy-plugin-qt.AppImage \ "https://api.github.com/repos/linuxdeploy/linuxdeploy-plugin-qt/releases/assets/${QT_PLUGIN_ASSET_ID}" echo "$LINUXDEPLOY_SHA256 linuxdeploy.AppImage" | sha256sum -c - -chmod +x linuxdeploy.AppImage wsjtx-build/appimage-tools/qt-plugin.AppImage -# shellcheck disable=SC2016 # variables expand when the generated wrapper runs -printf '%s\n' \ - '#!/bin/sh' \ - 'exec "${ARMHF_QEMU_EXECUTABLE:?}" /work/wsjtx-build/appimage-tools/qt-plugin.AppImage "$@"' \ - > linuxdeploy-plugin-qt.AppImage -chmod +x linuxdeploy-plugin-qt.AppImage -# Supply linuxdeploy with the non-executing ARMHF resolver; native ldd cannot -# safely enter the target loader from this already-emulated container. +chmod +x linuxdeploy.AppImage linuxdeploy-plugin-qt.AppImage +# linuxdeploy resolves dependencies with the non-executing ARMHF resolver, +# which reads the clean runtime prefix first and refuses a libquadmath +# dependency the ARMHF runtime cannot satisfy. +mkdir -p wsjtx-build/appimage-tools ln -sfn /work/.github/scripts/armhf-static-ldd.sh wsjtx-build/appimage-tools/ldd for target in AppDir/usr/bin/wsjtx AppDir/usr/bin/jt9 AppDir/usr/bin/qmap \ @@ -113,7 +105,6 @@ done export APPIMAGE_EXTRACT_AND_RUN=1 export OUTPUT="wsjtx-${VERSION}-linux-${ARCH}.AppImage" env -u GITHUB_TOKEN PATH="/work/wsjtx-build/appimage-tools:$PATH" \ - "$ARMHF_QEMU_EXECUTABLE" \ ./linuxdeploy.AppImage --appimage-extract-and-run \ --appdir AppDir \ --plugin qt \ @@ -124,7 +115,7 @@ file "$OUTPUT" echo "::endgroup::" echo "::group::Validate AppImage payload" -"$ARMHF_QEMU_EXECUTABLE" ./"$OUTPUT" --appimage-extract >/dev/null +./"$OUTPUT" --appimage-extract >/dev/null validate_linux_application_tree squashfs-root appimage "$ARCH" rm -rf /work/squashfs-root echo "::endgroup::" @@ -134,4 +125,26 @@ run_packaged_appimage_startup_smoke \ "./$OUTPUT" wsjtx-build/appimage-startup-smoke.log echo "::endgroup::" +echo "::group::Package release tarballs" +PATH="/work/wsjtx-build/appimage-tools:$PATH" .github/scripts/package-cli-tools.sh \ + --platform linux \ + --version "$VERSION" \ + --arch "$ARCH" \ + --groups CMake/release-tarballs.txt \ + --source wsjtx-build \ + --linuxdeploy /work/linuxdeploy.AppImage \ + --out release-tarballs +echo "::endgroup::" + +# LD_LIBRARY_PATH, exported above, would hide a GCC runtime library missing +# from a tarball; the smoke test unsets it for every program it runs. +echo "::group::Smoke-test release tarballs" +.github/scripts/smoke-release-tarballs.sh \ + --platform linux \ + --version "$VERSION" \ + --target "linux-$ARCH" \ + --groups CMake/release-tarballs.txt \ + --dir release-tarballs +echo "::endgroup::" + echo "ARMHF package phase complete for version=$VERSION" diff --git a/.github/scripts/release-linux-images.py b/.github/scripts/release-linux-images.py new file mode 100644 index 00000000..260617ed --- /dev/null +++ b/.github/scripts/release-linux-images.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Prepare and validate the Linux dependency selection committed with a release.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +PUBLIC = "ghcr.io/wsjtx/wsjtx" +PRIVATE = "ghcr.io/wsjtx/wsjtx-internal" +IMAGES = { + "x86_64": ("linux-noble", "normal-noble", "linux/amd64", "normal", "x86_64"), + "aarch64": ("linux-arm64-bookworm", "normal-bookworm", "linux/arm64", "normal", "aarch64"), + "armhf_cross": ("linux-armhf-cross-bookworm", "armhf-cross-bookworm", "linux/amd64", "cross-builder", "armhf"), + "armhf_runtime": ("linux-armv7-bookworm", "armhf-runtime-bookworm", "linux/arm/v7", "runtime", "armhf"), +} +DIGEST = re.compile(r"sha256:[0-9a-f]{64}\Z") +GENERATION = re.compile(r"validated-build-[0-9]{8}-[0-9]+-[0-9]+\Z") + + +def run(args, **kwargs): + return subprocess.run(args, check=True, text=True, capture_output=True, **kwargs).stdout.strip() + + +def fingerprint(profile): + return run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", profile]) + + +def inspect(reference, anonymous=False, missing_ok=False): + command = ["skopeo", "inspect"] + if anonymous: + command += ["--no-creds"] + command += ["--raw", "docker://" + reference] + try: + manifest = subprocess.run(command, check=True, capture_output=True).stdout + except subprocess.CalledProcessError as error: + # Authentication, transport and server errors must not authorize an overwrite. + if missing_ok and b"manifest unknown" in error.stderr.lower(): + return None + raise + return "sha256:" + hashlib.sha256(manifest).hexdigest() + + +def anonymous_digest(reference): + repository, digest = reference.removeprefix("ghcr.io/").split("@", 1) + query = urlencode({"service": "ghcr.io", "scope": f"repository:{repository}:pull"}) + with urlopen("https://ghcr.io/token?" + query, timeout=30) as response: + token = json.load(response)["token"] + request = Request(f"https://ghcr.io/v2/{repository}/manifests/{digest}", headers={ + "Authorization": f"Bearer {token}", + "Accept": ", ".join(("application/vnd.oci.image.manifest.v1+json", + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", + "application/vnd.docker.distribution.manifest.list.v2+json")), + }) + with urlopen(request, timeout=30) as response: + return "sha256:" + hashlib.sha256(response.read()).hexdigest() + + +def validate(lock, check_remote=False): + if not isinstance(lock, dict) or lock.get("schema") != 1: + raise ValueError("Unsupported Linux image selection schema") + if not isinstance(lock.get("generation"), str) or not GENERATION.fullmatch(lock["generation"]): + raise ValueError("Select an explicit validated-build generation") + if not isinstance(lock.get("images"), dict) or set(lock["images"]) != set(IMAGES): + raise ValueError("Linux image selection must contain all four release images") + for key, (package, profile, *_rest) in IMAGES.items(): + image = lock["images"][key] + if not isinstance(image, dict): + raise ValueError(f"Malformed image selection: {key}") + reference = image.get("reference", "") + prefix = f"{PUBLIC}/{package}@" + if not isinstance(reference, str) or not reference.startswith(prefix) or not DIGEST.fullmatch(reference[len(prefix):]): + raise ValueError(f"Expected public digest-pinned image: {key}") + if image.get("recipe_sha256") != fingerprint(profile): + raise ValueError(f"Stale recipe for {key}; refresh and prepare the dependency images") + if check_remote and anonymous_digest(reference) != reference.split("@", 1)[1]: + raise ValueError(f"Public image digest mismatch: {key}") + return lock + + +def provenance(lock_path): + lock = validate(json.loads(Path(lock_path).read_text())) + return { + "lock_sha256": hashlib.sha256(Path(lock_path).read_bytes()).hexdigest(), + "builders": {key: image["reference"].split("@", 1)[1] for key, image in lock["images"].items()}, + } + + +def image_manifest(reference, spec, recipe, generation): + _package, _profile, platform, role, arch = spec + root = str(Path.cwd()) + helper = "verify-linux-ci-image.sh" if role == "normal" else "verify-armhf-ci-image.sh" + hamlib = run(["bash", "-c", '. .github/scripts/linux-ci-image-config.sh; printf "%s" "$LINUX_HAMLIB_REF"']) + command = ["docker", "run", "--rm", "--platform", platform, "--network", "none", + "--mount", f"type=bind,source={root},target=/source,readonly", "--workdir", "/source", + "-e", f"IMAGE_RECIPE_SHA256={recipe}", reference] + run(command + ["bash", f".github/scripts/{helper}", role, arch, hamlib]) + raw = run(command + ["cat", "/opt/wsjtx-ci/image.env"]) + manifest = dict(line.split("=", 1) for line in raw.splitlines() if "=" in line) + if manifest.get("generation") != generation.removeprefix("validated-"): + raise ValueError(f"Image generation mismatch: {reference}") + return manifest + + +def prepare(generation): + if not GENERATION.fullmatch(generation): + raise ValueError("Select an explicit validated-build generation") + lock = {"schema": 1, "generation": generation, "images": {}} + sources = {} + manifests = {} + # Freeze the entire cohort before downloading or copying any image. + for key, spec in IMAGES.items(): + package, profile, *_rest = spec + source = f"{PRIVATE}/{package}" + digest = inspect(f"{source}:{generation}") + sources[key] = f"{source}@{digest}" + lock["images"][key] = {"reference": f"{PUBLIC}/{package}@{digest}", "recipe_sha256": fingerprint(profile)} + for key, spec in IMAGES.items(): + manifests[key] = image_manifest(sources[key], spec, lock["images"][key]["recipe_sha256"], generation) + cross, runtime = manifests["armhf_cross"], manifests["armhf_runtime"] + for field in ("generation", "recipe_sha256", "toolchain_id"): + if not cross.get(field) or runtime.get("cross_" + field) != cross[field]: + raise ValueError(f"ARMHF image pair mismatch: {field}") + if not cross.get("runtime_sha256") or runtime.get("runtime_sha256") != cross["runtime_sha256"]: + raise ValueError("ARMHF image pair mismatch: runtime_sha256") + for key, spec in IMAGES.items(): + destination = f"{PUBLIC}/{spec[0]}:release-deps-{generation}" + digest = sources[key].split("@", 1)[1] + existing = inspect(destination, missing_ok=True) + if existing is not None and existing != digest: + raise ValueError(f"Conflicting retained image tag: {destination}") + if existing is None: + run(["skopeo", "copy", "--all", "--preserve-digests", "docker://" + sources[key], "docker://" + destination]) + if inspect(destination, anonymous=True) != digest: + raise ValueError(f"Public image digest mismatch: {destination}") + validate(lock, check_remote=True) + return lock, manifests + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + check = commands.add_parser("validate") + check.add_argument("lock") + check.add_argument("--check-remote", action="store_true") + check.add_argument("--github-output") + binding = commands.add_parser("provenance") + binding.add_argument("lock") + verify = commands.add_parser("verify-provenance") + verify.add_argument("lock") + verify.add_argument("provenance") + preparation = commands.add_parser("prepare") + preparation.add_argument("generation") + preparation.add_argument("--output-directory", required=True) + args = parser.parse_args() + if args.command == "prepare": + output = Path(args.output_directory) + if output.exists(): + raise ValueError("Preparation output directory must not already exist") + lock, manifests = prepare(args.generation) + output.mkdir(parents=True) + (output / "release-linux-images.json").write_text(json.dumps(lock, indent=2) + "\n") + record = {"source_sha": run(["git", "rev-parse", "HEAD"]), "run_url": os.environ.get("PREPARATION_RUN_URL"), "manifests": manifests} + (output / "preparation-record.json").write_text(json.dumps(record, indent=2) + "\n") + elif args.command == "provenance": + print(json.dumps(provenance(args.lock))) + elif args.command == "verify-provenance": + if json.loads(Path(args.provenance).read_text()).get("linux_images") != provenance(args.lock): + raise ValueError("Candidate Linux image provenance does not match the committed selection") + else: + lock = validate(json.loads(Path(args.lock).read_text()), args.check_remote) + bound = provenance(args.lock) + outputs = {"image_tag": lock["generation"], "lock_sha256": bound["lock_sha256"]} + for key, digest in bound["builders"].items(): + outputs[("armhf" if key == "armhf_runtime" else key) + "_digest"] = digest + if args.github_output: + with open(args.github_output, "a") as target: + target.write("".join(f"{key}={value}\n" for key, value in outputs.items())) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write("## Linux release dependencies\n\n") + summary.write(f"Generation: `{lock['generation']}`. All recipe fingerprints match.\n\n") + for key, image in lock["images"].items(): + summary.write(f"- {key}: `{image['reference']}`\n") + print(json.dumps(bound)) + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, subprocess.CalledProcessError) as error: + detail = error.stderr if isinstance(error, subprocess.CalledProcessError) else str(error) + if isinstance(detail, bytes): + detail = detail.decode("utf-8", errors="replace") + print(f"Linux release dependencies: {detail}", file=sys.stderr) + sys.exit(1) diff --git a/.github/scripts/release-policy.py b/.github/scripts/release-policy.py index ec7abe09..b2e160ce 100644 --- a/.github/scripts/release-policy.py +++ b/.github/scripts/release-policy.py @@ -7,33 +7,381 @@ import argparse import hashlib import json import re +import subprocess import sys import tarfile import zipfile +from collections.abc import Callable from pathlib import Path -VERSION_RE = re.compile(r"^(?P<numeric>\d+\.\d+\.\d+)(?:-rc(?P<rc>[1-9]\d*))?$") +VERSION_RE = re.compile(r"^(?P<numeric>\d+\.\d+\.\d+)(?:-(?P<label>beta|rc)(?P<number>[1-9]\d*))?$") +RELEASE_BRANCH_RE = re.compile(r"^release/(?P<major>\d+)\.(?P<minor>\d+)$") +OBJECT_ID_RE = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$") MACOS_MODES = ("validation", "distribution") WINDOWS_MODES = ("signpath", "unsigned") +CHANNEL_RANK = {"BETA": 0, "RC": 1, "GA": 2} +BETA_TAG_PATTERN = "v*-beta*" +RELEASE_TARGETS = ("arm64-macOS", "x86_64-macOS", "linux-x86_64", "linux-aarch64", "linux-armhf", "windows-x86_64") +RELEASE_TARBALLS_FILE = Path(__file__).resolve().parents[2] / "CMake" / "release-tarballs.txt" +# Artifact name endings that already mean another kind of release asset. +RESERVED_ASSET_KINDS = ("deb", "rpm", "installer", "signed", "unsigned", "src") def classify(version: str) -> dict[str, str]: match = VERSION_RE.fullmatch(version) if not match: - raise ValueError("version must be X.Y.Z or X.Y.Z-rcN") - rc = match.group("rc") or "" + raise ValueError("version must be X.Y.Z, X.Y.Z-betaN, or X.Y.Z-rcN") + label = match.group("label") numeric = match.group("numeric") major, minor, _ = numeric.split(".") return { "version": version, "numeric": numeric, - "channel": "RC" if rc else "GA", - "rc_number": rc, + "channel": label.upper() if label else "GA", + "prerelease_number": match.group("number") or "", "release_branch": f"release/{major}.{minor}", } +def release_order(identity: dict[str, str]) -> tuple[int, ...]: + return ( + *(int(part) for part in identity["numeric"].split(".")), + CHANNEL_RANK[identity["channel"]], + int(identity["prerelease_number"] or 0), + ) + + +def parse_public_ref_listing(output: str) -> tuple[dict[str, str], str]: + refs: dict[str, str] = {} + peeled_tags: dict[str, str] = {} + records = [] + for line in output.splitlines(): + fields = line.split() + if len(fields) != 2 or not OBJECT_ID_RE.fullmatch(fields[0]): + raise ValueError("public git ref listing is malformed") + object_id, name = fields + records.append(f"{object_id} {name}") + if name.endswith("^{}"): + tag = name[:-3] + if tag.startswith("refs/tags/v"): + peeled_tags[tag] = object_id + elif ( + name == "refs/heads/master" + or name.startswith("refs/heads/release/") + or name.startswith("refs/tags/v") + ): + refs[name] = object_id + refs.update(peeled_tags) + digest = hashlib.sha256("\n".join(sorted(records)).encode("utf-8")).hexdigest() + return refs, digest + + +def public_release_line_policy(version: str, refs: dict[str, str]) -> dict[str, object]: + identity = classify(version) + ga_versions: list[tuple[int, int, int]] = [] + line_tags: list[tuple[tuple[int, ...], str, str]] = [] + release_branch_count = 0 + for name, sha in refs.items(): + if name.startswith("refs/heads/release/"): + branch = name.removeprefix("refs/heads/") + match = RELEASE_BRANCH_RE.fullmatch(branch) + if not match: + raise ValueError(f"public release branch is malformed: {branch}") + release_branch_count += 1 + elif name.startswith("refs/tags/v"): + tag_version = name.removeprefix("refs/tags/v") + try: + tag_identity = classify(tag_version) + except ValueError as error: + raise ValueError(f"public version tag is malformed: {name}") from error + numeric_version = tuple(int(part) for part in tag_identity["numeric"].split(".")) + line_tags.append((release_order(tag_identity), name.removeprefix("refs/tags/"), sha)) + if tag_identity["channel"] == "GA": + ga_versions.append(numeric_version) + if not ga_versions: + raise ValueError( + "cannot determine the newest GA line: no immutable public vX.Y.Z GA tags exist" + ) + candidate_version = tuple(int(part) for part in identity["numeric"].split(".")) + candidate_line = candidate_version[:2] + newest_version = max(ga_versions) + candidate_line_versions = [ + ga_version for ga_version in ga_versions if ga_version[:2] == candidate_line + ] + highest_candidate_line_version = ( + max(candidate_line_versions) if candidate_line_versions else None + ) + candidate_line_tags = [tag for tag in line_tags if tag[0][:2] == candidate_line] + latest_candidate_line_tag = max(candidate_line_tags, default=None) + newest_line = newest_version[:2] + return { + "candidate_line": f"{candidate_line[0]}.{candidate_line[1]}", + "newest_ga_line": f"{newest_line[0]}.{newest_line[1]}", + "ga_line_is_newest": candidate_line >= newest_line, + "newest_ga_version": ".".join(str(part) for part in newest_version), + "highest_ga_version_on_candidate_line": ( + ".".join(str(part) for part in highest_candidate_line_version) + if highest_candidate_line_version + else None + ), + "latest_public_tag_on_candidate_line": ( + latest_candidate_line_tag[1] if latest_candidate_line_tag else None + ), + "latest_public_tag_sha_on_candidate_line": ( + latest_candidate_line_tag[2] if latest_candidate_line_tag else None + ), + "ga_release_is_latest": ( + identity["channel"] == "GA" and candidate_version >= newest_version + ), + "legacy_tag_only": release_branch_count == 0, + } + + +def plan_public_promotion( + version: str, + sha: str, + refs: dict[str, str], + is_ancestor: Callable[[str, str], bool], +) -> dict[str, object]: + if not OBJECT_ID_RE.fullmatch(sha): + raise ValueError("candidate SHA must be a full lowercase Git object ID") + identity = classify(version) + line_policy = public_release_line_policy(version, refs) + public_tag = f"v{version}" + tag_ref = f"refs/tags/{public_tag}" + branch_ref = f"refs/heads/{identity['release_branch']}" + current_tag = refs.get(tag_ref) + current_branch = refs.get(branch_ref) + if current_tag and current_tag != sha: + raise ValueError(f"public {public_tag} already points to {current_tag}; tags are never moved") + if current_branch and not is_ancestor(current_branch, sha): + raise ValueError( + f"public {identity['release_branch']} at {current_branch} is not an ancestor of {sha}; " + "refusing a non-fast-forward update" + ) + if not current_branch and line_policy["latest_public_tag_sha_on_candidate_line"]: + tag_sha = line_policy["latest_public_tag_sha_on_candidate_line"] + if not is_ancestor(tag_sha, sha): + tag = line_policy["latest_public_tag_on_candidate_line"] + raise ValueError( + f"public {identity['release_branch']} is missing and its latest public tag " + f"{tag} at {tag_sha} is not an ancestor of {sha}; " + "refusing a disconnected branch initialization" + ) + + highest_candidate_line_version = line_policy["highest_ga_version_on_candidate_line"] + if ( + identity["channel"] == "GA" + and highest_candidate_line_version + and tuple(int(part) for part in identity["numeric"].split(".")) + < tuple(int(part) for part in highest_candidate_line_version.split(".")) + ): + raise ValueError( + f"public GA tags already reach {highest_candidate_line_version} on this line; " + "a lower GA version cannot advance it" + ) + latest_line_tag = line_policy["latest_public_tag_on_candidate_line"] + if ( + not current_tag + and latest_line_tag + and release_order(identity) <= release_order(classify(latest_line_tag.removeprefix("v"))) + ): + raise ValueError( + f"{latest_line_tag} is the latest public tag on this line; {public_tag} must sort above it" + ) + + advance_master = identity["channel"] == "GA" and line_policy["ga_line_is_newest"] + current_master = refs.get("refs/heads/master") + if advance_master: + if not current_master: + raise ValueError("public master is missing; cannot fast-forward the newest GA line") + if not is_ancestor(current_master, sha): + raise ValueError( + f"public master at {current_master} is not an ancestor of {sha}; " + "review and complete the private release history bridge before GA promotion" + ) + + updates = [branch_ref] + if not current_tag: + updates.append(tag_ref) + if advance_master: + updates.append("refs/heads/master") + return { + **line_policy, + "version": version, + "channel": identity["channel"], + "sha": sha, + "public_tag": public_tag, + "release_branch": identity["release_branch"], + "prior_release_branch": current_branch, + "prior_master": current_master, + "tag_exists": current_tag == sha, + "advance_master": advance_master, + "updates": updates, + } + + +def git_output( + arguments: list[str], error_context: str, *, cwd: Path | None = None +) -> str: + result = subprocess.run(["git", *arguments], capture_output=True, text=True, cwd=cwd) + if result.returncode: + detail = result.stderr.strip() or result.stdout.strip() + raise ValueError(f"{error_context}: {detail}") + return result.stdout.strip() + + +def git_is_ancestor(ancestor: str, descendant: str, *, cwd: Path | None = None) -> bool: + result = subprocess.run( + ["git", "merge-base", "--is-ancestor", ancestor, descendant], + capture_output=True, + text=True, + cwd=cwd, + ) + if result.returncode not in (0, 1): + detail = result.stderr.strip() or result.stdout.strip() + raise ValueError(f"unable to verify public commit ancestry: {detail}") + return result.returncode == 0 + + +def public_refs(remote: str, *, cwd: Path | None = None) -> tuple[dict[str, str], str]: + listing = git_output( + [ + "ls-remote", + remote, + "refs/heads/master", + "refs/heads/release/*", + "refs/tags/v*", + ], + "unable to read public release refs", + cwd=cwd, + ) + return parse_public_ref_listing(listing) + + +def inspect_public_promotion( + version: str, sha: str, remote: str, *, cwd: Path | None = None +) -> dict[str, object]: + refs, digest = public_refs(remote, cwd=cwd) + identity = classify(version) + refs_to_fetch = ["refs/heads/master", f"refs/heads/{identity['release_branch']}"] + if f"refs/heads/{identity['release_branch']}" not in refs: + line_policy = public_release_line_policy(version, refs) + latest_tag = line_policy["latest_public_tag_on_candidate_line"] + if latest_tag: + refs_to_fetch.append(f"refs/tags/{latest_tag}") + for name in refs_to_fetch: + if name in refs: + git_output( + ["fetch", "--no-tags", remote, name], + f"unable to fetch {name}", + cwd=cwd, + ) + plan = plan_public_promotion( + version, + sha, + refs, + lambda ancestor, descendant: git_is_ancestor(ancestor, descendant, cwd=cwd), + ) + plan["public_refs_digest"] = digest + return plan + + +def push_public_ref_updates( + remote: str, plan: dict[str, object], *, cwd: Path | None = None +) -> None: + refspecs = [f"{plan['sha']}:{ref}" for ref in plan["updates"]] + result = subprocess.run( + ["git", "push", "--atomic", remote, *refspecs], + capture_output=True, + text=True, + cwd=cwd, + ) + if result.returncode: + detail = result.stderr.strip() or result.stdout.strip() + raise ValueError(f"atomic public ref update failed; no refs were changed: {detail}") + + +def promote_public_source( + version: str, + sha: str, + remote: str, + expected_refs_digest: str, + *, + cwd: Path | None = None, +) -> dict[str, object]: + plan = inspect_public_promotion(version, sha, remote, cwd=cwd) + if plan["public_refs_digest"] != expected_refs_digest: + raise ValueError("public release refs changed after validation; rerun validation before promotion") + push_public_ref_updates(remote, plan, cwd=cwd) + return plan + + +def inspect_public_release_line( + version: str, remote: str, *, cwd: Path | None = None +) -> dict[str, object]: + refs, digest = public_refs(remote, cwd=cwd) + return { + **public_release_line_policy(version, refs), + "public_refs_digest": digest, + } + + +def publication_environment(channel: str) -> str: + return "beta-release" if channel == "BETA" else "public-release" + + +def validate_publication_environment( + environment: object, channel: str = "GA", deployment_policies: object = None +) -> None: + name = publication_environment(channel) + if not isinstance(environment, dict) or environment.get("name") != name: + raise ValueError(f"{name} environment response is malformed") + rules = environment.get("protection_rules") + if not isinstance(rules, list): + raise ValueError(f"{name} environment has no protection_rules list") + reviewer_rules = [ + rule for rule in rules + if isinstance(rule, dict) and rule.get("type") == "required_reviewers" + ] + if channel == "BETA": + if reviewer_rules: + raise ValueError("beta-release environment must not require reviewers") + if environment.get("deployment_branch_policy") != { + "protected_branches": False, "custom_branch_policies": True + }: + raise ValueError("beta-release environment must restrict deployments to custom deployment patterns") + policies = deployment_policies.get("branch_policies") if isinstance(deployment_policies, dict) else None + if ( + not isinstance(policies, list) + or len(policies) != 1 + or not isinstance(policies[0], dict) + or (policies[0].get("name"), policies[0].get("type")) != (BETA_TAG_PATTERN, "tag") + ): + raise ValueError(f"beta-release environment must admit exactly the {BETA_TAG_PATTERN} tag pattern") + return + if len(reviewer_rules) != 1: + raise ValueError("public-release environment must have one required-reviewers rule") + rule = reviewer_rules[0] + if rule.get("prevent_self_review") is not False: + raise ValueError("public-release required-reviewers rule must allow self-review") + reviewers = rule.get("reviewers") + if not isinstance(reviewers, list) or not reviewers: + raise ValueError("public-release required-reviewers rule must list eligible reviewers") + for reviewer in reviewers: + identity = reviewer.get("reviewer") if isinstance(reviewer, dict) else None + reviewer_type = reviewer.get("type") if isinstance(reviewer, dict) else None + if ( + not isinstance(reviewer_type, str) + or reviewer_type not in {"User", "Team"} + or not isinstance(identity, dict) + or type(identity.get("id")) is not int + or identity["id"] <= 0 + ): + raise ValueError("public-release required-reviewers rule contains a malformed reviewer") + + def parse_state(contents: str, *, expected_revision: str | None = None) -> dict[str, str]: state = {} for line in contents.splitlines(): @@ -41,21 +389,23 @@ def parse_state(contents: str, *, expected_revision: str | None = None) -> dict[ if not separator or key in state: raise ValueError("release-state.txt must contain unique key=value lines") state[key] = value - required_keys = {"version", "channel", "rc", "revision"} + required_keys = {"version", "channel", "prerelease", "revision"} if not required_keys <= set(state) or set(state) - required_keys - {"windows_signing"}: - raise ValueError("release-state.txt must define version, channel, rc, revision, and optionally windows_signing") + raise ValueError("release-state.txt must define version, channel, prerelease, revision, and optionally windows_signing") state.setdefault("windows_signing", "signpath") if state["windows_signing"] not in WINDOWS_MODES: raise ValueError("release-state.txt windows_signing must be signpath or unsigned") - if state["channel"] not in {"DEVEL", "RC", "GA"}: - raise ValueError("release-state.txt channel must be DEVEL, RC, or GA") + if state["channel"] not in {"DEVEL", "BETA", "RC", "GA"}: + raise ValueError("release-state.txt channel must be DEVEL, BETA, RC, or GA") + if state["channel"] == "BETA" and state["windows_signing"] != "unsigned": + raise ValueError("BETA release state requires windows_signing=unsigned") if not re.fullmatch(r"\d+\.\d+\.\d+", state["version"]): raise ValueError("release-state.txt version must be X.Y.Z") - if state["channel"] == "RC": - if not re.fullmatch(r"[1-9]\d*", state["rc"]): - raise ValueError("RC release state requires a positive RC number") - elif state["rc"]: - raise ValueError("DEVEL and GA release states require an empty RC number") + if state["channel"] in {"BETA", "RC"}: + if not re.fullmatch(r"[1-9]\d*", state["prerelease"]): + raise ValueError("BETA and RC release states require a positive prerelease number") + elif state["prerelease"]: + raise ValueError("DEVEL and GA release states require an empty prerelease number") required_revision = expected_revision or "$Format:%H$" if state["revision"].lower() != required_revision.lower(): raise ValueError(f"release-state.txt revision must be {required_revision}") @@ -77,8 +427,8 @@ def validate_source(root: Path, version: str) -> dict[str, str]: errors.append(f"release-state version {state['version']} does not match {identity['numeric']}") if state["channel"] != identity["channel"]: errors.append(f"release channel {state['channel']} does not match {identity['channel']}") - if state["rc"] != identity["rc_number"]: - errors.append(f"RC number {state['rc'] or '<empty>'} does not match {identity['rc_number'] or '<empty>'}") + if state["prerelease"] != identity["prerelease_number"]: + errors.append(f"prerelease number {state['prerelease'] or '<empty>'} does not match {identity['prerelease_number'] or '<empty>'}") if errors: raise ValueError("; ".join(errors)) identity["windows_signing"] = state["windows_signing"] @@ -111,10 +461,30 @@ def validate_archive(path: Path, version: str, commit: str) -> None: raise ValueError("source archive must not contain .git metadata") identity = classify(version) state = parse_state(release_state_contents, expected_revision=commit) - if state["version"] != identity["numeric"] or state["channel"] != identity["channel"] or state["rc"] != identity["rc_number"]: + if state["version"] != identity["numeric"] or state["channel"] != identity["channel"] or state["prerelease"] != identity["prerelease_number"]: raise ValueError("source archive release identity does not match its tag") +def tarball_groups(path: Path = RELEASE_TARBALLS_FILE) -> list[str]: + groups = [] + for line in path.read_text(encoding="utf-8").splitlines(): + fields = line.split() + if not fields or fields[0].startswith("#"): + continue + if len(fields) < 2: + raise ValueError(f"release tarball {fields[0]} names no programs in {path.name}") + if not re.fullmatch(r"[a-z0-9]+", fields[0]) or fields[0] in RESERVED_ASSET_KINDS: + raise ValueError(f"release tarball name {fields[0]} cannot name a release asset") + groups.append(fields[0]) + if not groups or len(groups) != len(set(groups)): + raise ValueError(f"{path.name} must name each release tarball once") + return groups + + +def release_tarballs(version: str) -> list[str]: + return [f"wsjtx-{version}-{target}-{group}" for target in RELEASE_TARGETS for group in tarball_groups()] + + def expected_assets(version: str, distribution: bool) -> list[str]: mac_suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg" return [ @@ -124,6 +494,7 @@ def expected_assets(version: str, distribution: bool) -> list[str]: f"wsjtx-{version}-linux-aarch64-AppImage", f"wsjtx-{version}-linux-armhf-AppImage", f"wsjtx-{version}-windows-x86_64-installer-signed" if distribution else f"wsjtx-{version}-windows-x86_64-installer", + *release_tarballs(version), ] @@ -140,16 +511,23 @@ def public_expected_assets(version: str, macos_mode: str, windows_mode: str = "s f"wsjtx-{version}-linux-aarch64-AppImage", f"wsjtx-{version}-linux-armhf-AppImage", f"wsjtx-{version}-windows-x86_64-installer{'-signed' if windows_mode == 'signpath' else ''}", + *release_tarballs(version), ] +def asset_suffix(artifact: str) -> str: + if artifact.rsplit("-", 1)[-1] in tarball_groups(): + return ".tar.gz" + return ".pkg" if "macOS" in artifact else ".AppImage" if "linux" in artifact else ".exe" + + def collect_asset_files(root: Path, expected: list[str]) -> list[Path]: files: list[Path] = [] for artifact in expected: directory = root / artifact if not directory.is_dir(): raise ValueError(f"missing artifact directory: {artifact}") - suffix = ".pkg" if "macOS" in artifact else ".AppImage" if "linux" in artifact else ".exe" + suffix = asset_suffix(artifact) matches = sorted(path for path in directory.rglob(f"*{suffix}") if path.is_file()) if len(matches) != 1: raise ValueError(f"{artifact} must contain exactly one {suffix} file; found {len(matches)}") @@ -171,13 +549,14 @@ def find_asset_files(root: Path, version: str, distribution: bool) -> list[Path] def find_public_asset_files( root: Path, version: str, macos_mode: str, windows_mode: str = "signpath" ) -> list[Path]: - files = collect_asset_files(root, public_expected_assets(version, macos_mode, windows_mode)) + expected = public_expected_assets(version, macos_mode, windows_mode) + files = collect_asset_files(root, expected) if macos_mode == "distribution": unsigned = sorted(root.rglob("*-unsigned.pkg")) if unsigned: raise ValueError(f"unsigned macOS packages cannot be published: {unsigned[0]}") if windows_mode == "unsigned": - installer = files[-1] + installer = files[expected.index(f"wsjtx-{version}-windows-x86_64-installer")] if installer.name != f"wsjtx-{version}-win64.exe": raise ValueError(f"unexpected unsigned Windows installer: {installer.name}") if (root / f"wsjtx-{version}-windows-x86_64-installer-signed").exists(): @@ -290,10 +669,13 @@ def write_manifest(args: argparse.Namespace) -> None: for arch, digest in digests.items(): if not re.fullmatch(r"sha256:[0-9a-f]{64}", digest): raise ValueError(f"Linux {arch} builder digest is not an immutable sha256 digest") + beta = classify(args.version)["channel"] == "BETA" + if beta and args.macos_mode != "validation": + raise ValueError("BETA releases publish the validated unsigned macOS packages") files = release_files(root, args.version, args.macos_mode, args.windows_mode) replaceable_macos = ( {f"wsjtx-{args.version}-{arch}-macOS.pkg" for arch in ("arm64", "x86_64")} - if args.macos_mode == "validation" + if args.macos_mode == "validation" and not beta else set() ) entries = [ @@ -309,7 +691,7 @@ def write_manifest(args: argparse.Namespace) -> None: "workflow_run": args.run_id, "linux_builders": digests, "macos_signing": { - "mode": "manual" if args.macos_mode == "validation" else "distribution", + "mode": "unsigned" if beta else "manual" if args.macos_mode == "validation" else "distribution", "replaceable_assets": sorted(replaceable_macos), }, "windows_signing": {"mode": args.windows_mode}, @@ -329,6 +711,22 @@ def main() -> int: subparsers = parser.add_subparsers(dest="command", required=True) classify_parser = subparsers.add_parser("classify") classify_parser.add_argument("version") + line_parser = subparsers.add_parser("public-release-line") + line_parser.add_argument("version") + line_parser.add_argument("--remote", required=True) + plan_parser = subparsers.add_parser("plan-public-promotion") + plan_parser.add_argument("version") + plan_parser.add_argument("--sha", required=True) + plan_parser.add_argument("--remote", required=True) + promote_parser = subparsers.add_parser("promote-public-source") + promote_parser.add_argument("version") + promote_parser.add_argument("--sha", required=True) + promote_parser.add_argument("--remote", required=True) + promote_parser.add_argument("--expected-refs-digest", required=True) + environment_parser = subparsers.add_parser("validate-publication-environment") + environment_parser.add_argument("environment_json") + environment_parser.add_argument("--channel", choices=sorted(CHANNEL_RANK), required=True) + environment_parser.add_argument("--deployment-policies") state_parser = subparsers.add_parser("read-state") state_parser.add_argument("--root", default=".") validate_parser = subparsers.add_parser("validate-source") @@ -372,6 +770,27 @@ def main() -> int: try: if args.command == "classify": print(json.dumps(classify(args.version))) + elif args.command == "public-release-line": + print(json.dumps(inspect_public_release_line(args.version, args.remote))) + elif args.command == "plan-public-promotion": + print(json.dumps(inspect_public_promotion(args.version, args.sha, args.remote))) + elif args.command == "promote-public-source": + print(json.dumps(promote_public_source( + args.version, args.sha, args.remote, args.expected_refs_digest + ))) + elif args.command == "validate-publication-environment": + policies = ( + json.loads(Path(args.deployment_policies).read_text(encoding="utf-8")) + if args.deployment_policies + else None + ) + validate_publication_environment( + json.loads(Path(args.environment_json).read_text(encoding="utf-8")), args.channel, policies + ) + if args.channel == "BETA": + print(f"Validated beta-release: no reviewer, deployments only from {BETA_TAG_PATTERN} tags") + else: + print("Validated public-release required-reviewer protection") elif args.command == "read-state": print(json.dumps(read_state(Path(args.root)))) elif args.command == "validate-source": diff --git a/.github/scripts/select-linux-packaging.sh b/.github/scripts/select-linux-packaging.sh index 371ea4fb..489cbd5e 100755 --- a/.github/scripts/select-linux-packaging.sh +++ b/.github/scripts/select-linux-packaging.sh @@ -3,95 +3,59 @@ set -euo pipefail -path_triggers_packaging() { - case "$1" in - CMakeLists.txt|*/CMakeLists.txt|CMake/*|cmake/*|CMakeCPackOptions.cmake.in|package_description.txt|\ - debian/*|bundle_fixup/*|artwork/*|icons/*|sounds/*|data/*|Palettes/*|translations/*|\ - example_log_configurations/*|contrib/Ephemeris/*|contrib/gpl-v3-logo.svg|*.desktop|\ - ALLCALL7.TXT|CALL3.TXT|cty.dat|cty.dat_copyright.txt|grid.dat|sat.dat|eclipse.txt|\ - COPYING|AUTHORS|THANKS|NEWS|BUGS|README.md|\ - .github/actions/build-linux-payload/*|\ - .github/workflows/ci.yml|.github/workflows/build-linux.yml|.github/workflows/build-selected-artifacts.yml|.github/workflows/release.yml|\ - .github/scripts/select-linux-packaging.sh|.github/scripts/linux-artifact-validation.sh|.github/scripts/package-linux-armhf.sh|\ - .github/scripts/validate-linux-armhf-runtime.sh|.github/scripts/build-linux-armhf-cross.sh|\ - .github/cmake/*|.github/images/linux-ci/*) - return 0 +should_build_linux_packages() { + local event_name=$1 + local ref=$2 + local full_ci=$3 + + case "$event_name" in + pull_request) + [ "$full_ci" = true ] + ;; + push) + [ "$ref" != "refs/heads/develop" ] ;; *) - return 1 + return 0 ;; esac } -expect_trigger() { - if ! path_triggers_packaging "$1"; then - echo "self-test failed: expected packaging for $1" >&2 - exit 1 +expect_policy() { + local expected=$1 + shift + local actual=false + if should_build_linux_packages "$@"; then + actual=true fi -} - -expect_no_trigger() { - if path_triggers_packaging "$1"; then - echo "self-test failed: did not expect packaging for $1" >&2 + if [ "$actual" != "$expected" ]; then + echo "self-test failed: expected packaging=$expected for $*, got $actual" >&2 exit 1 fi } if [ "${1:-}" = "--self-test" ]; then - expect_trigger "CMakeLists.txt" - expect_trigger "tests/unit/audio/CMakeLists.txt" - expect_trigger "CMake/Install.cmake" - expect_trigger "debian/postinst" - expect_trigger "sounds/73.wav" - expect_trigger "cty.dat" - expect_trigger "contrib/Ephemeris/JPLEPH" - expect_trigger "wsjtx.desktop" - expect_trigger ".github/actions/build-linux-payload/action.yml" - expect_trigger ".github/workflows/build-linux.yml" - expect_trigger ".github/scripts/select-linux-packaging.sh" - expect_trigger ".github/scripts/linux-artifact-validation.sh" - expect_trigger ".github/images/linux-ci/install-packages.sh" - - expect_no_trigger "widgets/mainwindow.cpp" - expect_no_trigger "tests/unit/audio/test_tx_request.cpp" - expect_no_trigger ".github/workflows/build-macos.yml" - expect_no_trigger "doc/user_guide/en/wsjtx-main.adoc" + expect_policy false pull_request refs/pull/581/merge false + expect_policy true pull_request refs/pull/581/merge true + expect_policy false push refs/heads/develop false + expect_policy false push refs/heads/develop true + expect_policy true push refs/heads/release/3.2 false + expect_policy true workflow_dispatch refs/heads/develop false + expect_policy true workflow_dispatch refs/heads/topic false + expect_policy true schedule refs/heads/develop false echo "select-linux-packaging.sh self-test passed" exit 0 fi -build_packages=true -reason="${EVENT_NAME:-unknown} event" - -if [ "${EVENT_NAME:-}" = "pull_request" ] && [ "${FULL_CI:-false}" != "true" ]; then - base="${PR_BASE_SHA:-}" - head="${CURRENT_SHA:-}" - build_packages=false - reason="ordinary pull request" - - if ! git cat-file -e "${base}^{commit}" 2>/dev/null; then - git fetch --no-tags --depth=1 origin "$base" || true - fi - - if git cat-file -e "${base}^{commit}" 2>/dev/null && - git cat-file -e "${head}^{commit}" 2>/dev/null; then - while IFS= read -r path; do - [ -z "$path" ] && continue - if path_triggers_packaging "$path"; then - build_packages=true - reason="$path" - break - fi - done < <(git diff --name-only "$base" "$head") - else - build_packages=true - reason="unreadable ${base}..${head}" - fi +build_packages=false +if should_build_linux_packages \ + "${EVENT_NAME:-}" "${GITHUB_REF:-}" "${FULL_CI:-false}"; then + build_packages=true fi echo "Build Linux packages: $build_packages" -echo "Packaging policy reason: $reason" +echo "Packaging policy: event=${EVENT_NAME:-unknown}, ref=${GITHUB_REF:-unknown}, full-ci=${FULL_CI:-false}" if [ -n "${GITHUB_OUTPUT:-}" ]; then echo "build_packages=$build_packages" >> "$GITHUB_OUTPUT" fi diff --git a/.github/scripts/smoke-release-tarballs.sh b/.github/scripts/smoke-release-tarballs.sh new file mode 100755 index 00000000..d9f1766c --- /dev/null +++ b/.github/scripts/smoke-release-tarballs.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Run every program of the release tarballs from its own extracted tarball. +# +# smoke-release-tarballs.sh --platform macos|linux|windows --version V \ +# --target T --groups FILE --dir DIR [--ldd] +# +# Each tarball DIR/wsjtx-V-T-<tarball>.tar.gz is extracted into a directory of +# its own, so a library only another tarball carries cannot hide a gap, and +# each program runs from a scratch working directory with the library search +# variables unset, for at most 120 s on Linux; Windows programs launch +# through smoke-launch-windows.sh, which allows 20 s and removes the MinGW +# runtime from PATH. --ldd (Linux) also requires +# every library a tarball bundles to resolve to the bundled copy, because a +# build container has the same libraries installed system-wide. +set -euo pipefail + +PLATFORM=""; VERSION=""; TARGET=""; GROUPS_FILE=""; DIR=""; LDD="" +while [ "$#" -gt 0 ]; do + case "$1" in + --platform) PLATFORM="$2"; shift 2 ;; + --version) VERSION="$2"; shift 2 ;; + --target) TARGET="$2"; shift 2 ;; + --groups) GROUPS_FILE="$2"; shift 2 ;; + --dir) DIR="$2"; shift 2 ;; + --ldd) LDD=1; shift ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done +for option in PLATFORM VERSION TARGET GROUPS_FILE DIR; do + if [ -z "${!option}" ]; then echo "missing --$(echo "${option%_FILE}" | tr '[:upper:]' '[:lower:]')" >&2; exit 2; fi +done + +SCRIPTS="$(cd "$(dirname "$0")" && pwd)" +SAMPLE="${SCRIPTS}/../../samples/WSPR/150426_0918.wav" +DIR="$(cd "$DIR" && pwd)" + +fail() { echo "::error::$*" >&2; exit 1; } + +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +run_program() { + local tree="$1" program="$2" scratch="${WORK}/run-${2}" path arguments=() limit=() + mkdir -p "$scratch" + case "$program" in + jt9|jt9stream) arguments=(--help) ;; + wsprd) + [ -f "$SAMPLE" ] || fail "WSPR sample not found: $SAMPLE" + arguments=(-a "$scratch" "$SAMPLE") + ;; + encode77) arguments=("CQ K1ABC FN42") ;; + wsprcode|ft4sim|jt4sim|jt65sim|cwsim|sfoxsim) ;; + *) fail "no smoke invocation for ${program}" ;; + esac + case "$PLATFORM" in + macos) path="${tree}/${program}" ;; + linux) path="${tree}/bin/${program}"; limit=(timeout 120) ;; + windows) path="${tree}/${program}.exe" ;; + *) echo "unknown platform: $PLATFORM" >&2; exit 2 ;; + esac + [ -f "$path" ] || fail "${program} is not in ${tree##*/}" + if [ "$PLATFORM" = windows ]; then + (cd "$scratch" && "${SCRIPTS}/smoke-launch-windows.sh" "$path" ${arguments[@]+"${arguments[@]}"}) || + fail "${program} from ${tree##*/} failed" + return + fi + if ! (cd "$scratch" && env -u LD_LIBRARY_PATH -u LD_PRELOAD -u DYLD_LIBRARY_PATH \ + -u DYLD_FALLBACK_LIBRARY_PATH -u DYLD_FRAMEWORK_PATH -u DYLD_INSERT_LIBRARIES \ + ${limit[@]+"${limit[@]}"} "$path" ${arguments[@]+"${arguments[@]}"} > "${scratch}/output.txt" 2>&1); then + cat "${scratch}/output.txt" >&2 + fail "${program} from ${tree##*/} failed" + fi + echo "smoke OK: ${tree##*/}/${path#"${tree}"/}" +} + +check_ldd() { + local tree="$1" file line name resolved directory libdir output bundled=() wrong=() + libdir=$(cd "${tree}/lib" && pwd -P) + while IFS= read -r file; do + bundled+=("${file##*/}") + done < <(find "${tree}/lib" -type f) + while IFS= read -r file; do + output=$(env -u LD_LIBRARY_PATH -u LD_PRELOAD ldd "$file" 2>&1) || fail "ldd failed on ${file#"${tree}"/}: ${output}" + while IFS= read -r line; do + case "$line" in + *'=> not found'*) wrong+=("${line%% *}(${file#"${tree}"/}): not found"); continue ;; + *' => '*) ;; + *) continue ;; + esac + read -r name _ resolved _ <<< "$line" + for library in ${bundled[@]+"${bundled[@]}"}; do + [ "$library" = "$name" ] || continue + directory=$(cd "$(dirname "$resolved")" 2>/dev/null && pwd -P) || directory="" + if [ "${directory}/${resolved##*/}" != "${libdir}/${name}" ]; then + wrong+=("${name}(${file#"${tree}"/}): ${resolved}") + fi + done + done <<< "$output" + done < <(find "${tree}/bin" "${tree}/lib" -type f) + [ "${#wrong[@]}" -eq 0 ] || fail "libraries of ${tree##*/} that do not resolve to its bundled copies: ${wrong[*]}" +} + +count=0 +while IFS= read -r line || [ -n "$line" ]; do + line="${line%$'\r'}" + read -r -a fields <<< "$line" || true + [ "${#fields[@]}" -gt 1 ] || continue + case "${fields[0]}" in '#'*) continue ;; esac + name="wsjtx-${VERSION}-${TARGET}-${fields[0]}" + tarball="${DIR}/${name}.tar.gz" + [ -f "$tarball" ] || fail "release tarball not found: $tarball" + mkdir -p "${WORK}/${fields[0]}" + tar -xzf "$tarball" -C "${WORK}/${fields[0]}" + tree="${WORK}/${fields[0]}/${name}" + [ -d "$tree" ] || fail "${name}.tar.gz does not extract to ${name}/" + if [ -n "$LDD" ]; then check_ldd "$tree"; fi + for program in "${fields[@]:1}"; do + run_program "$tree" "$program" + count=$((count + 1)) + done +done < "$GROUPS_FILE" +[ "$count" -gt 0 ] || fail "no programs named in ${GROUPS_FILE}" +echo "ran ${count} programs from their release tarballs" diff --git a/.github/scripts/summarize-native-caches.py b/.github/scripts/summarize-native-caches.py new file mode 100644 index 00000000..190ef520 --- /dev/null +++ b/.github/scripts/summarize-native-caches.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Report cache restores and build outcomes without claiming cache readiness.""" + +import argparse +import json +import os + + +LABELS = { + "qt": "Qt", "libusb": "libusb", "portaudio": "PortAudio", "fftw": "FFTW", + "boost": "Boost", "hamlib": "Hamlib", "pfunit": "pFUnit", +} + + +def restore_status(step, cold): + if cold: + return "bypassed (cold build)" + outcome = step.get("outcome", "skipped") + if outcome != "success": + return "not run" if outcome == "skipped" else outcome + outputs = step.get("outputs", {}) + if outputs.get("cache-hit") == "true": + return "exact hit" + if outputs.get("cache-matched-key"): + return "fallback restore" + return "miss" + + +def build_status(step): + outcome = step.get("outcome", "skipped") + return {"success": "succeeded", "skipped": "not run"}.get(outcome, outcome) + + +def render(steps, dependencies, cold=False, recache=False, compiler=False): + lines = ["### Native caches", "", "| Cache | Restore | Build |", + "| --- | --- | --- |"] + for name in dependencies: + restored = restore_status(steps.get(f"{name}-cache", {}), cold) + built = build_status(steps.get(f"{name}-build", {})) + lines.append(f"| {LABELS[name]} | {restored} | {built} |") + if compiler: + restored = restore_status(steps.get("ccache", {}), cold) + built = build_status(steps.get("compile", {})) + if recache: + built += "; forced recompilation requested" + lines.append(f"| Compiler objects | {restored} | {built} |") + lines.extend(["", "Build outcomes describe compilation only; verification and job results are reported separately."]) + if cold: + lines.extend(["", "Workflow cache restores and saves are disabled. Runner-installed software remains available."]) + return "\n".join(lines) + "\n" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("dependencies", nargs="*", metavar="dependency") + parser.add_argument("--compiler", action="store_true") + args = parser.parse_args() + for name in args.dependencies: + if name not in LABELS: + parser.error(f"unknown dependency: {name}") + print(render(json.loads(os.environ["CACHE_STEPS"]), args.dependencies, + os.environ.get("COLD_BUILD") == "true", + os.environ.get("RECACHE") == "true", args.compiler), end="") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/tests/test_armhf_cross_configuration.py b/.github/scripts/tests/test_armhf_cross_configuration.py index 0893e99a..5bf78800 100644 --- a/.github/scripts/tests/test_armhf_cross_configuration.py +++ b/.github/scripts/tests/test_armhf_cross_configuration.py @@ -30,7 +30,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn(setting, config) self.assertNotIn("CT_CC_GCC_LIBQUADMATH=y", config) - image_config = self.read(".github/scripts/armhf-ci-image-config.sh") + image_config = self.read(".github/scripts/armhf-toolchain-config.sh") self.assertIn("ARMHF_GCC_VERSION=13.4.0", image_config) self.assertIn("ARMHF_GLIBC_VERSION=2.36", image_config) self.assertIn("ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf", image_config) @@ -42,6 +42,44 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn("reject_private_glibc_dependency", verifier) self.assertIn("private glibc symbol", audit) + def test_toolchain_stage_is_independent_of_image_refresh_inputs(self): + builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross") + toolchain, image = builder.split("FROM debian:bookworm AS cross_builder", 1) + self.assertRegex( + toolchain.splitlines()[0], + r"^FROM debian:bookworm@sha256:[0-9a-f]{64} AS toolchain$", + ) + for unrelated_input in ( + "IMAGE_REFRESH_EPOCH", + "IMAGE_RECIPE_SHA256", + "IMAGE_GENERATION", + "armhf-ci-image-config.sh", + "linux-ci-image-config.sh", + "build-hamlib-armhf-cross.sh", + ): + self.assertNotIn(unrelated_input, toolchain) + self.assertLess( + toolchain.index('test -n "$ARMHF_TOOLCHAIN_REBUILD_REVISION"'), + toolchain.index("run-apt-get update"), + ) + self.assertIn("armhf-cross-toolchain.config", toolchain) + self.assertNotIn("target=/tmp/wsjtx-ctng-build", toolchain) + self.assertIn('mkdir "$build_dir"', toolchain) + self.assertIn('rm -rf "$build_dir"', toolchain) + self.assertIn( + "COPY --from=toolchain /opt/wsjtx/armhf-toolchain " + "/opt/wsjtx/armhf-toolchain", image, + ) + self.assertIn("IMAGE_REFRESH_EPOCH", image) + self.assertIn("IMAGE_RECIPE_SHA256", image) + + def test_shared_toolchain_config_is_copied_to_both_image_roles(self): + config = self.read(".github/scripts/armhf-ci-image-config.sh") + self.assertIn('. "$_armhf_config_dir/armhf-toolchain-config.sh"', config) + for role in ("cross", "runtime"): + dockerfile = self.read(f".github/images/linux-ci/Dockerfile.armhf-{role}") + self.assertIn(".github/scripts/armhf-toolchain-config.sh", dockerfile) + def test_armhf_cache_identity_parsing_fails_closed(self): workflow = self.read(".github/workflows/build-linux.yml") self.assertIn( @@ -84,7 +122,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): def test_builder_and_runtime_keep_distinct_native_architectures(self): builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross") runtime = self.read(".github/images/linux-ci/Dockerfile.armhf-runtime") - self.assertTrue(builder.startswith("FROM debian:bookworm\n")) + self.assertIn("FROM debian:bookworm AS cross_builder\n", builder) self.assertIn("--architectures=armhf", builder) self.assertIn("qemu-user-static", builder) self.assertIn("normalize-armhf-sysroot-symlinks.sh", builder) @@ -108,12 +146,19 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): self.assertIn("cpack -G RPM", runtime_package) self.assertIn("CPACK_INSTALL_CMAKE_PROJECTS=", runtime_package) self.assertIn("CPACK_INSTALLED_DIRECTORIES=/work/AppDir;/", runtime_package) - self.assertIn('"$ARMHF_QEMU_EXECUTABLE"', runtime_package) - self.assertIn( - 'LINUX_APPIMAGE_RUNNER="$ARMHF_QEMU_EXECUTABLE"', runtime_package - ) + self.assertNotIn("qemu", runtime_package.lower()) + self.assertNotIn("LINUX_APPIMAGE_RUNNER", runtime_package) + self.assertIn(" ./linuxdeploy.AppImage --appimage-extract-and-run \\\n", runtime_package) + self.assertIn('./"$OUTPUT" --appimage-extract >/dev/null', runtime_package) + self.assertIn("-o linuxdeploy-plugin-qt.AppImage", runtime_package) self.assertIn("armhf-static-ldd.sh", runtime_package) self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH"', runtime_package) + packaging = runtime_package[runtime_package.index("Package release tarballs"):] + self.assertLess(runtime_package.index("--output appimage"), runtime_package.index("package-cli-tools.sh")) + self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH" .github/scripts/package-cli-tools.sh', packaging) + self.assertIn("--linuxdeploy /work/linuxdeploy.AppImage", packaging) + self.assertIn(".github/scripts/smoke-release-tarballs.sh", packaging) + self.assertNotIn("--ldd", packaging) def test_hybrid_is_the_only_armhf_build_implementation(self): workflow = self.read(".github/workflows/build-linux.yml") @@ -169,7 +214,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase): properties = q65.split( "set_tests_properties (test_q65_decode_pipeline", 1 )[1].split(")", 1)[0] - self.assertIn("TIMEOUT 180", properties) + self.assertIn("TIMEOUT 360", properties) if __name__ == "__main__": diff --git a/.github/scripts/tests/test_armhf_sysroot_symlinks.py b/.github/scripts/tests/test_armhf_sysroot_symlinks.py index 991971f6..42647345 100644 --- a/.github/scripts/tests/test_armhf_sysroot_symlinks.py +++ b/.github/scripts/tests/test_armhf_sysroot_symlinks.py @@ -23,7 +23,7 @@ class ArmhfSysrootSymlinkTests(unittest.TestCase): subprocess.run(["bash", str(NORMALIZER), str(sysroot)], check=True) self.assertFalse(os.readlink(link).startswith("/")) - self.assertEqual(link.resolve(), target) + self.assertEqual(link.resolve(), target.resolve()) def test_relative_links_remain_unchanged(self): with tempfile.TemporaryDirectory() as temporary: diff --git a/.github/scripts/tests/test_beta_scheduler.py b/.github/scripts/tests/test_beta_scheduler.py new file mode 100644 index 00000000..47f74d60 --- /dev/null +++ b/.github/scripts/tests/test_beta_scheduler.py @@ -0,0 +1,1368 @@ +#!/usr/bin/env python3 +"""Scheduled beta state machine, continuation, alerts, git mechanics and workflow wiring.""" +import importlib.util +import io +import itertools +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch +import urllib.error +import urllib.parse +import zipfile + +ROOT = Path(__file__).resolve().parents[3] +SPEC = importlib.util.spec_from_file_location("beta_scheduler", Path(__file__).parents[1] / "beta-scheduler.py") +beta = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(beta) + +BOT = "wsjtx-release-bot[bot]" +BOT_EMAIL = f"41+{BOT}@users.noreply.github.com" +MAINTAINER = "maintainer@example.invalid" +LINE = "release/3.3" +TIP = "1" * 40 +OLD_LINE_TIP = "2" * 40 +DEVELOP = "d" * 40 +GREEN = "e" * 40 +CUT = "c" * 40 +RECIPES = {key: str(index) * 64 for index, key in enumerate(beta.images.IMAGES, start=3)} +DRIFTED = {key: "f" * 64 for key in beta.images.IMAGES} +STATE = beta.STATE_FILE +LOCK = beta.LOCK_FILE +RUN_IDS = itertools.count(1000) + + +def state(channel="BETA", number=2, version="3.3.0"): + lines = [f"version={version}", f"channel={channel}", f"prerelease={number if channel in ('BETA', 'RC') else ''}", + "revision=$Format:%H$"] + if channel == "BETA": + lines.append("windows_signing=unsigned") + return ("\n".join(lines) + "\n").encode() + + +OLD_CONTRACT = b"version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n" + + +def lock(recipes=RECIPES, generation="validated-build-20260929-600-1"): + return (json.dumps({"schema": 1, "generation": generation, "images": { + key: {"reference": f"{beta.images.PUBLIC}/{spec[0]}@sha256:{'a' * 64}", "recipe_sha256": recipes[key]} + for key, spec in beta.images.IMAGES.items() + }}, indent=2) + "\n").encode() + + +def run(workflow, *, status="completed", conclusion="success", sha=TIP, branch=LINE, event="push", title=None, + created="2026-10-06T18:00:00Z", actor=BOT, triggering_actor=None, run_id=None): + run_id = next(RUN_IDS) if run_id is None else run_id + return { + "id": run_id, "path": f".github/workflows/{workflow}", "status": status, + "conclusion": conclusion if status == "completed" else None, "head_sha": sha, "head_branch": branch, + "event": event, "display_title": title or workflow, "created_at": created, + "actor": {"login": actor, "type": "Bot" if actor.endswith("[bot]") else "User"}, + "triggering_actor": {"login": triggering_actor or actor}, + "html_url": f"https://example.invalid/runs/{run_id}", + } + + +def candidate(version="3.3.0-beta2", operation="create", **fields): + fields.setdefault("event", "workflow_dispatch") + return run(beta.CANDIDATE, title=f"Prepare Release Candidate build/v{version} ({operation})", **fields) + + +def preparation(generation, **fields): + fields.setdefault("event", "workflow_dispatch") + fields.setdefault("branch", "develop") + fields.setdefault("sha", DEVELOP) + return run(beta.PREPARATION, title=f"Prepare Release Dependencies develop {generation}", **fields) + + +class FakeRepository: + def __init__(self): + self.heads = {} + self.files = {} + self.tags = {} + self.ancestors = set() + self.absent = set() + self.missing = [] + self.recipes = {} + self.conflicts = [] + self.validation_error = None + self.push_error = None + self.merge = None + self.written = None + self.committed = None + self.pushed = [] + self.discarded = [] + self.synced = [] + + def sync(self, *, shallow=False): + self.synced.append(shallow) + + def release_heads(self): + return dict(self.heads) + + def develop(self): + return DEVELOP + + def tag(self, name): + return self.tags.get(name) + + def read(self, commit, path): + return self.files.get((commit, path)) + + def contains(self, commit): + return commit not in self.absent + + def is_ancestor(self, ancestor, descendant): + return ancestor == descendant or (ancestor, descendant) in self.ancestors + + def commits_missing_from_develop(self, tip): + return list(self.missing) + + def fingerprints(self, commit): + return self.recipes.get(commit) + + def start_merge(self, tip, commit, name, email): + self.merge = (tip, commit) + return Path("merge-worktree"), list(self.conflicts) + + def write(self, worktree, files): + self.written = dict(files) + + def validate_lock(self, worktree): + if self.validation_error: + raise RuntimeError(self.validation_error) + + def commit(self, worktree, name, email, message): + self.committed = (name, email, message) + return CUT + + def push(self, commit, branch): + if self.push_error: + raise RuntimeError(self.push_error) + self.pushed.append((commit, branch)) + + def discard(self, worktree): + self.discarded.append(worktree) + + +class FakeGitHub: + def __init__(self): + self.workflow_runs = {} + self.queries = [] + self.dispatches = [] + self.published = set() + self.artifacts = {} + self.job_lists = {} + + def add(self, *runs): + for item in runs: + self.workflow_runs.setdefault(Path(item["path"]).name, []).append(item) + + def runs(self, workflow, **filters): + self.queries.append(workflow) + selected = [] + for item in self.workflow_runs.get(workflow, []): + if "branch" in filters and item["head_branch"] != filters["branch"]: + continue + if "event" in filters and item["event"] != filters["event"]: + continue + if "head_sha" in filters and item["head_sha"] != filters["head_sha"]: + continue + if "status" in filters and filters["status"] not in (item["status"], item["conclusion"]): + continue + selected.append(item) + return selected + + def jobs(self, run_id): + return self.job_lists.get(run_id, []) + + def dispatch(self, workflow, ref, inputs): + self.dispatches.append((workflow, ref, inputs)) + + def release_published(self, tag): + return tag in self.published + + def artifact_file(self, run_id, name, member): + return self.artifacts.get(run_id) if (name, member) == (beta.PREPARED_ARTIFACT, LOCK) else None + + +class FakePackages: + def __init__(self): + self.tags = {package: set() for package in beta.IMAGE_PACKAGES} + self.calls = [] + + def list_versions(self, owner, package): + self.calls.append((owner, package)) + return [SimpleNamespace(tags=tuple(sorted(self.tags[package]))), SimpleNamespace(tags=("stable",))] + + +class SchedulerTestCase(unittest.TestCase): + """A published beta2 on release/3.3; develop moved to a green commit with unchanged recipes.""" + + def setUp(self): + self.build() + + def build(self): + self.repo = FakeRepository() + self.internal = FakeGitHub() + self.public = FakeGitHub() + self.packages = FakePackages() + self.repo.heads = {"release/3.2": OLD_LINE_TIP, LINE: TIP} + self.repo.files[(OLD_LINE_TIP, STATE)] = OLD_CONTRACT + self.repo.files[(TIP, STATE)] = state(number=2) + self.repo.files[(TIP, LOCK)] = lock() + self.repo.tags["build/v3.3.0-beta2"] = TIP + self.public.published.add("v3.3.0-beta2") + self.repo.ancestors.add((GREEN, DEVELOP)) + self.repo.recipes[GREEN] = dict(RECIPES) + self.repo.recipes[DEVELOP] = dict(RECIPES) + self.repo.missing = [ + beta.Commit(TIP, BOT_EMAIL, ("CMakeLists.txt", STATE)), + beta.Commit("3" * 40, MAINTAINER, (LOCK, STATE)), + ] + self.internal.add(run(beta.CI, sha=GREEN, branch="develop", created="2026-10-06T10:00:00Z", actor="k1jt")) + + def cut(self): + return beta.Scheduler(self.repo, self.internal, self.public, self.packages, + bot_login=BOT, bot_email=BOT_EMAIL).cut() + + def stop(self): + with self.assertRaises(beta.Stop) as raised: + self.cut() + return raised.exception + + def assertNothingDone(self): + self.assertEqual(self.internal.dispatches, []) + self.assertEqual(self.repo.pushed, []) + + +class BetaLineTest(SchedulerTestCase): + def test_no_beta_line_between_a_freeze_and_the_next_line_is_a_quiet_skip(self): + self.repo.files[(TIP, STATE)] = state("RC", 1) + with self.assertRaisesRegex(beta.Skip, "No release/X.Y branch is in BETA state"): + self.cut() + self.assertNothingDone() + + def test_lines_without_state_with_the_old_contract_or_another_name_are_not_beta(self): + self.repo.heads.update({"release/3.0": "5" * 40, "release/3.4-hotfix": "6" * 40}) + self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1) + self.cut() + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_several_beta_lines_stop(self): + self.repo.heads["release/3.4"] = "6" * 40 + self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1) + stop = self.stop() + self.assertEqual(stop.stage, "line") + self.assertIn("release/3.3, release/3.4", str(stop)) + self.assertNothingDone() + + def test_an_invalid_beta_state_stops_instead_of_reading_as_no_line(self): + self.repo.files[(TIP, STATE)] = b"version=3.3.0\nchannel=BETA\nprerelease=2\nrevision=$Format:%H$\n" + stop = self.stop() + self.assertEqual(stop.stage, "line") + self.assertIn(f"{LINE}'s {STATE} says channel=BETA but does not validate", str(stop)) + self.assertNothingDone() + + def test_beta_state_for_another_line_stops(self): + self.repo.files[(TIP, STATE)] = state(version="3.4.0") + self.assertEqual(self.stop().stage, "line") + self.assertNothingDone() + + +class RetryCutTest(SchedulerTestCase): + def setUp(self): + super().setUp() + del self.repo.tags["build/v3.3.0-beta2"] + self.public.published.clear() + + def expected_candidate(self, version="3.3.0-beta2"): + return [(beta.CANDIDATE, LINE, {"version": version, "expected_sha": TIP, "operation": "create"})] + + def test_new_line_first_run_cuts_beta1_at_its_tip_without_a_merge(self): + self.repo.files[(TIP, STATE)] = state(number=1) + self.repo.missing = [beta.Commit(TIP, MAINTAINER, (LOCK, STATE))] + self.repo.ancestors.add((GREEN, TIP)) + self.internal.add(run(beta.CI, sha=TIP, actor="k1jt")) + self.cut() + self.assertEqual(self.internal.dispatches, self.expected_candidate("3.3.0-beta1")) + self.assertIsNone(self.repo.merge) + self.assertEqual(self.repo.pushed, []) + + def test_retry_waits_while_the_tip_ci_runs(self): + self.internal.add(run(beta.CI, sha=TIP, conclusion="failure"), run(beta.CI, sha=TIP, status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "still running"): + self.cut() + self.assertNothingDone() + + def test_failed_tip_ci_recuts_the_same_number_from_newer_green_develop(self): + self.internal.add(run(beta.CI, sha=TIP), + run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z")) + message = self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 2).encode(), LOCK: lock()}) + self.assertEqual(self.repo.committed[:2], (BOT, BOT_EMAIL)) + self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta2 from develop\n\n")) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.internal.dispatches, []) + self.assertIn("3.3.0-beta2", message) + + def test_failed_tip_ci_without_newer_green_develop_stops(self): + failed = run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z") + for name, setup in ( + ("develop already merged", lambda: self.repo.ancestors.add((GREEN, TIP))), + ("no green develop", lambda: self.internal.workflow_runs.update({beta.CI: []})), + ): + with self.subTest(name=name): + self.setUp() + setup() + self.internal.add(run(beta.CI, sha=TIP), failed) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"])) + self.assertIsNone(self.repo.merge) + self.assertNothingDone() + + def test_recut_after_failed_tip_ci_follows_the_lock_and_conflict_rules(self): + self.internal.add(run(beta.CI, sha=TIP, conclusion="cancelled")) + self.repo.recipes[GREEN] = dict(DRIFTED) + self.repo.recipes[DEVELOP] = dict(DRIFTED) + self.repo.recipes["a5" * 20] = dict(DRIFTED) + self.internal.add(run(beta.WARMER, sha="a5" * 20, branch="develop", actor="k1jt", run_id=713)) + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add("validated-build-20261001-713-1") + with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"): + self.cut() + self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches], [beta.PREPARATION]) + self.assertEqual(self.repo.pushed, []) + self.setUp() + self.internal.add(run(beta.CI, sha=TIP, conclusion="failure")) + self.repo.conflicts = ["CMakeLists.txt"] + self.assertEqual(self.stop().stage, "merge") + self.assertNothingDone() + + def test_retry_stops_without_a_tip_ci_run(self): + self.assertEqual(self.stop().stage, "ci") + self.assertNothingDone() + + def test_a_running_tip_ci_or_candidate_a_person_started_alerts_because_nothing_resumes_the_cut(self): + for stage, runs in ( + ("ci", lambda: [run(beta.CI, sha=TIP, status="in_progress", actor="k1jt")]), + ("candidate", lambda: [run(beta.CI, sha=TIP), candidate(status="queued", actor="k1jt")]), + ): + with self.subTest(stage=stage): + self.setUp() + added = runs() + self.internal.add(*added) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, added[-1]["html_url"])) + self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop)) + self.assertNothingDone() + + def test_retry_waits_for_a_running_candidate(self): + self.internal.add(run(beta.CI, sha=TIP), candidate(status="queued")) + with self.assertRaisesRegex(beta.Skip, "candidate"): + self.cut() + self.assertNothingDone() + + def test_failed_candidate_is_retried_with_the_same_number(self): + self.internal.add( + run(beta.CI, sha=TIP), + candidate(conclusion="failure"), + candidate(operation="validate", status="in_progress", actor="k1jt"), + candidate("3.3.0-beta1", status="in_progress"), + ) + self.cut() + self.assertEqual(self.internal.dispatches, self.expected_candidate()) + + def test_retry_stops_on_a_fix_committed_only_to_the_release_branch(self): + self.internal.add(run(beta.CI, sha=TIP)) + self.repo.missing.append(beta.Commit("4" * 40, MAINTAINER, ("main.cpp",))) + stop = self.stop() + self.assertEqual(stop.stage, "fixes") + self.assertIn("4" * 40, str(stop)) + self.assertNothingDone() + + +class UnpublishedBetaTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.public.published.clear() + self.ci = run(beta.CI, sha=TIP) + self.candidate = candidate() + self.promotion = run(beta.PROMOTION, event="workflow_dispatch") + self.publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", actor="KJ5HST") + + def test_unpublished_beta_waits_quietly_while_any_of_its_runs_is_in_progress(self): + for stage, running in ( + ("CI", lambda: run(beta.CI, status="waiting")), + ("candidate", lambda: candidate(status="waiting")), + ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="waiting")), + ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="waiting")), + ): + with self.subTest(stage=stage): + self.setUp() + self.internal.add(self.ci, self.candidate) + target = self.public if stage == "public release" else self.internal + target.add(running()) + with self.assertRaisesRegex(beta.Skip, f"its {stage} run is still in progress"): + self.cut() + self.assertNothingDone() + + def test_unpublished_beta_alerts_on_a_running_run_a_person_started_but_waits_for_the_public_release(self): + for stage, running, alerts in ( + ("ci", lambda: run(beta.CI, status="in_progress", actor="k1jt"), True), + ("candidate", lambda: candidate(status="in_progress", actor="k1jt"), True), + ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="in_progress", actor="k1jt"), + True), + ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="in_progress", + actor="KJ5HST"), False), + ): + with self.subTest(stage=stage): + self.setUp() + self.internal.add(self.ci, self.candidate) + added = running() + (self.public if stage == "public release" else self.internal).add(added) + if alerts: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, added["html_url"])) + else: + with self.assertRaisesRegex(beta.Skip, "public release run is still in progress"): + self.cut() + self.assertNothingDone() + + def test_candidate_failed_after_its_tag_spends_the_number_and_cuts_the_next_from_green_develop(self): + self.internal.add(self.ci, candidate(conclusion="failure")) + scheduler = beta.Scheduler(self.repo, self.internal, self.public, self.packages, + bot_login=BOT, bot_email=BOT_EMAIL) + scheduler.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta3 from develop\n\n")) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertTrue(any("3.3.0-beta2 is spent" in note for note in scheduler.notes)) + + def test_spent_number_without_newer_green_develop_alerts_with_the_failed_run(self): + failed = candidate(conclusion="failure") + self.internal.add(self.ci, failed) + self.repo.ancestors.add((GREEN, TIP)) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("3.3.0-beta2 is spent", str(stop)) + self.assertIn("3.3.0-beta3", str(stop)) + self.assertNothingDone() + + def test_a_successful_candidate_at_the_tag_outweighs_a_newer_failed_duplicate(self): + self.internal.add(self.ci, self.candidate, + candidate(conclusion="failure", created="2026-10-06T19:00:00Z")) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("promotion", self.candidate["html_url"])) + self.assertNothingDone() + + def test_a_promoted_beta_is_never_spent_even_if_its_candidate_run_now_reads_failed(self): + failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure") + self.internal.add(self.ci, candidate(conclusion="failure"), self.promotion) + self.public.add(failed_publication) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("publication", failed_publication["html_url"])) + self.assertNothingDone() + + def test_candidate_and_promotion_runs_of_other_commits_do_not_count(self): + elsewhere = {"sha": GREEN} + for name, runs, stage in ( + ("successful candidate elsewhere", (candidate(conclusion="failure"), candidate(**elsewhere)), None), + ("running candidate elsewhere", (candidate(conclusion="failure"), candidate(status="queued", **elsewhere)), + None), + ("promotion elsewhere", (self.candidate, run(beta.PROMOTION, event="workflow_dispatch", **elsewhere)), + "promotion"), + ): + with self.subTest(name=name): + self.build() + self.public.published.clear() + self.internal.add(self.ci, *runs) + if stage is None: + self.cut() + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + else: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, self.candidate["html_url"])) + self.assertNothingDone() + + def test_unpublished_beta_alerts_at_its_first_missing_or_failed_stage(self): + failed_promotion = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure") + failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure") + promoted = (self.ci, self.candidate, self.promotion) + for internal, public, stage, link in ( + ((self.ci,), (), "candidate", None), + ((self.ci, self.candidate), (), "promotion", self.candidate["html_url"]), + ((self.ci, self.candidate, failed_promotion), (), "promotion", failed_promotion["html_url"]), + (promoted, (), "publication", self.promotion["html_url"]), + (promoted, (failed_publication,), "publication", failed_publication["html_url"]), + (promoted, (self.publication,), "publication", self.publication["html_url"]), + ): + with self.subTest(stage=stage, link=link): + self.build() + self.public.published.clear() + self.internal.add(*internal) + self.public.add(*public) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), (stage, link)) + self.assertNothingDone() + + +class NextCutTest(SchedulerTestCase): + def test_published_beta_merges_the_newest_green_develop_as_the_next_number(self): + self.internal.add( + run(beta.CI, sha="9" * 40, branch="develop", conclusion="failure", created="2026-10-06T11:00:00Z"), + run(beta.CI, sha="8" * 40, branch="develop", created="2026-10-05T11:00:00Z"), + run(beta.CI, sha="7" * 40, branch="topic", created="2026-10-06T12:00:00Z"), + ) + self.repo.ancestors.update({("9" * 40, DEVELOP), ("8" * 40, DEVELOP), ("7" * 40, DEVELOP)}) + message = self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 3).encode(), LOCK: lock()}) + name, email, commit_message = self.repo.committed + self.assertEqual((name, email), (BOT, BOT_EMAIL)) + self.assertTrue(commit_message.startswith("Cut 3.3.0-beta3 from develop\n\n")) + self.assertIn(GREEN, commit_message) + self.assertTrue(all(len(line) <= 72 for line in commit_message.splitlines())) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + self.assertEqual(self.internal.dispatches, []) + self.assertIn(CUT, message) + + def test_cut_fetches_develop_and_the_release_branches_in_full(self): + self.cut() + self.assertEqual(self.repo.synced, [False]) + + def test_green_runs_for_commits_not_on_develop_or_not_fetched_are_passed_over(self): + not_on_develop, not_fetched = "9" * 40, "8" * 40 + self.internal.add( + run(beta.CI, sha=not_on_develop, branch="develop", created="2026-10-06T12:00:00Z"), + run(beta.CI, sha=not_fetched, branch="develop", created="2026-10-06T11:00:00Z"), + ) + self.repo.ancestors.add((not_fetched, DEVELOP)) + self.repo.absent.add(not_fetched) + self.cut() + self.assertEqual(self.repo.merge, (TIP, GREEN)) + + def test_cut_state_is_a_valid_beta_state_that_keeps_the_line_version(self): + self.assertEqual(beta.policy.parse_state(beta.render_state("3.3.0", 3)), { + "version": "3.3.0", "channel": "BETA", "prerelease": "3", + "revision": "$Format:%H$", "windows_signing": "unsigned", + }) + + def test_unchanged_develop_skips_without_an_alert(self): + self.repo.ancestors.add((GREEN, TIP)) + with self.assertRaisesRegex(beta.Skip, "develop has not moved"): + self.cut() + self.assertNothingDone() + + def test_no_green_develop_stops(self): + self.internal.workflow_runs[beta.CI] = [run(beta.CI, sha=GREEN, branch="develop", conclusion="failure")] + self.assertEqual(self.stop().stage, "develop") + self.assertNothingDone() + + +class FixesOnDevelopTest(SchedulerTestCase): + def test_bot_merges_and_metadata_only_commits_are_not_fixes(self): + self.repo.missing += [beta.Commit("7" * 40, MAINTAINER, (LOCK,)), beta.Commit("8" * 40, MAINTAINER, ())] + self.cut() + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_release_branch_commits_missing_from_develop_stop_the_cut(self): + for files, email in ( + (("main.cpp",), MAINTAINER), + (("main.cpp", STATE), MAINTAINER), + (("CMakeLists.txt", STATE, LOCK), "someone-else@example.invalid"), + ): + with self.subTest(files=files, email=email): + self.build() + self.repo.missing.append(beta.Commit("4" * 40, email, files)) + stop = self.stop() + self.assertEqual(stop.stage, "fixes") + self.assertIn("4" * 40, str(stop)) + self.assertNothingDone() + + +class ImageLockTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.repo.recipes[GREEN] = dict(DRIFTED) + self.repo.recipes[DEVELOP] = dict(DRIFTED) + + def publish_generation(self, run_id, sha, recipes, *, created="2026-10-01T00:00:00Z", attempt=1, + packages=beta.IMAGE_PACKAGES, status="completed"): + generation = f"validated-build-20261001-{run_id}-{attempt}" + for package in packages: + self.packages.tags[package].add(generation) + self.repo.recipes[sha] = dict(recipes) + self.internal.add(run(beta.WARMER, sha=sha, branch="develop", created=created, actor="k1jt", + status=status, run_id=run_id)) + return generation + + def test_unchanged_recipes_keep_the_branch_lock_without_image_lookups(self): + self.repo.recipes[GREEN] = dict(RECIPES) + self.cut() + self.assertEqual(self.repo.written[LOCK], lock()) + self.assertEqual(self.packages.calls, []) + self.assertNotIn(beta.WARMER, self.internal.queries) + self.assertNotIn(beta.PREPARATION, self.internal.queries) + + def test_recipe_drift_prepares_the_newest_generation_built_for_those_recipes(self): + self.publish_generation(702, "a2" * 20, DRIFTED, created="2026-10-01T00:00:00Z") + newest = self.publish_generation(703, "a3" * 20, DRIFTED, created="2026-10-03T00:00:00Z") + rerun = newest.removesuffix("-1") + "-2" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(rerun) + self.publish_generation(704, "a4" * 20, RECIPES, created="2026-10-04T00:00:00Z") + self.internal.add(preparation("validated-build-20261001-702-1", status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"): + self.cut() + self.assertEqual(self.internal.dispatches, [ + (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": rerun}), + ]) + self.assertEqual(self.repo.pushed, []) + + def assertRefreshAlert(self, refresh): + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", refresh["html_url"])) + self.assertIn("still being refreshed", str(stop)) + self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop)) + self.assertNothingDone() + + def test_recipe_drift_alerts_while_the_image_refresh_runs_because_nothing_resumes_the_cut(self): + self.publish_generation(705, "b1" * 20, RECIPES) + self.repo.recipes["b2" * 20] = dict(DRIFTED) + refresh = run(beta.WARMER, sha="b2" * 20, branch="develop", status="in_progress", actor="k1jt") + self.internal.add(refresh) + self.assertRefreshAlert(refresh) + + def test_only_a_warmer_run_that_refreshes_the_images_holds_the_cut(self): + detect = {"name": "detect", "status": "completed", "conclusion": "success"} + for name, jobs, waits in ( + ("refresh skipped", [detect, {"name": "refresh-linux-images", "status": "completed", + "conclusion": "skipped"}], False), + ("TSan image only", [detect, {"name": "refresh-linux-images / build-normal", "status": "completed", + "conclusion": "skipped"}], False), + ("normal images building", [detect, {"name": "refresh-linux-images / build-normal", + "status": "in_progress", "conclusion": None}], True), + ("built, not yet promoted", [detect, {"name": "refresh-linux-images / build-normal", + "status": "completed", "conclusion": "success"}], True), + ("refresh pending", [detect, {"name": "refresh-linux-images", "status": "queued", + "conclusion": None}], True), + ("not yet decided", [{"name": "detect", "status": "in_progress", "conclusion": None}], True), + ): + with self.subTest(name=name): + self.setUp() + self.publish_generation(720, "c1" * 20, RECIPES) + self.repo.recipes["c2" * 20] = dict(DRIFTED) + warmer = run(beta.WARMER, sha="c2" * 20, branch="develop", status="in_progress", actor="k1jt") + self.internal.add(warmer) + self.internal.job_lists[warmer["id"]] = jobs + if waits: + self.assertRefreshAlert(warmer) + else: + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", None)) + self.assertIn("No validated Linux image generation", str(stop)) + self.assertNothingDone() + + def test_a_generation_promoted_by_a_run_still_in_progress_is_used(self): + generation = self.publish_generation(722, "c4" * 20, DRIFTED, status="in_progress") + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + + def test_generations_from_a_direct_image_publication_on_develop_count(self): + generation = "validated-build-20261002-723-1" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(generation) + self.repo.recipes["c5" * 20] = dict(DRIFTED) + self.internal.add(run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch", + actor="dchristle", run_id=723)) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + self.setUp() + building = run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch", + status="in_progress", actor="dchristle") + self.repo.recipes["c5" * 20] = dict(DRIFTED) + self.internal.add(building) + self.internal.job_lists[building["id"]] = [{"name": "build-normal", "status": "in_progress", + "conclusion": None}] + self.assertRefreshAlert(building) + + def test_generation_reruns_are_ordered_by_attempt_number(self): + generation = self.publish_generation(721, "c3" * 20, DRIFTED, attempt=9) + tenth = generation.removesuffix("-9") + "-10" + for package in beta.IMAGE_PACKAGES: + self.packages.tags[package].add(tenth) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], tenth) + + def test_recipe_drift_without_a_generation_or_refresh_stops(self): + self.publish_generation(706, "b3" * 20, RECIPES) + self.publish_generation(707, "b4" * 20, DRIFTED, packages=beta.IMAGE_PACKAGES[:3]) + self.repo.recipes["b5" * 20] = dict(RECIPES) + self.internal.add(run(beta.WARMER, sha="b5" * 20, branch="develop", status="in_progress", actor="k1jt")) + self.assertEqual(self.stop().stage, "lock") + self.assertNothingDone() + + def test_recipe_drift_waits_for_a_running_preparation(self): + generation = self.publish_generation(708, "b6" * 20, DRIFTED) + self.internal.add(preparation(generation, status="in_progress")) + with self.assertRaisesRegex(beta.Skip, "Prepare Release Dependencies"): + self.cut() + self.assertNothingDone() + + def test_recipe_drift_commits_the_prepared_lock_in_the_cut(self): + generation = self.publish_generation(709, "b7" * 20, DRIFTED) + prepared = preparation(generation, created="2026-10-06T08:00:00Z") + failed_earlier = preparation(generation, created="2026-10-06T07:00:00Z", conclusion="failure") + self.internal.add(prepared, failed_earlier) + self.internal.artifacts[prepared["id"]] = lock(DRIFTED, generation) + self.cut() + self.assertEqual(self.repo.written[LOCK], lock(DRIFTED, generation)) + self.assertIn(generation, self.repo.committed[2]) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + self.assertEqual(self.internal.dispatches, []) + + def test_prepared_lock_for_other_recipes_or_generation_is_prepared_again(self): + generation = self.publish_generation(710, "b8" * 20, DRIFTED) + for prepared_lock in (lock(RECIPES, generation), lock(DRIFTED, "validated-build-20261001-1-1"), None): + with self.subTest(prepared_lock=prepared_lock): + self.internal.dispatches.clear() + stale = preparation(generation) + self.internal.add(stale) + self.internal.artifacts[stale["id"]] = prepared_lock + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches, [ + (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": generation}), + ]) + + def test_failed_preparation_stops_with_its_run(self): + generation = self.publish_generation(711, "b9" * 20, DRIFTED) + failed = preparation(generation, conclusion="failure") + self.internal.add(failed) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"])) + self.assertNothingDone() + + def test_a_develop_tip_with_other_recipes_alerts_instead_of_preparing_a_lock_that_would_fail(self): + generation = self.publish_generation(724, "c6" * 20, DRIFTED) + self.repo.recipes[DEVELOP] = {key: "9" * 64 for key in beta.images.IMAGES} + stop = self.stop() + self.assertEqual(stop.stage, "lock") + self.assertIn(f"develop's tip {DEVELOP} has other Linux image recipes", str(stop)) + self.assertIn(generation, str(stop)) + self.assertNothingDone() + + def test_a_running_preparation_someone_else_started_alerts(self): + generation = self.publish_generation(725, "c7" * 20, DRIFTED) + running = preparation(generation, status="in_progress", actor="dchristle") + self.internal.add(running) + stop = self.stop() + self.assertEqual((stop.stage, stop.link), ("lock", running["html_url"])) + self.assertNothingDone() + + def test_missing_branch_lock_is_prepared(self): + self.repo.recipes[GREEN] = dict(RECIPES) + self.repo.recipes[DEVELOP] = dict(RECIPES) + del self.repo.files[(TIP, LOCK)] + generation = self.publish_generation(712, "ba" * 20, RECIPES) + with self.assertRaisesRegex(beta.Skip, "Dispatched"): + self.cut() + self.assertEqual(self.internal.dispatches[0][2]["generation"], generation) + + +class MergeTest(SchedulerTestCase): + def test_metadata_conflicts_are_resolved_by_the_bot(self): + self.repo.conflicts = [STATE, LOCK] + self.cut() + self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode()) + self.assertEqual(self.repo.pushed, [(CUT, LINE)]) + + def test_other_conflicts_stop_without_a_push(self): + self.repo.conflicts = [STATE, "CMakeLists.txt"] + stop = self.stop() + self.assertEqual(stop.stage, "merge") + self.assertIn("CMakeLists.txt", str(stop)) + self.assertIsNone(self.repo.written) + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + self.assertNothingDone() + + def test_lock_that_fails_validation_stops_without_a_push(self): + self.repo.validation_error = "Stale recipe for x86_64" + stop = self.stop() + self.assertEqual(stop.stage, "lock") + self.assertIn("Stale recipe", str(stop)) + self.assertIsNone(self.repo.committed) + self.assertNothingDone() + + def test_rejected_push_stops(self): + self.repo.push_error = "non-fast-forward" + self.assertEqual(self.stop().stage, "merge") + self.assertEqual(self.repo.discarded, [Path("merge-worktree")]) + + +class ContinueTest(SchedulerTestCase): + def setUp(self): + super().setUp() + self.repo.files[(TIP, STATE)] = state(number=3) + + def proceed(self, event_run): + return beta.Scheduler(self.repo, self.internal, bot_login=BOT).continue_after(event_run) + + def skipped(self, event_run): + with self.assertRaises(beta.Skip): + self.proceed(event_run) + self.assertEqual(self.internal.dispatches, []) + + def stopped(self, event_run): + with self.assertRaises(beta.Stop) as raised: + self.proceed(event_run) + self.assertEqual(self.internal.dispatches, []) + return raised.exception + + def test_green_cut_ci_dispatches_candidate_creation(self): + self.proceed(run(beta.CI)) + self.assertEqual(self.internal.dispatches, [ + (beta.CANDIDATE, LINE, {"version": "3.3.0-beta3", "expected_sha": TIP, "operation": "create"}), + ]) + self.assertEqual(self.repo.synced, [True]) + + def test_runs_not_started_by_the_release_bot_do_nothing(self): + for actor in ("k1jt", "dependabot[bot]", "github-actions[bot]"): + with self.subTest(actor=actor): + self.skipped(run(beta.CI, actor=actor)) + self.assertEqual(self.repo.synced, []) + + def test_a_person_rerunning_a_release_bot_run_resumes_the_beta(self): + self.proceed(run(beta.CI, triggering_actor="k1jt")) + self.repo.tags["build/v3.3.0-beta3"] = TIP + rerun = candidate("3.3.0-beta3", triggering_actor="dchristle") + self.proceed(rerun) + self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches], + [beta.CANDIDATE, beta.PROMOTION]) + + def test_green_cut_ci_waits_for_a_candidate_already_running(self): + self.internal.add(candidate("3.3.0-beta3", status="in_progress")) + self.skipped(run(beta.CI)) + + def test_runs_away_from_the_beta_line_tip_do_nothing(self): + for fields in ({"sha": GREEN}, {"branch": "release/3.2", "sha": OLD_LINE_TIP}, {"branch": "release/3.2"}, + {"event": "pull_request"}): + with self.subTest(fields=fields): + self.skipped(run(beta.CI, **fields)) + + def test_failed_cut_ci_alerts(self): + failed = run(beta.CI, conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"])) + + def test_existing_candidate_tag_is_not_created_again(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + self.skipped(run(beta.CI)) + + def test_successful_candidate_dispatches_promotion(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + done = candidate("3.3.0-beta3") + self.proceed(done) + self.assertEqual(self.internal.dispatches, [(beta.PROMOTION, LINE, { + "version": "3.3.0-beta3", "candidate_run_id": str(done["id"]), "operation": "promote", + })]) + + def test_failed_candidate_alerts_that_a_rerun_resumes_or_the_next_cut_moves_on(self): + self.repo.tags["build/v3.3.0-beta3"] = TIP + failed = candidate("3.3.0-beta3", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("Re-run it if the failure is transient", str(stop)) + self.assertIn("moves on to BETA 4", str(stop)) + + def test_candidate_refused_before_its_tag_alerts_that_the_next_cut_retries_the_number(self): + failed = candidate("3.3.0-beta3", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"])) + self.assertIn("the next scheduled cut retries 3.3.0-beta3", str(stop)) + self.assertNotIn("BETA 4", str(stop)) + + def test_candidate_without_its_tag_at_the_tip_alerts(self): + for tag_sha in (None, GREEN): + with self.subTest(tag_sha=tag_sha): + self.repo.tags["build/v3.3.0-beta3"] = tag_sha + self.assertEqual(self.stopped(candidate("3.3.0-beta3")).stage, "candidate") + + def test_other_candidate_runs_do_nothing(self): + for other in ( + candidate("3.3.0-beta3", "validate"), + candidate("3.3.0-beta2"), + run(beta.CANDIDATE, event="workflow_dispatch", title="Prepare Release Candidate"), + ): + with self.subTest(title=other["display_title"]): + self.repo.tags["build/v3.3.0-beta3"] = TIP + self.skipped(other) + + def test_failed_promotion_alerts_so_a_rerun_can_resume(self): + failed = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("promotion", failed["html_url"])) + + def test_successful_promotion_leaves_publication_to_the_public_release_run(self): + self.skipped(run(beta.PROMOTION, event="workflow_dispatch")) + + def test_successful_bot_preparation_dispatches_the_beta_cut_on_develop(self): + self.proceed(preparation("validated-build-20261001-714-1")) + self.assertEqual(self.internal.dispatches, [(beta.BETA_CUT, "develop", {})]) + self.assertEqual(self.repo.synced, []) + + def test_other_preparation_and_develop_runs_do_nothing(self): + for other in ( + preparation("validated-build-20261001-714-1", actor="dchristle"), + preparation("validated-build-20261001-714-1", branch=LINE), + preparation("validated-build-20261001-714-1", event="push"), + run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP, + title="Prepare Release Dependencies release/3.2 validated-build-20260918-35390550558-1"), + run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP, + title="Prepare Release Dependencies"), + run(beta.CI, branch="develop", sha=DEVELOP), + ): + with self.subTest(path=other["path"], title=other["display_title"], branch=other["head_branch"], + event=other["event"], actor=other["actor"]["login"]): + self.skipped(other) + + def test_failed_bot_preparation_alerts(self): + failed = preparation("validated-build-20261001-714-1", conclusion="failure") + stop = self.stopped(failed) + self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"])) + + +class StepReportTest(unittest.TestCase): + def outcome(self, action): + return beta.run_step("cut", action, ["Beta line: release/3.3."]) + + def test_actions_and_skips_report_without_an_alert(self): + status, summary, alert = self.outcome(lambda: "Dispatched the candidate.") + self.assertEqual((status, alert), (0, None)) + self.assertIn("- Beta line: release/3.3.", summary) + self.assertIn("Dispatched the candidate.", summary) + + def skip(): + raise beta.Skip("develop has not moved") + status, summary, alert = self.outcome(skip) + self.assertEqual((status, alert), (0, None)) + self.assertIn("develop has not moved", summary) + + def test_stops_and_unexpected_errors_alert_and_fail(self): + def stop(): + raise beta.Stop("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1") + + def crash(): + raise RuntimeError("API outage") + status, summary, alert = self.outcome(stop) + self.assertEqual((status, alert), (1, ("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1"))) + self.assertIn("release/3.3 holds a fix.", summary) + with patch("traceback.print_exc"): + status, summary, alert = self.outcome(crash) + self.assertEqual((status, alert), (1, ("cut", "Unexpected error: API outage", None))) + + +class EntryPointTest(unittest.TestCase): + ENV = {"GITHUB_REPOSITORY": "example/internal", "GITHUB_RUN_ID": "5", "GITHUB_TOKEN": "workflow-token", + "RELEASE_BOT_TOKEN": "bot-token", "RELEASE_BOT_SLUG": "wsjtx-release-bot", + "PUBLIC_READ_TOKEN": "public-token"} + + def test_scheduler_acts_as_the_release_bot(self): + with patch.object(beta.GitHub, "user_id", lambda github, login: 41): + cut = beta.build_scheduler("cut", self.ENV, []) + proceed = beta.build_scheduler("continue", self.ENV, []) + self.assertEqual((cut.bot_login, cut.bot_email), (BOT, BOT_EMAIL)) + self.assertEqual((proceed.bot_login, proceed.bot_email), (BOT, None)) + self.assertEqual(cut.public.repository, beta.PUBLIC_REPOSITORY) + + def main(self, outcome): + posted = [] + with tempfile.TemporaryDirectory() as directory: + output, summary = Path(directory, "output"), Path(directory, "summary") + output.touch() + env = {**self.ENV, "GITHUB_OUTPUT": str(output), "GITHUB_STEP_SUMMARY": str(summary)} + with patch.dict(os.environ, env), \ + patch.object(beta, "build_scheduler", lambda command, environ, notes: SimpleNamespace(cut=outcome)), \ + patch.object(beta.Alerts, "post", lambda alerts, *alert: posted.append(alert)), \ + patch("sys.stdout", io.StringIO()): + status = beta.main(["cut"]) + return status, posted, output.read_text(), summary.read_text() + + def test_a_stop_is_posted_once_and_recorded_so_the_fallback_alert_stays_silent(self): + def stop(): + raise beta.Stop("candidate", "The candidate failed.", "https://example.invalid/runs/2") + status, posted, output, summary = self.main(stop) + self.assertEqual(status, 1) + self.assertEqual(posted, [("candidate", "The candidate failed.", "https://example.invalid/runs/2")]) + self.assertEqual(output, "alerted=true\n") + self.assertIn("The candidate failed.", summary) + + def test_a_skip_posts_nothing(self): + def skip(): + raise beta.Skip("develop has not moved") + status, posted, output, summary = self.main(skip) + self.assertEqual((status, posted, output), (0, [], "")) + self.assertIn("develop has not moved", summary) + + +class FakeIssuesApi: + repository = "example/internal" + + def __init__(self, issues): + self.issues = issues + self.calls = [] + + def call(self, method, path, *, params=None, body=None, missing_ok=False): + self.calls.append((method, path, params, body)) + return self.issues if method == "GET" else {} + + +class AlertsTest(unittest.TestCase): + RUN = "https://example.invalid/runs/1" + + def test_first_alert_opens_the_tracking_issue(self): + api = FakeIssuesApi([ + {"number": 5, "title": beta.ALERT_TITLE + " (old)", "user": {"login": beta.ALERT_CREATOR}}, + {"number": 6, "title": beta.ALERT_TITLE, "user": {"login": "k1jt"}}, + {"number": 7, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}, "pull_request": {}}, + ]) + beta.Alerts(api, self.RUN).post("candidate", "The candidate failed.", "https://example.invalid/runs/2") + self.assertEqual(api.calls[0][:3], ("GET", "/repos/example/internal/issues", + {"state": "open", "creator": beta.ALERT_CREATOR, "per_page": 100})) + method, path, _params, body = api.calls[-1] + self.assertEqual((method, path, body["title"]), ("POST", "/repos/example/internal/issues", beta.ALERT_TITLE)) + for text in ("**Stage:** candidate", "**Reason:** The candidate failed.", + "**Run:** https://example.invalid/runs/2", f"**Reported by:** {self.RUN}"): + self.assertIn(text, body["body"]) + + def test_later_alerts_comment_on_the_open_tracking_issue(self): + api = FakeIssuesApi([ + {"number": 12, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}}, + {"number": 9, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}}, + ]) + beta.Alerts(api, self.RUN).post("lock", "No generation.") + method, path, _params, body = api.calls[-1] + self.assertEqual((method, path), ("POST", "/repos/example/internal/issues/9/comments")) + self.assertIn(f"**Run:** {self.RUN}", body["body"]) + self.assertNotIn("Reported by", body["body"]) + + +class FakeResponse(io.BytesIO): + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +class GitHubClientTest(unittest.TestCase): + def test_missing_release_is_unpublished_and_other_errors_raise(self): + github = beta.GitHub("token", "example/public") + + def missing(request, timeout): + raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, None) + with patch("urllib.request.urlopen", missing): + self.assertFalse(github.release_published("v3.3.0-beta2")) + with patch("urllib.request.urlopen", lambda request, timeout: FakeResponse(b'{"draft": false}')): + self.assertTrue(github.release_published("v3.3.0-beta2")) + + def denied(request, timeout): + raise urllib.error.HTTPError(request.full_url, 403, "Forbidden", {}, None) + with patch("urllib.request.urlopen", denied), self.assertRaisesRegex(RuntimeError, "HTTP 403"): + github.release_published("v3.3.0-beta2") + + def test_run_and_job_listings_send_their_filters(self): + requests = [] + + def urlopen(request, timeout): + requests.append(request) + return FakeResponse(json.dumps({"workflow_runs": [{"id": 1}], "jobs": [{"id": 2}]}).encode()) + + github = beta.GitHub("token", "example/internal") + with patch("urllib.request.urlopen", urlopen): + self.assertEqual(github.runs(beta.CI, branch="develop", event="push", status="success", + head_sha="ab" * 20), [{"id": 1}]) + self.assertEqual(github.jobs(77), [{"id": 2}]) + runs, jobs = (urllib.parse.urlsplit(request.full_url) for request in requests) + self.assertEqual(runs.path, f"/repos/example/internal/actions/workflows/{beta.CI}/runs") + self.assertEqual(urllib.parse.parse_qs(runs.query), { + "per_page": ["100"], "branch": ["develop"], "event": ["push"], "status": ["success"], + "head_sha": ["ab" * 20], + }) + self.assertEqual((jobs.path, urllib.parse.parse_qs(jobs.query)), + ("/repos/example/internal/actions/runs/77/jobs", {"per_page": ["100"]})) + + def test_artifact_download_follows_the_redirect_without_the_token(self): + bundle = io.BytesIO() + with zipfile.ZipFile(bundle, "w") as archive: + archive.writestr(LOCK, lock()) + requests = [] + + class Opener: + def open(self, request, timeout): + requests.append(request) + location = {"Location": "https://blob.example.invalid/a"} + raise urllib.error.HTTPError(request.full_url, 302, "Found", location, None) + + def urlopen(request, timeout): + requests.append(request) + if isinstance(request, str): + return FakeResponse(bundle.getvalue()) + return FakeResponse(json.dumps({"artifacts": [ + {"id": 9, "name": beta.PREPARED_ARTIFACT, "expired": True}, + {"id": 8, "name": beta.PREPARED_ARTIFACT, "expired": False}, + ]}).encode()) + + github = beta.GitHub("token", "example/internal") + with patch("urllib.request.urlopen", urlopen), patch("urllib.request.build_opener", lambda *handlers: Opener()): + self.assertEqual(github.artifact_file(77, beta.PREPARED_ARTIFACT, LOCK), lock()) + self.assertIn("/actions/runs/77/artifacts?", requests[0].full_url) + self.assertTrue(requests[1].full_url.endswith("/actions/artifacts/8/zip")) + self.assertEqual(requests[1].get_header("Authorization"), "Bearer token") + self.assertEqual(requests[2], "https://blob.example.invalid/a") + + +class RepositoryTest(unittest.TestCase): + """The git layer against a local origin, with no global git identity, as on a runner.""" + + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + environment = patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": str(self.root / "no-global-config"), + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "user.useConfigOnly", + "GIT_CONFIG_VALUE_0": "true"}) + environment.start() + self.addCleanup(environment.stop) + self.origin = self.root / "origin.git" + self.work = self.root / "work" + self.git(self.root, "init", "--bare", "--initial-branch=develop", str(self.origin)) + self.git(self.root, "init", "--initial-branch=develop", str(self.work)) + # Background auto-maintenance would race the directory's removal. + for repository in (self.origin, self.work): + self.git(repository, "config", "maintenance.auto", "false") + (self.work / "app.txt").write_text("one\n") + (self.work / STATE).write_bytes(state("DEVEL", version="9.1.0")) + self.base = self.commit("develop base") + (self.work / STATE).write_bytes(state(number=1, version="9.1.0")) + (self.work / LOCK).write_bytes(lock()) + self.line_start = self.commit("open 9.1 beta line") + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.1") + self.git(self.work, "checkout", "--quiet", "--detach", self.base) + (self.work / "app.txt").write_text("two\n") + self.develop = self.commit("develop work") + self.git(self.work, "push", str(self.origin), f"{self.develop}:refs/heads/develop") + self.checkout = self.root / "checkout" + self.git(self.root, "clone", "--quiet", "--config", "maintenance.auto=false", + str(self.origin), str(self.checkout)) + self.repository = beta.Repository(self.checkout, str(self.origin)) + self.repository.sync() + + def git(self, cwd, *arguments): + return subprocess.run(["git", *arguments], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() + + def commit(self, message, author=MAINTAINER): + self.git(self.work, "add", "--all") + self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={author}", + "commit", "--quiet", "-m", message) + return self.git(self.work, "rev-parse", "HEAD") + + def origin_git(self, *arguments): + return self.git(self.origin, *arguments) + + def test_reads_refs_files_tags_and_ancestry(self): + self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start}) + self.assertEqual(self.repository.develop(), self.develop) + self.assertEqual(self.repository.read(self.line_start, STATE), state(number=1, version="9.1.0")) + self.assertIsNone(self.repository.read(self.base, LOCK)) + self.assertTrue(self.repository.contains(self.develop)) + self.assertFalse(self.repository.contains("0" * 40)) + self.assertTrue(self.repository.is_ancestor(self.base, self.develop)) + self.assertFalse(self.repository.is_ancestor(self.line_start, self.develop)) + self.assertIsNone(self.repository.tag("build/v9.1.0-beta1")) + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/tags/build/v9.1.0-beta1") + self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}", + "tag", "-a", "-m", "annotated", "annotated", self.base) + self.git(self.work, "push", str(self.origin), "refs/tags/annotated") + self.assertEqual(self.repository.tag("build/v9.1.0-beta1"), self.line_start) + self.assertEqual(self.repository.tag("annotated"), self.base) + + def test_cut_merges_develop_writes_metadata_and_pushes_as_the_bot(self): + self.assertEqual(self.repository.commits_missing_from_develop(self.line_start), + [beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE))]) + worktree, conflicts = self.repository.start_merge(self.line_start, self.develop, BOT, BOT_EMAIL) + self.assertEqual(conflicts, []) + self.repository.write(worktree, {STATE: beta.render_state("9.1.0", 2).encode(), LOCK: lock(DRIFTED)}) + cut = self.repository.commit(worktree, BOT, BOT_EMAIL, "Cut 9.1.0-beta2 from develop\n") + self.repository.push(cut, "release/9.1") + self.repository.discard(worktree) + self.assertFalse(worktree.exists()) + self.assertEqual(self.origin_git("rev-parse", "refs/heads/release/9.1"), cut) + self.assertEqual(self.origin_git("show", "-s", "--format=%P%n%an <%ae>%n%cn <%ce>", cut).splitlines(), [ + f"{self.line_start} {self.develop}", f"{BOT} <{BOT_EMAIL}>", f"{BOT} <{BOT_EMAIL}>", + ]) + self.assertEqual(self.origin_git("show", f"{cut}:app.txt"), "two") + self.assertEqual(self.origin_git("show", f"{cut}:{STATE}") + "\n", beta.render_state("9.1.0", 2)) + self.assertEqual((self.origin_git("show", f"{cut}:{LOCK}") + "\n").encode(), lock(DRIFTED)) + self.repository.sync() + self.assertEqual(self.repository.commits_missing_from_develop(cut), [ + beta.Commit(cut, BOT_EMAIL, ("app.txt", LOCK, STATE)), + beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE)), + ]) + + def test_fix_detection_reads_the_author_not_the_committer(self): + self.git(self.work, "checkout", "--quiet", "--detach", self.line_start) + (self.work / "app.txt").write_text("release fix\n") + self.git(self.work, "add", "--all") + subprocess.run(["git", "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}", + "commit", "--quiet", "-m", "fix committed by the bot"], cwd=self.work, check=True, + env={**os.environ, "GIT_COMMITTER_NAME": BOT, "GIT_COMMITTER_EMAIL": BOT_EMAIL}) + fixed = self.git(self.work, "rev-parse", "HEAD") + self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1") + self.repository.sync() + self.assertEqual(self.repository.commits_missing_from_develop(fixed)[0], + beta.Commit(fixed, MAINTAINER, ("app.txt",))) + + def test_full_sync_forgets_deleted_release_branches(self): + self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.2") + self.repository.sync() + self.assertIn("release/9.2", self.repository.release_heads()) + self.git(self.work, "push", str(self.origin), ":refs/heads/release/9.2") + self.repository.sync() + self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start}) + + def test_merge_reports_conflicts_and_push_refuses_to_rewind(self): + self.git(self.work, "checkout", "--quiet", "--detach", self.line_start) + (self.work / "app.txt").write_text("release fix\n") + fixed = self.commit("fix on the release branch") + self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1") + self.repository.sync() + worktree, conflicts = self.repository.start_merge(fixed, self.develop, BOT, BOT_EMAIL) + self.addCleanup(self.repository.discard, worktree) + self.assertEqual(conflicts, ["app.txt"]) + with self.assertRaisesRegex(RuntimeError, "git push"): + self.repository.push(self.line_start, "release/9.1") + + def test_fingerprints_run_each_commits_own_recipe_scripts(self): + shutil.copytree(ROOT / ".github", self.work / ".github") + recipes = self.commit("add the pipeline") + self.git(self.work, "push", str(self.origin), f"{recipes}:refs/heads/develop") + dockerfile = self.work / ".github/images/linux-ci/Dockerfile.noble" + dockerfile.write_text(dockerfile.read_text() + "# drift\n") + drifted = self.commit("drift the noble recipe") + self.git(self.work, "push", str(self.origin), f"{drifted}:refs/heads/develop") + self.repository.sync() + expected = { + key: subprocess.run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", spec[1]], cwd=ROOT, + check=True, capture_output=True, text=True).stdout.strip() + for key, spec in beta.images.IMAGES.items() + } + self.assertEqual(self.repository.fingerprints(recipes), expected) + changed = self.repository.fingerprints(drifted) + self.assertNotEqual(changed["x86_64"], expected["x86_64"]) + self.assertEqual(changed["armhf_runtime"], expected["armhf_runtime"]) + self.assertIsNone(self.repository.fingerprints("0" * 40)) + + def test_lock_validation_runs_the_merged_trees_validator(self): + shutil.copytree(ROOT / ".github", self.work / ".github") + (self.work / LOCK).write_text('{"schema": 2}\n') + self.commit("add the pipeline") + with self.assertRaisesRegex(RuntimeError, "Unsupported Linux image selection schema"): + self.repository.validate_lock(self.work) + + +class WorkflowWiringTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.CUT = (ROOT / ".github/workflows/beta-cut.yml").read_text() + cls.CONTINUE = (ROOT / ".github/workflows/beta-continue.yml").read_text() + + @staticmethod + def jobs(workflow): + body = workflow.split("\njobs:\n", 1)[1] + names = re.findall(r"^ ([A-Za-z0-9_-]+):$", body, re.M) + blocks = re.split(r"^ [A-Za-z0-9_-]+:$", body, flags=re.M)[1:] + return dict(zip(names, blocks)) + + def test_candidate_run_name_is_what_the_continuation_parses(self): + helper = (ROOT / ".github/workflows/release-tag-helper.yml").read_text() + run_name = re.search(r"^run-name: (.+)$", helper, re.M).group(1) + rendered = run_name.replace("${{ inputs.version }}", "3.3.0-beta2").replace("${{ inputs.operation }}", "create") + self.assertEqual(beta.candidate_of({"display_title": rendered}), ("3.3.0-beta2", "create")) + + def test_preparation_run_name_is_what_the_scheduler_parses(self): + workflow = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text() + run_name = re.search(r"^run-name: (.+)$", workflow, re.M).group(1) + rendered = run_name.replace("${{ inputs.source_branch }}", "develop").replace( + "${{ inputs.generation }}", "validated-build-20261001-1-1") + self.assertEqual(beta.preparation_of({"display_title": rendered}), ("develop", "validated-build-20261001-1-1")) + + def test_beta_workflows_act_only_when_beta_automation_is_exactly_enabled(self): + for workflow in (self.CUT, self.CONTINUE): + jobs = self.jobs(workflow) + gate = jobs["gate"] + self.assertIn("BETA_AUTOMATION: ${{ vars.BETA_AUTOMATION }}", gate) + self.assertRegex( + gate, r'if \[ "\$BETA_AUTOMATION" = enabled \]; then\s+echo "enabled=true" >> "\$GITHUB_OUTPUT"') + self.assertIn('>> "$GITHUB_STEP_SUMMARY"', gate) + # Expression comparisons ignore case, so the variable is compared only in the shell. + self.assertEqual(workflow.count("vars.BETA_AUTOMATION"), 1) + acting = [name for name, block in jobs.items() if "environment: beta-automation" in block] + self.assertEqual(len(acting), 1) + self.assertIn("needs: gate", jobs[acting[0]]) + # Neither a manual dispatch nor always() may bypass the pause. + self.assertRegex(jobs[acting[0]], r"\n if: needs\.gate\.outputs\.enabled == 'true'\n") + + def test_beta_cut_runs_weekly_on_tuesday_at_2000_utc_and_on_dispatch(self): + triggers = re.search(r"^on:\n((?: .*\n)+)", self.CUT, re.M).group(1) + self.assertEqual(triggers, ' schedule:\n - cron: "0 20 * * 2"\n workflow_dispatch:\n') + + def test_cut_and_continuation_act_one_at_a_time(self): + for workflow in (self.CUT, self.CONTINUE): + # A workflow-level group would also hold the gate runs, whose arrival cancels a pending acting run. + self.assertNotRegex(workflow, r"(?m)^concurrency:") + acting = [block for block in self.jobs(workflow).values() if "environment: beta-automation" in block] + self.assertIn(" concurrency:\n group: beta-scheduler\n cancel-in-progress: false\n", acting[0]) + + def test_beta_continue_follows_beta_runs_and_preparations_from_develop(self): + self.assertIn( + 'on:\n workflow_run:\n' + ' workflows: ["CI", "Prepare Release Candidate", "Prepare Release Dependencies", "Promote Release Source"]\n' + ' types: [completed]\n branches: ["release/**", "develop"]\n', self.CONTINUE) + # Every other run on develop, such as a person's push CI, skips the gate and starts no job. + self.assertIn( + " if: >-\n" + " github.event.workflow_run.actor.type == 'Bot' &&\n" + " (github.event.workflow_run.head_branch != 'develop' ||\n" + " github.event.workflow_run.path == '.github/workflows/prepare-release-dependencies.yml')\n", + self.jobs(self.CONTINUE)["gate"]) + + def test_release_bot_token_is_minted_only_in_the_beta_automation_job(self): + for workflow in (self.CUT, self.CONTINUE): + for name, block in self.jobs(workflow).items(): + minted = "actions/create-github-app-token@" in block + self.assertEqual(minted, "environment: beta-automation" in block, name) + if minted: + self.assertRegex(block, r"uses: actions/create-github-app-token@[0-9a-f]{40} # v\d") + self.assertIn("client-id: ${{ vars.RELEASE_BOT_APP_ID }}", block) + self.assertIn("private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}", block) + self.assertIn("persist-credentials: false", block) + self.assertIn("issues: write", block) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_check_candidate_tag.py b/.github/scripts/tests/test_check_candidate_tag.py index cf44ccf4..9212c4ec 100644 --- a/.github/scripts/tests/test_check_candidate_tag.py +++ b/.github/scripts/tests/test_check_candidate_tag.py @@ -14,6 +14,8 @@ class CheckCandidateTagTest(unittest.TestCase): self.addCleanup(self.directory.cleanup) self.repo = Path(self.directory.name) self.git("init", "-q") + # Background auto-maintenance would race the directory's removal. + self.git("config", "maintenance.auto", "false") self.git( "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-qm", "first", diff --git a/.github/scripts/tests/test_ghcr_retention.py b/.github/scripts/tests/test_ghcr_retention.py index 9bffad2d..57232eba 100755 --- a/.github/scripts/tests/test_ghcr_retention.py +++ b/.github/scripts/tests/test_ghcr_retention.py @@ -51,11 +51,22 @@ class RetentionPlanTests(unittest.TestCase): version(1, 100, ("stable", "build-20260101-1-1"), self.now), version(2, 100, ("debug",), self.now), version(3, 100, (), self.now), + version(4, 100, ("buildcache",), self.now), ] plan = self.plan(versions, keep=1) self.assertEqual(plan[1].reason, "stable") self.assertEqual(plan[2].reason, "unknown-or-untagged") self.assertEqual(plan[3].reason, "unknown-or-untagged") + self.assertEqual(plan[4].reason, "unknown-or-untagged") + self.assertFalse(plan[4].delete) + + def test_prepared_release_tags_are_not_disposable_generations(self): + plan = self.plan([ + version(1, 100, ("release-deps-validated-build-20260101-1-1",), self.now), + version(2, 100, ("build-20260101-2-1", "release-deps-validated-build-20260101-2-1"), self.now), + ], keep=0) + self.assertFalse(plan[1].delete) + self.assertFalse(plan[2].delete) def test_exact_sixty_day_boundary_is_kept(self): plan = self.plan([version(1, 60, ("candidate-1-1",), self.now)], keep=1) diff --git a/.github/scripts/tests/test_linux_ccache_policy.py b/.github/scripts/tests/test_linux_ccache_policy.py index 42c97e01..4a6ff3d8 100644 --- a/.github/scripts/tests/test_linux_ccache_policy.py +++ b/.github/scripts/tests/test_linux_ccache_policy.py @@ -1,4 +1,5 @@ import pathlib +import re import unittest @@ -9,6 +10,32 @@ class LinuxCcachePolicyTests(unittest.TestCase): def read(self, relative_path): return (REPOSITORY / relative_path).read_text(encoding="utf-8") + def sanitizer_step(self, name): + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + match = re.search( + rf"^ - name: {re.escape(name)}\n(?P<body>.*?)(?=^ - |\Z)", + action, + re.MULTILINE | re.DOTALL, + ) + self.assertIsNotNone(match, name) + return match.group("body") + + def armhf_job(self, name): + workflow = self.read(".github/workflows/build-linux.yml") + body = workflow.split(f"\n {name}:\n", 1)[1] + following = re.search(r"\n [A-Za-z0-9_-]+:\n", body) + return body[:following.start() + 1] if following else body + + def armhf_step(self, name, job="build-armhf"): + workflow = self.armhf_job(job) + match = re.search( + rf"^ - name: {re.escape(name)}\n(?P<body>.*?)(?=^ - |\Z)", + workflow, + re.MULTILINE | re.DOTALL, + ) + self.assertIsNotNone(match, name) + return match.group("body") + def assert_cache_tiers(self, text, prefix): primary = ( f"{prefix}${{{{ steps.image.outputs.ccache_compatibility_id }}}}-" @@ -42,6 +69,63 @@ class LinuxCcachePolicyTests(unittest.TestCase): action, ) + def test_sanitizer_save_requires_trusted_successful_build(self): + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + save = self.sanitizer_step("Save sanitizer objects") + for condition in ( + "inputs.save_ccache == 'true'", + "github.ref == 'refs/heads/develop'", + "steps.image.outputs.recipe_match == 'true'", + "steps.ccache.outputs.cache-hit != 'true'", + ): + self.assertIn(condition, save) + self.assertNotIn("always()", save) + self.assertNotIn("!cancelled()", save) + self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save) + self.assertIn("path: ${{ steps.sanitizer.outputs.ccache_dir }}", save) + self.assertLess( + action.index("- name: Require sanitizer tests to pass"), + action.index("- name: Save sanitizer objects"), + ) + + def test_sanitizer_tests_remain_enabled_by_default(self): + workflow = self.read(".github/workflows/build-linux-sanitizers.yml") + action = self.read(".github/actions/build-linux-sanitizers/action.yml") + self.assertRegex( + workflow, + r" run_tests:\n(?: .*\n)*? type: boolean\n default: true", + ) + self.assertRegex( + action, + r' run_tests:\n(?: .*\n)*? default: "true"', + ) + self.assertIn("run_tests: ${{ inputs.run_tests }}", workflow) + self.assertIn("inputs.sanitizer == 'tsan' && 180 || 60", workflow) + + def test_build_only_sanitizer_keeps_test_targets_and_instrumentation(self): + configure = self.sanitizer_step("Configure sanitizer build") + self.assertIn("-DWSJT_ENABLE_TESTS=ON", configure) + self.assertIn("-DWSJT_ENABLE_GUI_SMOKE_TESTS=ON", configure) + for name in ( + "Configure sanitizer build", + "Build sanitizer targets", + "Verify sanitizer instrumentation", + ): + self.assertNotIn("inputs.run_tests", self.sanitizer_step(name)) + for name in ( + "Prepare test scratch directory", + "Run tests", + "Publish test summary", + "Upload test results", + "Require sanitizer tests to pass", + ): + with self.subTest(step=name): + self.assertIn("inputs.run_tests == 'true'", self.sanitizer_step(name)) + enforce = self.sanitizer_step("Require sanitizer tests to pass") + self.assertIn("always()", enforce) + self.assertIn('steps.ctest.outcome }}" != "success"', enforce) + self.assertIn("exit 1", enforce) + def test_sanitizer_cache_keeps_profile_and_generation(self): action = self.read(".github/actions/build-linux-sanitizers/action.yml") self.assert_cache_tiers( @@ -52,10 +136,6 @@ class LinuxCcachePolicyTests(unittest.TestCase): 'export CCACHE_COMPILERCHECK="${{ steps.image.outputs.ccache_compiler_check }}"', action, ) - self.assertIn( - "if: inputs.save_ccache == 'true' && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", - action, - ) def test_armhf_verifies_and_forwards_cache_identity(self): workflow = self.read(".github/workflows/build-linux.yml") @@ -72,7 +152,7 @@ class LinuxCcachePolicyTests(unittest.TestCase): workflow.count( "RUNTIME_IMAGE: ${{ needs.resolve-image.outputs.image_reference }}" ), - 2, + 4, ) self.assertIn("build-linux-armhf-cross.sh", workflow) self.assertIn("validate-linux-armhf-runtime.sh", workflow) @@ -83,16 +163,109 @@ class LinuxCcachePolicyTests(unittest.TestCase): self.assertIn("cross_recipe_match", workflow) self.assertIn("runtime_recipe_match", workflow) self.assertIn( - "if: inputs.save_ccache && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", + "if: inputs.save_ccache && (!inputs.armhf_build_only || github.ref == 'refs/heads/develop') && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'", workflow, ) - def test_release_accepts_separately_promoted_armhf_recipe(self): + def test_armhf_build_only_preserves_compilation_audits_and_pair_verification(self): + workflow = self.read(".github/workflows/build-linux.yml") + self.assertEqual(len(re.findall( + r" armhf_build_only:\n(?: .*\n)*? type: boolean\n default: false", + workflow, + )), 2) + self.assertIn('if [ "$ARMHF_BUILD_ONLY" = true ] && [ "$ARCH" != armhf ]; then', workflow) + for name in ("Inspect ARMHF image pair", "Cross-build ARMHF binaries"): + self.assertNotIn("if:", self.armhf_step(name)) + compile_step = self.armhf_step("Cross-build ARMHF binaries") + self.assertIn("ARMHF_BUILD_ONLY: ${{ inputs.armhf_build_only }}", compile_step) + self.assertIn("-e ARMHF_BUILD_ONLY", compile_step) + script = self.read(".github/scripts/build-linux-armhf-cross.sh") + self.assertIn("-DWSJT_ENABLE_TESTS=ON", script) + skip_install = script.index('if [ "$ARMHF_BUILD_ONLY" = true ]; then', script.index("cmake --build")) + for audit in ("validate_linux_build_executables", ".github/scripts/audit-armhf-cross-build.sh"): + self.assertLess(script.index(audit), skip_install) + self.assertLess(skip_install, script.index("cmake --install")) + self.assertIn("exit 0", script[skip_install:script.index("cmake --install")]) + + def test_armhf_build_only_skips_runtime_and_artifact_steps(self): + test_job = self.armhf_job("test-armhf") + self.assertIn(" if: inputs.arch == 'armhf' && !inputs.armhf_build_only\n", test_job) + for name in ( + "Test and package on native ARMv7", "Publish armhf test summary", + "Upload armhf AppImage startup diagnostics", "Upload .deb", "Upload RPM", + "Upload AppImage", "Upload build artifacts", "Upload test results", + "Upload release tarballs", + ): + with self.subTest(step=name): + self.assertIn(f" - name: {name}\n", test_job) + self.assertNotIn(f" - name: {name}\n", self.armhf_job("build-armhf")) + for name in ("Pack ARMHF build tree", "Upload ARMHF build tree"): + with self.subTest(step=name): + self.assertIn("if: ${{ !inputs.armhf_build_only }}", self.armhf_step(name)) + + def test_armhf_runtime_runs_natively_on_an_arm_runner_from_the_cross_build_tree(self): + build_job = self.armhf_job("build-armhf") + test_job = self.armhf_job("test-armhf") + self.assertIn(" runs-on: ubuntu-24.04\n", build_job) + self.assertIn(" runs-on: ubuntu-24.04-arm\n", test_job) + self.assertIn(" needs: [resolve-image, build-armhf]\n", test_job) + self.assertNotIn("setup-qemu-action", test_job) + self.assertNotIn("validate-linux-armhf-runtime.sh", build_job) + self.assertIn("bash .github/scripts/validate-linux-armhf-runtime.sh", self.armhf_step("Test and package on native ARMv7", "test-armhf")) + pack = self.armhf_step("Pack ARMHF build tree") + self.assertIn( + "sudo tar --create --file armhf-build-tree.tar --exclude='wsjtx-build/*.o' --exclude='wsjtx-build/*.a' wsjtx-build AppDir\n", + pack, + ) + self.assertLess(build_job.index("- name: Save armhf ccache"), build_job.index("- name: Pack ARMHF build tree")) + for step in ("actions/checkout@", "docker/login-action@"): + self.assertIn(step, test_job) + self.assertLess(test_job.index("docker/login-action@"), test_job.index("- name: Require native 32-bit ARM execution")) + self.assertLess(test_job.index("- name: Require native 32-bit ARM execution"), test_job.index("- name: Download ARMHF build tree")) + preflight = self.armhf_step("Require native 32-bit ARM execution", "test-armhf") + self.assertIn("grep -Eq '^CPU op-mode\\(s\\):.*32-bit'", preflight) + self.assertIn("/proc/sys/fs/binfmt_misc/qemu-arm", preflight) + self.assertIn('docker run --rm --platform linux/arm/v7 "$RUNTIME_IMAGE" getconf LONG_BIT', preflight) + runtime_step = self.armhf_step("Test and package on native ARMv7", "test-armhf") + for fragment in ("docker run --rm --platform linux/arm/v7", '-v "${GITHUB_WORKSPACE}:/work"', "-w /work", "-e ARMHF_RUNTIME_PHASE"): + self.assertIn(fragment, runtime_step) + for name in ("Publish armhf test summary", "Upload test results"): + self.assertIn(" if: always()\n", self.armhf_step(name, "test-armhf")) + for name, artifact in ( + ("Upload .deb", "wsjtx-${{ inputs.version }}-linux-armhf-deb"), + ("Upload RPM", "wsjtx-${{ inputs.version }}-linux-armhf-rpm"), + ("Upload AppImage", "wsjtx-${{ inputs.version }}-linux-armhf-AppImage"), + ): + self.assertIn(f" name: {artifact}\n", self.armhf_step(name, "test-armhf")) + self.assertIn("name: armhf-build-tree\n", self.armhf_step("Upload ARMHF build tree")) + self.assertIn("name: armhf-build-tree\n", self.armhf_step("Download ARMHF build tree", "test-armhf")) + self.assertIn("tar --extract --file armhf-build-tree.tar", self.armhf_step("Unpack ARMHF build tree", "test-armhf")) + self.assertLess(test_job.index("- name: Unpack ARMHF build tree"), test_job.index("- name: Test and package on native ARMv7")) + runtime = self.read(".github/scripts/validate-linux-armhf-runtime.sh") + self.assertIn("ctest --parallel 3 --output-on-failure", runtime) + self.assertNotIn("--exclude-regex", runtime) + + def test_armhf_build_only_save_requires_trusted_successful_audits(self): + save = self.armhf_step("Save armhf ccache") + self.assertIn("(!inputs.armhf_build_only || github.ref == 'refs/heads/develop')", save) + self.assertIn("inputs.save_ccache", save) + self.assertIn("steps.image.outputs.recipe_match == 'true'", save) + self.assertIn("steps.ccache.outputs.cache-hit != 'true'", save) + self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save) + self.assertNotIn("always()", save) + self.assertNotIn("!cancelled()", save) + build_job = self.armhf_job("build-armhf") + self.assertLess(build_job.index("- name: Cross-build ARMHF binaries"), build_job.index("- name: Save armhf ccache")) + + def test_release_requires_pinned_armhf_pair_without_stale_recipe_fallback(self): workflow = self.read(".github/workflows/release.yml") armhf_job = workflow.split(" linux-armhf:\n", 1)[1].split( "\n windows:\n", 1 )[0] - self.assertIn("allow_stale_image: true", armhf_job) + self.assertNotIn("allow_stale_image: true", armhf_job) + self.assertIn("image_source: public-release", armhf_job) + self.assertIn("image_digest: ${{ needs.prepare.outputs.armhf_digest }}", armhf_job) + self.assertIn("armhf_cross_image_digest: ${{ needs.prepare.outputs.armhf_cross_digest }}", armhf_job) if __name__ == "__main__": diff --git a/.github/scripts/tests/test_linux_image_publication_policy.py b/.github/scripts/tests/test_linux_image_publication_policy.py index cb88ac95..57d0ce1f 100644 --- a/.github/scripts/tests/test_linux_image_publication_policy.py +++ b/.github/scripts/tests/test_linux_image_publication_policy.py @@ -1,5 +1,10 @@ +import fnmatch +import os import pathlib import re +import subprocess +import tempfile +import textwrap import unittest @@ -10,10 +15,10 @@ WARM = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() CLASSIFIER = (ROOT / ".github/scripts/is-linux-ci-image-input.sh").read_text() -def job(name: str) -> str: +def job(name: str, workflow: str = PUBLISH) -> str: match = re.search( rf"^ {re.escape(name)}:\n(?P<body>.*?)(?=^ [a-z][a-z0-9-]*:\n|\Z)", - PUBLISH, + workflow, re.MULTILINE | re.DOTALL, ) if not match: @@ -22,6 +27,219 @@ def job(name: str) -> str: class LinuxImagePublicationPolicyTests(unittest.TestCase): + def test_armhf_cross_cache_import_and_export_share_registry_destination(self): + metadata = job("metadata") + for package_root in ("ghcr.io/wsjtx/wsjtx", "ghcr.io/wsjtx/wsjtx-internal"): + self.assertIn( + f"armhf_cross_cache_from=type=registry,ref={package_root}/linux-armhf-cross-bookworm:buildcache", + metadata, + ) + cross = job("build-armhf-cross") + self.assertIn("cache-from: ${{ needs.metadata.outputs.armhf_cross_cache_from }}", cross) + self.assertIn( + "cache-to: type=registry,ref=${{ needs.metadata.outputs.package_root }}/linux-armhf-cross-bookworm:buildcache,mode=max", + cross, + ) + + def select_warmers(self, event, *, target="", schedule="", paths=()): + selector = re.search( + r" run: \|\n(?P<body>.*?)(?=^ refresh-linux-images:)", + WARM, + re.MULTILINE | re.DOTALL, + ).group("body") + git_stub = """ +git() { + case "$1" in + cat-file) return 0 ;; + diff) printf '%s\\n' "$CHANGED_PATHS" ;; + *) return 2 ;; + esac +} +""" + with tempfile.TemporaryDirectory() as directory: + output = pathlib.Path(directory) / "output" + result = subprocess.run( + ["bash", "-c", git_stub + textwrap.dedent(selector)], + cwd=ROOT, + env={ + **os.environ, + "EVENT_NAME": event, + "TARGETS": target, + "SCHEDULE": schedule, + "BEFORE_SHA": "previous", + "CURRENT_SHA": "current", + "CHANGED_PATHS": "\n".join(paths), + "HAMLIB_BRANCH": "4.7.2", + "GITHUB_OUTPUT": str(output), + "GITHUB_STEP_SUMMARY": str(pathlib.Path(directory) / "summary"), + }, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return dict(line.split("=", 1) for line in output.read_text().splitlines()) + + def test_macos_warmer_selection_routes_both_architectures(self): + cases = [ + ({"event": "workflow_dispatch", "target": "macos-x86_64"}, "false", "true"), + ({"event": "workflow_dispatch", "target": "macos-arm64"}, "true", "false"), + ({"event": "workflow_dispatch", "target": "macos"}, "true", "true"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "true"), + ({"event": "workflow_dispatch", "target": "linux"}, "false", "false"), + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "true"), + ] + for path in ( + ".github/workflows/build-macos.yml", ".github/actions/warm-macos-deps/action.yml", + ".github/scripts/install-xpack-gfortran-macos.sh", ".github/scripts/build-qt-macos.sh", + ".github/scripts/macos-qt-cache-key.sh", ".github/scripts/verify-macos-static-archives.sh", + ".github/workflows/ci.yml", ".github/workflows/release.yml", + ): + cases.append(({"event": "push", "paths": [path]}, "true", "true")) + for inputs, arm, intel in cases: + with self.subTest(inputs=inputs): + outputs = self.select_warmers(**inputs) + self.assertEqual(outputs["macos_arm64"], arm) + self.assertEqual(outputs["macos_x86_64"], intel) + + def test_asan_warmer_selection(self): + cases = [ + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "linux-asan-ubsan"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"), + ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"), + ({"event": "push", "paths": [".github/scripts/build-hamlib-linux.sh"]}, "false", "normal"), + ({"event": "push", "paths": [".github/scripts/build-qt-tsan-linux.sh"]}, "false", "tsan"), + ({"event": "push", "paths": ["CMakeLists.txt", ".github/scripts/verify-linux-ci-image.sh"]}, "true", "normal-and-tsan"), + ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"), + ] + for arguments, selected, image_set in cases: + with self.subTest(arguments=arguments): + outputs = self.select_warmers(**arguments) + self.assertEqual(outputs["linux_asan_ubsan"], selected) + self.assertEqual(outputs["image_set"], image_set) + + def test_armhf_warmer_selection(self): + cases = [ + ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "linux-armhf"}, "true", "none"), + ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"), + ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"), + ({"event": "push", "paths": [".github/images/linux-ci/Dockerfile.armhf-cross"]}, "false", "normal"), + ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"), + ] + for arguments, selected, image_set in cases: + with self.subTest(arguments=arguments): + outputs = self.select_warmers(**arguments) + self.assertEqual(outputs["linux_armhf"], selected) + self.assertEqual(outputs["image_set"], image_set) + + def test_armhf_build_inputs_select_warming(self): + push_filters = re.findall(r'^ - "([^"]+)"$', WARM.split(" schedule:", 1)[0], re.MULTILINE) + for path in ( + ".github/workflows/build-linux.yml", + ".github/scripts/build-linux-armhf-cross.sh", + ".github/scripts/audit-armhf-cross-build.sh", + ".github/cmake/armhf-toolchain.cmake", + ".github/scripts/linux-artifact-validation.sh", + "CMakeLists.txt", "CMake/Sources.cmake", "tests/unit/CMakeLists.txt", + ): + with self.subTest(path=path): + self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters)) + outputs = self.select_warmers("push", paths=[path]) + self.assertEqual(outputs["linux_armhf"], "true") + self.assertEqual(outputs["image_set"], "none") + + def test_armhf_warmers_share_configuration_and_serialize(self): + standalone = job("warm-linux-armhf-ccache", WARM) + published = job("warm-armhf-ccache") + for warmer in (standalone, published): + for required in ( + "github.ref == 'refs/heads/develop'", + "uses: ./.github/workflows/build-linux.yml", "arch: armhf", + "armhf_build_only: true", "allow_stale_image: false", + "recache: false", "save_ccache: true", + "group: armhf-ccache-develop", "cancel-in-progress: false", + "contents: read", "packages: read", + ): + self.assertIn(required, warmer) + self.assertNotIn("packages: write", warmer) + for condition in ( + "needs.detect.outputs.linux_armhf == 'true'", + "needs.detect.outputs.image_set != 'normal'", + "needs.detect.outputs.image_set != 'normal-and-tsan'", + ): + self.assertIn(condition, standalone) + self.assertIn("- warm-linux-armhf-ccache", job("summary", WARM)) + for condition in ( + "needs.promote.result == 'success'", "inputs.publication_target == 'internal'", + "inputs.mode == 'refresh'", "inputs.promote", "inputs.include_armhf", + "(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')", + "image_tag: ${{ needs.metadata.outputs.build_tag }}", + ): + self.assertIn(condition, published) + self.assertIn("- metadata", published) + self.assertIn("- promote", published) + self.assertNotIn("warm-armhf-ccache", job("promote")) + + def test_sanitizer_build_inputs_select_warming(self): + push_filters = re.findall( + r'^ - "([^"]+)"$', + WARM.split(" schedule:", 1)[0], + re.MULTILINE, + ) + for path in ( + ".github/workflows/build-linux-sanitizers.yml", + ".github/actions/build-linux-sanitizers/action.yml", + ".github/scripts/verify-sanitizer-instrumentation.py", + "CMakeLists.txt", + "CMake/Sources.cmake", + "tests/CMakeLists.txt", + "tests/unit/CMakeLists.txt", + ): + with self.subTest(path=path): + self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters)) + outputs = self.select_warmers("push", paths=[path]) + self.assertEqual(outputs["linux_asan_ubsan"], "true") + self.assertEqual(outputs["image_set"], "none") + + def test_asan_warmers_share_configuration_and_serialize(self): + standalone = job("warm-linux-asan-ubsan-ccache", WARM) + published = job("warm-asan-ubsan-ccache") + for warmer in (standalone, published): + with self.subTest(warmer=warmer): + for required in ( + "github.ref == 'refs/heads/develop'", + "uses: ./.github/workflows/build-linux-sanitizers.yml", + "sanitizer: asan-ubsan", + "run_tests: false", + "recache: false", + "save_ccache: true", + "allow_stale_image: false", + "group: asan-ubsan-ccache-develop", + "cancel-in-progress: false", + "contents: read", + "packages: read", + ): + self.assertIn(required, warmer) + self.assertNotIn("packages: write", warmer) + self.assertIn("needs.detect.outputs.linux_asan_ubsan == 'true'", standalone) + self.assertIn("needs.detect.outputs.image_set != 'normal'", standalone) + self.assertIn("needs.detect.outputs.image_set != 'normal-and-tsan'", standalone) + self.assertIn("- warm-linux-asan-ubsan-ccache", job("summary", WARM)) + + def test_asan_warming_follows_internal_promotion_without_gating_it(self): + warm = job("warm-asan-ubsan-ccache") + self.assertIn("metadata", warm) + self.assertIn("promote", warm) + self.assertIn("needs.promote.result == 'success'", warm) + self.assertIn("inputs.publication_target == 'internal'", warm) + self.assertIn("inputs.mode == 'refresh'", warm) + self.assertIn("inputs.promote", warm) + self.assertIn("(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')", warm) + self.assertIn("image_tag: ${{ needs.metadata.outputs.build_tag }}", warm) + self.assertNotIn("warm-asan-ubsan-ccache", job("promote")) + def test_public_release_publication_is_tag_scoped_and_complete(self): validate = job("validate-inputs") self.assertIn('[ "$REQUEST_REPOSITORY" != WSJTX/wsjtx ]', validate) @@ -177,5 +395,35 @@ class LinuxImagePublicationPolicyTests(unittest.TestCase): self.assertIn("stable_packages+=(linux-noble)", rollback) + def test_release_paths_consume_the_same_committed_selection(self): + candidate = (ROOT / ".github/workflows/release.yml").read_text() + public = (ROOT / ".github/workflows/public-release.yml").read_text() + tagging = (ROOT / ".github/workflows/release-tag-helper.yml").read_text() + promotion = (ROOT / ".github/workflows/promote-release.yml").read_text() + for workflow in (candidate, public): + self.assertIn("release-linux-images.py validate release-linux-images.json", workflow) + self.assertIn('--check-remote --github-output "$GITHUB_OUTPUT"', workflow) + self.assertEqual(workflow.count("image_source: public-release"), 3) + for output in ("x86_64_digest", "aarch64_digest", "armhf_digest", "armhf_cross_digest"): + self.assertIn("needs.prepare.outputs." + output, workflow) + self.assertNotIn("allow_stale_image: true", workflow) + self.assertNotIn("resolve-linux-ci-image-tag.py", workflow) + self.assertNotIn("publish-linux-ci-images.yml", public) + self.assertNotIn("packages: write", public) + self.assertIn( + "environment: ${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}", + public, + ) + self.assertIn("linux_images: $linux_images", candidate) + self.assertIn("release-linux-images.py provenance release-linux-images.json", candidate) + self.assertIn("release-linux-images.py verify-provenance", promotion) + self.assertLess(tagging.index("release-linux-images.py validate"), tagging.index("- name: Create candidate tag")) + + def test_prepared_image_consumption_keeps_source_and_recipe_guards(self): + self.assertIn("WSJTX/wsjtx:refs/tags/v*|WSJTX/wsjtx-internal:refs/heads/release/*", BUILD) + self.assertIn('if [ "$ALLOW_STALE_IMAGE" = true ]; then', BUILD) + self.assertIn("Prepared public images require strict recipe verification", BUILD) + + if __name__ == "__main__": unittest.main() diff --git a/.github/scripts/tests/test_native_cache_policy.py b/.github/scripts/tests/test_native_cache_policy.py new file mode 100644 index 00000000..274344c6 --- /dev/null +++ b/.github/scripts/tests/test_native_cache_policy.py @@ -0,0 +1,86 @@ +import importlib.util +import pathlib +import os +import subprocess +import sys +import re +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] +SPEC = importlib.util.spec_from_file_location( + "summary", ROOT / ".github/scripts/summarize-native-caches.py") +summary = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(summary) + + +class NativeCachePolicyTests(unittest.TestCase): + def test_compiler_only_command(self): + result = subprocess.run( + [sys.executable, str(SPEC.origin), "--compiler"], + env={**os.environ, "CACHE_STEPS": "{}", "COLD_BUILD": "true"}, + capture_output=True, text=True, check=True) + self.assertIn("| Compiler objects | bypassed (cold build) | not run |", result.stdout) + + def test_unknown_dependency_is_rejected(self): + result = subprocess.run( + [sys.executable, str(SPEC.origin), "unknown"], + env={**os.environ, "CACHE_STEPS": "{}"}, + capture_output=True, text=True) + self.assertEqual(result.returncode, 2) + self.assertIn("unknown dependency: unknown", result.stderr) + + def test_restore_outcomes(self): + cases = [ + ({}, "not run"), + ({"outcome": "failure"}, "failure"), + ({"outcome": "cancelled"}, "cancelled"), + ({"outcome": "success", "outputs": {"cache-hit": "true"}}, "exact hit"), + ({"outcome": "success", "outputs": {"cache-hit": "false", "cache-matched-key": "older"}}, "fallback restore"), + ({"outcome": "success", "outputs": {"cache-hit": ""}}, "miss"), + ] + for step, expected in cases: + with self.subTest(expected=expected): + self.assertEqual(summary.restore_status(step, False), expected) + self.assertEqual(summary.restore_status({}, True), "bypassed (cold build)") + + def test_failed_rebuild_and_forced_recompilation_are_distinct(self): + report = summary.render({ + "qt-cache": {"outcome": "success"}, + "qt-build": {"outcome": "failure"}, + "ccache": {"outcome": "success", "outputs": {"cache-hit": "true"}}, + "compile": {"outcome": "skipped"}, + }, ["qt"], recache=True, compiler=True) + self.assertIn("| Qt | miss | failure |", report) + self.assertIn("| Compiler objects | exact hit | not run; forced recompilation requested |", report) + + def test_cold_build_blocks_every_workflow_cache_restore_and_save(self): + for platform in ["macos", "windows"]: + text = (ROOT / f".github/workflows/build-{platform}.yml").read_text() + self.assertEqual(len(re.findall(r"^ cold_build:", text, re.M)), 2) + for step in re.split(r"^ - ", text, flags=re.M)[1:]: + if "uses: actions/cache/" in step: + self.assertIn("!inputs.cold_build", step) + self.assertIn("CCACHE_DIR=$(mktemp -d", text) + self.assertIn("id: compile", text) + windows = (ROOT / ".github/workflows/build-windows.yml").read_text() + self.assertIn("cache: ${{ !inputs.cold_build }}", windows) + self.assertIn("cold_build: ${{ inputs.cold_build }}", windows) + action = (ROOT / ".github/actions/build-windows-deps/action.yml").read_text() + for step in re.split(r"^ - ", action, flags=re.M)[1:]: + if "uses: actions/cache/" in step: + self.assertIn("inputs.cold_build != 'true'", step) + + def test_summaries_run_after_failures(self): + paths = [".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml", + ".github/actions/warm-macos-deps/action.yml", ".github/actions/build-windows-deps/action.yml"] + for path in paths: + text = (ROOT / path).read_text() + for step in re.split(r"^\s+- name: ", text, flags=re.M)[1:]: + if step.startswith("Summarize"): + self.assertIn("if: always()", step) + warmer = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() + self.assertIn(" summary:\n if: always()", warmer) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_package_cli_tools.py b/.github/scripts/tests/test_package_cli_tools.py new file mode 100644 index 00000000..45e94497 --- /dev/null +++ b/.github/scripts/tests/test_package_cli_tools.py @@ -0,0 +1,745 @@ +import os +import pathlib +import subprocess +import tarfile +import tempfile +import unittest + + +ROOT = pathlib.Path(__file__).resolve().parents[3] +SCRIPT = ROOT / ".github/scripts/package-cli-tools.sh" +SMOKE = ROOT / ".github/scripts/smoke-release-tarballs.sh" +BUILD_MACOS = ROOT / ".github/workflows/build-macos.yml" + + +OTOOL_STUB = """#!/bin/sh +case "$1" in -L) kind=refs ;; -l) kind=load ;; -D) kind=id ;; *) exit 2 ;; esac +echo "$2:" +fixture="$STUB_FIXTURES/otool.$kind.$(basename "$2")" +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +OBJDUMP_STUB = """#!/bin/sh +fixture="$STUB_FIXTURES/objdump.$(basename "$2")" +[ -f "$fixture.fail" ] && exit 1 +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +READELF_STUB = """#!/bin/sh +case "$1" in -dW) kind=d ;; -VW) kind=V ;; *) exit 2 ;; esac +fixture="$STUB_FIXTURES/readelf.$kind.$(basename "$2")" +if [ -f "$fixture" ]; then cat "$fixture"; fi +""" + +# Copies each --executable into the AppDir, and into usr/lib the libraries +# $STUB_FIXTURES/deploys.<program> names, as linuxdeploy deploys them. +LINUXDEPLOY_STUB = """#!/bin/sh +printf '%s\\n' "$*" "token=${GITHUB_TOKEN-unset}" "extract=${APPIMAGE_EXTRACT_AND_RUN-unset}" >> "$STUB_FIXTURES/linuxdeploy.log" +[ -f "$STUB_FIXTURES/linuxdeploy.fail" ] && exit 1 +appdir="" +while [ "$#" -gt 0 ]; do + case "$1" in + --appdir) appdir="$2"; shift 2 ;; + --executable) + mkdir -p "$appdir/usr/bin" "$appdir/usr/lib" + [ -f "$STUB_FIXTURES/linuxdeploy.skip-programs" ] || cp "$2" "$appdir/usr/bin/" + while read -r library; do cp "$STUB_FIXTURES/appdir-lib/$library" "$appdir/usr/lib/"; done < "$STUB_FIXTURES/deploys.$(basename "$2")" + shift 2 ;; + *) shift ;; + esac +done +mkdir -p "$appdir/usr/share/doc/libqt5core5t64" +echo copyright > "$appdir/usr/share/doc/libqt5core5t64/copyright" +""" + + +def needed(*libraries, runpath=None): + lines = [f" 0x0000000000000001 (NEEDED) Shared library: [{library}]" for library in libraries] + if runpath is not None: + lines.append(f" 0x000000000000001d (RUNPATH) Library runpath: [{runpath}]") + return lines + + +def versions(*names): + return [ + "Version symbols section '.gnu.version' contains 9 entries:", + " 000: 0 (*local*) 2 (GLIBC_9.99)", + "Version needs section '.gnu.version_r' contains 1 entry:", + " 000000: Version: 1 File: libc.so.6 Cnt: 1", + *(f" 0x0010: Name: {name} Flags: none Version: 2" for name in names), + ] + + +def rpath(path): + return ["Load command 12", " cmd LC_RPATH", " cmdsize 32", f" path {path} (offset 12)"] + + +def minos(version): + return ["Load command 9", " cmd LC_BUILD_VERSION", " cmdsize 32", " platform 1", f" minos {version}"] + + +def version_min_macosx(version): + return ["Load command 9", " cmd LC_VERSION_MIN_MACOSX", " cmdsize 16", f" version {version}", " sdk 15.0"] + + +MINOS = minos("11.0") + + +class PackageCliToolsTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) + self.bin = self.root / "bin" + self.fixtures = self.root / "fixtures" + self.source = self.root / "build" + self.out = self.root / "out" + for directory in (self.bin, self.fixtures, self.source): + directory.mkdir() + for name, body in ( + ("otool", OTOOL_STUB), ("objdump", OBJDUMP_STUB), ("readelf", READELF_STUB), + ("linuxdeploy", LINUXDEPLOY_STUB), + ): + (self.bin / name).write_text(body, encoding="utf-8") + (self.bin / name).chmod(0o755) + + def fixture(self, name, lines): + (self.fixtures / name).write_text("".join(f"{line}\n" for line in lines), encoding="utf-8") + + def files(self, directory, names): + directory.mkdir(parents=True, exist_ok=True) + for name in names: + (directory / name).write_text(name, encoding="utf-8") + + def package(self, platform, groups, *arguments, newline="\n"): + groups_file = self.root / "release-tarballs.txt" + groups_file.write_bytes(("# comment" + newline + newline.join(groups) + newline).encode()) + return subprocess.run( + [ + "bash", str(SCRIPT), "--platform", platform, "--version", "9.9.9", "--arch", "x86_64", + "--groups", str(groups_file), "--source", str(self.source), "--out", str(self.out), *arguments, + ], + env=dict( + os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root), + STUB_FIXTURES=str(self.fixtures), GITHUB_TOKEN="secret", + ), + text=True, + capture_output=True, + check=False, + ) + + def members(self, name): + with tarfile.open(self.out / f"{name}.tar.gz") as archive: + tops = {member.name.split("/", 1)[0] for member in archive.getmembers()} + self.assertEqual(tops, {name}) + return sorted(member.name.split("/", 1)[1] for member in archive.getmembers() if member.isfile()) + + def text(self, name, member): + with tarfile.open(self.out / f"{name}.tar.gz") as archive: + return archive.extractfile(f"{name}/{member}").read().decode() + + def assert_failed(self, result, *messages): + self.assertEqual(result.returncode, 1, result.stderr) + for message in messages: + self.assertIn(message, result.stderr) + self.assertFalse(self.out.exists() and any(self.out.iterdir())) + + # macOS: the CLI assets directory as deploy-macos-cli-tools.sh leaves it. + # Fixture names differ by more than case: macOS file systems ignore it. + def macos_assets(self): + self.files(self.source, ["jt9", "jt9stream", "wsprd", "encode77"]) + self.files(self.source / "lib", ["QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib", "libmystery.dylib"]) + for program in ("jt9", "jt9stream", "encode77"): + self.fixture(f"otool.load.{program}", rpath("@loader_path/lib") + MINOS) + self.fixture("otool.load.wsprd", rpath("@loader_path") + rpath("@loader_path/lib") + MINOS) + for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", MINOS) + self.fixture(f"otool.id.{library}", [f"@rpath/{library}"]) + self.fixture("otool.id.libfftw3f.3.dylib", ["/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib"]) + self.fixture("otool.refs.jt9", [ + "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0, current version 9.10.0)", + "\t@rpath/QtCore (compatibility version 5.15.0, current version 5.15.18)", + "\t/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1900.180.0)", + ]) + self.fixture("otool.refs.jt9stream", ["\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)"]) + self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + self.fixture("otool.refs.encode77", ["\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0)"]) + self.fixture("otool.refs.QtCore", [ + "\t@rpath/QtCore (compatibility version 5.15.0)", + "\t/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0)", + ]) + self.fixture("otool.refs.libfftw3f_threads.3.dylib", [ + "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)", + "\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)", + ]) + self.fixture("otool.refs.libfftw3f.3.dylib", ["\t/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + + MACOS_GROUPS = ["jt9 jt9", "jt9stream jt9stream", "wsprd wsprd", "utilities encode77"] + + def test_macos_tarballs_hold_each_group_and_the_dylibs_it_reaches(self): + self.macos_assets() + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + documents = ["COPYING", "README.txt", "THIRD-PARTY.txt"] + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-jt9"), + sorted([*documents, "jt9", "lib/QtCore", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]), + ) + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream"), + sorted([*documents, "jt9stream", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]), + ) + self.assertEqual( + self.members("wsjtx-9.9.9-x86_64-macOS-wsprd"), sorted([*documents, "wsprd", "lib/libfftw3f.3.dylib"]) + ) + self.assertEqual(self.members("wsjtx-9.9.9-x86_64-macOS-utilities"), sorted([*documents, "encode77"])) + readme = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt") + self.assertIn("They require macOS 11.0 or later.", readme) + self.assertIn("xattr -d com.apple.quarantine", readme) + self.assertIn("wsjtx-9.9.9-src.tar.gz", readme) + self.assertIn("GNU General Public License version 3 (COPYING)", readme) + self.assertIn("are Copyright (C) 2001-", readme) + self.assertIn("Joseph Taylor, K1JT;", readme) + self.assertTrue(readme.rstrip().endswith("other members of the WSJT Development Group."), readme) + self.assertNotIn("_{prog}_", readme) + self.assertIn("jt9stream, in its own tarball, is the same decoder", readme) + self.assertNotIn("mingw-w64", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt")) + notices = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt") + self.assertIn("Files: QtCore", notices) + self.assertIn("Files: libfftw3f.3.dylib libfftw3f_threads.3.dylib", notices) + utilities = self.text("wsjtx-9.9.9-x86_64-macOS-utilities", "THIRD-PARTY.txt") + self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", utilities) + self.assertIn(" Linked statically into the programs\n", utilities) + self.assertNotIn("Files:", utilities) + self.assertEqual( + self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "COPYING"), (ROOT / "COPYING").read_text(encoding="utf-8") + ) + + def test_macos_unresolved_rpath_reference_fails_naming_it(self): + self.macos_assets() + with (self.fixtures / "otool.refs.wsprd").open("a", encoding="utf-8") as stream: + stream.write("\t@rpath/libmissing.dylib (compatibility version 1.0.0)\n") + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libmissing.dylib(wsprd)") + + def test_macos_build_tree_reference_fails(self): + self.macos_assets() + self.fixture("otool.refs.encode77", ["\t/opt/homebrew/lib/libgfortran.5.dylib (compatibility version 6.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "/opt/homebrew/lib/libgfortran.5.dylib(encode77)") + + def test_macos_absolute_rpath_fails(self): + self.macos_assets() + self.fixture("otool.load.libfftw3f.3.dylib", rpath("/Users/runner/work/fftw-prefix/lib") + MINOS) + self.assert_failed( + self.package("macos", self.MACOS_GROUPS), + "lib/libfftw3f.3.dylib has an absolute LC_RPATH: /Users/runner/work/fftw-prefix/lib", + ) + + def test_macos_program_with_absolute_rpath_fails(self): + self.macos_assets() + self.fixture("otool.load.wsprd", rpath("@loader_path/lib") + rpath("/opt/homebrew/lib") + MINOS) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "wsprd has an absolute LC_RPATH: /opt/homebrew/lib") + + def test_macos_library_missing_from_notices_table_fails(self): + self.macos_assets() + self.fixture("otool.refs.encode77", ["\t@rpath/libmystery.dylib (compatibility version 1.0.0)"]) + self.assert_failed( + self.package("macos", ["utilities encode77", "jt9 jt9"]), + "bundled libraries missing from third-party-libraries.tsv: libmystery.dylib", + ) + + def test_macos_dylib_outside_lib_fails(self): + self.macos_assets() + self.files(self.source, ["libfftw3f_top.dylib"]) + self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f_top.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libfftw3f_top.dylib(wsprd)") + + def test_macos_rpath_references_resolve_through_their_own_program(self): + self.macos_assets() + self.files(self.source, ["wsprcode"]) + self.files(self.source / "lib/extra", ["libfftw3f_extra.dylib"]) + self.fixture("otool.load.wsprcode", rpath("@executable_path/lib/extra") + rpath("@loader_path/lib") + MINOS) + self.fixture("otool.load.libfftw3f_extra.dylib", MINOS) + self.fixture("otool.refs.wsprcode", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"]) + result = self.package("macos", ["utilities wsprcode"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("lib/extra/libfftw3f_extra.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-utilities")) + self.out.joinpath("wsjtx-9.9.9-x86_64-macOS-utilities.tar.gz").unlink() + self.fixture("otool.refs.encode77", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", ["utilities wsprcode encode77"]), "@rpath/libfftw3f_extra.dylib(encode77)") + + def test_macos_loader_path_references_resolve_beside_the_dylib(self): + self.macos_assets() + self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/libfftw3f.3.dylib (compatibility version 9.0.0)"]) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("lib/libfftw3f.3.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream")) + + def test_macos_reference_escaping_the_source_fails(self): + self.macos_assets() + self.files(self.root, ["outside.dylib"]) + self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/../../outside.dylib (compatibility version 1.0.0)"]) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@loader_path/../../outside.dylib(lib/libfftw3f_threads.3.dylib)") + + def test_macos_program_rpath_outside_its_directory_fails(self): + self.macos_assets() + self.fixture("otool.load.jt9", rpath("@loader_path/../lib") + MINOS) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "jt9 has an LC_RPATH outside its directory: @loader_path/../lib") + + def test_macos_floor_is_the_highest_minos(self): + self.macos_assets() + self.fixture("otool.load.QtCore", minos("13.0")) + self.fixture("otool.load.libfftw3f.3.dylib", minos("9.5")) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("They require macOS 13.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt")) + self.assertIn("They require macOS 11.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "README.txt")) + + def test_macos_legacy_minimum_version_is_recorded_for_every_tarball(self): + self.macos_assets() + source_version = ["Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0"] + for program in ("jt9", "jt9stream", "wsprd", "encode77"): + self.fixture( + f"otool.load.{program}", + source_version + rpath("@loader_path/lib") + version_min_macosx("10.13") + source_version, + ) + for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", version_min_macosx("10.13") + source_version) + result = self.package("macos", self.MACOS_GROUPS) + self.assertEqual(result.returncode, 0, result.stderr) + for group in ("jt9", "jt9stream", "wsprd", "utilities"): + self.assertIn( + "They require macOS 10.13 or later.", + self.text(f"wsjtx-9.9.9-x86_64-macOS-{group}", "README.txt"), + ) + + def test_macos_floor_is_the_highest_across_both_version_commands(self): + self.macos_assets() + for modern, expected in (("10.12", "10.13"), ("13.0", "13.0")): + with self.subTest(modern=modern): + self.fixture("otool.load.jt9", rpath("@loader_path/lib") + minos(modern)) + self.fixture("otool.load.QtCore", version_min_macosx("10.13")) + for library in ("libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"): + self.fixture(f"otool.load.{library}", minos(modern)) + result = self.package("macos", ["jt9 jt9"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn( + f"They require macOS {expected} or later.", + self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt"), + ) + + def test_macos_minimum_does_not_read_fields_from_other_load_commands(self): + self.macos_assets() + for command in ("LC_BUILD_VERSION", "LC_VERSION_MIN_MACOSX"): + with self.subTest(command=command): + self.fixture("otool.load.encode77", [ + "Load command 9", f" cmd {command}", " cmdsize 16", + "Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0", + ]) + self.assert_failed( + self.package("macos", ["utilities encode77"]), + "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities", + ) + + def test_macos_without_a_minimum_version_fails(self): + self.macos_assets() + self.fixture("otool.load.encode77", rpath("@loader_path/lib")) + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities") + + def test_tarball_named_twice_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["wsprd wsprd", "jt9 jt9", "wsprd jt9stream"]), "release tarball wsprd is named twice") + + def test_tarball_without_readme_description_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["extra encode77"]), "no README description for release tarball extra") + + def test_missing_program_fails_naming_it(self): + self.macos_assets() + (self.source / "jt9stream").unlink() + self.assert_failed(self.package("macos", self.MACOS_GROUPS), "missing under", "jt9stream") + + def test_group_without_programs_fails(self): + self.macos_assets() + self.assert_failed(self.package("macos", ["jt9 jt9", "utilities"]), "release tarball utilities names no programs") + + # Windows + def windows_build(self, failing=()): + self.files(self.source, ["jt9.exe", "encode77.exe", "wsjtx.exe"]) + self.files(self.root / "dlls", ["libfftw3f-3.dll", "LIBGFORTRAN-5.DLL", "unused.dll"]) + self.files(self.root / "system", ["KERNEL32.dll", "msvcrt.dll"]) + self.fixture("objdump.jt9.exe", ["\tDLL Name: libfftw3f-3.dll", "\tDLL Name: KERNEL32.dll"]) + self.fixture("objdump.libfftw3f-3.dll", ["\tDLL Name: libgfortran-5.dll"]) + self.fixture("objdump.LIBGFORTRAN-5.DLL", ["\tDLL Name: KERNEL32.dll"]) + self.fixture("objdump.encode77.exe", ["\tDLL Name: msvcrt.dll"]) + for name in failing: + self.fixture(f"objdump.{name}.fail", []) + return self.package( + "windows", ["jt9 jt9", "utilities encode77"], + "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"), newline="\r\n", + ) + + def test_windows_tarballs_hold_each_group_and_its_dll_closure(self): + result = self.windows_build() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + self.members("wsjtx-9.9.9-windows-x86_64-jt9"), + ["COPYING", "LIBGFORTRAN-5.DLL", "README.txt", "THIRD-PARTY.txt", "jt9.exe", "libfftw3f-3.dll"], + ) + self.assertEqual( + self.members("wsjtx-9.9.9-windows-x86_64-utilities"), ["COPYING", "README.txt", "THIRD-PARTY.txt", "encode77.exe"] + ) + self.assertIn("no Authenticode signature", self.text("wsjtx-9.9.9-windows-x86_64-jt9", "README.txt")) + notices = self.text("wsjtx-9.9.9-windows-x86_64-jt9", "THIRD-PARTY.txt") + self.assertIn("FFTW 3\n License: GPL-2.0-or-later\n", notices) + self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", notices) + self.assertIn(" Files: LIBGFORTRAN-5.DLL\n", notices) + self.assertIn("mingw-w64 runtime\n", notices) + self.assertEqual(notices.count(" Linked statically into the programs"), 1) + self.assertNotIn("libquadmath", notices) + + def test_windows_import_outside_dll_and_system_dirs_fails(self): + (self.root / "system").mkdir() + self.fixture("objdump.encode77.exe", ["\tDLL Name: libmissing.dll"]) + self.files(self.source, ["jt9.exe", "encode77.exe"]) + self.files(self.root / "dlls", []) + self.fixture("objdump.jt9.exe", []) + result = self.package( + "windows", ["jt9 jt9", "utilities encode77"], + "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"), + ) + self.assert_failed(result, "libmissing.dll(encode77.exe)") + + def test_windows_objdump_failure_fails_naming_the_file(self): + self.assert_failed(self.windows_build(failing=["libfftw3f-3.dll"]), "objdump failed on libfftw3f-3.dll") + + # Linux: linuxdeploy and readelf are stubbed; the excludelist is the committed one. + def linux_build(self): + self.files(self.source, ["jt9", "jt9stream", "wsjtx"]) + self.files(self.fixtures / "appdir-lib", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"]) + self.fixture("deploys.jt9", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"]) + self.fixture("deploys.jt9stream", ["libgfortran.so.5"]) + self.fixture("readelf.d.jt9", needed("libQt5Core.so.5", "libgfortran.so.5", "libc.so.6", runpath="$ORIGIN/../lib")) + self.fixture("readelf.V.jt9", versions("GLIBC_2.34", "GLIBC_2.2.5")) + self.fixture("readelf.d.jt9stream", needed("libgfortran.so.5", "libm.so.6", runpath="${ORIGIN}/../lib")) + self.fixture("readelf.V.jt9stream", versions("GLIBC_2.29")) + self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74", "libstdc++.so.6", runpath="$ORIGIN")) + self.fixture("readelf.V.libQt5Core.so.5", versions("GLIBC_2.38", "GLIBCXX_3.4.9", "GLIBCXX_3.4.30", "CXXABI_1.3.13")) + self.fixture("readelf.d.libicuuc.so.74", needed("libstdc++.so.6", runpath="${ORIGIN}")) + self.fixture("readelf.d.libgfortran.so.5", needed("libc.so.6", "ld-linux-aarch64.so.1", runpath="$ORIGIN")) + + def linux_package(self, groups=("jt9 jt9", "jt9stream jt9stream")): + return self.package("linux", list(groups), "--linuxdeploy", str(self.bin / "linuxdeploy")) + + def test_linux_tarballs_bundle_deployed_libraries_and_state_host_requirements(self): + self.linux_build() + result = self.linux_package() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + self.members("wsjtx-9.9.9-linux-x86_64-jt9"), + [ + "COPYING", "README.txt", "THIRD-PARTY.txt", "bin/jt9", "lib/libQt5Core.so.5", "lib/libgfortran.so.5", + "lib/libicuuc.so.74", "share/doc/libqt5core5t64/copyright", + ], + ) + readme = self.text("wsjtx-9.9.9-linux-x86_64-jt9", "README.txt") + self.assertIn("glibc 2.38 or later, libstdc++ with GLIBCXX_3.4.30 or later", readme) + self.assertIn("these libraries: ld-linux-aarch64.so.1 libc.so.6 libstdc++.so.6.", readme) + self.assertIn("ICU 74\n", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt")) + self.assertIn("without it", readme) + self.assertIn("glibc 2.29 or later, and these libraries", self.text("wsjtx-9.9.9-linux-x86_64-jt9stream", "README.txt")) + self.assertIn("share/doc/", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt")) + log = (self.fixtures / "linuxdeploy.log").read_text(encoding="utf-8").splitlines() + self.assertTrue(log[0].startswith("--appimage-extract-and-run --appdir "), log[0]) + self.assertTrue(log[0].endswith(f"--executable {self.source}/jt9"), log[0]) + self.assertEqual(log[1:3], ["token=unset", "extract=1"]) + + def test_linux_library_neither_bundled_nor_excluded_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9stream", needed("libfftw3f.so.3", runpath="$ORIGIN/../lib")) + self.assert_failed(self.linux_package(), "libfftw3f.so.3(bin/jt9stream)") + + def test_linux_runpath_is_not_inherited_by_bundled_libraries(self): + self.linux_build() + self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74")) + self.assert_failed(self.linux_package(), "libicuuc.so.74(lib/libQt5Core.so.5)") + + def test_linux_runpath_outside_origin_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:/work/wsjtx-build")) + self.assert_failed(self.linux_package(), "bin/jt9 has a RUNPATH entry not relative to $ORIGIN: /work/wsjtx-build") + + def test_linux_empty_runpath_entry_fails(self): + self.linux_build() + self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:")) + self.assert_failed(self.linux_package(), "bin/jt9 has an empty RUNPATH entry: $ORIGIN/../lib:") + + def test_linux_program_linuxdeploy_did_not_deploy_fails(self): + self.linux_build() + self.fixture("linuxdeploy.skip-programs", []) + self.assert_failed(self.linux_package(), "linuxdeploy did not deploy jt9") + + def test_linux_linuxdeploy_failure_fails(self): + self.linux_build() + self.fixture("linuxdeploy.fail", []) + self.assert_failed(self.linux_package(), "linuxdeploy failed for wsjtx-9.9.9-linux-x86_64-jt9") + + def test_linux_requires_linuxdeploy(self): + self.linux_build() + result = self.package("linux", ["jt9 jt9"]) + self.assertEqual(result.returncode, 2) + self.assertIn("--linuxdeploy is required", result.stderr) + + +class LinuxdeployExcludelistTests(unittest.TestCase): + def test_excludelist_belongs_to_the_pinned_linuxdeploy(self): + excludelist = (ROOT / ".github/scripts/linuxdeploy-excludelist.txt").read_text(encoding="utf-8") + tag = excludelist.split("compiled into linuxdeploy ", 1)[1].split(",", 1)[0] + self.assertIn( + f'LINUXDEPLOY_TAG: "{tag}"', (ROOT / ".github/actions/build-linux-payload/action.yml").read_text(encoding="utf-8") + ) + self.assertIn(f"LINUXDEPLOY_TAG={tag}\n", (ROOT / ".github/scripts/package-linux-armhf.sh").read_text(encoding="utf-8")) + names = [line for line in excludelist.splitlines() if line and not line.startswith("#")] + self.assertEqual(len(names), 52) + for name in ("libc.so.6", "libstdc++.so.6", "libgcc_s.so.1", "libz.so.1", "libm.so.6"): + self.assertIn(name, names) + for name in ("libgfortran.so.5", "libgomp.so.1", "libQt5Core.so.5", "libfftw3f.so.3"): + self.assertNotIn(name, names) + + +class SmokeReleaseTarballsTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) + self.dir = self.root / "tarballs" + self.bin = self.root / "bin" + self.log = self.root / "smoke.log" + self.dir.mkdir() + self.bin.mkdir() + (self.bin / "timeout").write_text( + f'#!/bin/sh\necho "$1" >> "{self.root}/timeout.log"\nshift\nexec "$@"\n', encoding="utf-8" + ) + (self.bin / "timeout").chmod(0o755) + + def tarball(self, group, programs, layout="bin/", failing=(), libraries=(), target="linux-x86_64", top=None): + name = f"wsjtx-9.9.9-{target}-{group}" + tree = self.root / "trees" / name + for program in programs: + path = tree / f"{layout}{program}" + path.parent.mkdir(parents=True, exist_ok=True) + status = 3 if program in failing else 0 + path.write_text( + f'#!/bin/sh\necho "{program} $* lib=${{LD_LIBRARY_PATH-unset}} cwd=$(pwd)" >> "{self.log}"\nexit {status}\n', + encoding="utf-8", + ) + path.chmod(0o755) + for library in libraries: + (tree / "lib").mkdir(parents=True, exist_ok=True) + (tree / "lib" / library).write_text(library, encoding="utf-8") + with tarfile.open(self.dir / f"{name}.tar.gz", "w:gz") as archive: + archive.add(tree, arcname=top or name) + + def smoke(self, groups, *arguments, platform="linux", target="linux-x86_64", script=SMOKE): + groups_file = self.root / "release-tarballs.txt" + groups_file.write_text("# comment\n" + "".join(f"{line}\n" for line in groups), encoding="utf-8") + return subprocess.run( + [ + "bash", str(script), "--platform", platform, "--version", "9.9.9", "--target", target, + "--groups", str(groups_file), "--dir", str(self.dir), *arguments, + ], + env=dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root), LD_LIBRARY_PATH="/bogus"), + text=True, capture_output=True, check=False, + ) + + def test_every_program_runs_from_its_own_tarball_without_library_path(self): + self.tarball("jt9", ["jt9"]) + self.tarball("wsprd", ["wsprd"]) + self.tarball("utilities", ["encode77", "ft4sim"]) + result = self.smoke(["jt9 jt9", "wsprd wsprd", "utilities encode77 ft4sim"]) + self.assertEqual(result.returncode, 0, result.stderr) + lines = self.log.read_text(encoding="utf-8").splitlines() + self.assertEqual([line.split(" ", 1)[0] for line in lines], ["jt9", "wsprd", "encode77", "ft4sim"]) + self.assertTrue(lines[0].startswith("jt9 --help lib=unset"), lines[0]) + self.assertRegex(lines[1], r"^wsprd -a \S+/run-wsprd \S+/samples/WSPR/150426_0918\.wav lib=unset cwd=\S+/run-wsprd$") + self.assertTrue(lines[2].startswith("encode77 CQ K1ABC FN42 lib=unset"), lines[2]) + self.assertTrue(lines[3].startswith("ft4sim lib=unset"), lines[3]) + self.assertEqual((self.root / "timeout.log").read_text(encoding="utf-8").split(), ["120"] * 4) + + def scripts_copy(self): + scripts = self.root / "repo/.github/scripts" + scripts.mkdir(parents=True) + (scripts / SMOKE.name).write_bytes(SMOKE.read_bytes()) + (scripts / "smoke-launch-windows.sh").write_text( + f'#!/bin/sh\necho "launch $(basename "$1") cwd=$(pwd) args=$*" >> "{self.log}"\n' + 'case "$1" in *ft4sim.exe) exit 1 ;; esac\n', + encoding="utf-8", + ) + (scripts / "smoke-launch-windows.sh").chmod(0o755) + sample = self.root / "repo/samples/WSPR/150426_0918.wav" + sample.parent.mkdir(parents=True) + sample.write_bytes(b"RIFF") + return scripts / SMOKE.name + + def test_windows_programs_launch_through_the_clean_path_launcher(self): + script = self.scripts_copy() + self.tarball("jt9", ["jt9.exe"], layout="", target="windows-x86_64") + self.tarball("utilities", ["encode77.exe"], layout="", target="windows-x86_64") + result = self.smoke(["jt9 jt9", "utilities encode77"], platform="windows", target="windows-x86_64", script=script) + self.assertEqual(result.returncode, 0, result.stderr) + lines = self.log.read_text(encoding="utf-8").splitlines() + self.assertRegex(lines[0], r"^launch jt9\.exe cwd=\S+/run-jt9 args=\S+/wsjtx-9\.9\.9-windows-x86_64-jt9/jt9\.exe --help$") + self.assertRegex(lines[1], r"^launch encode77\.exe cwd=\S+/run-encode77 args=\S+ CQ K1ABC FN42$") + + def test_windows_launch_failure_fails(self): + script = self.scripts_copy() + self.tarball("utilities", ["ft4sim.exe"], layout="", target="windows-x86_64") + result = self.smoke(["utilities ft4sim"], platform="windows", target="windows-x86_64", script=script) + self.assertEqual(result.returncode, 1) + self.assertIn("ft4sim from wsjtx-9.9.9-windows-x86_64-utilities failed", result.stderr) + + def test_macos_programs_run_from_the_top_of_their_tarball(self): + script = self.scripts_copy() + self.tarball("wsprd", ["wsprd"], layout="", target="arm64-macOS") + result = self.smoke(["wsprd wsprd"], platform="macos", target="arm64-macOS", script=script) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertRegex(self.log.read_text(encoding="utf-8"), r"wsprd -a \S+/run-wsprd \S+/repo/\.github/scripts/\.\./\.\./samples/WSPR/150426_0918\.wav ") + self.assertFalse((self.root / "timeout.log").exists()) + + def test_tarball_with_another_top_directory_fails(self): + self.tarball("jt9", ["jt9"], top="jt9") + result = self.smoke(["jt9 jt9"]) + self.assertEqual(result.returncode, 1) + self.assertIn("wsjtx-9.9.9-linux-x86_64-jt9.tar.gz does not extract to wsjtx-9.9.9-linux-x86_64-jt9/", result.stderr) + + def test_failing_program_fails_naming_it(self): + self.tarball("utilities", ["encode77", "ft4sim"], failing=["ft4sim"]) + result = self.smoke(["utilities encode77 ft4sim"]) + self.assertEqual(result.returncode, 1) + self.assertIn("ft4sim from wsjtx-9.9.9-linux-x86_64-utilities failed", result.stderr) + + def test_program_missing_from_its_tarball_fails(self): + self.tarball("jt9", ["jt9stream"]) + result = self.smoke(["jt9 jt9"]) + self.assertEqual(result.returncode, 1) + self.assertIn("jt9 is not in wsjtx-9.9.9-linux-x86_64-jt9", result.stderr) + + def test_program_without_a_smoke_invocation_fails(self): + self.tarball("extra", ["newtool"]) + result = self.smoke(["extra newtool"]) + self.assertEqual(result.returncode, 1) + self.assertIn("no smoke invocation for newtool", result.stderr) + + def ldd_stub(self, resolution, status=0): + (self.bin / "ldd").write_text( + "#!/bin/sh\n" + f'[ "${{LD_LIBRARY_PATH-unset}}" = unset ] || exit 9\n' + 'tree=$(dirname "$(dirname "$1")")\n' + "printf '\\tlinux-vdso.so.1 (0x1)\\n'\n" + f"printf '\\tlibQt5Core.so.5 => %s (0x2)\\n' \"{resolution}\"\n" + "printf '\\tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x3)\\n'\n" + f"exit {status}\n", + encoding="utf-8", + ) + (self.bin / "ldd").chmod(0o755) + + def test_ldd_reports_a_library_not_found(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("not found") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("libQt5Core.so.5(bin/jt9): not found", result.stderr) + + def test_ldd_failure_fails(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("$tree/lib/libQt5Core.so.5", status=1) + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("ldd failed on bin/jt9", result.stderr) + + def test_ldd_accepts_a_library_without_dependencies(self): + # ICU's data library needs nothing; ldd says so and exits 0. + self.tarball("jt9", ["jt9"], libraries=["libicudata.so.74"]) + (self.bin / "ldd").write_text("#!/bin/sh\necho '\tstatically linked'\n", encoding="utf-8") + (self.bin / "ldd").chmod(0o755) + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_ldd_accepts_bundled_copies_through_origin(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("$tree/bin/../lib/libQt5Core.so.5") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_ldd_rejects_a_system_copy_of_a_bundled_library(self): + self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"]) + self.ldd_stub("/usr/lib/x86_64-linux-gnu/libQt5Core.so.5") + result = self.smoke(["jt9 jt9"], "--ldd") + self.assertEqual(result.returncode, 1) + self.assertIn("libQt5Core.so.5(bin/jt9): /usr/lib/x86_64-linux-gnu/libQt5Core.so.5", result.stderr) + + +class MacosPostinstallTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) / "volume" + self.scripts = pathlib.Path(temporary.name) / "scripts" + self.scripts.mkdir() + lines = BUILD_MACOS.read_text(encoding="utf-8").splitlines() + start = next(i for i, line in enumerate(lines) if line.strip() == 'cat > "${SCRIPTS}/postinstall" << \'SCRIPT\'') + indent = len(lines[start]) - len(lines[start].lstrip()) + end = next(i for i in range(start + 1, len(lines)) if lines[i] == " " * indent + "SCRIPT") + body = [line[indent:] for line in lines[start + 1:end]] + self.assertFalse(any("launchctl" in line or "sysctl" in line for line in body)) + self.assertTrue(any(line.startswith('root="${3%/}"') for line in body)) + for line in body: + for prefix in line.split("/usr/local")[:-1]: + self.assertTrue(prefix.endswith(("$root", '"$root"')), line) + self.postinstall = self.scripts / "postinstall" + self.postinstall.write_text("\n".join(body) + "\n", encoding="utf-8") + (self.scripts / "installed-cli-tools.txt").write_text("jt9\nwsprd\n", encoding="utf-8") + + def executable(self, path): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("#!/bin/sh\n", encoding="utf-8") + path.chmod(0o755) + + def run_postinstall(self): + return subprocess.run( + ["bash", str(self.postinstall), "pkg", "/", str(self.root), "/"], + stdin=subprocess.DEVNULL, text=True, capture_output=True, check=False, + ) + + def test_upgrade_removes_unshipped_programs_and_their_links(self): + programs = self.root / "usr/local/wsjtx" + links = self.root / "usr/local/bin" + for name in ("jt9", "wsprd", "wsprcode"): + self.executable(programs / name) + links.mkdir(parents=True) + (links / "wsprcode").symlink_to(programs / "wsprcode") + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(sorted(path.name for path in programs.iterdir()), ["jt9", "wsprd"]) + self.assertEqual(sorted(path.name for path in links.iterdir()), ["jt9", "wsprd"]) + + def test_symlinked_program_directory_is_not_cleaned(self): + elsewhere = self.root / "Users/someone/bin" + for name in ("jt9", "backup.sh"): + self.executable(elsewhere / name) + (self.root / "usr/local").mkdir(parents=True) + (self.root / "usr/local/wsjtx").symlink_to(elsewhere) + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((elsewhere / "backup.sh").exists()) + + def test_trailing_non_executable_entry_does_not_fail_the_install(self): + programs = self.root / "usr/local/wsjtx" + self.executable(programs / "jt9") + (programs / "zz-notes.txt").write_text("notes", encoding="utf-8") + result = self.run_postinstall() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((self.root / "usr/local/bin/jt9").is_symlink()) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_linux_images.py b/.github/scripts/tests/test_release_linux_images.py new file mode 100644 index 00000000..10a3fd0f --- /dev/null +++ b/.github/scripts/tests/test_release_linux_images.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Release dependency selection and registry-copy regression checks.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location("release_linux_images", Path(__file__).parents[1] / "release-linux-images.py") +images = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(images) +GENERATION = "validated-build-20260925-123-1" +DIGEST = "sha256:" + "a" * 64 +RECIPE = "b" * 64 + + +def selection(): + return {"schema": 1, "generation": GENERATION, "images": { + key: {"reference": f"{images.PUBLIC}/{spec[0]}@{DIGEST}", "recipe_sha256": RECIPE} + for key, spec in images.IMAGES.items() + }} + + +def manifests(): + common = {"generation": GENERATION.removeprefix("validated-"), "recipe_sha256": RECIPE, + "toolchain_id": "gcc13-armhf-abc", "runtime_sha256": "c" * 64} + runtime = dict(common) + runtime.update({"cross_" + key: common[key] for key in ("generation", "recipe_sha256", "toolchain_id")}) + return [dict(common), dict(common), dict(common), runtime] + + +class SelectionTests(unittest.TestCase): + def setUp(self): + self.fingerprint = patch.object(images, "fingerprint", return_value=RECIPE) + self.fingerprint.start() + self.addCleanup(self.fingerprint.stop) + + def test_complete_selection_and_anonymous_reads(self): + with patch.object(images, "anonymous_digest", return_value=DIGEST) as remote: + self.assertEqual(images.validate(selection(), True), selection()) + self.assertEqual(remote.call_count, 4) + + def test_missing_malformed_and_untrusted_selection(self): + cases = [] + lock = selection(); del lock["images"]["armhf_cross"]; cases.append(lock) + lock = selection(); lock["images"]["x86_64"] = None; cases.append(lock) + lock = selection(); lock["generation"] = "stable"; cases.append(lock) + lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PRIVATE}/linux-noble@{DIGEST}"; cases.append(lock) + lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PUBLIC}/linux-noble:stable"; cases.append(lock) + lock = selection(); lock["images"]["aarch64"]["recipe_sha256"] = "c" * 64; cases.append(lock) + for lock in cases: + with self.subTest(lock=lock), self.assertRaises(ValueError): + images.validate(lock) + + def test_remote_digest_mismatch(self): + with patch.object(images, "anonymous_digest", return_value="sha256:" + "c" * 64), self.assertRaisesRegex(ValueError, "digest mismatch"): + images.validate(selection(), True) + + def test_provenance_binds_exact_lock_bytes_and_four_builders(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "lock.json" + path.write_text(json.dumps(selection())) + first = images.provenance(path) + self.assertEqual(first["builders"], dict.fromkeys(images.IMAGES, DIGEST)) + path.write_text(json.dumps(selection(), indent=2)) + self.assertNotEqual(first["lock_sha256"], images.provenance(path)["lock_sha256"]) + + def test_candidate_provenance_mismatch_fails(self): + with tempfile.TemporaryDirectory() as directory: + lock = Path(directory) / "lock.json" + record = Path(directory) / "provenance.json" + lock.write_text(json.dumps(selection())) + expected = images.provenance(lock) + record.write_text(json.dumps({"linux_images": expected})) + with patch("sys.argv", ["helper", "verify-provenance", str(lock), str(record)]): + images.main() + expected["builders"]["armhf_cross"] = "sha256:" + "c" * 64 + record.write_text(json.dumps({"linux_images": expected})) + with self.assertRaisesRegex(ValueError, "provenance does not match"): + images.main() + + def test_existing_output_is_never_reused(self): + with tempfile.TemporaryDirectory() as directory: + with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", directory]), \ + patch.object(images, "prepare") as prepare, \ + self.assertRaisesRegex(ValueError, "must not already exist"): + images.main() + prepare.assert_not_called() + + def prepare(self, existing=None, manifest_values=None): + def inspect(reference, anonymous=False, missing_ok=False): + return existing if missing_ok else DIGEST + with patch.object(images, "inspect", side_effect=inspect), \ + patch.object(images, "image_manifest", side_effect=manifest_values or manifests()), \ + patch.object(images, "anonymous_digest", return_value=DIGEST), \ + patch.object(images, "run") as command: + result = images.prepare(GENERATION) + return result, command.call_args_list + + def test_copy_preserves_all_manifests_and_digest(self): + (lock, _), commands = self.prepare() + self.assertEqual(lock, selection()) + self.assertEqual(len(commands), 4) + for call in commands: + args = call.args[0] + self.assertEqual(args[:4], ["skopeo", "copy", "--all", "--preserve-digests"]) + self.assertIn("@" + DIGEST, args[4]) + self.assertTrue(args[5].endswith(":release-deps-" + GENERATION)) + + def test_identical_rerun_skips_copy(self): + _, commands = self.prepare(existing=DIGEST) + self.assertEqual(commands, []) + + def test_conflicting_retained_tag_fails(self): + with self.assertRaisesRegex(ValueError, "Conflicting retained"): + self.prepare(existing="sha256:" + "c" * 64) + + def test_mixed_armhf_pair_fails_before_copy(self): + for field in ("cross_generation", "cross_recipe_sha256", "cross_toolchain_id", "runtime_sha256"): + values = manifests() + values[-1][field] = "wrong" + with self.subTest(field=field), self.assertRaisesRegex(ValueError, "pair mismatch"): + self.prepare(manifest_values=values) + + def test_partial_copy_failure_emits_no_selection(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", str(output)]), \ + patch.object(images, "inspect", side_effect=lambda ref, anonymous=False, missing_ok=False: None if missing_ok else DIGEST), \ + patch.object(images, "image_manifest", side_effect=manifests()), \ + patch.object(images, "run", side_effect=["", subprocess.CalledProcessError(1, "copy", stderr="denied")]), \ + self.assertRaises(subprocess.CalledProcessError): + images.main() + self.assertFalse(output.exists()) + + def test_registry_inspection_hashes_exact_manifest_without_platform_selection(self): + raw = b'{"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}\n' + result = subprocess.CompletedProcess([], 0, stdout=raw) + with patch.object(images.subprocess, "run", return_value=result) as command: + digest = images.inspect("ghcr.io/wsjtx/wsjtx/linux-armv7-bookworm:test", anonymous=True) + self.assertEqual(digest, "sha256:" + hashlib.sha256(raw).hexdigest()) + self.assertIn("--raw", command.call_args.args[0]) + self.assertIn("--no-creds", command.call_args.args[0]) + + def test_authentication_error_is_not_missing_tag(self): + with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"unauthorized")), self.assertRaises(subprocess.CalledProcessError): + images.inspect("test", missing_ok=True) + + def test_only_manifest_unknown_allows_first_copy(self): + with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"manifest unknown")): + self.assertIsNone(images.inspect("test", missing_ok=True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_release_policy.py b/.github/scripts/tests/test_release_policy.py index a7929484..7a1c6b1e 100644 --- a/.github/scripts/tests/test_release_policy.py +++ b/.github/scripts/tests/test_release_policy.py @@ -1,5 +1,6 @@ import importlib.util import json +import re import io import shutil import subprocess @@ -19,15 +20,763 @@ SPEC.loader.exec_module(release_policy) class ReleasePolicyTest(unittest.TestCase): - def test_classifies_ga_and_rc(self): - self.assertEqual(release_policy.classify("3.2.0")["channel"], "GA") + def test_candidate_and_public_inventories_require_both_macos_architectures(self): + version = "3.2.0-rc1" + for distribution in (False, True): + mode = "distribution" if distribution else "validation" + suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg" + required = {f"wsjtx-{version}-{arch}-{suffix}" for arch in ("arm64", "x86_64")} + for inventory in ( + release_policy.expected_assets(version, distribution), + release_policy.public_expected_assets(version, mode), + ): + with self.subTest(mode=mode, inventory=inventory): + self.assertEqual({name for name in inventory if name.endswith(suffix)}, required) + + def test_newest_ga_line_uses_immutable_ga_tags_not_release_order_or_rc_line(self): + refs = { + "refs/tags/v2.7.0": "a" * 40, + "refs/tags/v3.0.2": "b" * 40, + "refs/tags/v3.2.0-rc1": "c" * 40, + } + newest = release_policy.public_release_line_policy("3.2.0", refs) + latest_ga_patch = release_policy.public_release_line_policy("3.0.3", refs) + self.assertEqual(newest["newest_ga_line"], "3.0") + self.assertTrue(newest["ga_line_is_newest"]) + self.assertTrue(newest["legacy_tag_only"]) + self.assertTrue(latest_ga_patch["ga_line_is_newest"]) + + def test_public_release_line_rejects_missing_or_ambiguous_history(self): + with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"): + release_policy.public_release_line_policy("3.2.0", {}) + with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"): + release_policy.public_release_line_policy("3.2.0", { + "refs/tags/v3.2.0-rc1": "a" * 40, + "refs/tags/v3.3.0-beta1": "c" * 40, + "refs/heads/release/3.2": "b" * 40, + }) + for refs in ( + {"refs/heads/release/next": "a" * 40}, + {"refs/tags/v3.2.0-beta0": "a" * 40}, + {"refs/tags/v3.2.0-alpha1": "a" * 40}, + ): + with self.subTest(refs=refs), self.assertRaisesRegex(ValueError, "malformed"): + release_policy.public_release_line_policy("3.2.0", refs) + + def test_latest_line_tag_orders_beta_below_rc_below_ga_and_numbers_numerically(self): + for tags, latest in ( + (("v3.3.0-beta9", "v3.3.0-beta10"), "v3.3.0-beta10"), + (("v3.3.0-beta10", "v3.3.0-rc1"), "v3.3.0-rc1"), + (("v3.3.0-rc2", "v3.3.0"), "v3.3.0"), + (("v3.3.0", "v3.3.1-beta1"), "v3.3.1-beta1"), + ): + refs = {"refs/tags/v3.0.2": "a" * 40} + refs.update({f"refs/tags/{tag}": "b" * 40 for tag in tags}) + with self.subTest(tags=tags): + policy = release_policy.public_release_line_policy("3.3.2", refs) + self.assertEqual(policy["latest_public_tag_on_candidate_line"], latest) + + def test_public_ref_listing_resolves_annotated_tags_and_hashes_the_snapshot(self): + refs, digest = release_policy.parse_public_ref_listing( + "".join(( + f"{'a' * 40} refs/heads/master\n", + f"{'b' * 40} refs/tags/v2.7.0\n", + f"{'c' * 40} refs/tags/v2.7.0^{{}}\n", + )) + ) + self.assertEqual(refs["refs/heads/master"], "a" * 40) + self.assertEqual(refs["refs/tags/v2.7.0"], "c" * 40) + line_policy = release_policy.public_release_line_policy("2.7.1", refs) + self.assertEqual(line_policy["latest_public_tag_on_candidate_line"], "v2.7.0") + self.assertEqual(line_policy["latest_public_tag_sha_on_candidate_line"], "c" * 40) + self.assertEqual(len(digest), 64) + + def test_first_public_promotion_creates_release_branch_and_tag_without_master(self): + master = "a" * 40 + candidate = "b" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0-rc1", + candidate, + { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + }, + lambda ancestor, descendant: ancestor == master and descendant == candidate, + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc1"], + ) + self.assertIsNone(plan["prior_release_branch"]) + self.assertFalse(plan["advance_master"]) + + def test_first_branch_initialization_requires_latest_same_line_tag_ancestry(self): + baseline = "a" * 40 + candidate = "b" * 40 + refs = { + "refs/heads/master": "c" * 40, + "refs/tags/v3.0.2": "c" * 40, + "refs/tags/v3.2.0-rc1": baseline, + } + plan = release_policy.plan_public_promotion( + "3.2.0-rc2", + candidate, + refs, + lambda ancestor, descendant: (ancestor, descendant) == (baseline, candidate), + ) + self.assertEqual(plan["updates"], [ + "refs/heads/release/3.2", "refs/tags/v3.2.0-rc2" + ]) + with self.assertRaisesRegex(ValueError, "disconnected branch initialization"): + release_policy.plan_public_promotion( + "3.2.0-rc2", + candidate, + refs, + lambda ancestor, descendant: False, + ) + + def test_newest_ga_advances_release_branch_tag_and_master(self): + branch = "a" * 40 + master = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0", + candidate, + { + "refs/heads/master": master, + "refs/heads/release/3.2": branch, + "refs/tags/v3.0.2": master, + "refs/tags/v3.2.0-rc1": branch, + }, + lambda ancestor, descendant: (ancestor, descendant) in { + (branch, candidate), + (master, candidate), + }, + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"], + ) + self.assertTrue(plan["advance_master"]) + + def test_newer_patch_on_current_ga_line_advances_master(self): + current = "a" * 40 + candidate = "b" * 40 + plan = release_policy.plan_public_promotion( + "3.2.2", + candidate, + { + "refs/heads/master": current, + "refs/heads/release/3.2": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.1": current, + }, + lambda ancestor, descendant: ancestor == current and descendant == candidate, + ) + self.assertTrue(plan["ga_release_is_latest"]) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.2", "refs/heads/master"], + ) + + def test_same_sha_public_promotion_skips_existing_tag_and_is_idempotent(self): + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.0", + candidate, + { + "refs/heads/master": candidate, + "refs/heads/release/3.2": candidate, + "refs/tags/v3.2.0": candidate, + "refs/tags/v3.2.0-rc1": "a" * 40, + }, + lambda ancestor, descendant: ancestor == descendant, + ) + self.assertTrue(plan["tag_exists"]) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/heads/master"], + ) + + def test_public_promotion_rejects_conflicting_tag_and_non_fast_forward_branch(self): + candidate = "c" * 40 + refs = { + "refs/heads/master": "a" * 40, + "refs/tags/v3.0.2": "a" * 40, + "refs/tags/v3.2.0-rc1": "b" * 40, + } + with self.assertRaisesRegex(ValueError, "tags are never moved"): + release_policy.plan_public_promotion( + "3.2.0-rc1", candidate, + {**refs, "refs/tags/v3.2.0-rc1": "d" * 40}, + lambda ancestor, descendant: True, + ) + with self.assertRaisesRegex(ValueError, "non-fast-forward"): + release_policy.plan_public_promotion( + "3.2.0-rc2", candidate, + {**refs, "refs/heads/release/3.2": "d" * 40}, + lambda ancestor, descendant: False, + ) + + def test_older_line_ga_advances_only_its_release_branch(self): + old_branch = "a" * 40 + newest = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.0.3", + candidate, + { + "refs/heads/master": newest, + "refs/heads/release/3.0": old_branch, + "refs/heads/release/3.2": newest, + "refs/tags/v3.0.2": old_branch, + "refs/tags/v3.2.0": newest, + }, + lambda ancestor, descendant: (ancestor, descendant) == (old_branch, candidate), + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.0", "refs/tags/v3.0.3"], + ) + self.assertFalse(plan["advance_master"]) + + def test_newest_ga_requires_master_history_bridge(self): + with self.assertRaisesRegex(ValueError, "history bridge"): + release_policy.plan_public_promotion( + "3.2.0", + "c" * 40, + { + "refs/heads/master": "d" * 40, + "refs/heads/release/3.2": "a" * 40, + "refs/tags/v3.0.2": "d" * 40, + "refs/tags/v3.2.0-rc1": "a" * 40, + }, + lambda ancestor, descendant: (ancestor, descendant) == ("a" * 40, "c" * 40), + ) + + def test_lower_ga_patch_on_current_line_cannot_be_promoted_as_latest(self): + current = "a" * 40 + candidate = "b" * 40 + refs = { + "refs/heads/master": current, + "refs/heads/release/3.2": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.1": current, + } + decision = release_policy.public_release_line_policy("3.2.0", refs) + self.assertFalse(decision["ga_release_is_latest"]) + with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"): + release_policy.plan_public_promotion( + "3.2.0", + candidate, + refs, + lambda ancestor, descendant: ancestor == current, + ) + + def test_lower_ga_patch_on_older_line_cannot_be_promoted(self): + current = "a" * 40 + with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"): + release_policy.plan_public_promotion( + "3.0.1", + "b" * 40, + { + "refs/heads/master": current, + "refs/tags/v3.0.2": current, + "refs/tags/v3.2.0": current, + }, + lambda ancestor, descendant: True, + ) + + def test_first_beta_promotion_creates_line_branch_and_tag_without_master(self): + master = "a" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta1", + "b" * 40, + { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + "refs/heads/release/3.2": "c" * 40, + "refs/tags/v3.2.0-rc1": "c" * 40, + }, + lambda ancestor, descendant: False, + ) + self.assertEqual(plan["channel"], "BETA") + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta1"]) + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + + def test_beta_on_the_newest_line_never_advances_master(self): + master = "a" * 40 + beta1 = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta2", + candidate, + { + "refs/heads/master": master, + "refs/tags/v3.2.0": master, + "refs/heads/release/3.3": beta1, + "refs/tags/v3.3.0-beta1": beta1, + }, + lambda ancestor, descendant: (ancestor, descendant) in {(beta1, candidate), (master, candidate)}, + ) + self.assertTrue(plan["ga_line_is_newest"]) + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"]) + + def test_promotion_requires_the_candidate_to_sort_above_the_latest_line_tag(self): + def refs(latest: str) -> dict: + line = latest[1:].rsplit(".", 1)[0] + return { + "refs/heads/master": "c" * 40, + "refs/tags/v3.0.2": "c" * 40, + f"refs/heads/release/{line}": "a" * 40, + f"refs/tags/{latest}": "a" * 40, + } + + for version, latest in ( + ("3.2.0-rc1", "v3.2.0-rc2"), + ("3.2.0-rc3", "v3.2.0"), + ("3.3.0-beta2", "v3.3.0-rc1"), + ("3.3.0-beta9", "v3.3.0-beta10"), + ): + with self.subTest(version=version, latest=latest), self.assertRaisesRegex( + ValueError, f"{latest} is the latest public tag on this line; v{version} must sort above it" + ): + release_policy.plan_public_promotion( + version, "b" * 40, refs(latest), lambda ancestor, descendant: True + ) + for version, latest in ( + ("3.3.0-beta10", "v3.3.0-beta9"), + ("3.3.0-rc1", "v3.3.0-beta5"), + ("3.3.0", "v3.3.0-rc2"), + ("3.3.1-beta1", "v3.3.0"), + ): + with self.subTest(version=version, latest=latest): + plan = release_policy.plan_public_promotion( + version, "b" * 40, refs(latest), lambda ancestor, descendant: True + ) + self.assertIn(f"refs/tags/v{version}", plan["updates"]) + + def test_same_sha_beta_repromotion_is_idempotent(self): + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.3.0-beta1", + candidate, + { + "refs/heads/master": "a" * 40, + "refs/tags/v3.0.2": "a" * 40, + "refs/heads/release/3.3": candidate, + "refs/tags/v3.3.0-beta1": candidate, + }, + lambda ancestor, descendant: ancestor == descendant, + ) + self.assertTrue(plan["tag_exists"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3"]) + + def test_old_line_ga_and_rc_plans_with_public_beta_tags(self): + master = "a" * 40 + rc1 = "b" * 40 + beta1 = "d" * 40 + candidate = "c" * 40 + refs = { + "refs/heads/master": master, + "refs/tags/v3.0.2": master, + "refs/heads/release/3.2": rc1, + "refs/tags/v3.2.0-rc1": rc1, + "refs/heads/release/3.3": beta1, + "refs/tags/v3.3.0-beta1": beta1, + } + ancestry = {(rc1, candidate), (master, candidate)} + + ga = release_policy.plan_public_promotion( + "3.2.0", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry + ) + self.assertEqual(ga["newest_ga_line"], "3.0") + self.assertTrue(ga["ga_line_is_newest"]) + self.assertTrue(ga["ga_release_is_latest"]) + self.assertEqual( + ga["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"], + ) + + rc2 = release_policy.plan_public_promotion( + "3.2.0-rc2", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry + ) + self.assertFalse(rc2["advance_master"]) + self.assertEqual(rc2["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"]) + + self.assertFalse(release_policy.public_release_line_policy("3.2.0-rc2", refs)["ga_release_is_latest"]) + beta2 = release_policy.public_release_line_policy("3.3.0-beta2", refs) + self.assertFalse(beta2["ga_release_is_latest"]) + self.assertEqual(beta2["latest_public_tag_on_candidate_line"], "v3.3.0-beta1") + + def test_older_line_ga_patch_with_newer_line_beta_tags_leaves_master(self): + newest = "a" * 40 + branch = "b" * 40 + candidate = "c" * 40 + plan = release_policy.plan_public_promotion( + "3.2.1", + candidate, + { + "refs/heads/master": newest, + "refs/tags/v3.3.0": newest, + "refs/heads/release/3.2": branch, + "refs/tags/v3.2.0": branch, + "refs/tags/v3.4.0-beta1": "d" * 40, + }, + lambda ancestor, descendant: (ancestor, descendant) == (branch, candidate), + ) + self.assertEqual(plan["newest_ga_line"], "3.3") + self.assertFalse(plan["advance_master"]) + self.assertFalse(plan["ga_release_is_latest"]) + self.assertEqual(plan["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.1"]) + + def test_public_promotion_fetches_legacy_line_tag_before_branch_bootstrap(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + source = root / "source" + legacy = root / "legacy" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + # Background auto-maintenance would race the directory's removal. + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + for repository in (source, legacy): + subprocess.run(["git", "init", repository], check=True, capture_output=True) + for key, value in ( + ("user.name", "Release Test"), + ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false"), + ): + subprocess.run(["git", "-C", repository, "config", key, value], check=True) + (repository / "source.txt").write_text(repository.name, encoding="utf-8") + subprocess.run(["git", "-C", repository, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", repository, "commit", "-m", repository.name], + check=True, + capture_output=True, + ) + + def head(repository: Path) -> str: + return subprocess.run( + ["git", "-C", repository, "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + source_head = head(source) + legacy_head = head(legacy) + for repository in (source, legacy): + subprocess.run( + ["git", "-C", repository, "remote", "add", "public", bare], + check=True, + ) + subprocess.run( + ["git", "-C", source, "push", "public", f"{source_head}:refs/heads/master"], + check=True, + capture_output=True, + ) + subprocess.run( + ["git", "-C", source, "push", "public", f"{source_head}:refs/tags/v3.0.2"], + check=True, + capture_output=True, + ) + subprocess.run( + ["git", "-C", legacy, "push", "public", f"{legacy_head}:refs/tags/v3.2.0-rc1"], + check=True, + capture_output=True, + ) + + (source / "source.txt").write_text("disconnected", encoding="utf-8") + subprocess.run(["git", "-C", source, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", source, "commit", "-m", "disconnected candidate"], + check=True, + capture_output=True, + ) + with self.assertRaisesRegex(ValueError, "disconnected branch initialization"): + release_policy.inspect_public_promotion( + "3.2.0-rc2", head(source), "public", cwd=source + ) + + subprocess.run( + ["git", "-C", source, "checkout", "--detach", legacy_head], + check=True, + capture_output=True, + ) + (source / "source.txt").write_text("descends from public RC", encoding="utf-8") + subprocess.run(["git", "-C", source, "add", "source.txt"], check=True) + subprocess.run( + ["git", "-C", source, "commit", "-m", "connected candidate"], + check=True, + capture_output=True, + ) + plan = release_policy.inspect_public_promotion( + "3.2.0-rc2", head(source), "public", cwd=source + ) + self.assertEqual( + plan["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"], + ) + + def test_atomic_public_push_rejects_raced_branch_update_without_creating_tag(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + work = root / "source" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + subprocess.run(["git", "init", work], check=True, capture_output=True) + for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false")): + subprocess.run(["git", "-C", work, "config", key, value], check=True) + + def commit(parent: str | None, content: str, subject: str) -> str: + if parent: + subprocess.run(["git", "-C", work, "checkout", "--detach", parent], check=True, capture_output=True) + (work / "source.txt").write_text(content, encoding="utf-8") + subprocess.run(["git", "-C", work, "add", "source.txt"], check=True) + subprocess.run(["git", "-C", work, "commit", "-m", subject], check=True, capture_output=True) + return subprocess.run( + ["git", "-C", work, "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + initial = commit(None, "initial", "initial") + subprocess.run(["git", "-C", work, "remote", "add", "public", bare], check=True) + subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/heads/master"], check=True, capture_output=True) + subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/tags/v3.0.2"], check=True, capture_output=True) + + first_candidate = commit(initial, "rc1", "rc1") + first_plan = release_policy.inspect_public_promotion( + "3.2.0-rc1", first_candidate, "public", cwd=work + ) + release_policy.push_public_ref_updates("public", first_plan, cwd=work) + release_policy.push_public_ref_updates( + "public", + release_policy.inspect_public_promotion( + "3.2.0-rc1", first_candidate, "public", cwd=work + ), + cwd=work, + ) + subprocess.run( + ["git", "-C", work, "push", "public", f"{initial}:refs/heads/release/3.4"], + check=True, + capture_output=True, + ) + with self.assertRaisesRegex(ValueError, "changed after validation"): + release_policy.promote_public_source( + "3.2.0-rc1", + first_candidate, + "public", + first_plan["public_refs_digest"], + cwd=work, + ) + + second_candidate = commit(first_candidate, "rc2", "rc2") + second_plan = release_policy.inspect_public_promotion( + "3.2.0-rc2", second_candidate, "public", cwd=work + ) + release_policy.push_public_ref_updates("public", second_plan, cwd=work) + + stale_candidate = commit(second_candidate, "rc3", "rc3") + stale_plan = release_policy.inspect_public_promotion( + "3.2.0-rc3", stale_candidate, "public", cwd=work + ) + concurrent = commit(initial, "concurrent", "concurrent branch update") + subprocess.run(["git", "-C", work, "push", "public", f"{concurrent}:refs/heads/race"], check=True, capture_output=True) + subprocess.run( + ["git", "--git-dir", bare, "update-ref", "refs/heads/release/3.2", concurrent], + check=True, + ) + + with self.assertRaisesRegex(ValueError, "atomic public ref update failed"): + release_policy.push_public_ref_updates("public", stale_plan, cwd=work) + actual_branch = subprocess.run( + ["git", "--git-dir", bare, "rev-parse", "refs/heads/release/3.2"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + self.assertEqual(actual_branch, concurrent) + missing_tag = subprocess.run( + ["git", "--git-dir", bare, "show-ref", "--verify", "refs/tags/v3.2.0-rc3"], + capture_output=True, + text=True, + ) + self.assertNotEqual(missing_tag.returncode, 0) + + def test_public_promotion_reads_annotated_public_beta_tags(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bare = root / "public.git" + work = root / "source" + subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True) + subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True) + subprocess.run(["git", "init", work], check=True, capture_output=True) + for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"), + ("maintenance.auto", "false")): + subprocess.run(["git", "-C", work, "config", key, value], check=True) + + def git(*arguments: str) -> str: + return subprocess.run( + ["git", "-C", work, *arguments], check=True, capture_output=True, text=True + ).stdout.strip() + + def commit(parent: str, subject: str) -> str: + if parent: + git("checkout", "--detach", parent) + (work / "source.txt").write_text(subject, encoding="utf-8") + git("add", "source.txt") + git("commit", "-m", subject) + return git("rev-parse", "HEAD") + + initial = commit("", "initial") + rc1 = commit(initial, "rc1") + beta1 = commit(rc1, "beta1") + git("tag", "-a", "v3.3.0-beta1", "-m", "beta1", beta1) + git("remote", "add", "public", str(bare)) + for source, ref in ( + (initial, "refs/heads/master"), + (initial, "refs/tags/v3.0.2"), + (rc1, "refs/heads/release/3.2"), + (rc1, "refs/tags/v3.2.0-rc1"), + (beta1, "refs/heads/release/3.3"), + ("refs/tags/v3.3.0-beta1", "refs/tags/v3.3.0-beta1"), + ): + git("push", "public", f"{source}:{ref}") + + rc2 = commit(rc1, "rc2") + self.assertEqual( + release_policy.inspect_public_promotion("3.2.0-rc2", rc2, "public", cwd=work)["updates"], + ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"], + ) + beta2 = commit(beta1, "beta2") + plan = release_policy.inspect_public_promotion("3.3.0-beta2", beta2, "public", cwd=work) + self.assertEqual(plan["latest_public_tag_sha_on_candidate_line"], beta1) + self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"]) + + def test_accepts_publication_environment_with_one_or_more_reviewers_and_self_review(self): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [{ + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [ + {"type": "User", "reviewer": {"id": 42}}, + {"type": "Team", "reviewer": {"id": 7}}, + ], + }], + }) + + def test_rejects_missing_publication_reviewers(self): + with self.assertRaisesRegex(ValueError, "one required-reviewers rule"): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [], + }) + + def test_rejects_malformed_or_self_review_blocking_publication_rule(self): + for rule in ( + {"type": "required_reviewers", "reviewers": [{"type": "User", "reviewer": {"id": 42}}]}, + { + "type": "required_reviewers", + "prevent_self_review": True, + "reviewers": [{"type": "User", "reviewer": {"id": 42}}], + }, + { + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "User", "reviewer": {"id": "42"}}], + }, + ): + with self.subTest(rule=rule), self.assertRaises(ValueError): + release_policy.validate_publication_environment({ + "name": "public-release", + "protection_rules": [rule], + }) + + def test_beta_publication_requires_beta_release_without_reviewers_for_beta_tags_only(self): + environment = { + "name": "beta-release", + "protection_rules": [{"type": "branch_policy"}], + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}, + } + policies = {"total_count": 1, "branch_policies": [{"id": 3, "name": "v*-beta*", "type": "tag"}]} + release_policy.validate_publication_environment(environment, "BETA", policies) + reviewers = { + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "Team", "reviewer": {"id": 7}}], + } + protected_only = {"protected_branches": True, "custom_branch_policies": False} + only_beta_tags = "exactly the v\\*-beta\\* tag pattern" + for broken, broken_policies, message in ( + ({**environment, "name": "public-release"}, policies, "beta-release environment response"), + ({**environment, "protection_rules": [reviewers]}, policies, "must not require reviewers"), + ({**environment, "deployment_branch_policy": None}, policies, "custom deployment patterns"), + ({**environment, "deployment_branch_policy": protected_only}, policies, "custom deployment patterns"), + (environment, None, only_beta_tags), + (environment, {"branch_policies": []}, only_beta_tags), + (environment, {"branch_policies": [{"name": "v*", "type": "tag"}]}, only_beta_tags), + (environment, {"branch_policies": [{"name": "v*-beta*", "type": "branch"}]}, only_beta_tags), + ( + environment, + {"branch_policies": [{"name": "v*-beta*", "type": "tag"}, {"name": "v*-rc*", "type": "tag"}]}, + only_beta_tags, + ), + ): + with self.subTest(message=message, environment=broken, policies=broken_policies): + with self.assertRaisesRegex(ValueError, message): + release_policy.validate_publication_environment(broken, "BETA", broken_policies) + + def test_rc_and_ga_publication_keep_the_public_release_reviewer_rule(self): + public = { + "name": "public-release", + "protection_rules": [{ + "type": "required_reviewers", + "prevent_self_review": False, + "reviewers": [{"type": "Team", "reviewer": {"id": 7}}], + }], + } + beta = { + "name": "beta-release", + "protection_rules": [], + "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True}, + } + policies = {"branch_policies": [{"name": "v*-beta*", "type": "tag"}]} + for channel in ("RC", "GA"): + with self.subTest(channel=channel): + release_policy.validate_publication_environment(public, channel) + with self.assertRaisesRegex(ValueError, "public-release environment response"): + release_policy.validate_publication_environment(beta, channel, policies) + with self.assertRaisesRegex(ValueError, "one required-reviewers rule"): + release_policy.validate_publication_environment( + {"name": "public-release", "protection_rules": []}, channel + ) + + def test_classifies_ga_beta_and_rc(self): + ga = release_policy.classify("3.2.0") + self.assertEqual((ga["channel"], ga["prerelease_number"]), ("GA", "")) identity = release_policy.classify("3.2.0-rc2") self.assertEqual(identity["channel"], "RC") - self.assertEqual(identity["rc_number"], "2") + self.assertEqual(identity["prerelease_number"], "2") self.assertEqual(identity["release_branch"], "release/3.2") + beta = release_policy.classify("3.3.0-beta10") + self.assertEqual( + (beta["channel"], beta["prerelease_number"], beta["release_branch"]), + ("BETA", "10", "release/3.3"), + ) def test_rejects_non_release_versions(self): - for version in ("v3.2.0", "3.2.0-beta1", "3.2", "3.2.0-rc0"): + for version in ( + "v3.2.0", "3.2", "3.2.0-rc0", "3.2.0-beta0", "3.2.0-beta", "3.2.0-alpha1", + "3.2.0-beta1-rc1", "3.2.0-BETA1", "3.2.0-devel", + ): with self.subTest(version=version), self.assertRaises(ValueError): release_policy.classify(version) @@ -37,7 +786,7 @@ class ReleasePolicyTest(unittest.TestCase): (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1\n" + "prerelease=1\n" "revision=$Format:%H$\n" ) identity = release_policy.validate_source(root, "3.2.0-rc1") @@ -46,18 +795,74 @@ class ReleasePolicyTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, "release channel"): release_policy.validate_source(root, "3.2.0") (root / "release-state.txt").write_text( - "version=3.2.0\nchannel=RC\nrc=1\nrevision=" + "a" * 40 + "\n" + "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=" + "a" * 40 + "\n" ) with self.assertRaisesRegex(ValueError, "revision"): release_policy.validate_source(root, "3.2.0-rc1") - def test_read_state_cli_accepts_single_digit_rc(self): + def test_parse_state_prerelease_contract(self): + def state(channel: str, prerelease: str, *extra: str) -> str: + lines = ("version=3.3.0", f"channel={channel}", f"prerelease={prerelease}", "revision=$Format:%H$") + return "\n".join((*lines, *extra)) + "\n" + + beta = release_policy.parse_state(state("BETA", "1", "windows_signing=unsigned")) + self.assertEqual( + (beta["channel"], beta["prerelease"], beta["windows_signing"]), + ("BETA", "1", "unsigned"), + ) + self.assertEqual(release_policy.parse_state(state("RC", "2"))["windows_signing"], "signpath") + self.assertEqual(release_policy.parse_state(state("DEVEL", ""))["prerelease"], "") + for contents, message in ( + (state("BETA", "1"), "BETA release state requires windows_signing=unsigned"), + (state("BETA", "1", "windows_signing=signpath"), "BETA release state requires windows_signing=unsigned"), + (state("BETA", "", "windows_signing=unsigned"), "positive prerelease number"), + (state("BETA", "0", "windows_signing=unsigned"), "positive prerelease number"), + (state("RC", "0"), "positive prerelease number"), + (state("DEVEL", "1"), "empty prerelease number"), + (state("GA", "1"), "empty prerelease number"), + (state("ALPHA", "1"), "channel must be DEVEL, BETA, RC, or GA"), + (state("RC", "1").replace("prerelease=", "rc="), "must define version, channel, prerelease, revision"), + ): + with self.subTest(contents=contents), self.assertRaisesRegex(ValueError, message): + release_policy.parse_state(contents) + + def test_validates_beta_source_and_archive(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + state = ( + "version=3.3.0\nchannel=BETA\nprerelease=1\n" + "revision=$Format:%H$\nwindows_signing=unsigned\n" + ) + (root / "release-state.txt").write_text(state) + identity = release_policy.validate_source(root, "3.3.0-beta1") + self.assertEqual( + (identity["channel"], identity["prerelease_number"], identity["windows_signing"]), + ("BETA", "1", "unsigned"), + ) + for version, message in ( + ("3.3.0-beta2", "prerelease number 1 does not match 2"), + ("3.3.0-rc1", "release channel BETA does not match RC"), + ): + with self.subTest(version=version), self.assertRaisesRegex(ValueError, message): + release_policy.validate_source(root, version) + commit = "e" * 40 + archived_state = state.replace("$Format:%H$", commit).encode() + archive = root / "source.tar.gz" + with tarfile.open(archive, "w:gz") as output: + info = tarfile.TarInfo("wsjtx-3.3.0-beta1/release-state.txt") + info.size = len(archived_state) + output.addfile(info, io.BytesIO(archived_state)) + release_policy.validate_archive(archive, "3.3.0-beta1", commit) + with self.assertRaisesRegex(ValueError, "release identity does not match"): + release_policy.validate_archive(archive, "3.3.0-beta2", commit) + + def test_read_state_cli_accepts_single_digit_prerelease(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1\n" + "prerelease=1\n" "revision=$Format:%H$\n" ) result = subprocess.run( @@ -71,7 +876,7 @@ class ReleasePolicyTest(unittest.TestCase): { "version": "3.2.0", "channel": "RC", - "rc": "1", + "prerelease": "1", "revision": "$Format:%H$", "windows_signing": "signpath", }, @@ -80,7 +885,7 @@ class ReleasePolicyTest(unittest.TestCase): (root / "release-state.txt").write_text( "version=3.2.0\n" "channel=RC\n" - "rc=1beta\n" + "prerelease=1beta\n" "revision=$Format:%H$\n" ) result = subprocess.run( @@ -89,13 +894,13 @@ class ReleasePolicyTest(unittest.TestCase): text=True, ) self.assertNotEqual(result.returncode, 0) - self.assertIn("positive RC number", result.stderr) + self.assertIn("positive prerelease number", result.stderr) def test_source_pins_unsigned_mode_and_rejects_unknown_mode(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) state = ( - "version=3.2.0\nchannel=RC\nrc=1\n" + "version=3.2.0\nchannel=RC\nprerelease=1\n" "revision=$Format:%H$\nwindows_signing=unsigned\n" ) (root / "release-state.txt").write_text(state) @@ -118,7 +923,7 @@ class ReleasePolicyTest(unittest.TestCase): with tempfile.TemporaryDirectory() as directory: root = Path(directory) commit = "b" * 40 - state = f"version=3.2.0\nchannel=RC\nrc=1\nrevision={commit}\n".encode() + state = f"version=3.2.0\nchannel=RC\nprerelease=1\nrevision={commit}\n".encode() tar_path = root / "source.tar.gz" with tarfile.open(tar_path, "w:gz") as archive: info = tarfile.TarInfo("wsjtx-3.2.0-rc1/release-state.txt") @@ -132,6 +937,43 @@ class ReleasePolicyTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, "revision"): release_policy.validate_archive(tar_path, "3.2.0-rc1", "c" * 40) + def test_candidate_and_public_gates_reject_missing_intel_payloads(self): + version = "3.3.0-beta1" + for distribution in (False, True): + mode = "distribution" if distribution else "validation" + for public in (False, True): + with self.subTest(mode=mode, public=public), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + expected = ( + release_policy.public_expected_assets(version, mode) + if public else release_policy.expected_assets(version, distribution) + ) + for name in expected: + target = root / name + target.mkdir() + suffix = release_policy.asset_suffix(name) + filename = name.replace("-unsigned", "") + if not filename.endswith(suffix): + filename += suffix + (target / filename).write_bytes(name.encode()) + def verify(): + if public: + return release_policy.find_public_asset_files(root, version, mode) + return release_policy.find_asset_files(root, version, distribution) + verify() + suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg" + required = [f"wsjtx-{version}-x86_64-{suffix}"] + [ + f"wsjtx-{version}-x86_64-macOS-{group}" + for group in ("jt9", "jt9stream", "wsprd", "utilities") + ] + for name in required: + artifact = root / name + held = root / "held" + artifact.rename(held) + with self.subTest(missing=name), self.assertRaisesRegex(ValueError, re.escape(name)): + verify() + held.rename(artifact) + def test_distribution_gate_rejects_unsigned_package(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -139,7 +981,7 @@ class ReleasePolicyTest(unittest.TestCase): for name in release_policy.expected_assets(version, True): target = root / name target.mkdir() - suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe" + suffix = release_policy.asset_suffix(name) (target / f"artifact{suffix}").write_bytes(b"signed") (root / "extra").mkdir() (root / "extra" / "unexpected-unsigned.pkg").write_bytes(b"unsigned") @@ -153,7 +995,7 @@ class ReleasePolicyTest(unittest.TestCase): for name in release_policy.expected_assets(version, True): target = root / name target.mkdir() - suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe" + suffix = release_policy.asset_suffix(name) (target / f"{name}{suffix}" if not name.endswith(suffix) else target / name).write_bytes(name.encode()) for arch in ("x86_64", "aarch64", "armhf"): for package_type in ("deb", "rpm"): @@ -180,21 +1022,82 @@ class ReleasePolicyTest(unittest.TestCase): self.assertEqual(manifest["macos_signing"]["mode"], "distribution") self.assertEqual(manifest["macos_signing"]["replaceable_assets"], []) self.assertEqual(manifest["windows_signing"]["mode"], "signpath") - self.assertEqual(len(manifest["assets"]), 13) + self.assertEqual(len(manifest["assets"]), 37) + self.assertTrue( + {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + <= {entry["name"] for entry in manifest["assets"]} + ) def test_manual_macos_assets_keep_release_names_without_immutable_hashes(self): + for version in ("3.2.0", "3.2.0-rc1"): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for name in release_policy.public_expected_assets(version, "validation"): + target = root / name + target.mkdir() + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: + filename = name.replace("-unsigned", "") + elif "linux" in name: + filename = f"{name}.AppImage" + else: + filename = "wsjtx-win64.exe" + (target / filename).write_bytes(name.encode()) + for arch in ("x86_64", "aarch64", "armhf"): + for package_type in ("deb", "rpm"): + target = root / f"wsjtx-{version}-linux-{arch}-{package_type}" + target.mkdir() + (target / f"wsjtx-{arch}.{package_type}").write_bytes(arch.encode()) + (root / f"wsjtx-{version}-src.tar.gz").write_bytes(b"source") + args = type("Args", (), { + "artifacts": str(root), "version": version, "repository": "WSJTX/wsjtx", + "commit": "a" * 40, "run_id": "123", + "linux_x86_64_digest": "sha256:" + "1" * 64, + "linux_aarch64_digest": "sha256:" + "2" * 64, + "linux_armhf_cross_digest": "sha256:" + "3" * 64, + "linux_armhf_digest": "sha256:" + "4" * 64, + "macos_mode": "validation", + "windows_mode": "signpath", + })() + + release_policy.write_manifest(args) + + manifest = json.loads((root / "release-manifest.json").read_text()) + replaceable = { + f"wsjtx-{version}-arm64-macOS.pkg", + f"wsjtx-{version}-x86_64-macOS.pkg", + } + release_names = {path.name for path in release_policy.release_files(root, version, "validation")} + immutable_names = {entry["name"] for entry in manifest["assets"]} + checksum_names = { + line.split(" ", 1)[1] + for line in (root / "SHA256SUMS").read_text().splitlines() + } + self.assertEqual(manifest["macos_signing"]["mode"], "manual") + self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable) + self.assertTrue(replaceable <= release_names) + self.assertTrue(replaceable.isdisjoint(immutable_names)) + self.assertTrue(replaceable.isdisjoint(checksum_names)) + self.assertIn("wsjtx-win64.exe", immutable_names) + tarballs = {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + self.assertTrue(tarballs <= immutable_names & checksum_names) + + def test_unsigned_windows_manifest_selects_and_hashes_installer(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) - version = "3.2.0" - for name in release_policy.public_expected_assets(version, "validation"): + version = "3.2.0-rc1" + for name in release_policy.public_expected_assets(version, "validation", "unsigned"): target = root / name target.mkdir() - if "macOS" in name: + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: filename = name.replace("-unsigned", "") elif "linux" in name: filename = f"{name}.AppImage" else: - filename = "wsjtx-win64.exe" + filename = f"wsjtx-{version}-win64.exe" (target / filename).write_bytes(name.encode()) for arch in ("x86_64", "aarch64", "armhf"): for package_type in ("deb", "rpm"): @@ -209,38 +1112,147 @@ class ReleasePolicyTest(unittest.TestCase): "linux_aarch64_digest": "sha256:" + "2" * 64, "linux_armhf_cross_digest": "sha256:" + "3" * 64, "linux_armhf_digest": "sha256:" + "4" * 64, - "macos_mode": "validation", - "windows_mode": "signpath", + "macos_mode": "validation", "windows_mode": "unsigned", })() - release_policy.write_manifest(args) - manifest = json.loads((root / "release-manifest.json").read_text()) - replaceable = { - f"wsjtx-{version}-arm64-macOS.pkg", - f"wsjtx-{version}-x86_64-macOS.pkg", - } - release_names = {path.name for path in release_policy.release_files(root, version, "validation")} - immutable_names = {entry["name"] for entry in manifest["assets"]} - checksum_names = { - line.split(" ", 1)[1] - for line in (root / "SHA256SUMS").read_text().splitlines() - } - self.assertEqual(manifest["macos_signing"]["mode"], "manual") - self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable) - self.assertTrue(replaceable <= release_names) - self.assertTrue(replaceable.isdisjoint(immutable_names)) - self.assertTrue(replaceable.isdisjoint(checksum_names)) - self.assertIn("wsjtx-win64.exe", immutable_names) + installer = f"wsjtx-{version}-win64.exe" + self.assertEqual(manifest["windows_signing"]["mode"], "unsigned") + self.assertIn(installer, {entry["name"] for entry in manifest["assets"]}) + for group in ("jt9", "jt9stream", "wsprd", "utilities"): + self.assertIn( + f"wsjtx-{version}-windows-x86_64-{group}.tar.gz", {entry["name"] for entry in manifest["assets"]} + ) + self.assertIn(installer, (root / "SHA256SUMS").read_text()) + installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer + installer_path.rename(installer_path.with_name("unexpected.exe")) + with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"): + release_policy.find_public_asset_files(root, version, "validation", "unsigned") + installer_path.with_name("unexpected.exe").rename(installer_path) + signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed" + signed_dir.mkdir() + with self.assertRaisesRegex(ValueError, "signed Windows installer"): + release_policy.find_public_asset_files(root, version, "validation", "unsigned") - def test_unsigned_windows_manifest_selects_and_hashes_installer(self): + def test_release_tarballs_are_required_by_candidate_and_public_gates(self): + version = "3.2.0-rc1" + tools = release_policy.release_tarballs(version) + self.assertEqual( + tools, + [ + f"wsjtx-{version}-{target}-{group}" + for target in ("arm64-macOS", "x86_64-macOS", "linux-x86_64", "linux-aarch64", "linux-armhf", "windows-x86_64") + for group in ("jt9", "jt9stream", "wsprd", "utilities") + ], + ) + self.assertEqual([release_policy.asset_suffix(name) for name in tools], [".tar.gz"] * 24) + self.assertEqual( + [release_policy.asset_suffix(name) for name in release_policy.expected_assets(version, False)[:6]], + [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"], + ) + for distribution in (False, True): + self.assertTrue(set(tools) <= set(release_policy.expected_assets(version, distribution))) + for macos_mode in release_policy.MACOS_MODES: + for windows_mode in release_policy.WINDOWS_MODES: + self.assertTrue( + set(tools) <= set(release_policy.public_expected_assets(version, macos_mode, windows_mode)) + ) with tempfile.TemporaryDirectory() as directory: root = Path(directory) - version = "3.2.0-rc1" + for name in release_policy.expected_assets(version, False): + target = root / name + target.mkdir() + (target / f"{name}{release_policy.asset_suffix(name)}").write_bytes(name.encode()) + files = release_policy.find_asset_files(root, version, False) + self.assertEqual( + sorted(path.name for path in files if path.name.endswith(".tar.gz")), + sorted(f"{name}.tar.gz" for name in tools), + ) + armhf = root / f"wsjtx-{version}-linux-armhf-jt9stream" + (armhf / f"{armhf.name}.tar.gz").unlink() + with self.assertRaisesRegex(ValueError, "linux-armhf-jt9stream must contain exactly one .tar.gz"): + release_policy.find_asset_files(root, version, False) + + def test_release_tarball_uploads_agree_with_the_group_file_and_the_policy(self): + root = SCRIPT.parents[2] + action = (root / ".github/actions/upload-release-tarballs/action.yml").read_text(encoding="utf-8") + prefix = r"wsjtx-\$\{\{ inputs\.version \}\}-\$\{\{ inputs\.target \}\}-" + names = re.findall(rf"\n name: {prefix}(\S+)\n", action) + paths = re.findall(rf"\n path: \$\{{\{{ inputs\.directory \}}\}}/{prefix}(\S+)\.tar\.gz\n", action) + self.assertEqual(names, release_policy.tarball_groups()) + self.assertEqual(paths, names) + self.assertEqual(action.count("if-no-files-found: error"), len(names)) + + version = "3.3.0" + installers = [] + for name in release_policy.public_expected_assets(version, "validation", "unsigned"): + if name not in release_policy.release_tarballs(version): + installers.append(re.sub(r"-(unsigned\.pkg|AppImage|installer)$", "", name.removeprefix(f"wsjtx-{version}-")).removesuffix(".pkg")) + self.assertEqual(installers, list(release_policy.RELEASE_TARGETS)) + macos_arches = [target.removesuffix("-macOS") for target in installers if target.endswith("-macOS")] + linux_arches = [target.removeprefix("linux-") for target in installers if target.startswith("linux-")] + + uploads = [] + for path in ( + ".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml", + ".github/workflows/build-linux.yml", ".github/actions/build-linux-payload/action.yml", + ): + text = (root / path).read_text(encoding="utf-8") + calls = re.findall( + r"uses: \./\.github/actions/upload-release-tarballs\n\s+with:\n\s+version: \$\{\{ inputs\.version \}\}\n" + r"\s+target: (.+)\n\s+directory: release-tarballs\n", + text, + ) + self.assertEqual(len(calls), text.count("upload-release-tarballs"), path) + uploads += [(path, target) for target in calls] + targets = {target for _, target in uploads if "${{" not in target} + for path, target in uploads: + if target == "${{ inputs.arch }}-macOS": + targets |= {f"{arch}-macOS" for arch in macos_arches} + elif target == "linux-${{ inputs.arch }}": + targets |= {f"linux-{arch}" for arch in linux_arches if f"linux-{arch}" not in targets} + self.assertEqual(targets, set(release_policy.RELEASE_TARGETS)) + + def test_tarball_groups_come_from_the_group_file(self): + self.assertEqual(release_policy.tarball_groups(), ["jt9", "jt9stream", "wsprd", "utilities"]) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "release-tarballs.txt" + path.write_bytes(b"# comment\r\njt9 jt9\r\n\r\nengine jt9stream wsprd\r\n") + self.assertEqual(release_policy.tarball_groups(path), ["jt9", "engine"]) + for contents, message in ( + ("", "must name each release tarball once"), + ("# only a comment\n", "must name each release tarball once"), + ("jt9 jt9\njt9 jt9stream\n", "must name each release tarball once"), + ("jt9 jt9\nutilities\n", "release tarball utilities names no programs"), + ("jt9 jt9\ninstaller wsprd\n", "release tarball name installer cannot name a release asset"), + ("jt9 jt9\nsrc wsprd\n", "release tarball name src cannot name a release asset"), + ("jt9 jt9\nAppImage wsprd\n", "release tarball name AppImage cannot name a release asset"), + ): + with self.subTest(contents=contents): + path.write_text(contents, encoding="utf-8") + with self.assertRaisesRegex(ValueError, message): + release_policy.tarball_groups(path) + + def test_asset_suffix_tells_tarballs_from_installers_on_every_target(self): + version = "3.3.0-beta1" + for name in release_policy.release_tarballs(version): + with self.subTest(name=name): + self.assertEqual(release_policy.asset_suffix(name), ".tar.gz") + self.assertEqual( + [release_policy.asset_suffix(name) for name in release_policy.public_expected_assets(version, "validation", "unsigned")[:6]], + [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"], + ) + + def test_beta_manifest_hashes_unsigned_macos_packages_as_immutable_assets(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + version = "3.3.0-beta2" for name in release_policy.public_expected_assets(version, "validation", "unsigned"): target = root / name target.mkdir() - if "macOS" in name: + if name in release_policy.release_tarballs(version): + filename = f"{name}.tar.gz" + elif "macOS" in name: filename = name.replace("-unsigned", "") elif "linux" in name: filename = f"{name}.AppImage" @@ -262,21 +1274,29 @@ class ReleasePolicyTest(unittest.TestCase): "linux_armhf_digest": "sha256:" + "4" * 64, "macos_mode": "validation", "windows_mode": "unsigned", })() + release_policy.write_manifest(args) + manifest = json.loads((root / "release-manifest.json").read_text()) - installer = f"wsjtx-{version}-win64.exe" - self.assertEqual(manifest["windows_signing"]["mode"], "unsigned") - self.assertIn(installer, {entry["name"] for entry in manifest["assets"]}) - self.assertIn(installer, (root / "SHA256SUMS").read_text()) - installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer - installer_path.rename(installer_path.with_name("unexpected.exe")) - with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"): - release_policy.find_public_asset_files(root, version, "validation", "unsigned") - installer_path.with_name("unexpected.exe").rename(installer_path) - signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed" - signed_dir.mkdir() - with self.assertRaisesRegex(ValueError, "signed Windows installer"): - release_policy.find_public_asset_files(root, version, "validation", "unsigned") + beta_assets = {f"wsjtx-{version}-{arch}-macOS.pkg" for arch in ("arm64", "x86_64")} + beta_assets |= {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)} + immutable_names = {entry["name"] for entry in manifest["assets"]} + checksum_names = { + line.split(" ", 1)[1] + for line in (root / "SHA256SUMS").read_text().splitlines() + } + self.assertEqual(manifest["macos_signing"], {"mode": "unsigned", "replaceable_assets": []}) + self.assertTrue(beta_assets <= immutable_names) + self.assertTrue(beta_assets <= checksum_names) + hashes = {entry["name"]: entry["sha256"] for entry in manifest["assets"]} + for arch in ("arm64", "x86_64"): + name = f"wsjtx-{version}-{arch}-macOS.pkg" + package = root / f"wsjtx-{version}-{arch}-macOS-unsigned.pkg" / name + self.assertEqual(hashes[name], release_policy.hash_file(package)) + + args.macos_mode = "distribution" + with self.assertRaisesRegex(ValueError, "BETA releases publish the validated unsigned macOS packages"): + release_policy.write_manifest(args) def test_signing_reports_bind_hashes_and_source(self): with tempfile.TemporaryDirectory() as directory: @@ -316,6 +1336,18 @@ class ReleasePolicyTest(unittest.TestCase): "signer_thumbprint": "5678", "identity_verified": True, })) release_policy.verify_signing_reports(root, version, commit, tag) + intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json" + contents = intel_report.read_bytes() + intel_report.unlink() + with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"): + release_policy.verify_signing_reports(root, version, commit, tag) + intel_report.write_bytes(contents) + intel_report_data = json.loads(contents) + intel_report_data["sha256"] = "0" * 64 + intel_report.write_text(json.dumps(intel_report_data)) + with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"): + release_policy.verify_signing_reports(root, version, commit, tag) + intel_report.write_bytes(contents) (verification_dir / "verification.json").write_text("{}") with self.assertRaisesRegex(ValueError, "release ref"): release_policy.verify_signing_reports(root, version, commit, tag) @@ -357,6 +1389,18 @@ class ReleasePolicyTest(unittest.TestCase): })) release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json" + contents = intel_report.read_bytes() + intel_report.unlink() + with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"): + release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report.write_bytes(contents) + intel_report_data = json.loads(contents) + intel_report_data["sha256"] = "0" * 64 + intel_report.write_text(json.dumps(intel_report_data)) + with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"): + release_policy.verify_signing_reports(root, version, commit, tag, "validation") + intel_report.write_bytes(contents) report = json.loads( (root / f"macos-signing-report-{version}-arm64" / "macos-signing-report.json").read_text() diff --git a/.github/scripts/tests/test_release_workflow_policy.py b/.github/scripts/tests/test_release_workflow_policy.py new file mode 100644 index 00000000..8765cbe1 --- /dev/null +++ b/.github/scripts/tests/test_release_workflow_policy.py @@ -0,0 +1,186 @@ +import pathlib +import re +import unittest + + +ROOT = pathlib.Path(__file__).resolve().parents[3] +PUBLIC = (ROOT / ".github/workflows/public-release.yml").read_text() +SIGN = (ROOT / ".github/workflows/sign-windows-release.yml").read_text() +PREPARE = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text() + + +def step(workflow: str, name: str) -> str: + start = workflow.index(f" - name: {name}\n") + following = re.search(r"\n - ", workflow[start + 1:]) + return workflow[start:start + 1 + following.start()] if following else workflow[start:] + + +def job(workflow: str, name: str) -> str: + start = workflow.index(f"\n {name}:\n") + 1 + following = re.search(r"\n [A-Za-z0-9_-]+:\n", workflow[start:]) + return workflow[start:start + following.start() + 1] if following else workflow[start:] + + +class ReleaseWorkflowPolicyTests(unittest.TestCase): + def test_both_macos_jobs_are_required_before_candidate_and_public_assembly(self): + release = (ROOT / ".github/workflows/release.yml").read_text() + for workflow, gate in ((release, "candidate-ready"), (PUBLIC, "assemble")): + self.assertIn("needs: [prepare, macos, macos-intel, linux, linux-arm, linux-armhf, windows]", job(workflow, gate)) + for name, arch, runner, target in ( + ("macos", "arm64", "macos-15", "11.0"), + ("macos-intel", "x86_64", "macos-15-intel", "10.13"), + ): + body = job(workflow, name) + self.assertIn("needs: prepare", body) + self.assertNotIn(" if:", body) + self.assertIn("uses: ./.github/workflows/build-macos.yml", body) + self.assertIn(f"arch: {arch}", body) + self.assertIn(f"runner: {runner}", body) + self.assertIn(f'deployment_target: "{target}"', body) + self.assertNotIn("rc_number:", body) + self.assertNotIn("release_channel:", body) + signing = "validation" if gate == "candidate-ready" else "${{ needs.prepare.outputs.macos_sign_mode }}" + self.assertIn(f"signing_mode: {signing}", body) + + def test_intel_ci_is_opt_in_and_selected_artifacts_include_it(self): + ci = (ROOT / ".github/workflows/ci.yml").read_text() + intel = job(ci, "macos-intel") + self.assertIn("needs: [prepare, linux]", intel) + predicate = intel.split(" if: >-\n", 1)[1].split(" uses:", 1)[0] + self.assertEqual(predicate.strip(), "github.event_name == 'workflow_dispatch' ||\n contains(github.event.pull_request.labels.*.name, 'full-ci')") + selected = (ROOT / ".github/workflows/build-selected-artifacts.yml").read_text() + self.assertIn(" - macos-x64\n", selected) + body = job(selected, "macos-x64") + self.assertIn("(inputs.targets == 'macos-x64' || inputs.targets == 'all')", body) + self.assertIn("needs: [prepare, linux-smoke-x64]", body) + for body in (intel, body): + self.assertIn('arch: "x86_64"', body) + self.assertIn('runner: "macos-15-intel"', body) + self.assertIn('deployment_target: "10.13"', body) + self.assertNotIn("release_channel:", body) + self.assertNotIn("rc_number:", body) + + def test_macos_dispatch_defaults_and_compiler_selection_support_intel(self): + build = (ROOT / ".github/workflows/build-macos.yml").read_text() + runner = "${{ inputs.runner || (inputs.arch == 'x86_64' && 'macos-15-intel' || 'macos-15') }}" + self.assertIn("runs-on: " + runner, job(build, "build")) + self.assertIn("RUNNER: " + runner, job(build, "build")) + self.assertIn("runs-on: " + runner, job(build, "sign_distribution")) + self.assertIn("DEPLOYMENT_TARGET: ${{ inputs.deployment_target || (inputs.arch == 'x86_64' && '10.13' || '11.0') }}", build) + self.assertIn(" - x86_64\n", build) + action = (ROOT / ".github/actions/warm-macos-deps/action.yml").read_text() + for text in (build, action): + self.assertIn("arm64:macos-15:11.0|x86_64:macos-15-intel:10.13)", text) + self.assertIn("if: inputs.arch == 'x86_64'", text) + self.assertIn(".github/scripts/install-xpack-gfortran-macos.sh", text) + self.assertIn('if [ "${{ inputs.arch }}" = "x86_64" ]; then', text) + self.assertIn("steps.controlled-intel-fc.outputs.runtime_archives", text) + + def test_intel_cache_jobs_outputs_and_summary_are_connected(self): + warm = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text() + self.assertIn(" - macos-x86_64\n", warm) + self.assertIn("macos_x86_64: ${{ steps.detect.outputs.macos_x86_64 }}", job(warm, "detect")) + deps = job(warm, "warm-macos-x86_64-deps") + compiler = job(warm, "warm-macos-x86_64-ccache") + self.assertIn("needs: detect", deps) + self.assertIn("needs: [detect, warm-macos-x86_64-deps]", compiler) + for body in (deps, compiler): + self.assertIn("if: needs.detect.outputs.macos_x86_64 == 'true'", body) + self.assertIn("arch: x86_64", body) + self.assertIn("runner: macos-15-intel", body) + self.assertIn('deployment_target: "10.13"', body) + self.assertIn("runs-on: macos-15-intel", deps) + self.assertIn("save_ccache: true", compiler) + summary = job(warm, "summary") + self.assertIn("- warm-macos-x86_64-deps", summary) + self.assertIn("- warm-macos-x86_64-ccache", summary) + + def test_public_release_marks_every_non_ga_channel_prerelease_and_latest_stays_ga_only(self): + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+EXPECTED_PRERELEASE=true\s+fi') + self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+FLAGS\+=\(--prerelease\)\s+fi') + self.assertEqual(publish.count("--prerelease"), 1) + self.assertRegex( + publish, + r'LATEST=false\s+if \[ "\$CHANNEL" = GA \] && \[ "\$GA_RELEASE_IS_LATEST" = true \]; then\s+LATEST=true\s+fi', + ) + self.assertEqual(publish.count("LATEST=true"), 1) + self.assertIn('FLAGS+=("--latest=$LATEST")', publish) + + def test_publication_environment_and_its_validation_follow_the_channel(self): + selected = "${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}" + self.assertIn(f" environment: {selected}\n", job(PUBLIC, "publish")) + guard = step(PUBLIC, "Validate final publication environment protection") + self.assertRegex( + guard, + r'ENVIRONMENT=public-release\s+POLICIES=\(\)\s+' + r'if \[ "\$CHANNEL" = BETA \]; then\s+ENVIRONMENT=beta-release', + ) + self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT/deployment-branch-policies"', guard) + self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT"', guard) + self.assertIn('--channel "$CHANNEL" "${POLICIES[@]}"', guard) + self.assertLess(PUBLIC.index(guard), PUBLIC.index("\n macos:\n")) + + def test_betas_publish_validated_macos_packages_with_nothing_replaceable(self): + identity = step(PUBLIC, "Validate public release tag and source identity") + self.assertRegex( + identity, + r'if \[ "\$CHANNEL" = BETA \]; then\s+echo "macos_sign_mode=validation" >> "\$GITHUB_OUTPUT"', + ) + self.assertLess( + identity.index('[ "$CHANNEL" = BETA ]'), + identity.index('[ "$MACOS_DISTRIBUTION_SIGNING_ENABLED" = true ]'), + ) + recheck = step(PUBLIC, "Recheck bundle and immutable public tag") + self.assertRegex(recheck, r'if \[ "\$CHANNEL" = BETA \]; then\s+EXPECTED_MACOS_MODE=unsigned\s+elif') + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn(".macos_signing.replaceable_assets[]", publish) + self.assertNotIn("MACOS_MODE", publish) + + def test_a_rerun_compares_every_published_asset_except_the_manifests_replaceable_ones(self): + publish = step(PUBLIC, "Publish public GitHub Release") + self.assertIn("mapfile -t REPLACEABLE_NAMES < <(jq -r '.macos_signing.replaceable_assets[]' " + "release-bundle/release-manifest.json)", publish) + preserve = [ + "if printf '%s\\n' \"${REPLACEABLE_NAMES[@]}\" | grep -Fxq \"$name\"; then", + "if printf '%s\\n' \"${ACTUAL_NAMES[@]}\" | grep -Fxq \"$name\"; then", + "echo \"Preserving manually replaceable macOS asset: $name\"", + ] + self.assertRegex(publish, r"\s+".join(map(re.escape, preserve))) + self.assertEqual(len(re.findall(r"^\s+continue$", publish, re.M)), 1) + self.assertEqual(publish.count('cmp "$file"'), 1) + + def test_windows_signing_guard_admits_only_rc_and_ga(self): + guard = step(SIGN, "Require a public RC or GA invocation") + self.assertIn('test "$(jq -r .channel <<<"$IDENTITY")" = "$CHANNEL"', guard) + self.assertIn('test "$CHANNEL" = RC || test "$CHANNEL" = GA', guard) + self.assertLess(SIGN.index(guard), SIGN.index("uses: signpath/github-action-submit-signing-request")) + + def test_dependency_preparation_fails_unless_develop_and_the_source_branch_are_protected(self): + prepare = job(PREPARE, "prepare") + self.assertIn("github.ref == 'refs/heads/develop'", prepare.split("\n steps:\n", 1)[0]) + self.assertEqual(PREPARE.count("ref_protected"), 1) + self.assertNotIn("continue-on-error", prepare) + guard = step(PREPARE, "Require protected develop") + self.assertNotRegex(guard, r"\n if:") + self.assertIn("REF_PROTECTED: ${{ github.ref_protected }}", guard) + self.assertRegex(guard, r'if \[ "\$REF_PROTECTED" != true \]; then\s+echo "::error::[^"]+"\s+exit 1') + self.assertLess(prepare.index("Require protected develop"), prepare.index("actions/checkout")) + source = step(PREPARE, "Resolve protected source branch to an exact commit") + self.assertRegex( + source, + r'if \[ "\$\(jq -r \'\.protected\' <<< "\$branch"\)" != true \]; then\s+echo "::error::[^"]+"\s+exit 1', + ) + + def test_full_artifact_downloads_drop_the_armhf_build_tree(self): + release = (ROOT / ".github/workflows/release.yml").read_text() + for workflow, job_name, next_step in ((release, "candidate-ready", "Verify all candidate artifacts"), (PUBLIC, "assemble", "Build corresponding source archive")): + body = job(workflow, job_name) + download = body.index("uses: actions/download-artifact@v8\n with:\n path: artifacts\n") + drop = body.index(" - name: Drop the ARMHF build tree\n run: rm -rf artifacts/armhf-build-tree\n") + self.assertLess(download, drop, job_name) + self.assertLess(drop, body.index(f" - name: {next_step}\n"), job_name) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/third-party-libraries.tsv b/.github/scripts/third-party-libraries.tsv new file mode 100644 index 00000000..4c86f38f --- /dev/null +++ b/.github/scripts/third-party-libraries.tsv @@ -0,0 +1,27 @@ +# Tab-separated: file pattern, component, license as upstream states it, license address. +# Every library a release tarball bundles must match a pattern (case is +# ignored; the first match wins); package-cli-tools.sh lists them in each +# tarball's THIRD-PARTY.txt. @<platform> rows name code linked statically +# into every tarball of that platform. +QtCore Qt 5 Core, with the third-party code https://doc.qt.io/qt-5/licenses-used-in-qt.html lists LGPL-3.0, GPL-2.0, or GPL-3.0 or a later version approved by the KDE Free Qt Foundation, at the recipient's choice https://github.com/qt/qtbase/blob/v5.15.18-lts-lgpl/LICENSE.LGPL3 +Qt5Core.dll Qt 5 Core, with the third-party code https://doc.qt.io/qt-5/licenses-used-in-qt.html lists LGPL-3.0, GPL-2.0, or GPL-3.0 or a later version approved by the KDE Free Qt Foundation, at the recipient's choice https://github.com/qt/qtbase/blob/v5.15.18-lts-lgpl/LICENSE.LGPL3 +libQt5Core.so.* Qt 5 Core, with the third-party code https://doc.qt.io/qt-5/licenses-used-in-qt.html lists LGPL-3.0, GPL-2.0, or GPL-3.0 or a later version approved by the KDE Free Qt Foundation, at the recipient's choice https://github.com/qt/qtbase/blob/v5.15.18-lts-lgpl/LICENSE.LGPL3 +libicu*.so.72 ICU 72 Unicode, Inc. License Agreement - Data Files and Software, with third-party terms in the same file https://github.com/unicode-org/icu/blob/release-72-1/icu4c/LICENSE +libicu*.so.74 ICU 74 Unicode License V3 (Unicode-3.0), with third-party terms in the same file https://github.com/unicode-org/icu/blob/release-74-1/LICENSE +libicu*.dll ICU Unicode License V3 (Unicode-3.0), with third-party terms in the same file https://github.com/unicode-org/icu/blob/main/LICENSE +libdouble-conversion* double-conversion BSD-3-Clause https://github.com/google/double-conversion/blob/master/LICENSE +libpcre2-* PCRE2 BSD-3-Clause WITH PCRE2-exception https://github.com/PCRE2Project/pcre2/blob/master/LICENCE.md +libzstd* Zstandard BSD-3-Clause or GPL-2.0, at the recipient's choice https://github.com/facebook/zstd/blob/dev/LICENSE +zlib1.dll zlib Zlib https://zlib.net/zlib_license.html +libglib-2.0* GLib LGPL-2.1-or-later https://gitlab.gnome.org/GNOME/glib/-/blob/main/LICENSES/LGPL-2.1-or-later.txt +libgfortran* GCC runtime libraries GPL-3.0-or-later WITH GCC-exception-3.1 https://www.gnu.org/licenses/gcc-exception-3.1.html +libgomp* GCC runtime libraries GPL-3.0-or-later WITH GCC-exception-3.1 https://www.gnu.org/licenses/gcc-exception-3.1.html +libstdc++* GCC runtime libraries GPL-3.0-or-later WITH GCC-exception-3.1 https://www.gnu.org/licenses/gcc-exception-3.1.html +libgcc_s* GCC runtime libraries GPL-3.0-or-later WITH GCC-exception-3.1 https://www.gnu.org/licenses/gcc-exception-3.1.html +libquadmath* libquadmath (GCC) LGPL-2.1-or-later https://github.com/gcc-mirror/gcc/blob/master/libquadmath/COPYING.LIB +libwinpthread* mingw-w64 winpthreads MIT and BSD-3-Clause https://github.com/mingw-w64/mingw-w64/blob/master/mingw-w64-libraries/winpthreads/COPYING +libfftw3f* FFTW 3 GPL-2.0-or-later https://www.fftw.org/doc/License-and-Copyright.html +libboost_* Boost BSL-1.0 https://www.boost.org/LICENSE_1_0.txt +@macos GCC runtime libraries GPL-3.0-or-later WITH GCC-exception-3.1 https://www.gnu.org/licenses/gcc-exception-3.1.html +@macos libquadmath (GCC) LGPL-2.1-or-later https://github.com/gcc-mirror/gcc/blob/master/libquadmath/COPYING.LIB +@windows mingw-w64 runtime ZPL-2.1, with the other terms the file lists https://github.com/mingw-w64/mingw-w64/blob/master/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt diff --git a/.github/scripts/validate-ci-inputs.sh b/.github/scripts/validate-ci-inputs.sh index e801a6eb..049f6752 100755 --- a/.github/scripts/validate-ci-inputs.sh +++ b/.github/scripts/validate-ci-inputs.sh @@ -9,7 +9,8 @@ # # Only variables that are set are checked, so each workflow can pass # the subset it uses. Empty values are rejected except for -# WSJT_RC_NUMBER, which is optional. +# WSJT_RELEASE_CHANNEL, where empty selects release-state.txt, and +# WSJT_PRERELEASE_NUMBER, which is optional. # # Usage: # WSJTX_VERSION=... HAMLIB_BRANCH=... .github/scripts/validate-ci-inputs.sh @@ -57,18 +58,18 @@ validate_inputs() { if [ -n "${WSJT_RELEASE_CHANNEL+x}" ]; then case "$WSJT_RELEASE_CHANNEL" in - DEVEL|RC|GA) ;; + ''|DEVEL|BETA|RC|GA) ;; *) - fail "Invalid release_channel '${WSJT_RELEASE_CHANNEL}': use DEVEL, RC, or GA" + fail "Invalid release_channel '${WSJT_RELEASE_CHANNEL}': use DEVEL, BETA, RC, GA, or empty" ;; esac fi - if [ -n "${WSJT_RC_NUMBER+x}" ]; then - case "$WSJT_RC_NUMBER" in + if [ -n "${WSJT_PRERELEASE_NUMBER+x}" ]; then + case "$WSJT_PRERELEASE_NUMBER" in ''|*[!0-9]*) - if [ -n "$WSJT_RC_NUMBER" ]; then - fail "Invalid rc_number '${WSJT_RC_NUMBER}': use digits only" + if [ -n "$WSJT_PRERELEASE_NUMBER" ]; then + fail "Invalid prerelease_number '${WSJT_PRERELEASE_NUMBER}': use digits only" fi ;; esac @@ -123,7 +124,7 @@ validate_inputs() { run_isolated() { env -u WSJTX_VERSION -u HAMLIB_BRANCH -u WSJT_RELEASE_CHANNEL \ - -u WSJT_RC_NUMBER -u ARCH -u IMAGE_TAG -u DEPLOYMENT_TARGET -u RUNNER \ + -u WSJT_PRERELEASE_NUMBER -u ARCH -u IMAGE_TAG -u DEPLOYMENT_TARGET -u RUNNER \ -u VALIDATE_FORTRAN_FALLBACK \ "$@" "$0" } @@ -140,15 +141,21 @@ expect_failure() { if [ "${1:-}" = "--self-test" ]; then run_isolated \ env WSJTX_VERSION="3.2.0-devel" HAMLIB_BRANCH="4.7.2" \ - WSJT_RELEASE_CHANNEL="DEVEL" WSJT_RC_NUMBER="" \ + WSJT_RELEASE_CHANNEL="DEVEL" WSJT_PRERELEASE_NUMBER="" \ >/dev/null run_isolated \ + env WSJTX_VERSION="3.3.0-beta1" \ + WSJT_RELEASE_CHANNEL="BETA" WSJT_PRERELEASE_NUMBER="1" \ + >/dev/null + run_isolated env WSJT_RELEASE_CHANNEL="" WSJT_PRERELEASE_NUMBER="" >/dev/null + run_isolated \ env WSJTX_VERSION="3.0.1-rc1" HAMLIB_BRANCH="4.7.2" \ - WSJT_RELEASE_CHANNEL="RC" WSJT_RC_NUMBER="1" \ + WSJT_RELEASE_CHANNEL="RC" WSJT_PRERELEASE_NUMBER="1" \ ARCH="x86_64" DEPLOYMENT_TARGET="10.13" RUNNER="macos-15-intel" \ IMAGE_TAG="candidate-123-1" \ VALIDATE_FORTRAN_FALLBACK="true" \ >/dev/null + run_isolated env ARCH="arm64" DEPLOYMENT_TARGET="11.0" RUNNER="macos-15" >/dev/null run_isolated env HAMLIB_BRANCH="integration/4.7" VALIDATE_FORTRAN_FALLBACK="false" >/dev/null expect_failure 'command substitution in version' WSJTX_VERSION='3.1.0$(id)' @@ -157,7 +164,7 @@ if [ "${1:-}" = "--self-test" ]; then expect_failure 'command substitution in hamlib_branch' HAMLIB_BRANCH='4.7.2$(touch /tmp/x)' expect_failure 'shell metacharacters in hamlib_branch' HAMLIB_BRANCH='4.7.2; id' expect_failure 'invalid channel' WSJT_RELEASE_CHANNEL='dev' - expect_failure 'non-numeric rc' WSJT_RC_NUMBER='1a' + expect_failure 'non-numeric prerelease number' WSJT_PRERELEASE_NUMBER='1a' expect_failure 'empty version' WSJTX_VERSION='' expect_failure 'invalid arch' ARCH='x86_64; id' expect_failure 'slash in image tag' IMAGE_TAG='candidate/unsafe' diff --git a/.github/scripts/validate-linux-armhf-runtime.sh b/.github/scripts/validate-linux-armhf-runtime.sh index 0909d512..2492db1c 100755 --- a/.github/scripts/validate-linux-armhf-runtime.sh +++ b/.github/scripts/validate-linux-armhf-runtime.sh @@ -22,7 +22,7 @@ source .github/scripts/armhf-ci-image-config.sh .github/scripts/verify-armhf-ci-image.sh runtime "$ARCH" "$HAMLIB_BRANCH" if [ "$phase" = all ] || [ "$phase" = test ]; then - echo "::group::ARMHF CTest under QEMU" + echo "::group::ARMHF CTest" started="$(date +%s)" set +e ( @@ -30,7 +30,7 @@ if [ "$phase" = all ] || [ "$phase" = test ]; then LD_LIBRARY_PATH="$ARMHF_RUNTIME_PREFIX" \ QT_QPA_PLATFORM=xcb \ xvfb-run -a -s "-screen 0 1280x1024x24" \ - ctest --output-on-failure --output-junit ctest-results.xml + ctest --parallel 3 --output-on-failure --output-junit ctest-results.xml ) 2>&1 | tee wsjtx-build/ctest-armhf.log status=${PIPESTATUS[0]} set -e diff --git a/.github/scripts/validate-workflow-timeouts.py b/.github/scripts/validate-workflow-timeouts.py index 256f5782..e3539a36 100755 --- a/.github/scripts/validate-workflow-timeouts.py +++ b/.github/scripts/validate-workflow-timeouts.py @@ -9,6 +9,8 @@ JOB_PATTERN = re.compile( r"^ (?P<quote>[\"']?)(?P<name>[A-Za-z_][A-Za-z0-9_-]*)(?P=quote):" r"(?:\s+&[A-Za-z_][A-Za-z0-9_-]*)?(?:\s*#.*)?$" ) +TIMEOUT_PATTERN = re.compile(r"^ timeout-minutes:\s*(\d+)\s*(?:#.*)?$") +MINIMUM_JOB_TIMEOUTS = {("build-macos.yml", "build"): 180} def unbounded_jobs(path: Path) -> list[str]: @@ -18,10 +20,18 @@ def unbounded_jobs(path: Path) -> list[str]: job_line = 0 has_runner = False has_timeout = False + timeout_minutes: int | None = None def finish_job() -> None: if job_name is not None and has_runner and not has_timeout: failures.append(f"{path}:{job_line}: job '{job_name}' has runs-on but no timeout-minutes") + minimum = MINIMUM_JOB_TIMEOUTS.get((path.name, job_name or "")) + if job_name is not None and has_runner and minimum is not None and ( + timeout_minutes is None or timeout_minutes < minimum + ): + failures.append( + f"{path}:{job_line}: job '{job_name}' timeout-minutes must be at least {minimum}" + ) for line_number, line in enumerate(path.read_text().splitlines(), start=1): if line == "jobs:": @@ -40,6 +50,7 @@ def unbounded_jobs(path: Path) -> list[str]: job_line = line_number has_runner = False has_timeout = False + timeout_minutes = None elif ( line.startswith(" ") and not line.startswith(" ") @@ -54,6 +65,9 @@ def unbounded_jobs(path: Path) -> list[str]: elif job_name is not None: has_runner = has_runner or line.startswith(" runs-on:") has_timeout = has_timeout or line.startswith(" timeout-minutes:") + timeout_match = TIMEOUT_PATTERN.match(line) + if timeout_match: + timeout_minutes = int(timeout_match.group(1)) else: finish_job() diff --git a/.github/scripts/verify-armhf-ci-image.sh b/.github/scripts/verify-armhf-ci-image.sh index b6746269..e6f3fd65 100755 --- a/.github/scripts/verify-armhf-ci-image.sh +++ b/.github/scripts/verify-armhf-ci-image.sh @@ -219,6 +219,7 @@ case "$expected_role" in *) echo "ARMHF AppImage QEMU helper is not x86-64: $qemu_metadata" >&2; exit 1 ;; esac for plugin in \ + /usr/lib/arm-linux-gnueabihf/libQt5Concurrent.so.5 \ /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqxcb.so \ /usr/lib/arm-linux-gnueabihf/qt5/plugins/sqldrivers/libqsqlite.so; do require_armhf_elf "$plugin" diff --git a/.github/scripts/verify-macos-artifacts.sh b/.github/scripts/verify-macos-artifacts.sh index 981e60d6..5caf31e0 100755 --- a/.github/scripts/verify-macos-artifacts.sh +++ b/.github/scripts/verify-macos-artifacts.sh @@ -9,6 +9,7 @@ Verifies Mach-O files under PATH for: * expected architecture * deployment target not newer than --target * no package-manager runtime library references + * no Qt load dependencies in jt9 Package-manager paths are always rejected: /opt/homebrew, /usr/local/Cellar, /usr/local/opt, /opt/local @@ -146,9 +147,20 @@ check_file() { fi install_name=$(otool -arch "$arch" -D "$file" 2>/dev/null | awk 'NR == 2 { print $1 }' || true) - refs=$(otool -arch "$arch" -L "$file" 2>/dev/null | awk 'NR > 1 { print $1 }' || true) + if ! refs=$(otool -arch "$arch" -L "$file" 2>/dev/null | awk 'NR > 1 { print $1 }'); then + echo "::error file=${file}::Could not inspect Mach-O load dependencies" + return 1 + fi while IFS= read -r ref; do [ -n "$ref" ] || continue + if [ "${file##*/}" = jt9 ]; then + case "${ref##*/}" in + Qt*|libQt*) + echo "::error file=${file}::jt9 must not depend on Qt: ${ref}" + fail=1 + ;; + esac + fi if [ "$ref" = "$install_name" ]; then case "$ref" in */*) ;; |
