Git pre-commit hooks are scripts that Git automatically runs at certain stages of the commit process. They're incredibly useful for ensuring code quality, enforcing coding standards, and automating tasks like running tests or updating changelog files. In this comprehensive guide, we'll explore an example of a pre-commit hook that checks for Git's commit message format.

Before we dive into the example, let's understand why pre-commit hooks are essential. In a team environment, consistent commit messages help maintain a uniform project history. Pre-commit hooks ensure that all contributors adhere to the agreed-upon commit message format, making it easier to understand and navigate the project's commit history.

Setting up the Pre-Commit Hook
To create a pre-commit hook, you'll need to create a script in your project's .git/hooks directory. If the hooks directory doesn't exist, you can create it yourself or initialize a new Git repository to generate it.

In this example, we'll create a JavaScript-powered pre-commit hook using Node.js and npm (Node Package Manager). If you're not familiar with Node.js, it's a JavaScript runtime environment that allows running JavaScript on the server. For this hook, we'll leverage the simple-git library to interact with the Git repository.
Installing Node.js and Setting up the Project

First, ensure Node.js is installed on your system. If not, download and install it from the official Node.js website. After installing Node.js, you can use npm (node --version and npm --version) to manage packages and dependencies.
Once Node.js is set up, create a new project directory for your pre-commit hook:
- Open your terminal or command prompt.
- Navigate to the desired project directory using the
cdcommand. - Initialize a new npm project:
npm init -y

Creating the Pre-Commit Hook Script
Now that your project is initialized, let's create the pre-commit hook script. We'll write a JavaScript file named pre-commit.js and install the simple-git library as a dependency.
- Create a new file named
pre-commit.jsin your project directory. - Open the file in your favorite code editor or IDE.
- Add the following code to the file:

```javascript const simpleGit = require('simple-git')(); const { exit } = require('process'); async function run() { const { messages } = await simpleGit.log([ '--pretty=format:%s', '--numstat=yes', '-1', ]); if (!messages) { console.log('No commit message found.'); exit(1); } const [message] = messages; const regex = /^([\w-]+):\s*(.+)$/; if (!message.match(regex)) { console.log('Invalid commit message format. Please use the following format:\n\n[Type]: Summary\n\nDescription.'); exit(1); } console.log(`Commit message is valid: ${message}`); } run().catch(console.error); ```
The script above checks the latest commit message's format. If the message doesn't match the expected format of [Type]: Summary (e.g., feat: Add login functionality), the script will exit with a non-zero status, preventing the commit from being made.
After creating the script, install the required dependencies:




















- Open your terminal or command prompt.
- Navigate to your project directory.
- Run
npm init -yto create apackage.jsonfile if you haven't already. - Run
npm install simple-gitto install thesimple-gitlibrary.
Configuring Git to Use the Pre-Commit Hook
Now that we've created the pre-commit hook script, let's tell Git to use it.
Making the Script Executable
For Git to recognize the script as a pre-commit hook, it must have executable permissions. You can set the permissions using the following command:
- Open your terminal or command prompt.
- Navigate to your project directory.
- Make the
pre-commit.jsscript executable:chmod +x pre-commit.js
Moving the Script to the Git Hooks Directory
Finally, move the script to the .git/hooks directory. If the hooks directory doesn't exist, create it first.
- Create the hooks directory if it doesn't exist:
mkdir -p .git/hooks - Move the
pre-commit.jsscript to the.git/hooksdirectory:mv pre-commit.js .git/hooks/pre-commit
The pre-commit hook is now set up and enabled. It will run automatically whenever you try to commit changes, enforcing the specified commit message format.
Testing the Pre-Commit Hook
Now that the pre-commit hook is configured, let's test it by making a commit with an invalid message format. If you've set up the hook correctly, Git should prevent the commit from being made until you provide a valid commit message.
Creating a New Commit with an Invalid Message
Try to commit changes with an invalid commit message format:
- Open your terminal or command prompt.
- Navigate to your project directory.
- Stage a file for commit:
git add filename.js - Attempt to commit with an invalid message format:
git commit -m 'Invalid commit message format'
The pre-commit hook should prevent the commit, displaying the error message: "Invalid commit message format. Please use the following format:
[Type]: Summary Description.
Now, try committing with a valid message format:
- Stage a file for commit:
git add filename.js - Commit with a valid message format:
git commit -m "feat: Addition of login functionality"
The commit should succeed this time, demonstrating that the pre-commit hook is working as expected.
In this example, we explored how to create a pre-commit hook script that enforces a specific commit message format. This is just one of many use cases for pre-commit hooks. You can adapt this script to suit your team's specific needs or automate other tasks, such as running tests or updating changelog files.
Happy coding, and may your pre-commit hooks serve you well!