Search code examples
git

How to revert a commit and create a new branch from those changes?


It's late Sunday and I made a bad mistake. I committed and pushed directly into the master branch, where I should have created a branch and pushed the changes to the new branch instead.

So I could do a git revert SHA to revert the last commit with a new commit.

However how about my changes, I don't want to loose them.

Shall I create a branch from already modified Master like git checkout -b feature and then revert the Master branch?

But what happens once I merge back feature into master, will it know that that commit was reverted on Master previously and eliminate it? git merge feature

Btw, there is no history rewriting problem, as I'm the only developer working on this project. Hence I would consider a hard reset, if it's the better choice.


Solution

  • If you are the only developer, then you can do a hard reset. If abc123 is the SHA1 of the accidental commit, then do:

    git checkout master
    git branch feature-branch
    git reset --hard abc123^
    

    This will keep your new commit in the new feature-branch branch (without switching to that new branch yet), and then rewind master back to the previous commit. Then you can push the corrected master branch using git push -f origin master.