pre-commit Git Hooks Tutorial 🎯

beginner
9 min

pre-commit Git Hooks Tutorial 🎯

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.

Understanding pre-commit Git Hooks 📝

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.

Why use pre-commit Git Hooks?

  • Consistency: Ensuring that everyone adheres to the same coding standards.
  • Quality: Running tests and checks to catch errors and inconsistencies early.
  • Efficiency: Saving time by automating repetitive tasks.

Setting up pre-commit Git Hooks 💡

Step 1: Install pre-commit

Install the pre-commit package using pip:

bash
pip install pre-commit

Step 2: Create a .pre-commit-config.yaml file

In 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.

Step 3: Add hooks to the .pre-commit-config.yaml file

Here's an example configuration file with two popular hooks: black (Python code formatter) and flake8 (style guide enforcement and linter):

yaml
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: flake8

Running and managing pre-commit Git Hooks ✅

Step 1: Initialize the hooks

To initialize the hooks, run:

bash
pre-commit install

Step 2: Testing the hooks

Before committing, you can test the hooks by running:

bash
pre-commit run --all-files

Advanced examples and troubleshooting 📝

For 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.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does pre-commit do?

Quick Quiz
Question 1 of 1

How do you install pre-commit?