Joy
Joy

Reputation: 4483

How to move multiple commits from a branch to another branch

I have cut a branch X from master, then I did certain commits say,

  C1, C2, C3, C4, C5, C6

Now I want to merge X with master branch upto commit C2 and I would like to move commit C3 and C6 to different branch Y that I have cut from X. So what I want, look like following:

  master
    \
     \
      X-C1-C2-C3-C4-C5-C6

Finally it should be something like this:

    master------master
      \        /
       \      /
        X-C1-C2
              \
               Y-C3-C4-C5-C6

Upvotes: 0

Views: 851

Answers (3)

Alex Wolf
Alex Wolf

Reputation: 20128

The answers given are either very short or not quite doing what you asked for, so I will provide another one.

Let me start with the explanation that branches in git are merely references onto commits; they are literally a file containing the hash of the their commit. So there is close to no overhead when working with branches.

While you could create another branch Y it is not necessary. The easiest approach would be a simple merge from the C2 commit into master.

git checkout master
git merge <hash-of-c2>

Note however that it's possible that this will result in a fast-forward merge. This will happen if there are no further commits on master so git just moves master to C2, if you want to force a merge commit and avoid a fast-forward you can use the --no-ff option when merging.

git merge --no-ff <hash-of-c2>

After you have done this your commit graph should look similar to this:

* (master) Merge commit
|\
| | * (X) C6
| | * C5
| | * C4
| | * C3
| |/
| * C2
| * C1
|/
* master commit

(master) and (X) are the current commits of the branches.


Obviously you can create multiple branches as you proposed. The easiest approach would be the following.

git branch Y X # Create Y branch which points at the same commit as X
git branch -f X <hash-of-c2> # Move X to point at C2

If there are any further questions don't hesitate to ask.

Upvotes: 2

Fred
Fred

Reputation: 1322

This is the most explicit way to accomplish what you're after:

git branch Y X
git checkout C2 # where "C2" is the commit hash of C2 commit - now Tip of X is at C2
git branch -f X # force repointing of X in .git/refs/heads/X
git checkout master
git merge X  

Re @cabellicar123's answer: I would prefer checkout over reset. Reset will move HEAD, detach you from the Y branch, and (effectively, they are always in the reflog) wipe out your C3-C6 commits.

Upvotes: 0

carloabelli
carloabelli

Reputation: 4349

You could create new branch Y from X. reset X back to the specified commit (C2). Then merge X into master.

Upvotes: 0

Related Questions