Today morning, as any other work day, I logged in to my GitHub account to check the status of my open pull requests. I saw I had some merge conflicts and I needed to sync with the main.
I found myself in a situation where I needed to delete the last two commits and re-sync with the main.
First of all, I switched to main and pulled the latest changes
git pull origin main
Then I checked back to my working branch. First of all, I need to delete the last two commits. We have two options:
: '
this will take you to the commit before the last two commits and then keep the changes of the last two commits in your work directory
'
git reset --soft HEAD~2
// or
: '
this will take you to the commit before the last two commits but you will lose your last two commits
'
git reset --hard HEAD~2
In my case I did't require the last two commits changes so I went with the option 2.
The I synced my current branch with the main
git merge main
: '
we can also use the re-basing technique but I was more comfortable with the merge in this situation
'
Now, we need to push these changes to the remote. Since we are changing the git history, we would require to use --force
flag. We have two options again:
git push origin <current_branch> --force
// and
git push origin <curren_branch> --force-with-lease
The --force
will overwrite the remote history unconditionally.
The --force-with-lease
will only overwrite the remote history if the remote branch is unchanged since our last fetch preventing any accidental overwrite of other people's work.
If you ever find yourself in this situation. I hope this helps.
Top comments (0)