Skip to content

Instantly share code, notes, and snippets.

@eelco
Last active November 8, 2016 22:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eelco/b7b811b3d6ff1733b95f to your computer and use it in GitHub Desktop.
Save eelco/b7b811b3d6ff1733b95f to your computer and use it in GitHub Desktop.
Script to merge branches in a way that keeps the repository history nice and clean.
#!/bin/bash
# Use the current branch as the source
SOURCE_BRANCH=`git rev-parse --abbrev-ref HEAD`
TARGET_BRANCH=${1:-master}
if [ "$SOURCE_BRANCH" = "" ]; then
# Something went wrong, but git probably already said what, just exit.
exit 1;
fi
if [ "`git rev-parse $TARGET_BRANCH 2>/dev/null`" = "$TARGET_BRANCH" ]; then
echo "Target branch '$TARGET_BRANCH' does not exist."
exit 1
fi
if [ "$SOURCE_BRANCH" = "$TARGET_BRANCH" ]; then
echo "On target branch '$TARGET_BRANCH', nothing to merge."
exit 1
fi
if [ ! -z "`git status -uno -s`" ]; then
echo "Working tree not clean, not merging."
exit 1
fi
if [ "`git merge-base $TARGET_BRANCH $SOURCE_BRANCH`" != "`git rev-parse $TARGET_BRANCH`" ]; then
echo "Branch can not be merged cleanly. Rebase '$SOURCE_BRANCH' onto '$TARGET_BRANCH' first."
exit 1
fi
echo "Trying to merge '$SOURCE_BRANCH' cleanly into '$TARGET_BRANCH'" && \
git checkout $TARGET_BRANCH && \
git merge --no-ff $SOURCE_BRANCH && \
git branch -d $SOURCE_BRANCH && \
echo "Branch '$SOURCE_BRANCH' succesfully merged into '$TARGET_BRANCH'"
# TODO:
# - [ ] Optional sync before merging (see older version)
# - [ ] Option to initiate rebasing if needed
# - [ ] Look up pull request (use git ls-remote)
# - [ ] Rewrite message when pull request (see github)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment