Skip to content

Instantly share code, notes, and snippets.

@jpopesculian
Last active June 16, 2016 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpopesculian/89621d5bc6af9ab16e55a789aaadaea1 to your computer and use it in GitHub Desktop.
Save jpopesculian/89621d5bc6af9ab16e55a789aaadaea1 to your computer and use it in GitHub Desktop.
Git utility to update master and test merge
#!/bin/bash
# Add to bashrc to alias as "git sync":
# git() { if [[ $@ == 'sync' ]]; then command git-umatm; else command git "$@"; fi }
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
REMOTE_NAME=${1:-"origin"}
MASTER_BRANCH_NAME=${2:-"master"}
print_header() {
echo -e "\e[1m$1\e[0m"
}
check_uncommited_changes() {
if ! git diff-index --quiet HEAD --; then
echo "You need to commit or stash your changes"
exit 1
fi
}
merge_dry_run() {
branch=$1
git merge --no-commit --no-ff $branch
git merge --abort &> /dev/null
}
need_to_push() {
read -p "You need to push to $REMOTE_NAME. Would you like to now (y/n)? " answer
case ${answer:0:1} in
y|Y )
git push $REMOTE_NAME $CURRENT_BRANCH
return 0
;;
* )
return 0
;;
esac
}
need_to_pull() {
merge_dry_run "$REMOTE_NAME/$CURRENT_BRANCH"
read -p "You need to pull from $REMOTE_NAME. Would you like to now (y/n)? " answer
case ${answer:0:1} in
y|Y )
git pull $REMOTE_NAME $CURRENT_BRANCH
return 0
;;
* )
echo "Can't continue sync until you pull from $REMOTE_NAME"
exit 1
;;
esac
}
check_up_to_date() {
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse @{u})
BASE=$(git merge-base @ @{u})
git status | awk "FNR == 2 {print}"
if [ $LOCAL = $REMOTE ]; then
return 0
elif [ $LOCAL = $BASE ]; then
need_to_pull
elif [ $REMOTE = $BASE ]; then
need_to_push
else
need_to_pull
need_to_push
fi
}
check_merge_master() {
git checkout --quiet $CURRENT_BRANCH
dry_run_result=$(merge_dry_run $MASTER_BRANCH_NAME)
echo $dry_run_result
if [ "$dry_run_result" = "Already up-to-date." ]; then
return 0
else
read -p "You need to merge from $MASTER_BRANCH_NAME. Would you like to now (y/n)? " answer
case ${answer:0:1} in
y|Y )
git merge $MASTER_BRANCH_NAME
need_to_push
return 0
;;
* )
exit 1
;;
esac
return 1
fi
}
check_uncommited_changes
print_header "Fetching"
git fetch
print_header "Checking Remote"
check_up_to_date
print_header "Updating Master"
git checkout --quiet $MASTER_BRANCH_NAME
git pull $REMOTE_NAME $MASTER_BRANCH_NAME
print_header "Testing Master Merge"
check_merge_master
echo "Happy coding!"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment