Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/build-sdk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -295,12 +295,12 @@ jobs:
repository: ${{ env.BUILDSCRIPTS_REPO }}
ref: ${{ needs.gate.outputs.buildscripts_revision }}
fetch-depth: 0
# One pattern-less download: single pattern matches extract flat, and
# two flat extractions into one directory overwrite each other's
# provenance.json. Every artifact of this run is a stage artifact, and
# more than one always exists, so this always nests per artifact name.
# Reruns retain artifacts from earlier attempts, including this job's
# own grouped snapshot. Only stage artifacts are inputs; leaving
# merge-multiple false keeps each provenance file in its artifact path.
- uses: actions/download-artifact@v8
with:
pattern: stage*-*
path: artifacts
- name: Group the release tree
shell: bash
Expand Down
13 changes: 8 additions & 5 deletions .github/workflows/dispatch-build.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
name: Announce a revision to autobuilds

# Discovery starts here: every commit that lands on the development branch
# is a new build input, and autobuilds is told about it. It deduplicates by
# build_id, so announcing a revision it already built costs one job.
# is a new build input for every profile this tree publishes. Autobuilds
# deduplicates by build_id, so announcing an input it already built costs one
# job and no build runners.
on:
push:
branches: [master]
Expand All @@ -11,6 +12,8 @@ jobs:
announce:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7

- name: Ask autobuilds to build this revision
env:
GH_TOKEN: ${{ secrets.REPO_DISPATCH_TOKEN }}
Expand All @@ -20,6 +23,6 @@ jobs:
echo "::error::REPO_DISPATCH_TOKEN secret is required for cross-repo dispatch to vitasdk/autobuilds"
exit 1
fi
gh api repos/vitasdk/autobuilds/dispatches \
-f event_type=run_build \
-f "client_payload[buildscripts_ref]=$GITHUB_SHA"
./scripts/announce-builds.py \
--repository vitasdk/autobuilds \
--revision "$GITHUB_SHA"
78 changes: 78 additions & 0 deletions scripts/announce-builds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Announce one SDK-core build for every profile published by this tree."""

import argparse
import pathlib
import subprocess
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from describe import DescribeError, parse_profiles # noqa: E402

REPOSITORY_ROOT = pathlib.Path(__file__).resolve().parent.parent
DEFAULT_PROFILES_PATH = REPOSITORY_ROOT / "cmake" / "Profiles.cmake"


class AnnounceError(Exception):
pass


def load_profiles(path):
try:
text = pathlib.Path(path).read_text(encoding="utf-8")
except OSError as exc:
raise AnnounceError(f"{path} cannot be read: {exc}") from exc
try:
return parse_profiles(text)
except DescribeError as exc:
raise AnnounceError(str(exc)) from exc


def announce(repository, revision, profiles):
failures = []
for profile in profiles:
try:
result = subprocess.run(
[
"gh",
"api",
f"repos/{repository}/dispatches",
"-f",
"event_type=run_build",
"-f",
f"client_payload[buildscripts_ref]={revision}",
"-f",
f"client_payload[profile]={profile}",
],
check=False,
)
except OSError as exc:
raise AnnounceError(f"cannot run gh: {exc}") from exc
if result.returncode != 0:
failures.append((profile, result.returncode))

if failures:
detail = ", ".join(f"{profile} (exit {status})" for profile, status in failures)
raise AnnounceError(f"dispatch failed for: {detail}")


def main(argv):
parser = argparse.ArgumentParser(prog="announce-builds")
parser.add_argument("--repository", required=True)
parser.add_argument("--revision", required=True)
parser.add_argument("--profiles-file", default=DEFAULT_PROFILES_PATH)
args = parser.parse_args(argv)

try:
profiles = load_profiles(args.profiles_file)
announce(args.repository, args.revision, profiles)
except AnnounceError as exc:
print(f"announce-builds: {exc}", file=sys.stderr)
return 1

print(f"announce-builds: requested {len(profiles)} profile build(s)")
return 0


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
108 changes: 108 additions & 0 deletions tests/ci/test-announce-builds.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/usr/bin/env bash

set -euo pipefail

repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)
temporary_root=$(mktemp -d "${TMPDIR:-/tmp}/vitasdk-announce-builds.XXXXXXXX")
cleanup() { rm -rf -- "$temporary_root"; }
trap cleanup EXIT

workflow="$repository_root/.github/workflows/dispatch-build.yml"
grep -Fq './scripts/announce-builds.py' "$workflow" || {
printf 'the revision announcement workflow does not use the profile fan-out helper\n' >&2
exit 1
}
grep -Fq 'actions/checkout@' "$workflow" || {
message='the revision announcement workflow cannot read the declared profiles without a checkout'
printf '%s\n' "$message" >&2
exit 1
}
grep -Fq -- '--repository vitasdk/autobuilds' "$workflow" || {
printf 'the revision announcement workflow targets the wrong repository\n' >&2
exit 1
}
grep -Fq -- '--revision "$GITHUB_SHA"' "$workflow" || {
printf 'the revision announcement workflow does not announce its pushed revision\n' >&2
exit 1
}

profiles="$temporary_root/Profiles.cmake"
cat > "$profiles" <<'CMAKEEOF'
set(VITASDK_PROFILES vita vita_softfp future_world)
CMAKEEOF

mkdir -p "$temporary_root/bin"
cat > "$temporary_root/bin/gh" <<'PYEOF'
#!/usr/bin/env python3
import json
import os
import sys

with open(os.environ["RECORDED_CALLS"], "a", encoding="utf-8") as handle:
json.dump(sys.argv[1:], handle)
handle.write("\n")

profile = next(
(argument.split("=", 1)[1] for argument in sys.argv[1:]
if argument.startswith("client_payload[profile]=")),
None,
)
if profile == os.environ.get("FAIL_PROFILE"):
sys.exit(17)
PYEOF
chmod +x "$temporary_root/bin/gh"

recorded="$temporary_root/calls.jsonl"
announce() {
PATH="$temporary_root/bin:$PATH" \
RECORDED_CALLS="$recorded" \
python3 "$repository_root/scripts/announce-builds.py" \
--profiles-file "$profiles" \
--repository vitasdk/autobuilds \
--revision 0123456789abcdef
}

announce
python3 - "$recorded" <<'PYEOF'
import json
import sys

calls = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]
expected_profiles = ["vita", "vita_softfp", "future_world"]
assert len(calls) == len(expected_profiles), calls
for call, profile in zip(calls, expected_profiles):
assert call == [
"api",
"repos/vitasdk/autobuilds/dispatches",
"-f",
"event_type=run_build",
"-f",
"client_payload[buildscripts_ref]=0123456789abcdef",
"-f",
f"client_payload[profile]={profile}",
], call
PYEOF

: > "$recorded"
if failure=$(FAIL_PROFILE=vita announce 2>&1); then
printf 'a failed profile dispatch did not fail the announcement\n' >&2
exit 1
fi
grep -q 'vita (exit 17)' <<< "$failure" || {
printf 'the failed dispatch was not identified: %s\n' "$failure" >&2
exit 1
}
python3 - "$recorded" <<'PYEOF'
import json
import sys

calls = [json.loads(line) for line in open(sys.argv[1], encoding="utf-8")]
profiles = [
next(argument.split("=", 1)[1] for argument in call
if argument.startswith("client_payload[profile]="))
for call in calls
]
assert profiles == ["vita", "vita_softfp", "future_world"], profiles
PYEOF

printf 'announce-builds: all checks passed\n'
44 changes: 44 additions & 0 deletions tests/ci/test-group-artifact-filter.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# A partial workflow rerun retains artifacts from earlier attempts. Grouping
# must consume only stage artifacts, never its own previous output.

set -euo pipefail

repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)

python3 - "$repository_root" <<'PY'
import fnmatch
import re
import sys

root = sys.argv[1]
text = open(f"{root}/.github/workflows/build-sdk.yml", encoding="utf-8").read()
group_match = re.search(
r"(?ms)^ group:\n(?P<body>.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", text
)
if group_match is None:
raise SystemExit("build-sdk.yml has no group job")
body = group_match.group("body")
downloads = list(
re.finditer(r"(?m)^ - uses: actions/download-artifact@[^\n]+$", body)
)
if len(downloads) != 1:
raise SystemExit(f"group job has {len(downloads)} artifact download steps, expected one")

step = body[downloads[0].start():]
next_step = re.search(r"(?m)^ - ", step[1:])
if next_step is not None:
step = step[: next_step.start() + 1]
pattern_match = re.search(r"(?m)^ pattern:\s*['\"]?([^'\"\n]+)['\"]?\s*$", step)
if pattern_match is None:
raise SystemExit("group artifact download has no filter and can ingest an earlier grouped-sdk-snapshot")
pattern = pattern_match.group(1).strip()

for artifact in ("stage1-host", "stage2-host", "stage3-host"):
if not fnmatch.fnmatchcase(artifact, pattern):
raise SystemExit(f"group artifact pattern {pattern!r} excludes {artifact!r}")
if fnmatch.fnmatchcase("grouped-sdk-snapshot", pattern):
raise SystemExit(f"group artifact pattern {pattern!r} re-ingests grouped-sdk-snapshot")
PY

printf 'group artifact filter contract passed\n'
Loading