Is there a way to trigger a hook after a new branch has been checked out in Git?
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.
The post-checkout
hook receives three parameters:
0
) or branch checkout (1
)You can use the fact that a branch created from the current HEAD will have the same value for parameters 1 and 2.
cat > .git/hooks/post-checkout <<"EOF"
if [ "$3" == "0" ]; then exit; fi
if [ "$1" == "$2" ]; then
echo "New branch created. (Probably)."
fi
EOF
chmod u+x .git/hooks/post-checkout
Limitations:
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
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.