A pre-commit hook that runs only on staged files

Our old pre-commit hook linted the whole repository and took forty seconds. This one lints only what you are committing.

Automate the boring checks

Small shell scripts in the repository beat long wiki pages. New teammates run one command and get a working site.

#!/usr/bin/env bash
set -euo pipefail

files=$(git diff --cached --name-only --diff-filter=ACM -- '*.php')
[ -z "$files" ] && exit 0

echo "Linting $(echo "$files" | wc -l) staged PHP files"
vendor/bin/phpcs --standard=phpcs.xml.dist $files

Our Git workflow is deliberately plain: short branches, small pull requests, and a squash merge with a message that explains why. The snippet above is the whole thing; the version in our repository only adds tests.

Sharing the setup

  • Run linters on staged files only
  • Keep setup in one script
  • Prefer short-lived branches
  • Commit editor config with the code

9 comments on “A pre-commit hook that runs only on staged files”

  1. Clara Lindqvist

    We tried something similar last year and gave up halfway. Seeing it laid out step by step makes me want to try again.

    1. Elin Sørensen

      Thanks for reading! We tested on a mid-range Android phone as well, and the results were close to the throttled runs.

    1. Elin Sørensen

      Thanks for reading! We tested on a mid-range Android phone as well, and the results were close to the throttled runs.

  2. Ben Carter

    This is exactly the write-up I needed this week. We hit the same problem and ended up with a much messier fix.

  3. Aiko Tanaka

    Clear and practical, thank you. One question: how long did the whole change take from start to finish?

    1. Elin Sørensen

      Good question. It took about three weeks, most of it waiting for review and measuring the results.

  4. Julia Novak

    We tried something similar last year and gave up halfway. Seeing it laid out step by step makes me want to try again.

Leave a comment

Your email address will not be published. Required fields are marked *