If, for you, it is just about 1 commit, then there are plenty of other easier resetting solutions available. For me, I had about 10 commits that I'd accidentally created on master
branch instead of, let's call it target
, and I did not want to lose the commit history.
What you could do, and what saved me was using this answer as a reference, using a 4 step process, which is -
temp
from master
temp
into the branch originally intended for commits, i.e. target
master
temp
.Here are the above steps in details -
Create a new branch from the master
(where I had accidentally committed a lot of changes)
git checkout -b temp
Note: -b
flag is used to create a new branch
Just to verify if we got this right, I'd do a quick git branch
to make sure we are on the temp
branch and a git log
to check if we got the commits right.
Merge the temporary branch into the branch originally intended for the commits, i.e. target
.
First, switch to the original branch i.e. target
(You might need to git fetch
if you haven't)
git checkout target
Note: Not using -b
flag
Now, let's merge the temporary branch into the branch we have currently checkout out target
git merge temp
You might have to take care of some conflicts here, if there are. You can push (I would) or move on to the next steps, after successfully merging.
Undo the accidental commits on master
using this answer as reference, first switch to the master
git checkout master
then undo it all the way back to match the remote using the command below (or to particular commit, using appropriate command, if you want)
git reset --hard origin/master
Again, I'd do a git log
before and after just to make sure that the intended changes took effect.
Erasing the evidence, that is deleting the temporary branch. For this, first you need to checkout the branch that the temp
was merged into, i.e. target
(If you stay on master
and execute the command below, you might get a error: The branch 'temp' is not fully merged
), so let's
git checkout target
and then delete the proof of this mishap
git branch -d temp
There you go.