In this lesson, you’ll learn how to slash your development iteration cycle by configuring pre-commit to process only the files that have actually changed.
The Bottleneck: Full Repository Scanning
By default, some static analysis tools or linters might be configured to scan your entire project directory every time you commit. While this ensures complete coverage, it is inefficient for daily development. If you are working on a single Python file, there is no need for mypy or ruff to re-analyze thousands of lines of code that haven’t been touched.
Leveraging pass_filenames
pre-commit is designed to be incremental. When a hook runs, pre-commit automatically passes the list of staged files as arguments to your tool. If your linter or static analyzer doesn't support receiving a file list via command-line arguments, it may default to scanning the whole project.
To optimize, ensure your hooks are configured to accept these staged filenames. Most modern tools support this natively. For example, in your .pre-commit-config.yaml, you can explicitly ensure hooks operate efficiently:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.0
hooks:
- id: ruff
# This hook automatically processes only staged files
args: [--fix]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
hooks:
- id: mypy
# Ensure mypy only checks the files changed in the commit
pass_filenames: true
Why this matters
By setting pass_filenames: true (which is the default for most hooks, but worth verifying), you tell pre-commit to append the changed files to the end of the command. If a tool requires a specific flag to accept these files, consult its documentation.
Furthermore, avoid using files or exclude patterns that are too broad. If you restrict a hook to only run on src/ directories or specific file extensions, you prevent the pre-commit runner from even inspecting unnecessary files, saving precious CPU cycles and keeping your git flow snappy.
Key Takeaway: Optimize your pre-commit hooks by ensuring they only process the files staged for the current commit, preventing redundant analysis of your entire codebase.