Skip to content

Instantly share code, notes, and snippets.

@puckbag
Last active August 29, 2015 13:58
Show Gist options
  • Save puckbag/10418995 to your computer and use it in GitHub Desktop.
Save puckbag/10418995 to your computer and use it in GitHub Desktop.
#!/bin/bash
# example usage:
# $ sync-branch origin/production production
# issues:
# * what if files have been modified? handle pull failure.
# http://stackoverflow.com/a/12791408/1596013
# http://stackoverflow.com/a/12142066/1596013
# http://stackoverflow.com/a/10520718/1596013
# http://stackoverflow.com/a/5168129/1596013
# exit statuses
EXIT_SUCCESS=0
EXIT_NOTGIT=1
EXIT_INVALID=2
EXIT_WRONGBRANCH=3
EXIT_AHEAD=4
# must be a git directory
git status >/dev/null 2>&1
if [ $? != 0 ]; then
echo 'this is not a git directory.'
exit $EXIT_NOTGIT
fi
# config
REMOTE="${1%/*}"
BRANCH_REMOTE="${1#*/}"
BRANCH_LOCAL="$2"
BRANCH_CURRENT=`git rev-parse --abbrev-ref HEAD`
echo "syncing ($BRANCH_LOCAL) with ($REMOTE/$BRANCH_REMOTE)"
# exit if invalid branches
git show-branch "$REMOTE/$BRANCH_REMOTE" >/dev/null 2>&1
if [ $? != 0 ]; then
echo "error: invalid remote branch ($1)"
exit $EXIT_INVALID
fi
git show-branch "$BRANCH_LOCAL" >/dev/null 2>&1
if [ $? != 0 ]; then
echo "error: invalid local branch ($2)"
exit $EXIT_INVALID
fi
# exit if wrong branch checked out
if [ $BRANCH_CURRENT != $BRANCH_LOCAL ]; then
echo "error: wrong branch checked out ($BRANCH_CURRENT). expecting ($BRANCH_LOCAL)"
exit $EXIT_WRONGBRANCH
fi
# find out where we are
git fetch
AHEAD=`git log $REMOTE/$BRANCH_REMOTE..HEAD --oneline`
BEHIND=`git log HEAD..$REMOTE/$BRANCH_REMOTE --oneline`
# exit if we're locally ahead of remote
if [ "$AHEAD" ]; then
echo 'AHEAD:'
echo $AHEAD
echo 'error: local ahead of remote'
exit $EXIT_AHEAD
fi
# if we're behind, lets pull.
if [ "$BEHIND" ]; then
echo 'BEHIND:'
echo $BEHIND
echo 'local behind remote. pull...'
git pull $REMOTE $REMOTE_BRANCH
else
echo 'up-to-date. nothing to do.'
fi
# win!
echo 'success'
exit $EXIT_SUCCESS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment