reubenjohn
reubenjohn

Reputation: 1419

How to copy a commit from one branch to another in git without any merging?

I have 2 branches a master and an experimental. A shown:

master-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-Y
                  \
                   -x-x-x-x

My experimental is quite outdated and i was hoping to update it by simply copying the last commit in the master branch (Y) to experimental:

master-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-Y
                  \
                   -x-x-x-x-Y

If possible, I don't want to have to do any merging I want to overwrite anything in the experimental (master is my main priority).

Edit: Let me briefly explain the situation: When i try to merge commits at the tips of the master and experimental branch, I get a lot of merge conflicts! The same happens if i try to cherry-pick from the experimental onto the master! I was hoping to avoid them as i simply don't want any of the changes on the experimental! Up until now, I have been cherry-picking from master to experimental and when there are merge conflicts, I just keep changes of master branch. But after doing it many times, i was hoping that there may be some way in which i can do something like a merge except where (i am not prompted with any merge conflicts as master changes is all i need (for all I know it wouldn't matter what was previously on the experimental branch!

Upvotes: 15

Views: 26881

Answers (2)

reubenjohn
reubenjohn

Reputation: 1419

Here is what I initially tried!:

git checkout experimental
git rebase --onto <COMMIT ID OF LAST MASTER COMMIT> experimental

On trying this code, I found that not only the commit at the tip of the master but also the entire experimental branch became a clone of the master! Yes, it is not an elegant solution and a bad usage of git!

However, as pointed out by @Johnsyweb, the optimum solution would be to do a merge of experimental and master but,

with Git preferring to take the changes on master over the changes on experimental

Hence doing a:

git checkout experimental
git merge -Xtheirs master

should work fine. Although it says merge, since it only considers the changes of the experimental branch over the master one, it is more like a copy from experimental to master for all practical purposes.
(See a similar discussion here)

Upvotes: 3

johnsyweb
johnsyweb

Reputation: 141958

To cherry-pick just commit Y from master onto experimental:

git checkout experimental
git cherry-pick Y

Alternatively:

git checkout experimental
git cherry-pick master

...Will apply the change introduced by the commit at the tip of the master branch and create a new commit in experimental with this change.

Upvotes: 23

Related Questions