-
Happens to me nearly every week:
-
I forget to create a new branch before I start coding, so all my commits end up on the
mainbranch -
Then, I get ready to push my changes and open a PR and finally realize that I’d be pushing my changes directly to production! (Or at least, I would be if this [add link] branch protection rule wasn’t in place.)
-
I like my commits, but I want to move them to a feature branch
-
If this happens to you,
git cherrypickis what you need- Or just undo the commits?
- cherrypick vs just checkout new branch
-
What if my feature is…
- Not yet created?
- Previously created?
-
What if I’ve pushed my changes to remote?
-
Lazygit method? CLI?
Count how many commits to move
-
From your
mainbranch, usegit logto view your recent commits:# command git log ## output commit HASH (HEAD -> trunk) Author: ME Date: TODAY commit message commit HASH Author: ME Date: TODAY commit message commit HASH (origin/trunk, origin/HEAD) Author: ME Date: TODAY commit message : -
Type
qto exit thegitpager -
Count how many
commit HASHlines you see before thecommit HASH (origin/main, origin/HEAD)line (in the example output above, there are two)
Moving commits to a new branch
-
Create a new branch that will include all of the commits currently on your
mainbranch (without switching to it):git branch new-feature -
While still on your
mainbranch, move it back by the number of commits you want to move (in this case, two) to reset it to how it was before you committed:git reset --keep HEAD~2 -
Check out your new branch so you can resume working:
git checkout new-feature
Moving commits to an existing branch
-
Check out the existing branch you want to move your commits to:
git checkout existing-feature -
Merge
mainintoexisting-feature:git merge master -
Go back to the
mainbranch:git checkout main -
Move the
mainbranch back by the number of commits you just moved (in this case, two):git reset --keep HEAD~2 -
Check out your new branch so you can resume working:
git checkout existing-feature
- That’s how you move commits you accidentally main to your
mainbranch to a new or existing feature branch where they belong. - If you need to move commits from a branch other than
main, …. (is that when you’d usegit checkoutinstead? is my solution only valid for moving commits frommain) - It’s also only valid for moving the lastest commit(s)
Further reading
- Move Commit to Another Branch in Git | Abdul Jabbar
- How to Git Move Commit to Another Branch Effortlessly | Vershd
Inbox
- Cherry-picking (copying a commit from one branch to another) does not delete the original commit. If you want to effectively move the commit to the new branch, you need to go back and delete the original commit after copy/pasting it.