Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split commits into two branches

Tags:

git

git-log

I am on a branch named feature-1. I run git log, which shows me a bunch of commits:

commit <HASH-1>
…
commit <HASH-2>
…
commit <HASH-3>
…
commit <HASH-4>
…

Now I want commit <Hash-3> and older commits to be on feature-1 branch, whereas commit <HASH-2> and newer commits to be on a new branch named feature-2. How can I do that?

like image 915
user842225 Avatar asked Jul 06 '15 09:07

user842225


People also ask

Can I split a commit?

To split the last commit, one needs to “undo” the commit, stage the changes partially, and create multiple commits. One can stage a file partially using interactive staging, but we'll do a full piece on it later, especially since it's rewritten in the new version of git.


2 Answers

Checkout the commit that you want to be under your new branch and then create branch from this point.

git log --oneline ...

commit <HASH-1>
commit <HASH-2>
commit <HASH-3>
commit <HASH-4>


git checkout -b feature-1 <HASH-3> 
git checkout -b feature-2 <HASH-2> 

and so on,

You simply checkout any commit you want (any point in your history) and then you create branch at this point


How to create branches?

Branches can be created in several ways:

Create branch from the current commit

  • By creating branch ant not checking them out
    git branch < branch_name>

  • By creating and switching to a new branch

    git checkout -b <branch_name>
    git checkout -t <branch_name>
    

The default SHA-1 if not specified is the HEAD

Create branch from selected commit

By adding sha-1 to the checkout command you "set" the commit that your branch will be created from.

    git checkout -b <branch_name> <sha-1>
    git checkout -t <branch_name> <sha-1>
like image 106
CodeWizard Avatar answered Oct 09 '22 11:10

CodeWizard


This is a great use case for the interactive rebase feature. First run git branch feature-2. This will create a new branch feature-2 on the same commit as your current HEAD (which points to feature-1).

No you just run git rebase -i origin/master. This will open your $EDITOR with something like this:

pick 3182a77e Commit 1
pick 6f717613 Commit 2
pick f30c1e92 Commit 3
pick b1c13f14 Commit 4

Now you just remove the first two lines, so only the commits you want in feature-1 are there anymore. Then just save the file. Now git will recreate the commits so that feature-1 contains the commits you want.

Not you run git checkout feature-2 and then again git rebase -i origin/master. You will again see all 4 commits, this time just keep the ones you want in feature-2. Then again save the file and you're done.

like image 34
Lux Avatar answered Oct 09 '22 13:10

Lux