Setting Up Pre-commit Hooks

Setting Up Pre-commit hooks #

What are they? #

Pre-commit hooks are automated scripts that run before each commit, helping you catch issues early and maintain consistent code quality.

Steps #

  • Installing and configuring pre-commit
  • Setting up hooks for markdown files

Installation #

First, install pre-commit using pip:

pip install pre-commit

Configuration #

Create a .pre-commit-config.yaml file in your repository root:

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
      - id: check-case-conflict
      - id: check-merge-conflict

What Each Hook Does #

Basic Hooks #

  • trailing-whitespace: Removes trailing whitespace from lines
  • end-of-file-fixer: Ensures files end with a newline
  • check-yaml: Validates YAML syntax
  • check-added-large-files: Prevents accidentally committing large files
  • check-case-conflict: Catches case conflicts that would cause issues on case-insensitive filesystems
  • check-merge-conflict: Detects merge conflict markers

For a complete list of all available hooks, check out the pre-commit-hooks repository.

Installation and Setup #

Install the hooks in your repository:

# Navigate to your repository
cd /path/to/your/repo

# Install the pre-commit hooks
pre-commit install

Testing Your Setup #

Run the hooks on all files to test your configuration:

pre-commit run --all-files

This will show you what issues were found and automatically fix what it can.

Automatic Execution #

Once installed, hooks run automatically on every commit:

git add .
git commit -m "Your commit message"
# Hooks run automatically here

Manual Execution #

Run hooks manually without committing:

# Run on staged files
pre-commit run

# Run on all files
pre-commit run --all-files

Skipping Hooks #

Sometimes you might need to skip hooks in an emergency situation:

git commit -m "Emergency fix" --no-verify