Reputation: 662
I'm working on .git/hooks/post-checkout
and having trouble either sourcing/exporting the branch name, or getting the prior branch name. I want to restart the server when switching to or from s3
branch.
I couldn't figure out how to source the env var in bash, so I tried using git to get the prior branch, but the closest I got was git checkout -
/git checkout @{-1}
, tho I'm not sure simply how to retrieve the prior branch name without the call to checkout.
Should I be using Git env vars instead of shell?
#!/bin/bash
touch tmp/restart.txt
echo " *** restarting puma-dev"
current_branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')
if [ "$current_branch" = "s3" ]
then
echo " *** please don't upload any files"
echo
fi
Upvotes: 0
Views: 579
Reputation: 471
Git passes the previous and current ref names to the post-checkout
hook, so you should be able to do something like:
#!/bin/sh
oldref="$1"
newref="$2"
branch_update="$3"
[ "$branch_update" = '1' ] || exit # exit if branch didn't change
[ "$oldref" = 'refs/heads/s3' ] && oldref_was_s3=1
[ "$newref" = 'refs/heads/s3' ] && newref_is_s3=1
if [ -z "$oldref_was_s3" -a -n "$newref_is_s3" ]; then
echo " *** please don't upload any files"
fi
Totally untested, but it should be close.
Upvotes: 2
Reputation: 662
Thanks in part to Chris, whose method I couldn't interpret or get working, but found the information helpful, and thanks to Keif Kraken, whose method I did get working.
Restart server when changing to or from a specific branch (s3)
.git/hooks/post-checkout
script
#!/bin/bash
oldref=$(git rev-parse --abbrev-ref @{-1})
newref=$(git rev-parse --abbrev-ref head)
if [[ ( "$oldref" = "s3" || "$newref" = "s3" ) && "$oldref" != "$newref" ]]
then
touch tmp/restart.txt
echo " *** restarting puma-dev"
echo " *** please don't upload any files"
fi
Upvotes: 0
Reputation: 10640
You should be able to use this line to grab the previous branch name:
git rev-parse --abbrev-ref @{-1}
and to get the current branch name:
git rev-parse --abbrev-ref HEAD
Upvotes: 1