Git Hooks

1 minute read

  • all the hooks are present by default with .sample file extension in .git/hooks
  • remove the file extension
  • execute this command to make it executable
touch pre-commit
chmod +x pre-commit

pre commit

https://github.com/nitinkc/SystemEnvironment/blob/master/gitHooks/pre-commit

Prevent commits to special branches

PROTECTED_BRANCHES="^(master|develop|release-*|bugfix-*)"
if [[ "$CURRENT_BRANCH" =~ ($SPECIAL_BRANCH) ]]; then
  echo >&2 "Preventing commit on $CURRENT_BRANCH branch"
  echo >&2 "commit with -n switch to bypass the pre-commit hook."
  echo >&2 "Hooks at Repo would prevent push directly to such branch"
  exit 1

-n to bypass the hook

 git commit -n -m "final commit"

Allow creation of a new branch if attempted to commit to a restricted branch

# Get the current branch name
current_branch=$(git symbolic-ref --short HEAD)
# List of branches where commits are restricted
restricted_branches=("main" "develop" "bugfix")

# Check if the current branch is restricted
if [[ " ${restricted_branches[@]} " =~ " ${current_branch} " ]]; then
    echo "Error: Commits to branch '${current_branch}' are not allowed."
    echo "Using git switch -c new-branch-name to switch to a new branch"
    
    # Generate a unique branch name with current date and timestamp
    new_branch_name="feature/new_branch_$(date +'%Y%m%d_%H%M%S')"
    echo " switching to the new branch $new_branch_name" 
    git switch -c $new_branch_name
    
    exit 1
fi

pre-push

#!/bin/bash

AUTHORINFO=$(git var GIT_AUTHOR_IDENT) || exit 1
NAME=$(printf '%s\n' "${AUTHORINFO}" | sed -n 's/^\(.*\) <.*$/\1/p')
EMAIL=$(printf '%s\n' "${AUTHORINFO}" | sed -n 's/^.* <\(.*\)> .*$/\1/p')

echo "Name and email for this commit: ${NAME}<${EMAIL}>"
if [ "${EMAIL}" =~ "abc@gmail.com" ]; then
  echo >&2 "Please commit using Enterprise ID instead of personal name ${NAME} and email <${EMAIL}>":
  exit 1;
fi
exit 0

Global githooks

Set up at machine level; to be applied for each project

Standardizing Hooks

mkdir -p ~/.git-templates/hooks
#Create a pre commit hook file and set its permissions
touch ~/.git-templates/hooks/pre-commit
chmod +x ~/.git-templates/hooks/pre-commit

Configure Git to Use the Global Hooks Directory:

This setting ensures that the hooks from ~/.git-templates/hooks are copied to the .git/hooks directory in every new repository you create.

git config --global init.templatedir '~/.git-templates'

For Existing Repositories:

Need to manually copy the hooks from the global directory into each repository’s .git/hooks directory.

for repo in $(find /path/to/your/repos -type d -name '.git'); do
  cp ~/.git-templates/hooks/* $repo/hooks/
done

Tags:

Categories:

Updated: