Backing Out Git Commits With
Reset And Stash

Our team had some of us working on master in our git repository, and a refactor was done in a branch so the team lead decided we should all move to from the master to the branch because the merge was painful for this particular feature.  If you have this situation and a few commits in the wrong branch here’s a method that might help out using git reset and git stash.  Reset can undo your last commit, and stash can save it off-stream to retrieve whenever you wish.

For this example I have several commits, not pushed,  in the local repository already.  Looking in Tortoise Git log you can see this state  is three commits ahead of origin/HEAD.

The task here is to  back out the commits from master, save them, then recommit them into the branch.  There are several ways to accomplish this in git but I am showing the revert-stash methodology.

Before starting the process, my recommonedation (that you do not need to follow) is to make sure your stash was clear —  I do so that I can just issue a series of pops to get back to my starting point easily on branch without worrying about mistakes.

git stash clear

Then clean up any other code/work in progress so that git status shows clean.

Next start backing out the commits back to the original HEAD.  Each commit should be backed and saved atomically as a separate entry to your stash.  For instance in this example, start at Commit 3 and work back to Commit 1.

git reset HEAD~1        //back out current top commit; 1 every time
git status             //check and see what files you have to stash
git add -A :/          //stage all the files listed
git stash save Commit# //save the commit to whatever name you choose
git status             //a good place to check status and Tortoise log

….repeat.

Now when you do git stash list you can see all the commits ready for moving to the branch, and Tortoise shows master at  origin/HEAD so you know that all changes were removed.

Time to switch branches.

Issue a git branch -a to list all the remotes as well. Switch to your branch:

git checkout remotebranch

Now you can just pop your first stash right off the stack, confirm it works, check it in and move onto the next stash item:

git stash list          //just checking
git stash pop           //takes first one off list and deletes from stash list
git add -A :/           //stage everything
//--> do some merging/work as needed
mvn clean install       //whatever build process you do to test and check
git commit -c "Commit#" //commit your code
git status              //always check your state!!

….repeat.

Now sync it up with remotebranch HEAD:

git pull --rebase //just checking that I'm up to date
git push          //send those commits to the homeworld

All done!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>