Fixing slow caching in GitHub Actions

almirsarajcic

almirsarajcic

Created 6 months ago

A bug in GitHub Actions recently started causing saving cache to slow down the whole workflow. Separating cache into restore and save steps fixes it.

- name: Restore npm cache
  uses: actions/cache/restore@v4
  id: npm-cache
  with:
    path: node_modules
    key: ${{ runner.os }}-prettier
- name: Install Prettier
  if: steps.npm-cache.outputs.cache-hit != 'true'
  run: npm i -D prettier prettier-plugin-toml
- name: Run Prettier
  run: npx prettier -c .
- name: Save npm cache
  uses: actions/cache/save@v4
  with:
    path: node_modules
    key: ${{ runner.os }}-prettier

See it in action: https://github.com/optimumBA/phx.tools/pull/28.
Source: https://github.com/actions/toolkit/issues/1578#issuecomment-2253355054.