Is there a way to trigger a hook after a new branch has been checked out in Git?
Checking out branches Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch. Think of it as a way to select which line of development you're working on.
If you want enforcement, use an update hook in the central repo. If the hook is doing per-commit verification, you can still provide a pre-commit hook; developers will likely adopt it voluntarily, so that they can find out right away when they've done something wrong, rather than waiting until they try to push.
The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer. If this script exits non-zero, Git aborts the commit process, so you can use it to validate your project state or commit message before allowing a commit to go through.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With