Search code examples
gitversion-controlworkflowbranchrevert

Basic git process - I coded in a wrong direction and now I want to back up


My scenario, using git:

  • Wrote some code and committed
  • Added feature 1 and committed
  • Added feature 2 and committed
  • Added feature 3 and committed
  • Added feature 4 and committed

and so on...

Everything is of course in master.

I have now decided that I don't want to implement features 3 and 4 at this time (may want them in the future). So I would like to "go back" (there is lots of debate about the word "revert" so I will avoid using it) to just after feature 2's commit and continue there.

I feel like branching is somehow in the equation here but I am not clear on what to do. I would like to understand the logical scenario first and then understand the commands to get me there.


Solution

  • There are a couple of options depending on if you have pushed these changes to the remote server or not.

    If you haven't pushed up to remote yet, I would create a feature branch pointed at feature 4, and reset master back to feature 2.

    git checkout -b <feature-branch> master
    git checkout master
    git reset --hard HEAD^^
    

    If you have pushed the changes to remote, I would go a different route as it's generally a bad idea to change up commits that are public.

    git checkout master
    git revert <feature 3 sha>
    git revert <feature 4 sha>
    git checkout -b <feature-branch> master
    git cherry-pick <feature 3 sha>
    git cherry-pick <feature 4 sha>