Welcome to this comprehensive guide on pre-commit Git hooks! This tutorial is designed to help both beginners and intermediate learners understand and utilize pre-commit Git hooks effectively.
Pre-commit Git hooks are scripts that run automatically before every commit, allowing you to enforce coding standards, run tests, and perform other checks to maintain the quality of your codebase.
Install the pre-commit package using pip:
pip install pre-commit.pre-commit-config.yaml fileIn the root of your repository, create a file named .pre-commit-config.yaml. This file will contain the list of hooks you want to use.
.pre-commit-config.yaml fileHere's an example configuration file with two popular hooks: black (Python code formatter) and flake8 (style guide enforcement and linter):
repos:
- repo: https://github.com/psf/black
hooks:
- id: black
- id: black-args
args: [--line-length=88]
- repo: https://github.com/PyCQA/flake8
hooks:
- id: flake8To initialize the hooks, run:
pre-commit installBefore committing, you can test the hooks by running:
pre-commit run --all-filesFor more advanced usage, you can create custom scripts and integrate them into your .pre-commit-config.yaml file. Check out the pre-commit documentation for more information.
What does pre-commit do?
How do you install pre-commit?