close
The Wayback Machine - https://web.archive.org/web/20241001050018/https://www.geeksforgeeks.org/git-hooks/
Open In App

Git – Hooks

Last Updated : 30 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Git Hooks are scripts that Git executes before or after events such as committing, pushing, and receiving changes. These hooks allow you to automate tasks, enforce policies, and customize your Git workflow. In this article, we’ll explore Git hooks in detail, covering their types, usage, and practical examples.

What are Git Hooks?

Git hooks are stored in the .git/hooks directory of your Git repository. Each hook is a script file named after the event it triggers. Git provides both client-side and server-side hooks. Client-side hooks run on your local machine, while server-side hooks execute on the Git server.

Why Use Git Hooks?

Implementing Git Hooks can help streamline your development process by:

  • Enforcing coding standards: Ensure all code adheres to your team’s guidelines before it gets committed.
  • Running tests: Automatically run tests before committing or pushing code to prevent breaking the build.
  • Generating documentation: Automatically generate documentation from comments in your code.
  • Sending notifications: Inform your team about code changes via email or chat.

Types of Git Hooks

  1. Client-Side hooks
  2. Server-Side hooks

BERJAYA

Types of Hooks

Client-Side hooksServer-Side hooks
pre-commitpre-receive
prepare-commit-msgupdate
commit-msgpost-receive
post-commit 
post-checkout 
pre-rebase 

Note: There are many other hooks are present except this but we are covering these major ones. Below is the representation for the same:

In order to use git hooks, we must follow some steps first to enable them which are as follows:

Step 1: First we need to change our directory to the below directory as follows:

repository/.git/hooks 

Below is a terminal window screenshot depicting the same as follows:

BERJAYA

At first, here we are in the ~/Desktop/GFG directory, which is a git repository. So we have used the below directory command to go to the specific directory. This directory contains all the hooks of a repository.

cd .git/hooks

Step 2: To use a hook first we need to enable it and to enable a hook we have to remove the .sample extension from the end of the files. In order to do so, we can use the following command as follows:

mv hookname.sample hookname 

Below is a terminal window screenshot depicting the same as follows: 

BERJAYA

Here we have removed the .sample extension of the pre-commit hook and enabled it.

Step 3: After that, we have to provide the execute permission for the hook. To do so we can use the following command as follows:

chmod +x hookname

Now we can write our scripts in different languages like Python, Bash, or Shell. In order to write a script first, you need to specify that in the first line of the script.

The first line of the script will be:

A. Python

#!/usr/bin/env python

B. Shell

#!/bin/sh

C. Bash

#!/bin/bash 

Note: We will be using Python scripts for this article.

Different Types of Hooks

A. Client-Side Hooks

1. pre-commit: The pre-commit hook runs on the git commit event. This can be used for Static analysis, Linting, Spell-checks, and Code style checks. It takes zero arguments and exiting with a non-zero status aborts the commit operation.

Let’s consider the simple script below for a demonstration. This script when runs will print the “This is a git hook” message on the console in case the commit is aborted. As here we have provided an exit code 1 which is a non-zero exit status that told git to abort the commit operation.

Example:

Python
#!/bin/python
import sys


def main():
    print("This is a git hook")
    sys.exit(1)


if __name__ == "__main__":
    main()


Here is the output when any commit operation is done on the repository –

BERJAYA

2. prepare-commit-msg: The prepare-commit-msg hook is run before the commit message editor is fired up but after the default message is created. It is useful for editing the default message before the commit author sees it. It is also useful for adding Ticket-ID, Branch name, Style Checklist, and Rules for commits. It takes three parameters they are as follows:

  • The path to holds the commit message so far
  • The type of commit
  • commit SHA-1 information 

3. commit-msg: This is useful to validate a commit. Developers can provide rules to validate the commit state or the commit message using this hook. Like it is helpful for spell-checks of commit messages. This hook takes one parameter and it is the path to a temporary file that contains the commit message. Let us take one small code snippet for this which is below as follows:

Example:

Python
#!/bin/python
import sys
def main():
        with open(sys.argv[1],'a+') as fp:
            # fp.read() can be used to read the commit msg
            fp.writelines(" and issue id is #1") #appending with issue id
            sys.exit(0) # indicates success

if __name__=="__main__":
    main()

BERJAYA

Here during the commit operation, the commit message is appended with the issue id.

4. post-commit: This hook runs after the commit operation successfully completed. This hook can be useful to provide notifications and it doesn’t take any parameters. Here is a small code snippet that gives an acknowledgment after committing.

Example:

Python
#!/bin/python
import sys
def main():
    print("Satyajit Ghosh successfully committed the changes in the repo")
    sys.exit(0) # indicates success

if __name__=="__main__":
    main()

5. post-checkout: The post-checkout hook runs after the git checkout operation. It can be used to set up a working directory, auto-generating documentation, etc. It works similar to the post-commit hook. This hook accepts three parameters as follows:

  • The ref of the previous HEAD
  • The ref of the new HEAD
  • A flag indicating branch checkout(1) or a file checkout (0).

6. pre-rebase: The pre-rebase hook runs before the rebase operation. A script can be used to validate the rebase matches the workflow or not. If not then a non-zero exit code from the script will halt the rebase process.

B. Server-Side Hooks

1. pre-receive: This hook reacts to git push and updates the references in its repository. It takes no arguments but for each ref to be updated it receives standard input in this format.

<old-value> SP <new-value> SP <ref-name> LF>

where <old-value> is the old object name stored in the ref, <new-value> is the new object name to be stored in the ref, and <ref-name> is the full name of the ref. If the hook exits with a non-zero status, none of the refs will be updated.

2. update: Before updating the ref on the remote repository, the update hook is invoked. Its exit status determines the success or failure of the ref update. It takes three arguments as follows: 

  • the name of the ref being updated
  • the old object name is stored in the ref
  • and the new object name to be stored in the ref.

3. post-receive: It executes on the remote repository once all the refs have been updated. It takes no arguments but gets the same information as the pre-receive hook does on its standard input.

Best Practices for Git Hooks

  • Keep hooks fast: Ensure hooks run quickly to avoid slowing down your workflow.
  • Use hooks sparingly: Only use hooks for essential tasks to prevent complexity.
  • Document your hooks: Provide clear documentation on what each hook does and how to modify it.
  • Use version control: Store your hooks in version control to maintain consistency across your team.


Previous Article
Next Article

Similar Reads

Difference Between Git remote prune, Git prune and Git fetch --prune
Git is a version control system that helps developers manage and track changes in their codebase. Among its many commands, git remote prune, git prune, and git fetch --prune are essential for maintaining a clean and organized repository. This article will explain the differences between these commands, their syntax, uses, and provide examples to il
4 min read
When is it best to use custom hooks instead of built-in React hooks?
Custom hooks in React are useful when you want to extract and reuse stateful logic across multiple components. While built-in React hooks like useState, useEffect, and useContext cover many common scenarios, there are cases where creating custom hooks can enhance code organization, readability, and reusability. When to Choose for Custom Hooks in Re
2 min read
Customizing Git Hooks for Workflow Automation
Git is a distributed version control system that monitors changes to a project. Git hooks are scripts that run in response to Git events such as commit or push. They automate tasks, enforce rules, and can be tailored to your project's requirements. A pre-commit hook, for example, can detect errors in the code, whereas a post-receive hook can send e
7 min read
How To Skip Git Commit Hooks?
Git commit hooks are powerful tools that automatically run scripts before or after specific Git operations, such as committing or pushing code. They are used to enforce coding standards, run tests, or automate tasks. However, there might be situations where you need to bypass these hooks temporarily, for instance, during large imports or debugging.
3 min read
Git - git-show Command Line Utility
Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git relies on the basis of distributed development of software where more than one developer may have access to the source code of a specific application and can modify changes to it that may be
3 min read
Git LFS: Managing Large Files in Git Repositories
Git, undoubtedly one of the most popular version control systems, is widely used for managing source code in software development projects. However, one of its limitations is its handling of large files. Traditional Git repositories struggle to efficiently manage large files, leading to bloated repositories and slow performance. This is where Git L
4 min read
Git Subtree vs. Git Submodule
Git Subtree and Git Submodule are both mechanisms in Git that allow you to incorporate external repositories into your own repository. They provide a way to manage dependencies and include code from other projects while keeping your repository organized and maintainable. Git Subtree: Git Subtree allows you to insert a separate repository as a subdi
4 min read
How to Set Up Git Using Git Config?
Git is a powerful version control system that helps developers manage and track changes in their code. Setting up Git correctly is important for maintaining an organized and efficient workflow. In this article, we'll walk you through the process of setting up Git using the git config command. PrerequisitesBefore we dive into the setup process, make
3 min read
How To Exit Git Log or Git Diff?
When working with Git, the git log and git diff commands are important for viewing commit history and changes between commits, respectively. However, if you're new to Git, you might find yourself stuck in these views, unsure how to exit. This article will guide you through the steps to exit git log or git diff, ensuring a smooth experience while na
2 min read
Difference between “git add -A” and “git add”
When working with Git, the git add command is used to move changes from your working directory to the staging area. However, there are different options and flags that can be used with git add, such as -A, which might lead to some confusion. In this article, we'll explore the differences between git add -A and git add. 1. Git add- CommandThe git ad
2 min read
Git - Difference Between Git Revert, Checkout and Reset
Git offers a range of commands to manage and manipulate your codebase. Among these commands, git revert, git checkout, and git reset are frequently used for different purposes. Understanding the differences between these commands is important for effective version control. In this article, we'll explore the functionalities and use cases of git reve
6 min read
How to Fix Git Error "Unable to create '/path/my_project/.git/index.lock'"?
The Git error "Unable to create '/path/my_project/.git/index.lock'" typically occurs when Git is unable to create or write to the index.lock file. This file is used to prevent simultaneous processes from modifying the repository, which could lead to corruption. Table of Content Remove the Lock File ManuallyUse Git Command to Remove the Lock FileRes
2 min read
Difference Between "git commit" and "git push"?
Git commit and git push are two essential commands you'll use a lot when working with Git. even their frequent use together, they have different functions. In order to help you understand when and how to use these two commands effectively in your version control workflow, this article will break down their differences. What is git commit?git commit
2 min read
Difference Between Git Fetch and Git Pull
Understanding the difference between git fetch and git pull is important for effective version control in Git. Git Fetch and Git Pull are two important commands in Git that help in managing remote repositories. While both commands involve retrieving data from remote repositories, they serve distinct purposes and are used in different contexts. In t
5 min read
Git - git prune
Git prune is used to remove the unreachable objects and clear up the local repository. Git is a powerful version control system that helps developers manage their code efficiently. However, as your project evolves, you may accumulate unnecessary data that clutters your repository. This is where git prune comes in view. Table of Content What is git
6 min read
Git For Non-Developers: How Different Industries Are Adopting Git?
While Git is widely recognized for its role in software development, it's increasingly being adopted by non-developers across various industries. This shift is driven by the growing need for version control, collaboration, and efficient project management in fields like marketing, design, data science, education, and even legal and finance sectors.
8 min read
Difference Between Git Push Origin and Git Push Origin Master
Understanding the difference between git push origin and git push origin master is important for efficient version control in Git. These commands are used to upload changes from your local repository to a remote repository, but they function differently. This article will explain these differences, how each command works, and when to use them. What
3 min read
Git vs. Other Version Control Systems: Why Git Stands Out?
Version control systems (VCS) are an essential tool for developers, enabling them to track changes, collaborate on projects, and manage codebases efficiently. Among the various VCS options available, Git has emerged as the dominant choice, used by millions of developers and organizations worldwide. While other systems like Subversion (SVN), Mercuri
8 min read
Async Hooks in Node.js
Async_hooks module is used because it provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application. Features: You can capture any asynchronous activity in a Node.js process.Minimal performance overhead.Powerful and flexible API. These resources are tracked in C++ and anything inheriting
2 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a ho
2 min read
React Suite Notification Props & Hooks
React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. The notification is also used with a toaster in react-based applications. <Notification> Props: closable: It is a boolean
4 min read
Things You Should Know About React Hooks
React...We all know the importance of this library in the tech industry. Most of the applications are switching to React because of its advantages and features. There are many features of React. React hooks is one of them. React hooks was first released in October 2018. In React a lot of developers use the lifecycle method which is nothing, but jus
4 min read
How to build a Tic-Tac-Toe Game using React Hooks ?
To build a Tic-Tac-Toe using react Hooks include the interactive components that represent the board, the signs, and at last the winner of the game. Preview of final output: Let us have a look at how the final application will look like. Prerequisite of Tic-Tac-Toe Game:Introduction to ReactFunctional Components in ReactReact HooksNPM & Node.js
8 min read
How to generate random colors by using React hooks ?
In web development, colors play a vital role in creating visually appealing and engaging user interfaces. In React we may need to generate random colors dynamically. In this article, we will explore how to achieve this using React hooks, a powerful feature introduced in ReactJs. Pre-requisite:NPM & Node.jsReact.jsReact HooksApproach:To generate
2 min read
How to define JavaScript Hooks ?
Hooks are nothing but functions, that you can use to disassociate the components that can be reused from the functional components. React state and lifecycle properties can be "hooked onto" from function component code via hooks. Hooks enable you to use React without classes considering they don't operate within classes. Prerequisites:NodeJS or NPM
3 min read
React JS Hooks Reference
React hooks are functions that enable functional components to use state and lifecycle features that were previously only available in class components. Example: Below is the basic representation of the React JS Hooks useState. C/C++ Code import React, { useState } from 'react'; import './App.css' const App = () => { const [num, setNum] = useSta
2 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building. We will discuss the following state management technique
6 min read
New Hooks in React 18
React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components,
6 min read
Article Tags :