How to revert Git soft reset?

1.2k views Asked by At

I was working on a branch and by accident I've done git reset HEAD~1 because I thought I'm resetting my last commit.

The problem is that I didn't even commit my changes so I've done reset to commit which was done by someone else. A lot of changes in that commit were done on files on which I was also working on so I didn't notice and continued my work. After I've committed and pushed my changes, I've noticed missing commit.

develop branch: commitA -> commitB -> commitC

my branch: commitA -> commitB -> myCommit

Is there any way to revert those changes and insert commitC before my commit?

2

There are 2 answers

1
Sajib Khan On

You can see your working tree by git reflog. First, back to commitC and pick your myCommit top of git log stack. Then just update remote.

$ git reflog
# copy the commit-hash of 'commitC'

$ git checkout <commitC-hash>
$ git reflog
# copy the 'myCommit-hash'

$ git cherry-pick  <myCommit-hash>         # take the 'commitC' top
$ git checkout -b 'new-my-branch'          # create 'new-my-branch' from current stage

# Replace 'my-branch' with 'new-my-branch'
$ git branch -D my-branch                  # delete 'my-branch'
$ git checkout -b my-branch                # create new 'my-branch' from 'new-y-branch'
$ git push -f origin HEAD                  # replace remote/my-branch by local/my-branch 
2
Tim Biegeleisen On

You don't need to revert your commit, because you can rebase your local branch on the remote one, and cleanly bring in commitC before reapplying your commit on top of that.

I don't know exactly what you have done locally to end up with the branch diagrams you showed us, but I think that you can simply rebase your branch on the remove develop to pull in commitC, and then replay your myCommit on top of it:

git fetch origin           # bring origin/develop up to date
git checkout develop       # checkout local develop branch
git rebase origin/develop  # rebase your local branch on the remote one

Now you should be able to simply fast-forward the remote branch via:

git push origin develop