Help, I committed to the wrong branch
Your commit landed on main instead of your feature branch. Move it over without losing anything.
The fix
git switch -c feature/loginCreates the branch right where you are and switches to it. Your commit is on it now, and uncommitted changes come along.
git branch -f main HEAD~1Moves main back one commit without touching your files. Three wrong commits? Use
HEAD~3.
feature/login is an example. Replace it with your own.
git switch feature/loginSwitch to the branch the commit belongs on.
git cherry-pick mainCopies the newest commit of main onto this branch. On a conflict: fix the file,
git addit, thengit cherry-pick --continue. Git refuses while anything is staged: rungit stashfirst andgit stash popat the very end.git switch mainBack to main.
git reset --keep HEAD~1Moves main back one commit. Unlike
--hard,--keepstops instead of overwriting uncommitted changes.
feature/login is an example. Replace it with your own.
Only for commits you have not pushed yet. If main on the remote already has the commit, revert it on main and cherry-pick it onto your branch instead.
Why this works
A branch is only a label pointing at a commit. The commit itself is fine, it just has the wrong label on it. So you put the right label on it, either a brand-new branch or a copy on an existing one, and then move main back by one commit. Nothing is deleted on the way.