One morning, I had already finished developing a feature on a separate branch. Before creating a Pull Request (PR), I merged main
into my feature branch to make sure everything was up to date.
After that, I switched to the main
branch and ran:
git pull
To my surprise, the local main
branch suddenly had 19 commits ahead of origin/main
, ready to push. Since the main
branch is protected, I couldnβt push directly.
I panicked and tried:
git reset
...but that didn't solve anything. So I decided to analyze the situation step-by-step.
git reflog
From there, I saw that commits from the feature branch I had worked on were somehow merged into main
during a brief moment.
git log origin/main -1 --oneline
Result:
15fa42562 (origin/main, origin/HEAD) Merged PR 28340: K01335
git log main -1 --oneline
Result:
3f783009f (HEAD -> main, origin/dev/_falsely_commit, dev/_falsely_commit) Merge branch 'main' of https://visualstudio.com/_git/HRMS2.Mobile
This confirmed: local main
was pointing to a completely different commit than origin/main
.
git log main..origin/main --oneline
Output: (empty)
β
This means: Local main
is not behind origin/main
.
git log origin/main..main --oneline
Output:
3f783009f Merge branch 'main'...
494a85db7 K1432 - minor style
396dd53cd Merge branch 'main' into dev/SAW/K1432
...
β‘οΈ These were exactly the same commits as those in my feature branch dev/SAW/K1432
.
This confirmed that the commits on local main
were just accidental merges from the feature branch, and didn't belong there.
Since I was confident that those commits already existed in the proper feature branches, I safely reset my local main
branch to match the remote:
git reset --hard origin/main
All done β the local main
was clean again with zero loss, and the remote commit history remained untouched.
-
If you want to remove commits permanently, you can refer to:
π https://gist.github.com/4sskick/7de05ee677a4c5853c744fda476225ef -
Always consider making a backup branch before doing a hard reset:
git branch backup-main-before-reset