When setting up a GitHub Actions workflow for the repo that deploys this site, I noticed the pre-commit action for GitHub Actions is deprecated, and also doesn’t cache the installation of pre-commit itself.

As a workaround, you can easily use the package dependency caching in actions/setup-python to cache the pre-commit installation and a custom actions/cache to cache the pre-commit cache itself (~/.cache/pre-commit/).

  • First, update or create requirements.txt with the current version of pre-commit:

    pip install pre-commit
    pip freeze|grep pre-commit >> requirements.txt
    

    Even if this file includes only the pre-commit package, you need a requirements.txt file for actions/setup-python to hash the cache key.

  • Update your GitHub Actions workflow based on the following:

    name: pre-commit
    
    on:
      pull_request:
      push:
        branches: [main]
    
    jobs:
      pre-commit:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - uses: actions/setup-python@v3
            with:
              cache: 'pip'
          - run: python -m pip install -r requirements.txt
          - uses: actions/cache@v3
            with:
              path: ~/.cache/pre-commit/
              key: pre-commit-4|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
          - run: pre-commit run --show-diff-on-failure --color=always --all-files