Git Pre-Commit Hook

Share on:

The following blog post illustrates how to use pre-commit hooks in a git workflow.

Pre-commit is a simple method for running abitrary commands prior to a Git commit. It allows automation of checks, such as code formatting, linting, security audits, and more, ensuring code quality and consistency. Hooks are typically scripts that pre-commit runs. A pre-commit hook, specifically, runs before each commit.

Catching issues early reduces debugging time and prevents broken code from entering the codebase. Use pre-commit hooks to enforce standards, improves collaboration, and maintains a cleaner repository history. Running a bash script via a pre-commit hook allows custom checks tailored to the specific project needs in a simple and reproducible manner.

The following will be covered in this blog.

  • Installing Pre-Commit
  • Create a Bash Script
  • Add a Pre-Commit
  • Test the Pre-Commit

Installing a Pre-Commit

The method of installing the pre-commit software will vary depending on your environment. Below are some common installations to get you started.

  1. Install via pip: pip install pre-commit (Recommended. Ensure pip is up-to-date: pip install --upgrade pip)
  2. Install via conda: conda install -c conda-forge pre-commit
  3. Install via brew (macOS): brew install pre-commit
  4. Install via apt (Debian/Ubuntu): sudo apt install pre-commit

Verify Installation: After installation, verify by running pre-commit --version. This should output the installed version number.

Create a Bash Script

  1. Create a file named commit_message.sh
  2. Add the following content to the file
1#!/bin/bash
2echo "Running pre-commit hook..."
3echo "Checking commit message..."
4echo "You are about to commit.  Have a great day!"
5exit 0
  1. Optional: Make the file executable.
1chmod +x commit_message.sh

Add a Pre-Commit Hook

  1. Create a new root file .pre-commit-config.yaml in the repository folder:
1repos:
2-   repo: local
3    hooks:
4    -   id: echo-message
5        name: Echo Message
6        entry: ./commit_message.sh
7        language: script
8        types: [text]
  1. The above configuration defines a pre-commit hook to execute a bash script.

Test the Pre-Commit

With the bash script and pre-commit hook created. A test run can be used to validate the desired outcome is seen.

  1. First test the bash script to validate it output the message.

    1bash commit_message.sh 
    

    You should see the commit message defined in the bash script.

  2. Make a change to the current repository

  3. When committing the change, the pre-commit hook will be invoked. At this point you will see the commit message defined in the bash script.