name: Restore Repository Cache
description: Restore the Bazel repository cache from our github action cache
inputs:
  bazel-cache:
    required: true
    description: A unique path for the Bazel cache.
    type: string

# By design, these actions will restore the latest cache for this branch/os,
# and only save a new version if something has changed.  Initially this will
# cause a lot of churn, since each test has a slightly different set of
# repositories to download.  Over time though, since we don't upload no-op
# changes, this should converge to a stable set of 3 caches per branch.  Every
# run will update the current cache with a new test's repositories, until there
# are no unique ones left.
#
# This saves asymptotic space, since each one of these can get up to ~500 MB
# and Github prunes the cache after 10 GB.
runs:
  using: 'composite'
  steps:
    - name: Setup Bazel repository cache variables
      shell: bash
      run: |
        REPOSITORY_CACHE_BASE=repository-cache-${{ github.base_ref || github.ref_name }}-${{ runner.os }}
        echo "REPOSITORY_CACHE_BASE=$REPOSITORY_CACHE_BASE" >> $GITHUB_ENV
        echo "REPOSITORY_CACHE_NAME=$REPOSITORY_CACHE_BASE-${{ inputs.bazel-cache}}-${{ github.sha }}" >> $GITHUB_ENV
        echo "REPOSITORY_CACHE_PATH=.repository-cache" >> $GITHUB_ENV

    - name: Restore Bazel repository cache
      id: restore-cache
      uses: actions/cache/restore@627f0f41f6904a5b1efbaed9f96d9eb58e92e920 # v3.2.4
      with:
        path: ${{ github.workspace }}/${{ env.REPOSITORY_CACHE_PATH }}
        key: ${{ env.REPOSITORY_CACHE_NAME }}
        restore-keys: ${{ env.REPOSITORY_CACHE_BASE }}

    - name: Initialize BAZEL environment variable
      if: ${{ steps.restore-cache.cache-hit }}
      shell: bash
      run: echo "REPOSITORY_CACHE_HASH=${{ hashFiles(format('{0}/**', env.REPOSITORY_CACHE_PATH)) }}" >> $GITHUB_ENV
