Automating your workflow with Git Hooks

Git hooks are like automatic helpers for your repository. They are scripts that Git runs automatically when specific actions happen (like committing or switching branches), helping you save time and enforce quality.

Common Hooks

How to Set Up a Hook

Hooks live inside your project’s .git/hooks folder. By default, this folder is filled with sample files.

  1. Find the Sample: Look for the sample file you want to use, like pre-commit.sample.
  2. Activate the Hook: To activate it, just rename the file by removing the .sample extension:
     mv .git/hooks/pre-commit.sample .git/hooks/pre-commit
    
  3. Make it Executable: Git requires the script to be executable. Use chmod to set the permission:
     chmod +x .git/hooks/pre-commit
    
  4. Write Your Script: Now you can open the pre-commit file and write your logic. This is typically a shell script, but you can use other languages like Python or Ruby.

Example1: A hook script to prevent direct commits to ‘main’ or ‘master’

#!/bin/sh
#
# A hook script to prevent direct commits to 'main' or 'master'.

current_branch=$(git rev-parse --abbrev-ref HEAD)

if [ "$current_branch" = "main" ] || [ "$current_branch" = "master" ]
then
  echo "---------------------------------------------------------------"
  echo "Error: Direct commits to the '$current_branch' branch are forbidden!"
  echo "Please create a feature branch (e.g., 'git checkout -b my-feature')"
  echo "and commit your changes there."
  echo "---------------------------------------------------------------"
  exit 1
else
  exit 0
fi

Example1: A hook to check if the commit message starts with a ticket ID (e.g., JIRA-123: Message)

  1. Create a new file in your hooks folder: .git/hooks/commit-msg.
    • Make it executable: chmod +x .git/hooks/commit-msg.

Paste the following code into that file:

#!/bin/sh
#
# A hook to check if the commit message starts with a ticket ID
# (e.g., JIRA-123: Message)

# Get the commit message from the file passed as an argument
commit_msg_file=$1
first_line=$(head -n1 "$commit_msg_file")

# Define the regular expression for the pattern (e.g., JIRA-123: Message)
# This checks for one or more uppercase letters, a hyphen, one or more numbers,
# a colon, and a space.
regex="^[A-Z]+-[0-9]+: .+"

# Check if the first line matches the regex
if ! echo "$first_line" | grep -qE "$regex"; then
  echo "---------------------------------------------------------------"
  echo "Error: Invalid commit message format!"
  echo "Your message must start with a ticket ID, like:"
  echo "  'JIRA-123: Fix login bug'"
  echo "---------------------------------------------------------------"
  exit 1
fi

exit 0

Think of hooks as a smart assistant that reminds you to double-check your work (like running a spell-check) before you’re allowed to send the email.