Undo a Git Merge
You are in charge to deploy or merge the code in production. Everything is working in the UAT environment. Devs are working in develop branch on new features. You needed to merge your uat to the main branch but accidentally you merged the develop branch. Now the main branch has features that are not production ready and have not been tested well.
Here comes your rescuer Git reset
command. Git reset
resets the current branch tip and also deletes any changes in the working directory and staging area.
First, you need to get the commit hash so you can use it to go back to the previous commit.
To get the hash, run git log
or git reflog
. git reflog
is a better option because things are more readable with it.
DELL@office /d/project (main)$ git reflog
9d9c026f1 (origin/main, main) HEAD@{3}: commit (merge): Merge issue fix
ee97be6b3 HEAD@{4}: pull origin develop: Fast-forward
086235b90 HEAD@{5}: checkout: moving from develop to main
Here, in line-5 you changed the branch from develop to main, and then pull-merge in line-4. So, you need to jump to line-5 to get rid of the unnecessary extra codes in the main branch.
Get the hash and do git reset --hard commit-hash
DELL@office /d/project (main)$ git reset --hard 086235b90
HEAD is now at 086235b90 main log
Now all of your changes are undone, and the HEAD
points to the hash 086235b90
. You can merge your uat branch and deploy it to production. If you do git reflog
again then,
DELL@office /d/project (main)$ git reflog
086235b90 (HEAD -> main) HEAD@{0}: reset: moving to 086235b90
9d9c026f1 (origin/main, main) HEAD@{3}: commit (merge): Merge issue fix
ee97be6b3 HEAD@{4}: pull origin develop: Fast-forward
086235b90 HEAD@{5}: checkout: moving from develop to main