Git Rewrite History, Removing Old Commits From History


"REWRITING History is a BAD PRACTICE and should AVOID as much as possible".
We recently came across this serious issue with "git" repositories. In our word; "WE MESSED UP OUR REPO". Had several reverts to fix it(But revert again is recorded as commit and so on...). Again needed to revert all revert commits. All these things altogether left us one option; which is the rewriting the history.

This post will show you how to re-write, but this will be an issue if lots of people have based their work on the remote master branch and have pulled that branch in their local repo (But if you haven't push the revert commits into remote repository; this would be the ideal solution).

What we are trying to achieve here is...
  1. go back to a past revision
  2. create and switch to a dummy branch
  3. rename dummy branch into the master.

Yep, That's it!

STEP 1:
First we need to rewind back to a specific commit. Below command will move the pointer to a specific commit. The "<SHA1>" is the commit id.

git reset --hard <SHA1>
git status

Should output something similar below. Note that in this example given commit id resulted current branch to move back 10 commits.

On branch master
Your branch is behind 'origin/master' by 10 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
nothing to commit, working directory clean

STEP 2:
Now create a new branch base on the current pointer and switch into it.
git checkout -b temp
STEP 3:
As the final step we are renaming our "master" branch into another and "temp" into "master".
git branch -m master old-master #rename master branch into old-master
git branch -m temp master #rename temp branch into master
git push -f origin master #do a force push changes
SHARE

Rasika Perera

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment