Possible to cache under two keys?

Hi all,

I’d quite like to cache by SHA and by branch name, so that if I tag a commit that has already been built on a branch then it uses the cache for that commit to rebuild it, but if I build a branch then I benefit from a cache populated from the previous build on that branch.

Is that possible?

If I use this cache key ${{ github.ref }}-${{ github.sha }} then the branch run will cache as main-abcdef and the tag run will look up with 0.1.0-abcdef and it will miss.

If I use this cache key ${{ github.sha }}-${{ github.ref }} then the branch build will cache as abcdef-main, the tag build will look up with abcdef-0.1.0 and it will hit the abcdef SHA cache, but a subsequent commit to main will look up with123456-main and miss.

I suppose I’d really like to cache it under two keys - once under ${{ github.ref }} and once under ${{github.sha}}. Then I can use this:

restore-keys: |
  ${{ github.sha }}
  ${{ github.ref }}

and (I think!) it’ll use the SHA cache for preference and fall back to the branch name cache if there’s no SHA cache. But I don’t think caching under two keys is supported? Am I wrong?

Anyone got a nice solution to this?

1 Like

I posted this in the Discussions on the GitHub repo BTW - will update with an answer from either.

I spoke too soon - my testing was inadequate. It seems **-${{ github.sha }} doesn’t respect the glob in the match.

Raised Allow caching by github.ref AND github.sha · Issue #740 · actions/cache · GitHub but there doesn’t seems to be much feedback from actual GitHub people on issues in there.