Cleaning up git history with git rebase

Git rebase is good when you want to combine some historical commits into one commit. This might be a good idea because your history contains too many unncessary test commits, or if you want to cut down the size of your git objects. On the other hand, changing history can be a dangerous thing, it means that everyone else using your repo needs to acknowledge the change by force pulling.

for example,

git log --oneline
291423b update setup
7732e24 update deployment files
5e0c60f Merge branch 'develop'
e656609 update paths
1f35b9a Merge branch 'develop'
c914ca6 update prod
746eff5 update readme
8754887 update readme
ce9563d update staging

Now we want to remove everything between 291423b and ce9563d. Basically, you want to crunch everything from 291423b down to a point in history, ie ce9563d. Here comes rebase.

git rebase -i ce9563d
pick 8c79382 update
pick 8754887 update readme
pick 746eff5 update readme
pick c914ca6 update prod
pick e656609 update paths
pick 7732e24 update deployment files
pick 291423b update setup

# Rebase ce9563d..cd268a9 onto ce9563d
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

Note that now the latest commit is at the bottom, exactly reverse of what you see in git log. If you delete any of the lines, the commit will be gone. This is a bad bad idea and its best not to do that, instead, use “f” or ‘s’ and leave the first commit as it is like so:

pick 8c79382 update
f 8754887 update readme
f 746eff5 update readme
f c914ca6 update prod
f e656609 update paths
f 7732e24 update deployment files
f 291423b update setup

# Rebase ce9563d..cd268a9 onto ce9563d
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#

rebase will tell you if it encounters any problems. Fix them and you have to force push

git push origin --force

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.