Will Vousden
Will Vousden

Reputation: 33358

Separating a feature into a new branch in Git

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 :)

Upvotes: 2

Views: 135

Answers (3)

Dan Ray
Dan Ray

Reputation: 21893

Checkout master, and edit the working directory to remove (or hide?) the feature, and commit that.

Make a branch for the "new" feature development (I'll call it "dev", but you should name it something meaningful). Then on dev, revert (not reset!) the previous commit, undoing the "removing" (or hiding) work you just did. Commit that reversion into the dev branch.

Step 3, profit. You now how a master branch without the feature, and a topic branch with it.

Upvotes: 1

Adam Dymitruk
Adam Dymitruk

Reputation: 129566

You can do it by cherry-picking the commits you want into it's own branch.

First branch off of the commit before the first commit you want private:

git checkout -b feature1 sha1^ # sha1 is the hash of the first private commit

Now cherry-pick each commit

git cherry-pick hash1 hash2 etc

Now remove the same ones in master

git checkout master
git rebase -i sha1^ # as in the first checkout

Now remove the commits that you cherry-picked.

Hope this helps

Upvotes: 1

svick
svick

Reputation: 244777

If you can rebase master (i.e. nobody else has the changes you want to move to the branch), I would use git rebase -i to 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 B denotes a commit you want to move, and M one that should stay):

M1---B1---M2---B2---M3

rebase them into

M1---M2---M3---B1---B2

Create the new branch and git reset --hard master to M3.

If you can't rebase master, create your branch, git revert the changes you don't want on master, and then do git 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.

Upvotes: 5

Related Questions