diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6aa7765..2dee4ca 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -164,6 +164,71 @@ jobs: # job compares its run in the cached project directory with a cold run of a # pristine copy, and the comparison covers every command's exit code and # output and every file the project holds afterwards. + # save-cache decides per run whether the caches are saved. The static test + # holds every saving cache step to that decision; the matrix proves the + # action loads and installs with each value, and that the decision is right + # for this run (a pull request is not the default branch). + test-save-cache: + name: "save-cache: ${{ matrix.value }}" + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - { value: "false", want: "false" } + # The default branch saves (a push to main, the daily schedule); a + # pull request does not. + - { value: "default-branch", want: "${{ github.event_name == 'pull_request' && 'false' || 'true' }}" } + - { value: "true", want: "true" } + steps: + - uses: actions/checkout@v6 + + - name: Every saving cache step follows the save-cache decision + run: python3 test/save-cache/restore-only.py action.yml + + - name: The decision over fabricated events, schedule included + run: bash test/save-cache/decision.sh + + - name: Setup kapi + id: setup + uses: ./ + with: + token: ${{ secrets.NEOKAPI_GITHUB_TOKEN }} + plugins: bowrain + save-cache: ${{ matrix.value }} + + - name: Verify the install, the decision and the cache-hit output + shell: bash + env: + INSTALLED_VERSION: ${{ steps.setup.outputs.version }} + CACHE_HIT: ${{ steps.setup.outputs.cache-hit }} + SAVES: ${{ steps.setup.outputs.saves-cache }} + WANT: ${{ matrix.want }} + run: | + set -euo pipefail + test -n "$INSTALLED_VERSION" + kapi version + case "$CACHE_HIT" in true|false) ;; *) echo "cache-hit output is '$CACHE_HIT'"; exit 1 ;; esac + echo "saves-cache=$SAVES, want $WANT" + test "$SAVES" = "$WANT" + + test-save-cache-invalid: + name: "save-cache: an invalid value fails" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - name: Setup kapi with save-cache maybe + id: setup + continue-on-error: true + uses: ./ + with: + token: ${{ secrets.NEOKAPI_GITHUB_TOKEN }} + save-cache: maybe + - name: The step failed + env: + OUTCOME: ${{ steps.setup.outcome }} + run: test "$OUTCOME" = failure + test-state-cache-save: name: "State cache save (${{ matrix.os }})" runs-on: ${{ matrix.os }} diff --git a/README.md b/README.md index 93ad123..a2f7545 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ steps: | `server` | Bowrain server URL, exported as `BOWRAIN_SERVER_URL` | — | No | | `parse-cache` | Keep kapi's parse cache between runs, so a later run replays files it already parsed; see [Project parse cache](#project-parse-cache). Runs only when a `kapi.yaml` recipe (or legacy `*.kapi`) is present. Set `false` to turn it off | `true` | No | | `cache-tm` | Deprecated name of `parse-cache`. When set, it decides in place of `parse-cache`, and the action prints a warning | `''` | No | +| `save-cache` | When to save the binary, plugin and parse caches at the end of the job. `true`: every run. `default-branch`: a push or `workflow_dispatch` whose ref is the repository's default branch, and every `schedule` run (GitHub runs schedules on the default branch only); every other run, pull requests included, only restores. `false`: never (restore only). The `saves-cache` output says what the run decided | `true` | No | | `project-dir` | Directory holding the `kapi.yaml` project whose parse cache is kept between runs | `.` | No | ## Outputs diff --git a/action.yml b/action.yml index ef45d2f..9499d07 100644 --- a/action.yml +++ b/action.yml @@ -52,14 +52,25 @@ inputs: description: "Directory holding the kapi.yaml project whose parse cache is kept between runs. Default: repository root." required: false default: "." + save-cache: + description: >- + When to save the binary, plugin and parse caches at the end of the job: + 'true' saves on every run (the default, as before); 'default-branch' + saves on a push or dispatch of the repository's default branch and on a + schedule run, and only restores elsewhere; 'false' only restores. + required: false + default: "true" outputs: version: description: "Installed kapi CLI version (e.g. '0.5.0')" value: ${{ steps.resolve.outputs.version }} + saves-cache: + description: "Whether this run saves the caches ('true' or 'false'), as save-cache decided" + value: ${{ steps.save.outputs.save }} cache-hit: description: "Whether the plugin cache was hit" - value: ${{ steps.plugin-cache.outputs.cache-hit }} + value: ${{ steps.plugin-cache.outputs.cache-hit || steps.plugin-cache-restore.outputs.cache-hit }} runs: using: "composite" @@ -98,17 +109,46 @@ runs: echo "ext=${ARCHIVE_EXT}" >> "$GITHUB_OUTPUT" echo "Platform: ${GOOS}/${GOARCH} (archive: .${ARCHIVE_EXT})" - # 3. Restore binary cache + # 3. Resolve save-cache to a yes or no for this run + # (scripts/save-cache-decision.sh). The default branch is read from the + # event, so the action works in any repository. + - name: Resolve save-cache + id: save + shell: bash + env: + INPUT_SAVE_CACHE: ${{ inputs.save-cache }} + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + ACTION_PATH: ${{ github.action_path }} + run: | + if ! save="$(bash "${ACTION_PATH}/scripts/save-cache-decision.sh" 2>"${RUNNER_TEMP}/save-cache.err")"; then + echo "::error title=setup-kapi::$(cat "${RUNNER_TEMP}/save-cache.err")" + exit 1 + fi + echo "save=$save" >> "$GITHUB_OUTPUT" + echo "save-cache=$INPUT_SAVE_CACHE: caches are $([ "$save" = true ] && echo saved || echo restored only) on this run" + + # 3b. Restore binary cache - name: Restore binary cache + if: steps.save.outputs.save == 'true' id: binary-cache uses: actions/cache@v5 with: path: ${{ runner.temp }}/setup-kapi key: kapi-${{ steps.resolve.outputs.version }}-${{ runner.os }}-${{ runner.arch }} + - name: Restore binary cache (no save) + if: steps.save.outputs.save != 'true' + id: binary-cache-restore + uses: actions/cache/restore@v5 + with: + path: ${{ runner.temp }}/setup-kapi + key: kapi-${{ steps.resolve.outputs.version }}-${{ runner.os }}-${{ runner.arch }} + # 4. Download + verify (on cache miss) - name: Download and verify - if: steps.binary-cache.outputs.cache-hit != 'true' + if: steps.binary-cache.outputs.cache-hit != 'true' && steps.binary-cache-restore.outputs.cache-hit != 'true' shell: bash env: GH_TOKEN: ${{ inputs.token }} @@ -183,7 +223,7 @@ runs: # 9. Restore plugin cache - name: Restore plugin cache - if: inputs.plugins != '' + if: inputs.plugins != '' && steps.save.outputs.save == 'true' id: plugin-cache uses: actions/cache@v5 with: @@ -198,9 +238,25 @@ runs: # another kapi or an older registry entry. key: kapi-plugins-v2-${{ steps.plugin-hash.outputs.hash }}-${{ runner.os }}-${{ runner.arch }} + - name: Restore plugin cache (no save) + if: inputs.plugins != '' && steps.save.outputs.save != 'true' + id: plugin-cache-restore + uses: actions/cache/restore@v5 + with: + # kapi installs plugins under $XDG_DATA_HOME/kapi/plugins — i.e. + # ~/.local/share/kapi/plugins when XDG_DATA_HOME is unset, as it is on a + # runner. The old ~/.config/kapi/plugins is the CONFIG dir: nothing was + # ever written there, so the cache saved an empty path and every run + # re-downloaded every plugin. + path: ~/.local/share/kapi/plugins + # + # No restore-keys: a partial match would restore plugins chosen for + # another kapi or an older registry entry. + key: kapi-plugins-v2-${{ steps.plugin-hash.outputs.hash }}-${{ runner.os }}-${{ runner.arch }} + # 10. Install plugins (on cache miss) - name: Install plugins - if: inputs.plugins != '' && steps.plugin-cache.outputs.cache-hit != 'true' + if: inputs.plugins != '' && steps.plugin-cache.outputs.cache-hit != 'true' && steps.plugin-cache-restore.outputs.cache-hit != 'true' shell: bash env: INPUT_PLUGINS: ${{ inputs.plugins }} @@ -349,7 +405,7 @@ runs: # the default (or base) branch's scope and often on behalf of someone # who cannot push, so there the cache is restored and never saved. - name: Restore kapi parse cache - if: steps.parse-cache-dir.outputs.dir != '' && !contains(fromJSON('["pull_request_target","workflow_run","issue_comment"]'), github.event_name) + if: steps.parse-cache-dir.outputs.dir != '' && steps.save.outputs.save == 'true' && !contains(fromJSON('["pull_request_target","workflow_run","issue_comment"]'), github.event_name) uses: actions/cache@v5 with: path: | @@ -361,7 +417,7 @@ runs: kapi-parse-${{ runner.os }}-${{ steps.resolve.outputs.version }}_ - name: Restore kapi parse cache (no save) - if: steps.parse-cache-dir.outputs.dir != '' && contains(fromJSON('["pull_request_target","workflow_run","issue_comment"]'), github.event_name) + if: steps.parse-cache-dir.outputs.dir != '' && (steps.save.outputs.save != 'true' || contains(fromJSON('["pull_request_target","workflow_run","issue_comment"]'), github.event_name)) uses: actions/cache/restore@v5 with: path: | diff --git a/scripts/save-cache-decision.sh b/scripts/save-cache-decision.sh new file mode 100644 index 0000000..0bd3ae3 --- /dev/null +++ b/scripts/save-cache-decision.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Decide whether this run saves the caches, from the save-cache input. +# +# true saves on every run +# false never saves (restore only) +# default-branch saves on a run of the default branch: a push or dispatch +# whose ref is refs/heads/, or a schedule +# run, which GitHub runs on the default branch only and +# whose payload names no repository. Any run where the +# branch cannot be told does not save. +# +# Reads INPUT_SAVE_CACHE, EVENT_NAME, REF and DEFAULT_BRANCH; prints true or +# false. Exits 2 on any other input value. +set -euo pipefail + +case "${INPUT_SAVE_CACHE:-}" in + true) echo true ;; + false) echo false ;; + default-branch) + if [ "${EVENT_NAME:-}" = schedule ]; then + echo true + elif [ -n "${DEFAULT_BRANCH:-}" ] && [ "${REF:-}" = "refs/heads/${DEFAULT_BRANCH}" ]; then + echo true + else + echo false + fi + ;; + *) + echo "save-cache must be true, false or default-branch, not '${INPUT_SAVE_CACHE:-}'" >&2 + exit 2 + ;; +esac diff --git a/test/save-cache/decision.sh b/test/save-cache/decision.sh new file mode 100644 index 0000000..1f72c61 --- /dev/null +++ b/test/save-cache/decision.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Unit test of scripts/save-cache-decision.sh over fabricated events. +set -uo pipefail +here="$(cd "$(dirname "$0")/../.." && pwd)" +decide="$here/scripts/save-cache-decision.sh" +failed=0 + +check() { + local want="$1" input="$2" event="$3" ref="$4" default="$5" got + got="$(INPUT_SAVE_CACHE="$input" EVENT_NAME="$event" REF="$ref" DEFAULT_BRANCH="$default" bash "$decide" 2>/dev/null)" || got="error" + if [ "$got" = "$want" ]; then + echo "ok $input $event $ref default=$default -> $got" + else + echo "FAIL $input $event $ref default=$default -> $got, want $want" + failed=1 + fi +} + +check true true pull_request refs/pull/1/merge main +check false false push refs/heads/main main +check true default-branch push refs/heads/main main +check true default-branch push refs/heads/trunk trunk +check false default-branch push refs/heads/main trunk +check false default-branch pull_request refs/pull/1/merge main +check true default-branch schedule refs/heads/main "" +check false default-branch workflow_run refs/heads/main "" +check true default-branch workflow_dispatch refs/heads/main main +check false default-branch workflow_dispatch refs/heads/feature main +check error maybe push refs/heads/main main +exit "$failed" diff --git a/test/save-cache/restore-only.py b/test/save-cache/restore-only.py new file mode 100644 index 0000000..e271523 --- /dev/null +++ b/test/save-cache/restore-only.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Assert that a run that resolves save-cache to "no" saves no cache. + +Every actions/cache step in action.yml must run only when the Resolve +save-cache step said yes, and have an actions/cache/restore twin, with the same +path and key, that runs otherwise. actions/cache saves in its post step; +actions/cache/restore never saves. +""" +import sys + +import yaml + +steps = yaml.safe_load(open(sys.argv[1] if len(sys.argv) > 1 else "action.yml"))["runs"]["steps"] +saving = [s for s in steps if str(s.get("uses", "")).startswith("actions/cache@")] +restoring = [s for s in steps if str(s.get("uses", "")).startswith("actions/cache/restore@")] +failures = [] +if not saving: + failures.append("no actions/cache step found") +for s in saving: + name = s.get("name") + if "steps.save.outputs.save == 'true'" not in str(s.get("if", "")): + failures.append(f"{name}: saves without the save-cache decision (its if: {s.get('if')!r})") + twins = [r for r in restoring if r.get("with", {}).get("key") == s.get("with", {}).get("key") + and r.get("with", {}).get("path") == s.get("with", {}).get("path")] + if not any("steps.save.outputs.save != 'true'" in str(r.get("if", "")) for r in twins): + failures.append(f"{name}: no actions/cache/restore twin that runs when save-cache says no") +text = open(sys.argv[1] if len(sys.argv) > 1 else "action.yml").read() +inputs = yaml.safe_load(text)["inputs"] +for name, spec in inputs.items(): + # GitHub refuses to load an action whose input description holds an + # expression, or whose default holds one beyond `${{ github.token }}`. + if "${{" in str(spec.get("description", "")): + failures.append(f"input {name}: its description holds an expression, which GitHub refuses to load") + default = str(spec.get("default", "")) + if "${{" in default and default.strip() != "${{ github.token }}": + failures.append(f"input {name}: its default holds an expression, which GitHub refuses to load") +for f in failures: + print(f"FAIL {f}") +if failures: + sys.exit(1) +print(f"ok: {len(saving)} saving cache step(s), each gated on the save-cache decision and twinned by a restore-only step")