Here’s the scenario: I’ve created a new repository for a codebase and made a few commits, but I’ve decided there’s some part of that codebase that should be in its own branch rather than on master. How do I separate that code off into another branch so that master is “unaware” of it? Obviously I can’t just create the branch and then delete the code from master, since any subsequent merges from master into the new branch will delete the code in the branch too.
I’m sure this has a trivial answer, but I can’t think how it should be done 🙂
If you can rebase master (i.e. nobody else has the changes you want to move to the branch), I would use
git rebase -ito rearrange the commits in master, so that all commits that should be in the branch are after all commits that should stay in master. After that, create the branch and reset master, so that it doesn’t contain any of the branch commits.For example, if you had commits (where
Bdenotes a commit you want to move, andMone that should stay):rebase them into
Create the new branch and
git reset --hardmaster toM3.If you can’t rebase master, create your branch,
git revertthe changes you don’t want on master, and then dogit merge -s ours master. This effectively tells the branch that you know about the revert and you don’t want it there.After that, if you merge master into the branch, changes in master are correctly merged, but the revert isn’t. What’s more, if you then decide the branch is done and you want to merge back into master, it works correctly too – all changes from the branch are merged, including those that were reverted.