diff --git a/.github/actions/input-default-probe/action.yml b/.github/actions/input-default-probe/action.yml new file mode 100644 index 0000000..12f4d42 --- /dev/null +++ b/.github/actions/input-default-probe/action.yml @@ -0,0 +1,31 @@ +name: 'Input default probe' +description: 'Fail unless the value input arrives as the caller expects: this repository''s own CI, holding how GitHub treats an input given as empty against a default.' + +# release-preflight defaults tag-prefix to v, and a repository whose tags have no prefix passes +# tag-prefix: '' to opt out. That works only if an input given as an empty string reaches the +# action empty, rather than falling back to its default, which GitHub does not document: its +# metadata syntax says only that a default is used when an input is not given. So the premerge +# job calls this probe both ways, and fails if either changes. +inputs: + value: + description: 'The value to check.' + required: false + default: 'v' + expected: + description: 'What value should be once GitHub has applied, or not applied, its default.' + required: true + +runs: + using: composite + steps: + - name: The value arrived as expected + shell: bash + env: + VALUE: ${{ inputs.value }} + EXPECTED: ${{ inputs.expected }} + run: | + if [ "$VALUE" != "$EXPECTED" ]; then + echo "::error::input-default-probe: the value input arrived as '$VALUE', but '$EXPECTED' was expected, so GitHub now treats an input given as empty differently from how release-preflight's tag-prefix relies on" >&2 + exit 1 + fi + echo "input-default-probe: the value input arrived as '$VALUE', as expected" diff --git a/.github/workflows/premerge.yaml b/.github/workflows/premerge.yaml index aab8d05..f2e8f9a 100644 --- a/.github/workflows/premerge.yaml +++ b/.github/workflows/premerge.yaml @@ -50,8 +50,9 @@ jobs: shared-behaviour: # What the Slack workflows do on a refusal, a fork or a draft cannot be made to happen from a - # pull request here, and the action-pins check needs references this repository does not - # contain, so both are run against stand-ins and sample input instead. + # pull request here, the action-pins check needs references this repository does not + # contain, and apt-install's retries need a mirror that fails, so each is run against + # stand-ins and sample input instead. runs-on: [ubuntu-latest] name: Shared workflows and actions behave timeout-minutes: 5 @@ -67,3 +68,65 @@ jobs: - name: Tests pass run: uvx --with pyyaml==6.0.3 pytest==8.3.5 -p no:cacheprovider -q tests + + apt-install: + # This repository's own action, from this commit, on a runner: what the tests' stand-ins + # cannot show - real apt, the archive directory's ownership, and the cache. Two calls in one + # job, the second with its packages one to a line, each keeping its own files. + runs-on: [ubuntu-latest] + name: apt-install installs + timeout-minutes: 15 + steps: + - name: Check out source repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install one package + id: first + uses: ./actions/apt-install + with: + packages: sl + + - name: Install another, one to a line + uses: ./actions/apt-install + with: + packages: | + figlet + + - name: Both are installed, and each call kept its own files + run: | + dpkg -s sl figlet >/dev/null + shopt -s nullglob + for package in sl figlet; do + files=(/var/cache/apt/apt-install/*/"${package}"_*.deb) + if (( ${#files[@]} != 1 )); then + echo "::error::expected one cached ${package} file, found ${#files[@]}: ${files[*]}" >&2 + exit 1 + fi + done + dirs=(/var/cache/apt/apt-install/*/) + if (( ${#dirs[@]} != 2 )); then + echo "::error::expected an archive directory per call, found ${#dirs[@]}: ${dirs[*]}" >&2 + exit 1 + fi + + input-defaults: + # release-preflight's tag-prefix defaults to v, and a repository with bare tags opts out by + # passing ''. GitHub does not document that an input given as empty overrides a default, so + # this holds it, from this repository's own CI, before any release relies on it. + runs-on: [ubuntu-latest] + name: An input given as empty overrides its default + timeout-minutes: 5 + steps: + - name: Check out source repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Not given, the default applies + uses: ./.github/actions/input-default-probe + with: + expected: v + + - name: Given as empty, it stays empty + uses: ./.github/actions/input-default-probe + with: + value: '' + expected: '' diff --git a/.github/workflows/release-cancelled.yaml b/.github/workflows/release-cancelled.yaml new file mode 100644 index 0000000..fc40a88 --- /dev/null +++ b/.github/workflows/release-cancelled.yaml @@ -0,0 +1,40 @@ +name: 'Report a cancelled release as a failure' + +# A job killed by its timeout-minutes ends as cancelled, not failed, so GitHub raises no +# failure notification for it, and a release that never finished reads as a cancellation. A +# release runs unattended when it is published, so the caller's release workflow ends with a +# job calling this one when its last job was cancelled, and this one fails, so the run reports: +# +# report-cancelled: +# needs: [build-and-release] +# if: always() && needs.build-and-release.result == 'cancelled' +# uses: L337-org/github-workflows/.github/workflows/release-cancelled.yaml@v2 +# with: +# job: build-and-release +# +# Only a release workflow, which nothing supersedes: in one whose runs cancel each other, a +# superseded run would be reported too. + +on: + workflow_call: + inputs: + job: + description: 'The job that was cancelled, as the caller names it, to say which in the error.' + required: true + type: string + +permissions: {} + +jobs: + fail: + name: Fail the run, because a cancellation would not notify + runs-on: [ubuntu-latest] + # Only has to bound runner startup: this job writes an error and exits. + timeout-minutes: 5 + steps: + - name: Fail + env: + JOB: ${{ inputs.job }} + run: | + echo "::error::The $JOB job ended as cancelled, which is what its timeout-minutes produces, so this run fails: the release did not finish, and a cancellation would not have said so" >&2 + exit 1 diff --git a/README.md b/README.md index c38bb76..dc73f13 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ without a pull request in each. See [Versions and releases](#versions-and-relea |---|---|---| | `actions/repo-hygiene` | Composite action: the conventions every repository shares - no internal references, every CI job bounded, every failed run reported, every Slack post given a channel, the instruction layer intact, the detail layer routed. | a step, after `actions/checkout` | | `actions/action-pins` | Composite action: every `uses:` names a 40-hex commit SHA, or a version tag of this repository. | a step, after `actions/checkout` | +| `actions/release-preflight` | Composite action: fails a release that is not this organisation's, whose tag is not the declared version, or whose major version is 0 and is not marked pre-release. | a step, first in a workflow triggered by `release` | +| `actions/release-attach` | Composite action: attaches built files to the release, replacing any an earlier failed run left, then checks the release serves each as built. | a step, with `files:` | +| `.github/workflows/release-cancelled.yaml` | Reusable workflow: fails the run when a release workflow's job was cancelled, as its timeout does, so the release reports. | a job with `uses:`, after the release's last job | +| `actions/apt-install` | Composite action: installs packages from the runner image's apt sources, with the downloaded files cached and checked against the signed index, and each apt call bounded and retried. | a step, with `packages:` | | `.github/workflows/claude-review.yaml` | Reusable workflow: a code review by Claude, full on the first round and a delta of the new commits after that. | a job with `uses:` | | `.github/workflows/slack-on-failure.yaml` | Reusable workflow: posts a failed run to Slack, naming the workflow and its failed jobs and linking the run. | a job with `uses:`, in a workflow triggered by `workflow_run` | | `.github/workflows/slack-on-pull-request.yaml` | Reusable workflow: posts a pull request that needs action to Slack - opened, reopened, or marked ready for review - and nothing else about it. | a job with `uses:`, in a workflow triggered by `pull_request` | @@ -37,6 +41,84 @@ A job that calls a reusable workflow cannot declare `timeout-minutes`; the calle jobs carry the bound. The hygiene check cannot see those jobs from the calling repository, so it reports such a call as not checked rather than failing or passing it. +## Installing from apt + +```yaml + - name: Install the musl C toolchain and lintian + uses: L337-org/github-workflows/actions/apt-install@v2 + with: + packages: musl-tools lintian +``` + +- **Retried, and bounded.** An Ubuntu mirror can refuse a download for a moment, hang, or list + a package version its pool does not hold yet. Each apt call has a timeout and apt's own + download retries, a failed install reads the package lists again before trying again, and the + whole is tried five times, 15 seconds apart, before the step fails naming what it was doing and + how the last attempt ended. `retry.sh` beside the action says which failure each part answers. + The job's `timeout-minutes` is still the bound over all of it. +- **Cached, never changed.** The downloaded `.deb` files are cached under a key naming each + package, version and architecture apt is about to install, so the cache changes how fast a + package arrives, never which version. Each restored file is checked against the SHA-256 the + signed index lists before it is installed, since apt checks only a cached file's size. +- **On the runner only.** It runs `sudo apt-get` on the runner image. An install inside a + container the job starts, such as `docker run debian:12`, cannot call an action and is not + covered. + +## Releasing + +A release workflow, triggered by `release: published`, checks the release first, builds, then +attaches what it built, and fails if a job was cancelled: + +```yaml +jobs: + build-and-release: + runs-on: [ubuntu-latest] + timeout-minutes: 20 + permissions: + contents: write + steps: + - uses: actions/checkout@ # vX.Y.Z + - name: Read the declared version + id: version + run: echo "version=$(scripts/version)" >>"$GITHUB_OUTPUT" + - uses: L337-org/github-workflows/actions/release-preflight@v2 + with: + version: ${{ steps.version.outputs.version }} + - name: Build + run: scripts/build-deb + - uses: L337-org/github-workflows/actions/release-attach@v2 + with: + files: dist/*.deb + + report-cancelled: + needs: [build-and-release] + if: always() && needs.build-and-release.result == 'cancelled' + uses: L337-org/github-workflows/.github/workflows/release-cancelled.yaml@v2 + with: + job: build-and-release +``` + +- **The tag is the declared version, as text.** Versions are compared as each repository writes + them, three parts or two, never parsed, after the `tag-prefix` the repository tags with: `v` + by default, as new repositories tag `v1.2.3`. One that tags the bare version, as in `6.2`, + passes `tag-prefix: ''`. Each repository only has to be consistent with its own history. + GitHub documents a default only for an input not given, so that one given as empty overrides + it is held by this repository's `input-defaults` premerge job. +- **A major version of 0 is always a pre-release.** Preflight fails such a release unless it is + marked pre-release, read from the release when the step runs, so ticking the flag and + re-running is enough. +- **A file already on the release is replaced.** Preflight lets through only releases that + should be built, so a file of the same name means an earlier run of this release failed after + attaching it, and this run is recovering: one identical to the build is left as it is, and + anything else, an unfinished upload included, is deleted and uploaded again, with a warning. +- **What the release serves is checked.** Each file is read back from the release and compared + with the build, rather than trusting the upload's exit status. +- **`files:` takes whitespace-separated paths**, and a shell glob in it is expanded by the + step's shell, so `dist/*.deb` works. Every file must exist before any is attached. +- **A cancelled job fails the run.** A job killed by its `timeout-minutes` ends as cancelled, + which raises no failure notification, so `release-cancelled` turns it into a failure. Use it + only where nothing supersedes a run, as in a release workflow with no `concurrency` group. + ## The Claude review The caller decides when a review runs and who may ask for one; this workflow decides how it @@ -290,8 +372,10 @@ Each release also gets its full tag, such as `v2.0.0`, which never moves. Everything here runs in other repositories' CI, so a change reaches them as soon as its release moves the major tag. This repository's own CI runs the action-pins action from the commit under review, lints every workflow and action with actionlint, runs the Slack workflows' and the Claude -review's posting steps against stand-ins for `curl` and `gh`, and the action-pins check over -sample references (`tests/`), and reviews each pull request with the pull request's own version +review's posting steps against stand-ins for `curl` and `gh`, the action-pins check over +sample references, apt-install's retries against stand-ins for apt, and the release actions +against a fake release (`tests/`), runs +apt-install itself on a runner, and reviews each pull request with the pull request's own version of the Claude review, so a change to the review reviews itself. The hygiene check does not run on this repository: it expects the instruction layer and detail layer of a product repository, which this one does not have. diff --git a/actions/apt-install/action.yml b/actions/apt-install/action.yml new file mode 100644 index 0000000..e23b179 --- /dev/null +++ b/actions/apt-install/action.yml @@ -0,0 +1,151 @@ +name: 'Install apt packages' +description: 'Install packages from the runner image''s apt sources, with the downloaded package files cached, and each apt call bounded and retried.' + +# A job that installs from apt does it with this action, so a slow Ubuntu mirror costs a cache +# restore rather than the download, and a mirror that refuses, hangs or serves a stale index +# costs a retry rather than the job. How each call is bounded and retried, and why, is in +# retry.sh beside this file. The cache holds only the .deb files: apt still reads the +# package lists from the mirror, and installs the versions they name, so what is installed is +# what an uncached install would get. +# +# The key is what apt is about to install - each package, version and architecture, from a +# simulated install - so an update published to the mirror makes a new key, and the files it +# brings are saved, rather than downloaded again on every run. The prefix restore brings back +# an older entry's files for what has not changed, and the rest are deleted unused. +# +# Each call downloads into an archive directory of its own, named for the packages it was asked +# for, not apt's shared one. The cache saves a directory's files when the job ends, so in a +# shared one a later call in the same job would delete an earlier call's files as unused, and +# the earlier call's entry would be saved holding the later call's files, useless on every run +# after. It also keeps the files out of reach of an image's hooks that empty apt's own. +# +# apt checks only the size of a file already in its archive directory, not its content: it +# hands a file of the right size to dpkg as it finds it. So before installing, each restored +# file is checked against the SHA-256 the signed index lists for its package, version and +# architecture, and deleted if it does not match, which leaves a cached file held to the same +# check as a downloaded one. +inputs: + packages: + description: 'The packages to install, separated by any whitespace, so one to a line in a YAML block scalar works too.' + required: true + +runs: + using: composite + steps: + - name: Read the package lists, and name what apt will install + id: plan + shell: bash + # Through the environment rather than interpolated into the script, so the package names + # are data to the shell, never code. + env: + PACKAGES: ${{ inputs.packages }} + run: | + # shellcheck source=/dev/null + source "$GITHUB_ACTION_PATH/retry.sh" + read -ra packages -d '' <<<"$PACKAGES" || true + if (( ${#packages[@]} == 0 )); then + echo "::error::apt-install: the packages input names no package" >&2 + exit 1 + fi + # Named for the packages asked for, sorted, so the same list in any order or layout + # shares a directory and a cache entry, and a long list cannot reach the key's limit. + names="$(printf '%s\n' "${packages[@]}" | sort -u | sha256sum | cut -c1-16)" + # APT_INSTALL_ROOT is for the tests, which cannot write under /var/cache. + archives="${APT_INSTALL_ROOT:-/var/cache/apt/apt-install}/$names" + plan="$RUNNER_TEMP/apt-install-plan-$names" + # The runner's, so the cache can restore into it; apt downloads into partial/ as its own + # unprivileged user where there is one. + sudo mkdir -p "$archives/partial" + sudo chown "$USER" "$archives" + if id _apt >/dev/null 2>&1; then + sudo chown _apt "$archives/partial" + fi + apt_retry "reading the package lists" apt_update_once + simulated="$(apt-get -s install --no-install-recommends "${packages[@]}")" + # An Inst line reads `Inst NAME [OLD] (VERSION ORIGIN... [ARCH])`, sometimes followed by a + # bracketed list, ` []`; kept as NAME VERSION ARCH, which is how an archive file is named. + sed -nE 's/^Inst ([^ ]+) (\[[^]]*\] )?\(([^ ]+) .*\[([^] ]+)\]\)( \[[^]]*\])?$/\1 \3 \4/p' <<<"$simulated" \ + | sort >"$plan" + # A line the pattern misses, say from a new apt's output, would leave its file unchecked + # and deleted as unused, and every run would download it, all without failing. + inst="$(grep -c '^Inst ' <<<"$simulated" || true)" + planned="$(wc -l <"$plan")" + if (( inst != planned )); then + echo "::error::apt-install: apt's simulated install has $inst Inst lines, but only $planned read as NAME VERSION ARCH, so its output format has changed; the lines were:" + grep '^Inst ' <<<"$simulated" + exit 1 + fi + echo "apt-install: apt will install $planned packages" + # The key once, here, so the restore and the warning that names it cannot differ. + prefix="apt-$RUNNER_ARCH-$names-" + { + echo "archives=$archives" + echo "plan=$plan" + echo "prefix=$prefix" + echo "key=$prefix$(sha256sum "$plan" | cut -c1-16)" + } >>"$GITHUB_OUTPUT" + + - name: Restore the downloaded packages + id: restore + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ steps.plan.outputs.archives }}/*.deb + key: ${{ steps.plan.outputs.key }} + restore-keys: | + ${{ steps.plan.outputs.prefix }} + + - name: Install + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + KEY: ${{ steps.plan.outputs.key }} + HIT: ${{ steps.restore.outputs.cache-hit }} + APT_ARCHIVES: ${{ steps.plan.outputs.archives }} + PLAN: ${{ steps.plan.outputs.plan }} + run: | + read -ra packages -d '' <<<"$PACKAGES" || true + # shellcheck source=/dev/null + source "$GITHUB_ACTION_PATH/retry.sh" + + shopt -s nullglob + kept=0 unused=0 + for deb in "$APT_ARCHIVES"/*.deb; do + name="$(basename "$deb" .deb)" + IFS=_ read -r package version arch <<<"$name" + version="${version//%3a/:}" + if ! grep -qxF "$package $version $arch" "$PLAN"; then + # Routine: an older entry's file for a version apt no longer installs. + rm -f "$deb" + unused=$((unused + 1)) + continue + fi + actual="$(sha256sum "$deb" | cut -d' ' -f1)" + # Read whole before searching: grep -q stops at its match, and under pipefail + # apt-cache's broken pipe would then count as no match. + listed="$(apt-cache show "$package:$arch=$version" | sed -n 's/^SHA256: //p')" + if grep -qxF "$actual" <<<"$listed"; then + kept=$((kept + 1)) + else + # apt resolved this exact version, so the index lists it: a different hash means + # the cached file is not the one the index signs for. An entry is never + # overwritten, so after an exact hit only deleting it stops this recurring. + case "$HIT" in + true) repair="this key's entry was restored exactly and is never overwritten, so delete it, with a token that has actions: write: gh cache delete $(printf %q "$KEY")" ;; + false) repair="it came from an older entry, so this job saves the good copy apt downloads under $(printf %q "$KEY") when it succeeds" ;; + *) repair="the cache step reported no result, so whether $(printf %q "$KEY") is saved is unknown: check its post step" ;; + esac + echo "::warning::apt-install: deleting cached $(printf %q "$name.deb"): its SHA-256 is $actual, but the index lists $(tr '\n' ' ' <<<"$listed")for $package $version $arch; $repair" + rm -f "$deb" + fi + done + echo "apt-install: $kept cached package files match the index; $unused older ones deleted unused" + + apt_retry "installing ${packages[*]}" apt_install_once "${packages[@]}" + + # The cache saves what is left here, so an image that deletes downloaded packages would + # leave nothing to save and every run would download again, unnoticed. A warning, not a + # failure: it also happens, rightly, when the image already has every package. + debs=("$APT_ARCHIVES"/*.deb) + if (( ${#debs[@]} == 0 )); then + echo "::warning::apt-install: no package file is left in $APT_ARCHIVES, so nothing will be cached: either the image has every package already, or its apt configuration deletes downloads (APT::Keep-Downloaded-Packages)" + fi diff --git a/actions/apt-install/retry.sh b/actions/apt-install/retry.sh new file mode 100644 index 0000000..bc47925 --- /dev/null +++ b/actions/apt-install/retry.sh @@ -0,0 +1,60 @@ +# shellcheck shell=bash +# Sourced by the apt-install action's steps, and by its tests: apt's two calls, each bounded and +# retried. +# +# A mirror fails in three ways: it refuses a download for a moment, which apt's own +# Acquire::Retries covers within one call; it hangs, which only a timeout ends, since nothing +# else bounds a call inside a composite action; and its index names a package version the pool +# does not hold yet, which no retry of the download fixes, only reading the index again once the +# pool has caught up. So each call +# has a timeout and apt's own retries, a failed install reads the index again, and the whole is +# tried APT_ATTEMPTS times, APT_DELAY seconds apart. The job's own timeout-minutes stays the +# backstop over all of it. + +APT_ATTEMPTS=5 +APT_DELAY=15 +APT_UPDATE_SECONDS=300 +APT_INSTALL_SECONDS=900 + +# Reads the package lists, once, bounded. +apt_update_once() { + sudo timeout "$APT_UPDATE_SECONDS" apt-get -o Acquire::Retries=3 update +} + +# Installs the packages named, once, bounded, downloading into APT_ARCHIVES where it is set; +# after a failure, reads the package lists again for the next attempt, since a stale index is +# one cause a retry of the download cannot fix. +apt_install_once() { + local status=0 archives=() + if [ -n "${APT_ARCHIVES:-}" ]; then + archives=(-o "Dir::Cache::archives=$APT_ARCHIVES/") + fi + sudo timeout "$APT_INSTALL_SECONDS" apt-get -o Acquire::Retries=3 "${archives[@]}" install -y \ + --no-install-recommends "$@" || status=$? + if ((status != 0)); then + apt_update_once || true + fi + return "$status" +} + +# Runs the command after WHAT until it succeeds, APT_ATTEMPTS times at most, and fails with the +# last attempt's status, saying what was being done. Exit status 124 is a timeout. +apt_retry() { + local what=$1 + shift + local attempt=1 status + while true; do + status=0 + "$@" || status=$? + if ((status == 0)); then + return 0 + fi + if ((attempt >= APT_ATTEMPTS)); then + echo "::error::apt-install: $what failed on all $APT_ATTEMPTS attempts; the last exited $status$( ((status == 124)) && echo ', a timeout' ), and apt's output above says why" >&2 + return "$status" + fi + echo "::warning::apt-install: $what failed with exit $status$( ((status == 124)) && echo ', a timeout,' ) on attempt $attempt of $APT_ATTEMPTS; trying again in ${APT_DELAY}s" + sleep "$APT_DELAY" + attempt=$((attempt + 1)) + done +} diff --git a/actions/release-attach/action.yml b/actions/release-attach/action.yml new file mode 100644 index 0000000..06a4764 --- /dev/null +++ b/actions/release-attach/action.yml @@ -0,0 +1,128 @@ +name: 'Attach files to a release' +description: 'Attach built files to the release that started the run, replacing any of the same name a failed earlier run left, then check the release serves each one as built.' + +# The one place a release's files are put on it, so publishing them somewhere else as well - a +# package repository that is pushed to, say, rather than one that pulls - is a change here. +# +# A file of the same name already on the release means an earlier run of this release got that +# far and then failed, since preflight refuses anything else. The run is recovering from that, +# so the file is replaced: one identical to the build is left as it is, and anything else - +# different bytes, or an upload that never finished - is deleted and uploaded again, with a +# warning naming it. +# +# What the release serves is read back afterwards and compared byte for byte with the build, +# rather than inferred from the upload's exit status. +inputs: + files: + description: 'The files to attach, separated by any whitespace; each may be a glob, such as dist/*.deb. Each is attached under its own name, which cannot hold whitespace.' + required: true + release-id: + description: 'The release to attach them to. The one that started the run by default.' + required: false + default: ${{ github.event.release.id }} + token: + description: 'A token that can write to the release: the job needs contents: write.' + required: false + default: ${{ github.token }} + +runs: + using: composite + steps: + - name: Attach each file, then check the release serves it as built + shell: bash + env: + FILES: ${{ inputs.files }} + RELEASE_ID: ${{ inputs.release-id }} + REPO: ${{ github.repository }} + GH_TOKEN: ${{ inputs.token }} + run: | + words=() + read -ra words -d '' <<<"$FILES" || true + # Each word is a path or a glob, expanded here; one matching nothing is kept as written, + # so the check below names it. + files=() + for word in "${words[@]}"; do + shopt -s nullglob + # shellcheck disable=SC2206 + matches=($word) + shopt -u nullglob + if (( ${#matches[@]} == 0 )); then files+=("$word"); else files+=("${matches[@]}"); fi + done + if (( ${#files[@]} == 0 )); then + echo "::error::release-attach: the files input names no file" >&2 + exit 1 + fi + if [ -z "$RELEASE_ID" ]; then + echo "::error::release-attach: no release to attach to: this run was not started by a release, and no release-id was given" >&2 + exit 1 + fi + # Every file is checked before any is attached, so a missing one leaves the release as + # it was rather than half-attached. + for file in "${files[@]}"; do + if [ ! -f "$file" ]; then + echo "::error::release-attach: $(printf %q "$file") does not exist, so nothing is attached; the step that builds it says why" >&2 + exit 1 + fi + done + + list() { + gh api "repos/$REPO/releases/$RELEASE_ID/assets" --paginate --jq '.[] | "\(.id) \(.name) \(.state)"' + } + fetch() { + gh api -H "Accept: application/octet-stream" "repos/$REPO/releases/assets/$1" >"$2" + } + + assets="$(list)" + for file in "${files[@]}"; do + name="$(basename "$file")" + id="" state="" + read -r id _ state <<<"$(awk -v n="$name" '$2 == n' <<<"$assets")" || true + if [ -n "${id:-}" ]; then + if [ "$state" = uploaded ]; then + fetch "$id" "$RUNNER_TEMP/release-attach-existing" + if cmp -s "$file" "$RUNNER_TEMP/release-attach-existing"; then + echo "release-attach: $name is already attached and identical; left as it is" + continue + fi + echo "::warning::release-attach: $name is already attached and differs from this build, so an earlier run of this release attached a different build; replacing it" + else + echo "::warning::release-attach: $name is already on the release as an upload that never finished ($state), left by an earlier run; replacing it" + fi + gh api --method DELETE "repos/$REPO/releases/assets/$id" >/dev/null + fi + # Encoded, so a name holding & # or % reaches GitHub as one parameter. + encoded="$(jq -rn --arg n "$name" '$n | @uri')" + case "$name" in + *.deb) type=application/vnd.debian.binary-package ;; + *) type=application/octet-stream ;; + esac + # GitHub's response is kept, because on a refusal its body is what says why. + if ! curl --fail-with-body --silent --show-error --max-time 300 \ + -H "Authorization: Bearer $GH_TOKEN" \ + -H "Accept: application/vnd.github+json" \ + -H "Content-Type: $type" \ + --data-binary "@$file" \ + --output "$RUNNER_TEMP/release-attach-upload.json" \ + "https://uploads.github.com/repos/$REPO/releases/$RELEASE_ID/assets?name=$encoded"; then + echo "::error::release-attach: uploading $name to release $RELEASE_ID failed; GitHub said: $(cat "$RUNNER_TEMP/release-attach-upload.json" 2>/dev/null)" >&2 + exit 1 + fi + echo "release-attach: $name attached, sha256 $(sha256sum <"$file" | cut -d' ' -f1)" + done + + assets="$(list)" + for file in "${files[@]}"; do + name="$(basename "$file")" + id="" state="" + read -r id _ state <<<"$(awk -v n="$name" '$2 == n' <<<"$assets")" || true + if [ -z "${id:-}" ] || [ "$state" != uploaded ]; then + echo "::error::release-attach: release $RELEASE_ID does not serve $name after attaching it" >&2 + exit 1 + fi + fetch "$id" "$RUNNER_TEMP/release-attach-served" + if ! cmp -s "$file" "$RUNNER_TEMP/release-attach-served"; then + echo "::error::release-attach: release $RELEASE_ID serves a $name that differs from the one built" >&2 + exit 1 + fi + echo "release-attach: $name served as built" + done diff --git a/actions/release-preflight/action.yml b/actions/release-preflight/action.yml new file mode 100644 index 0000000..34ff68e --- /dev/null +++ b/actions/release-preflight/action.yml @@ -0,0 +1,73 @@ +name: 'Release preflight' +description: 'Fail a release that is not this organisation''s, whose tag does not name the version the repository declares, or whose major version is 0 and that is not marked pre-release.' + +# Run first in a workflow triggered by `release: published`, so nothing is built for a release +# that should not have been published. +# +# - The repository's owner must be L337-org, so a fork's copy of the workflow builds nothing. +# - The tag must be the declared version exactly, after the prefix the repository tags with: +# versions are compared as text, never parsed, since repositories write them differently, +# three parts or two. The prefix is for people, saying the tag is a version, not part of the +# version itself; a repository's tags only need to be consistent with each other, so each says +# which it uses. The default is v, what new repositories use; one with bare tags passes an +# empty string. GitHub documents a default only for an input not given, so that an input +# given as empty overrides it is held by this repository's input-defaults premerge job. +# - A major version of 0 is always for trying out, so its release must be marked pre-release, +# which keeps it off anything a user might install from by accident. Read from the release +# now, not from the event, because a re-run replays the original event: ticking the flag and +# re-running is then enough. +inputs: + version: + description: 'The version the repository declares, as it writes it, such as 1.2.3 or 6.2.' + required: true + tag-prefix: + description: 'What the repository puts before the version in a release tag: v by default, as in v1.2.3. A repository that tags the bare version, as in 6.2, passes an empty string.' + required: false + default: 'v' + token: + description: 'A token that can read the release.' + required: false + default: ${{ github.token }} + +runs: + using: composite + steps: + - name: The release is this organisation's, and its tag names the declared version + shell: bash + env: + EVENT: ${{ github.event_name }} + OWNER: ${{ github.repository_owner }} + REPO: ${{ github.repository }} + TAG: ${{ github.event.release.tag_name }} + RELEASE_ID: ${{ github.event.release.id }} + VERSION: ${{ inputs.version }} + PREFIX: ${{ inputs.tag-prefix }} + GH_TOKEN: ${{ inputs.token }} + run: | + if [ "$EVENT" != release ]; then + echo "::error::release-preflight: checks a release, but this run was started by '$EVENT', so there is no release to check" >&2 + exit 1 + fi + if [ "$OWNER" != "L337-org" ]; then + echo "::error::release-preflight: this release was published from repository owner '$OWNER', not L337-org, so nothing is built" >&2 + exit 1 + fi + if [ -z "$VERSION" ]; then + echo "::error::release-preflight: the version input is empty, so the tag '$TAG' cannot be checked against it; pass the version the repository declares" >&2 + exit 1 + fi + if [ "$TAG" != "$PREFIX$VERSION" ]; then + echo "::error::release-preflight: the release's tag is '$TAG', but the repository declares $VERSION, so the tag must be '$PREFIX$VERSION'" >&2 + exit 1 + fi + if [ "${VERSION%%.*}" = 0 ]; then + if ! prerelease="$(gh api "repos/$REPO/releases/$RELEASE_ID" --jq .prerelease)"; then + echo "::error::release-preflight: could not read release $RELEASE_ID of $REPO to see whether it is marked pre-release; gh's error is above" >&2 + exit 1 + fi + if [ "$prerelease" != true ]; then + echo "::error::release-preflight: $VERSION has a major version of 0, so its release must be marked as a pre-release; edit release $RELEASE_ID, tick pre-release, and re-run this workflow" >&2 + exit 1 + fi + fi + echo "release-preflight: releasing $VERSION, tagged $TAG, from $GITHUB_SHA" diff --git a/tests/test_apt_install.py b/tests/test_apt_install.py new file mode 100644 index 0000000..45f8e16 --- /dev/null +++ b/tests/test_apt_install.py @@ -0,0 +1,269 @@ +"""Behaviour of the apt-install action's retries. + +`retry.sh` is sourced as it ships, and the action's steps are read out of `action.yml`, and all +are run under bash as GitHub runs a composite step, with `-e` and `pipefail`, against stand-ins +for `sudo`, `timeout`, `sleep`, `apt-get` and `apt-cache` on PATH. Each stand-in records its +call. What this cannot test, and the premerge job that runs the action on a runner does: a real +mirror and apt, the ownership of the archive directory, and the cache. +""" + +import hashlib +import os +import pathlib +import stat +import subprocess +import textwrap + +import pytest +import yaml + +ROOT = pathlib.Path(__file__).resolve().parent.parent +ACTION = ROOT / "actions" / "apt-install" + +# Fails its first STUB__FAILS calls of a subcommand with STUB_STATUS, then succeeds; +# a simulated install prints an Inst line for each package. +APT_GET = textwrap.dedent("""\ + #!/usr/bin/env bash + sub="" simulate=0 packages=() + for arg in "$@"; do + case "$arg" in + -s) simulate=1 ;; + -o|-y|-q|--no-install-recommends|Acquire::*) ;; + update|install) [ -z "$sub" ] && sub="$arg" || packages+=("$arg") ;; + *) [ -n "$sub" ] && packages+=("$arg") ;; + esac + done + if [ "$simulate" = 1 ]; then + for p in "${packages[@]}"; do echo "Inst $p (1.0-1 Ubuntu:24.04/noble [amd64])"; done + exit 0 + fi + echo "apt-get $*" >> "$STUB_DIR/calls" + count_file="$STUB_DIR/$sub.count" + count=$(( $(cat "$count_file" 2>/dev/null || echo 0) + 1 )) + echo "$count" > "$count_file" + fails_var="STUB_${sub^^}_FAILS" + if [ "$count" -le "${!fails_var:-0}" ]; then + exit "${STUB_STATUS:-100}" + fi +""") + +# Ownership needs root, which a test does not have: recorded, not changed. +SUDO = textwrap.dedent("""\ + #!/usr/bin/env bash + if [ "$1" = chown ]; then echo "sudo $*" >> "$STUB_DIR/calls"; exit 0; fi + exec "$@" +""") + +# The index's SHA-256 for PACKAGE:ARCH=VERSION, from the file the test wrote for it. +APT_CACHE = textwrap.dedent("""\ + #!/usr/bin/env bash + printf 'Package: x\\nSHA256: %s\\n' "$(cat "$STUB_DIR/sha/$2")" +""") +TIMEOUT = '#!/usr/bin/env bash\necho "timeout $1" >> "$STUB_DIR/calls"\nshift\nexec "$@"\n' +SLEEP = '#!/usr/bin/env bash\necho "sleep $1" >> "$STUB_DIR/calls"\n' + + +@pytest.fixture +def stubs(tmp_path): + stand_ins = ( + ("apt-get", APT_GET), ("apt-cache", APT_CACHE), ("sudo", SUDO), ("timeout", TIMEOUT), + ("sleep", SLEEP), + ) + for name, body in stand_ins: + path = tmp_path / name + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return tmp_path + + +def bash(script, stubs, **env): + full = { + "PATH": f"{stubs}:{os.environ['PATH']}", + "STUB_DIR": str(stubs), + "GITHUB_ACTION_PATH": str(ACTION), + "RUNNER_TEMP": str(stubs), + "RUNNER_ARCH": "X64", + "GITHUB_OUTPUT": str(stubs / "output"), + "APT_INSTALL_ROOT": str(stubs / "archives"), + "USER": "runner", + **{k: str(v) for k, v in env.items()}, + } + result = subprocess.run( + ["bash", "--noprofile", "--norc", "-eo", "pipefail", "-c", script], + env=full, capture_output=True, text=True, timeout=30, + ) + calls = (stubs / "calls").read_text().splitlines() if (stubs / "calls").exists() else [] + return result, calls + + +def install(stubs, **env): + script = f'source "{ACTION}/retry.sh"\napt_retry "installing a b" apt_install_once a b\n' + return bash(script, stubs, **env) + + +def step(name): + document = yaml.safe_load((ACTION / "action.yml").read_text()) + (found,) = [s for s in document["runs"]["steps"] if s.get("name") == name] + return found["run"] + + +PLAN = "Read the package lists, and name what apt will install" + + +def outputs(stubs): + return dict(line.split("=", 1) for line in (stubs / "output").read_text().splitlines()) + + +def test_every_call_is_bounded_and_retries_its_downloads(stubs): + result, calls = install(stubs) + assert result.returncode == 0, result.stderr + assert calls == [ + "timeout 900", + "apt-get -o Acquire::Retries=3 install -y --no-install-recommends a b", + ] + + +def test_a_failed_install_reads_the_lists_again_and_is_tried_again(stubs): + # The stale index: a fresh read of the lists is what lets the next attempt succeed. + result, calls = install(stubs, STUB_INSTALL_FAILS=2, STUB_STATUS=100) + assert result.returncode == 0, result.stderr + assert [c for c in calls if not c.startswith("timeout")] == [ + "apt-get -o Acquire::Retries=3 install -y --no-install-recommends a b", + "apt-get -o Acquire::Retries=3 update", + "sleep 15", + "apt-get -o Acquire::Retries=3 install -y --no-install-recommends a b", + "apt-get -o Acquire::Retries=3 update", + "sleep 15", + "apt-get -o Acquire::Retries=3 install -y --no-install-recommends a b", + ] + assert "installing a b failed with exit 100 on attempt 1 of 5; trying again in 15s" in result.stdout + assert "on attempt 2 of 5" in result.stdout + + +def test_an_install_failing_every_attempt_fails_saying_what_and_how(stubs): + result, calls = install(stubs, STUB_INSTALL_FAILS=99, STUB_STATUS=100) + assert result.returncode == 100 + assert calls.count("apt-get -o Acquire::Retries=3 install -y --no-install-recommends a b") == 5 + # No wait after the last attempt. + assert calls.count("sleep 15") == 4 + assert result.stderr.strip() == ( + "::error::apt-install: installing a b failed on all 5 attempts; the last exited 100, " + "and apt's output above says why" + ) + + +def test_a_timeout_is_named_as_one(stubs): + result, _ = install(stubs, STUB_INSTALL_FAILS=99, STUB_STATUS=124) + assert result.returncode == 124 + assert "the last exited 124, a timeout, and" in result.stderr + assert "failed with exit 124, a timeout, on attempt 1 of 5" in result.stdout + + +def test_a_read_of_the_lists_that_fails_does_not_end_an_attempt_early(stubs): + # The re-read after a failed install is best effort: the install's own status decides. + result, _ = install(stubs, STUB_INSTALL_FAILS=1, STUB_UPDATE_FAILS=99) + assert result.returncode == 0, result.stderr + + +def test_the_plan_step_retries_reading_the_lists(stubs): + result, calls = bash(step(PLAN), stubs, STUB_UPDATE_FAILS=2, PACKAGES="musl-tools lintian") + assert result.returncode == 0, result.stderr + assert calls.count("apt-get -o Acquire::Retries=3 update") == 3 + assert "reading the package lists failed with exit 100 on attempt 2 of 5" in result.stdout + found = outputs(stubs) + assert pathlib.Path(found["plan"]).read_text() == "lintian 1.0-1 amd64\nmusl-tools 1.0-1 amd64\n" + assert found["key"].startswith(found["prefix"]) + + +def test_the_plan_step_fails_when_the_lists_cannot_be_read(stubs): + result, _ = bash(step(PLAN), stubs, STUB_UPDATE_FAILS=99, PACKAGES="lintian") + assert result.returncode == 100 + assert "reading the package lists failed on all 5 attempts" in result.stderr + assert not list(stubs.glob("apt-install-plan-*")) + + +def test_packages_one_to_a_line_are_the_same_as_on_one(stubs, tmp_path_factory): + # A YAML block scalar gives them one to a line, with a trailing line break. + result, _ = bash(step(PLAN), stubs, PACKAGES="musl-tools\nlintian\n") + assert result.returncode == 0, result.stderr + lines = outputs(stubs) + other = tmp_path_factory.mktemp("other") + for name in ("apt-get", "apt-cache", "sudo", "timeout", "sleep"): + (other / name).write_bytes((stubs / name).read_bytes()) + (other / name).chmod(0o755) + result, _ = bash(step(PLAN), other, PACKAGES="lintian musl-tools") + assert result.returncode == 0, result.stderr + spaced = outputs(other) + assert lines["prefix"] == spaced["prefix"] + assert lines["key"] == spaced["key"] + assert pathlib.Path(lines["plan"]).read_text().count("\n") == 2 + + +def test_no_packages_is_an_error(stubs): + result, calls = bash(step(PLAN), stubs, PACKAGES=" \n ") + assert result.returncode == 1 + assert result.stderr.strip() == "::error::apt-install: the packages input names no package" + assert calls == [] + + +def test_each_list_of_packages_downloads_into_a_directory_of_its_own(stubs): + result, calls = bash(step(PLAN), stubs, PACKAGES="lintian") + assert result.returncode == 0, result.stderr + first = outputs(stubs)["archives"] + (stubs / "output").unlink() + result, _ = bash(step(PLAN), stubs, PACKAGES="musl-tools") + assert result.returncode == 0, result.stderr + second = outputs(stubs)["archives"] + assert first != second + for archives in (first, second): + assert pathlib.Path(archives, "partial").is_dir() + assert f"sudo chown runner {first}" in calls + + +INSTALL = "Install" + + +def deb(directory, package, version, arch, content): + """A cached archive file as apt names it, and its SHA-256.""" + name = f"{package}_{version.replace(':', '%3a')}_{arch}.deb" + (directory / name).write_bytes(content) + return hashlib.sha256(content).hexdigest() + + +def test_the_install_step_keeps_only_cached_files_the_index_signs_for(stubs): + archives = stubs / "archives" / "x" + archives.mkdir(parents=True) + plan = stubs / "plan" + plan.write_text("good 2:1.0-1 amd64\nbad 1.0-1 all\n") + (stubs / "sha").mkdir() + good = deb(archives, "good", "2:1.0-1", "amd64", b"good") + (stubs / "sha" / "good:amd64=2:1.0-1").write_text(good) + deb(archives, "bad", "1.0-1", "all", b"tampered") + (stubs / "sha" / "bad:all=1.0-1").write_text("0" * 64) + deb(archives, "old", "0.9-1", "amd64", b"old") + result, calls = bash( + step(INSTALL), stubs, PACKAGES="good bad", KEY="k", HIT="true", + APT_ARCHIVES=archives, PLAN=plan, + ) + assert result.returncode == 0, result.stderr + assert sorted(p.name for p in archives.iterdir()) == ["good_2%3a1.0-1_amd64.deb"] + assert "apt-install: 1 cached package files match the index; 1 older ones deleted unused" in result.stdout + assert "::warning::apt-install: deleting cached bad_1.0-1_all.deb: its SHA-256 is" in result.stdout + assert "gh cache delete k" in result.stdout + assert ( + f"apt-get -o Acquire::Retries=3 -o Dir::Cache::archives={archives}/ install -y " + "--no-install-recommends good bad" + ) in calls + + +def test_the_install_step_warns_when_nothing_is_left_to_cache(stubs): + archives = stubs / "archives" / "x" + archives.mkdir(parents=True) + plan = stubs / "plan" + plan.write_text("") + result, _ = bash( + step(INSTALL), stubs, PACKAGES="lintian", KEY="k", HIT="false", + APT_ARCHIVES=archives, PLAN=plan, + ) + assert result.returncode == 0, result.stderr + assert f"no package file is left in {archives}, so nothing will be cached" in result.stdout diff --git a/tests/test_release_actions.py b/tests/test_release_actions.py new file mode 100644 index 0000000..ad21891 --- /dev/null +++ b/tests/test_release_actions.py @@ -0,0 +1,292 @@ +"""Behaviour of the release preflight and attach actions, and the cancelled-release workflow. + +Each step's script is read out of its action or workflow file and run under bash as GitHub +runs a step, with `-e` and `pipefail`, with the environment GitHub would give it. The +stand-ins for `gh` and `curl` share a fake release on disk - `assets` lists each asset as +`ID NAME STATE`, and `asset-ID` holds its bytes - so an upload adds to it, a delete takes from +it, and a download reads it. What this cannot test: the GitHub expressions that fill the +environment, and GitHub itself. +""" + +import os +import pathlib +import stat +import subprocess +import textwrap + +import pytest +import yaml + +ROOT = pathlib.Path(__file__).resolve().parent.parent + +GH = textwrap.dedent("""\ + #!/usr/bin/env bash + echo "gh $*" >> "$STUB_DIR/calls" + args=("$@") + last="${args[-1]}" + case "$*" in + *"--jq .prerelease"*) + [ "${STUB_GH_EXIT:-0}" = 0 ] || { echo "gh: HTTP 404" >&2; exit 1; } + echo "$STUB_PRERELEASE" ;; + *"--method DELETE"*) + id="${last##*/}" + awk -v id="$id" '$1 != id' "$STUB_DIR/assets" > "$STUB_DIR/assets.new" + mv "$STUB_DIR/assets.new" "$STUB_DIR/assets" ;; + *"application/octet-stream"*) cat "$STUB_DIR/asset-${last##*/}" ;; + *"/assets --paginate"*) cat "$STUB_DIR/assets" ;; + *) echo "unexpected gh call: $*" >&2; exit 2 ;; + esac +""") + +CURL = textwrap.dedent("""\ + #!/usr/bin/env bash + url="${@: -1}" + while [ $# -gt 1 ]; do + case "$1" in + --data-binary) data="${2#@}"; shift ;; + --output) out="$2"; shift ;; + -H) echo "$2" >> "$STUB_DIR/curl.headers"; shift ;; + esac + shift + done + encoded="${url##*name=}" + name="$(printf '%b' "${encoded//%/\\\\x}")" + echo "upload $encoded" >> "$STUB_DIR/calls" + if [ -n "${STUB_CURL_FAIL:-}" ]; then + printf '%s' "$STUB_CURL_FAIL" > "$out" + exit 22 + fi + # A counter, never reused, as GitHub's ids are not after a delete. + id=$(( $(cat "$STUB_DIR/next-id" 2>/dev/null || echo 100) + 1 )) + echo "$id" > "$STUB_DIR/next-id" + echo "$id $name uploaded" >> "$STUB_DIR/assets" + if [ -n "${STUB_CORRUPT:-}" ]; then echo corrupt > "$STUB_DIR/asset-$id"; else cp "$data" "$STUB_DIR/asset-$id"; fi + echo '{}' > "$out" +""") + + +@pytest.fixture +def stubs(tmp_path): + for name, body in (("gh", GH), ("curl", CURL)): + path = tmp_path / name + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + (tmp_path / "assets").write_text("") + return tmp_path + + +def script(relative, name=None): + document = yaml.safe_load((ROOT / relative).read_text()) + if "runs" in document: + steps = document["runs"]["steps"] + else: + (job,) = document["jobs"].values() + steps = job["steps"] + (found,) = [s for s in steps if "run" in s and (name is None or s.get("name") == name)] + return found["run"] + + +def run(relative, stubs, **env): + full = { + "PATH": f"{stubs}:{os.environ['PATH']}", + "STUB_DIR": str(stubs), + "RUNNER_TEMP": str(stubs), + "GITHUB_SHA": "abc123", + "REPO": "L337-org/thing", + "GH_TOKEN": "token", + **{k: str(v) for k, v in env.items()}, + } + result = subprocess.run( + ["bash", "--noprofile", "--norc", "-eo", "pipefail", "-c", script(relative)], + env=full, capture_output=True, text=True, timeout=30, cwd=stubs, + ) + calls = (stubs / "calls").read_text().splitlines() if (stubs / "calls").exists() else [] + return result, calls + + +PREFLIGHT = "actions/release-preflight/action.yml" + + +def preflight(stubs, **env): + base = { + "EVENT": "release", "OWNER": "L337-org", "TAG": "v1.2.3", "RELEASE_ID": "7", + "VERSION": "1.2.3", "PREFIX": "v", + } + return run(PREFLIGHT, stubs, **{**base, **env}) + + +def test_a_release_tagged_with_the_declared_version_passes(stubs): + result, calls = preflight(stubs) + assert result.returncode == 0, result.stderr + assert "release-preflight: releasing 1.2.3, tagged v1.2.3, from abc123" in result.stdout + # A major version above 0 does not ask whether it is a pre-release. + assert calls == [] + + +def test_the_prefix_defaults_to_v_and_an_empty_one_is_held_by_the_probe(): + # A repository with bare tags passes tag-prefix: '', which works only because an input given + # as empty overrides its default: the input-defaults premerge job holds that on GitHub. + document = yaml.safe_load((ROOT / PREFLIGHT).read_text()) + assert document["inputs"]["tag-prefix"]["default"] == "v" + probe = yaml.safe_load((ROOT / ".github" / "actions" / "input-default-probe" / "action.yml").read_text()) + assert probe["inputs"]["value"]["default"] == "v" + premerge = yaml.safe_load((ROOT / ".github" / "workflows" / "premerge.yaml").read_text()) + steps = premerge["jobs"]["input-defaults"]["steps"] + assert {"value": "", "expected": ""} in [s.get("with") for s in steps] + + +def test_a_two_part_version_with_no_prefix_passes(stubs): + result, _ = preflight(stubs, TAG="6.2", VERSION="6.2", PREFIX="") + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize( + "env, message", + [ + ({"EVENT": "push"}, "checks a release, but this run was started by 'push'"), + ({"OWNER": "someone"}, "published from repository owner 'someone', not L337-org"), + ({"VERSION": ""}, "the version input is empty"), + ({"TAG": "1.2.3"}, "the release's tag is '1.2.3', but the repository declares 1.2.3, so the tag must be 'v1.2.3'"), + ({"TAG": "v6.2.0", "VERSION": "6.2"}, "so the tag must be 'v6.2'"), + ], +) +def test_preflight_refuses_naming_why(stubs, env, message): + result, _ = preflight(stubs, **env) + assert result.returncode == 1 + assert message in result.stderr + + +def test_a_major_version_of_0_must_be_a_pre_release(stubs): + result, calls = preflight(stubs, TAG="v0.4.0", VERSION="0.4.0", STUB_PRERELEASE="false") + assert result.returncode == 1 + assert ( + "0.4.0 has a major version of 0, so its release must be marked as a pre-release; edit " + "release 7, tick pre-release, and re-run this workflow" + ) in result.stderr + assert calls == ["gh api repos/L337-org/thing/releases/7 --jq .prerelease"] + result, _ = preflight(stubs, TAG="v0.4.0", VERSION="0.4.0", STUB_PRERELEASE="true") + assert result.returncode == 0, result.stderr + + +def test_a_release_that_cannot_be_read_fails_saying_so(stubs): + result, _ = preflight(stubs, TAG="v0.4.0", VERSION="0.4.0", STUB_GH_EXIT=1) + assert result.returncode == 1 + assert "could not read release 7 of L337-org/thing to see whether it is marked pre-release" in result.stderr + + +ATTACH = "actions/release-attach/action.yml" + + +def built(stubs, name, content): + (stubs / name).write_bytes(content) + return name + + +def attach(stubs, files, **env): + return run(ATTACH, stubs, FILES=files, RELEASE_ID="7", **env) + + +def served(stubs): + lines = (stubs / "assets").read_text().splitlines() + return {line.split()[1]: (stubs / f"asset-{line.split()[0]}").read_bytes() for line in lines} + + +def test_each_file_is_attached_and_checked(stubs): + built(stubs, "x_1.0_amd64.deb", b"amd") + built(stubs, "x_1.0_arm64.deb", b"arm") + result, calls = attach(stubs, "x_1.0_amd64.deb\nx_1.0_arm64.deb\n") + assert result.returncode == 0, result.stderr + assert served(stubs) == {"x_1.0_amd64.deb": b"amd", "x_1.0_arm64.deb": b"arm"} + assert "release-attach: x_1.0_amd64.deb served as built" in result.stdout + assert "Content-Type: application/vnd.debian.binary-package" in (stubs / "curl.headers").read_text() + # The token is in a header, never in the URL or on gh's command line. + assert not any("token" in call for call in calls) + + +def test_a_glob_attaches_what_it_matches_and_one_matching_nothing_is_named(stubs): + (stubs / "dist").mkdir() + (stubs / "dist" / "a.deb").write_bytes(b"a") + (stubs / "dist" / "b.deb").write_bytes(b"b") + result, _ = attach(stubs, "dist/*.deb") + assert result.returncode == 0, result.stderr + assert served(stubs) == {"a.deb": b"a", "b.deb": b"b"} + result, _ = attach(stubs, "dist/*.rpm") + assert result.returncode == 1 + assert "dist/\\*.rpm does not exist, so nothing is attached" in result.stderr + + +def test_a_name_url_syntax_would_split_reaches_github_whole(stubs): + built(stubs, "a&b#1%.deb", b"x") + result, calls = attach(stubs, "a&b#1%.deb") + assert result.returncode == 0, result.stderr + assert "upload a%26b%231%25.deb" in calls + assert served(stubs) == {"a&b#1%.deb": b"x"} + + +def test_an_identical_file_already_attached_is_left_as_it_is(stubs): + built(stubs, "x.deb", b"same") + (stubs / "assets").write_text("5 x.deb uploaded\n") + (stubs / "asset-5").write_bytes(b"same") + result, calls = attach(stubs, "x.deb") + assert result.returncode == 0, result.stderr + assert "x.deb is already attached and identical; left as it is" in result.stdout + assert not any(call.startswith("upload") for call in calls) + + +def test_a_different_file_left_by_an_earlier_run_is_replaced(stubs): + built(stubs, "x.deb", b"new") + (stubs / "assets").write_text("5 x.deb uploaded\n") + (stubs / "asset-5").write_bytes(b"old") + result, calls = attach(stubs, "x.deb") + assert result.returncode == 0, result.stderr + assert "::warning::release-attach: x.deb is already attached and differs from this build" in result.stdout + assert "gh api --method DELETE repos/L337-org/thing/releases/assets/5" in calls + assert served(stubs) == {"x.deb": b"new"} + + +def test_an_unfinished_upload_is_replaced(stubs): + built(stubs, "x.deb", b"new") + (stubs / "assets").write_text("5 x.deb starter\n") + result, _ = attach(stubs, "x.deb") + assert result.returncode == 0, result.stderr + assert "an upload that never finished (starter), left by an earlier run; replacing it" in result.stdout + assert served(stubs) == {"x.deb": b"new"} + + +def test_a_missing_file_attaches_nothing(stubs): + built(stubs, "x.deb", b"x") + result, calls = attach(stubs, "x.deb y.deb") + assert result.returncode == 1 + assert "y.deb does not exist, so nothing is attached" in result.stderr + assert calls == [] + + +def test_a_refused_upload_fails_with_githubs_answer(stubs): + built(stubs, "x.deb", b"x") + result, _ = attach(stubs, "x.deb", STUB_CURL_FAIL='{"message":"Validation Failed"}') + assert result.returncode == 1 + assert 'uploading x.deb to release 7 failed; GitHub said: {"message":"Validation Failed"}' in result.stderr + + +def test_a_release_serving_something_else_fails(stubs): + built(stubs, "x.deb", b"x") + result, _ = attach(stubs, "x.deb", STUB_CORRUPT="1") + assert result.returncode == 1 + assert "release 7 serves a x.deb that differs from the one built" in result.stderr + + +@pytest.mark.parametrize( + "files, release, message", + [(" \n", "7", "the files input names no file"), ("x.deb", "", "no release to attach to")], +) +def test_attach_refuses_what_it_cannot_do(stubs, files, release, message): + built(stubs, "x.deb", b"x") + result, _ = run(ATTACH, stubs, FILES=files, RELEASE_ID=release) + assert result.returncode == 1 + assert message in result.stderr + + +def test_a_cancelled_release_fails_naming_the_job(stubs): + result, _ = run(".github/workflows/release-cancelled.yaml", stubs, JOB="build-and-release") + assert result.returncode == 1 + assert "The build-and-release job ended as cancelled" in result.stderr