Member-only story
Automate Manual Commit Tasks With Git Hooks
A useful collection of Git pre-commit hooks
Git hooks play an important role in identifying simple issues before submitting code changes to the code base. Also, it’s a good practice to add relevant information to the commit message to ensure easier issue tracking.
Manually adding details like the branch name and verifying that trailing spaces are not present are repetitive manual tasks. Git hooks provide a convenient way to automate the flow. You can configure hooks to automatically add the necessary information and check that your code adheres to the project’s standards.
In this article, I’m going to show you a few useful commit hooks you can easily add to your repository. This way, you’ll save time to concentrate on your development work.
This article assumes that you already have an understanding of what Git hooks are. If you’re a beginner and want to learn more, check out the documentation linked above.
Let’s get started!
Pre-Commit
If you’re already familiar with Git hooks, you know that when you create a new repository, you have to copy all hooks to the new project’s .git/hook
folder. You also have to manually change the hooks to ensure they work for different project structures. pre-commit
, a library written in Python, offers a convenient solution to that problem.
You specify a list of hooks you want in a single config file. You can use it for various languages to solve different tasks, such as detecting AWS credentials, large files, trailing whitespaces, validating JSON, XML syntax, and much more.
It automatically deals with the installation and execution of any hook.
Run this command to install it:
pip install pre-commit
Create a file called .pre-commit-config.yaml
in your project’s root directory. Here, you can include all the hooks you want.
Example configuration:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: check-executables-have-shebangs
- id: trailing-whitespace
- id: mixed-line-ending
- id…