Let's say you have a Pull Request from myBranch
to master
with 3 commits, and you want them to appear as a single commit in master
.
If you're merging on the command line, this is trivial:
git checkout master
git merge --squash myBranch
git commit
But if you're merging with a GUI (like with a Github PR), you need to squash your commits on myBranch
before merging into master
:
# pull the latest master
git checkout master
git pull origin master
# ensure that all of your commits are on top of master's commits.
# for example, say myBranch's git log looks like this:
#
# 47c3031 <- my commit #3
# dfd9sd9 <- my commit #2
# 2a31f69 <- a commit that someone else merged to master
# b6500bd <- my commit #1
#
# after running `git rebase master`, your log might now look like this:
#
# de9d677 <- my commit #3
# db110fc <- my commit #2
# 854bd4b <- my commit #1
# 0abd05c <- a commit that someone else merged to master
#
# note that the git hashes have changed, but the contents of each commit have not
#
git checkout myBranch
git rebase master
# find the 1st commit in your series of commits.
# for example, in this example, we would expect "0abd05c"
git merge-base -a head master
# reset to the 1st commit in your series of commits.
# this will undo your commits, and move all the changes
# from your commits into the staging area
git reset --soft 0abd05c
# make sure everything looks right
git status
git diff origin/master
# create a new commit, that will replace the 3 commits
# you just reset
git commit -m "my new commit message"
# push to the origin (force push since we're rewriting history)
git push -f origin myBranch