Is there a way to trigger a hook after a new branch has been checked out in Git?
Is there a way to trigger a hook after a new branch has been checked out in Git?
A git hook is a script placed in a special location of your repository, that location is:
.git/hooks
The script can be any kind that you can execute in your environment i.e. bash, python, ruby etc.
The hook that is executed after a checkout is post-checkout. From the docs:
...The hook is given three parameters...
Example:
-
Create the hook (script):
touch .git/hooks/post-checkout chmod u+x .git/hooks/post-checkout
Hook sample content:
#!/bin/bash
set -e
printf '\npost-checkout hook\n\n'
prevHEAD=$1
newHEAD=$2
checkoutType=$3
[[ $checkoutType == 1 ]] && checkoutType='branch' ||
checkoutType='file' ;
echo 'Checkout type: '$checkoutType
echo ' prev HEAD: '`git name-rev --name-only $prevHEAD`
echo ' new HEAD: '`git name-rev --name-only $newHEAD`
Note: The shebang in the first line indicates the type of script.
This script (git hook) will only capture the three parameters passed and print them in a human-friendly format.
If one of these hooks won’t do it I’d be amazed:
https://schacon.github.io/git/githooks.html
Maybe this one:
post-checkout
This hook is invoked when a git-checkout is run after having updated the worktree. The hook is given three parameters: the ref of the previous HEAD, the ref of the new HEAD (which may or may not have changed), and a flag indicating whether the checkout was a branch checkout (changing branches, flag=1) or a file checkout (retrieving a file from the index, flag=0). This hook cannot affect the outcome of git-checkout.
Similar to others but verifies that the branch has been checked out once.
#!/bin/bash
# this is a file checkout – do nothing
if [ "$3" == "0" ]; then exit; fi
BRANCH_NAME=$(git symbolic-ref --short -q HEAD)
NUM_CHECKOUTS=`git reflog --date=local | grep -o ${BRANCH_NAME} | wc -l`
#if the refs of the previous and new heads are the same
#AND the number of checkouts equals one, a new branch has been created
if [ "$1" == "$2" ] && [ ${NUM_CHECKOUTS} -eq 1 ]; then
git push origin ${BRANCH_NAME}
fi