Skip to content

Instantly share code, notes, and snippets.

@jnothman
Last active December 17, 2015 06:28
Show Gist options
  • Save jnothman/5565409 to your computer and use it in GitHub Desktop.
Save jnothman/5565409 to your computer and use it in GitHub Desktop.
Merge a github branch (generally pull request), squashing its commits onto master.
#!/bin/bash
branch="$1"
if [ -z "$branch" -o -n "$2" ]
then
echo Usage: $0 gh_user:branch_name
exit 2
fi
if git remote | grep ^upstream$
then
upstream=upstream
else
upstream=origin
fi
repo=$(git remote -v | grep '//github.com' | grep -oP '(?<=/)[^/]+(?= )' | head -n1)
uname=$(echo $branch | grep -oP '^[^:]+')
ubranch=$(echo $branch | grep -oP '(?<=:).+')
lbranch="sqmrg/$ubranch" &&
fetch_args="https://github.com/$uname/$repo $ubranch:$lbranch" &&
echo Squash-merging $fetch_args >&2 &&
ed_dir=$(mktemp -d -t squash_ed) &&
ed_path="$ed_dir/squash_ed" &&
normal_ed="$EDITOR" &&
echo '#!/bin/bash
if grep -q "^# Rebase .* onto " "$1"
then
echo squash-editing >&2
tmp="$(mktemp -t squash_out)"
awk '"'"'NR != 1 { sub(/^pick/, "squash") } {print}'"'"' "$1" > "$tmp"
mv "$tmp" "$1"
else
echo launching '$normal_ed' >&2
"'$normal_ed'" "$1"
exit $?
fi
' > $ed_path &&
chmod +x $ed_path &&
git checkout master &&
git pull --rebase $upstream master &&
git fetch $fetch_args &&
git checkout $lbranch &&
EDITOR=$ed_path git rebase -i master &&
git checkout master &&
(test "$(git rev-parse master)" == "$(git rev-parse $lbranch^)" || (echo "Unexpected error: $lbranch^ != master" && exit 1)) &&
git merge $lbranch &&
git branch -d $lbranch
rm -r $ed_dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment