Rewriting Git history, correcting a previous commit in your PR

This blog post should be dedicated to my mentor jaragunde at Igalia, as he had been the one pointing me out to go back again and again to that wrong PR, I made, and correct it. The first time I did, it sounded a bit confusing, and here you go!

Scenario:
You are working on an XYZ Pull Request having a series of commits namely 234234, 11233 and the latest one being 5514134. Your mentor tells you there is a mistake in 11233, and you want to go back to that commit, and correct the same.

Alright, so lets assume you are in the branch myfaultybranch with the git log showing up 5514134 at the top.

Steps:

  1. git stash – lets make sure there are no debris left!
  2. git rebase -i 11233^ – make sure you put the ^ at the end, otherwise the following steps would fail miserably.
  3. on the screen that come up, you will have the other commits too listed, looking like
    pick 11233 [#222] Your faulty commit message here
    pick 234234 [#222] This commit has no problem
    

    Edit the first line, from pick to edit so that it looks like:

    edit 11233 [#222] Your faulty commit message here
    pick 234234 [#222] This commit has no problem
    
  4. Save, and you are in a state where you are one step before committing 11233. Yay! Now make all your changes you want, correct all the mistakes at your ease!
  5. Once set, git add and git commit --amend and modify the commit message too, if you want
  6. All set, and you can now execute git rebase --continue and you will be back in your commit 5514134. Yay!
  7. Push your changes to your origin via a git push -f myfaultybranch
  8. In case you screw up in between, please do git reset --hard 5514134 and you will be reverted back 🙂

Hope it helps! Lets rewrite history! Found something wrong ? Please do comment!

Reset a muddled up git local repo

This looks childs play, but often I have heard people wondering how to reset their git local repo once they find they have screwed it enough. This can happen usually due to branches diverging or a badly executed command, or even altering some wanted files.

* To reset the entire repo to the remote branch master:

git stash
git checkout master .
git checkout master
git fetch --all
git pull origin master
git reset --hard origin/master
git rebase origin/master

even the same would work without these entire commands, but given all of these, you will have your git repo back to normal and the HEAD pointer pointing to the topmost master commit.

* To reset a single file foo/bar.php with the remote master:

git checkout master foo/bar.php

* If you were in between some rebase, and you need to cancel the same, and get back

rm -fr .git/rebase-apply

Yay! Hope it helps someone.