Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: applying changes to two branches

I have two branches in my repository (for the purposes of this question): master and performance_testing. I have received changes for the master branch. I need to put them into performance_testing as well. I need to keep the two branches existent and separate, so merging would not be appropriate. I guess I could introduce the changes in one branch and commit, then do the same in the other branch. But this seems to be error-prone, and I would think that git would have some way to do this more directly. How do I do this?

like image 430
bob.sacamento Avatar asked Jul 18 '17 14:07

bob.sacamento


2 Answers

Often what you would do in this scenario is cherry picking, which involves applying only a sub-set of the commits of one branch onto another.

For example, you have commits A, B, C, D, E, F on master and you wish to bring commits B, C and D into performance_testing:

git checkout performance_testing
git cherry-pick B^..D

Or you can list individual commits in multiple, individual cherry-pick commands. This is useful when you don't necessarily want a continuous series of commits. For example:

git cherry-pick B D

Note that B comes before D in the history.

For more detail, see: How to cherry-pick multiple commits (which also includes some great diagrams I won't poach into this answer).

Yes, there are many different options to choose from. This is a basic and common solution which the reader can choose to apply now that they understand how it works. git rebase --onto is another option, as is different branch management, but without a very specific scenario in mind, cherry-picking should get the most mileage.

like image 106
msanford Avatar answered Sep 19 '22 23:09

msanford


The best approach would be creating a feature branch for the changes and merging it at the end in master and performance_testing. Cherry-picking is considered as an anti-pattern.

To create the feature branch, first find the most recent common ancestor of 2 branches:

git merge-base master performance_testing

Then create feature_branch using the output of the previous command:

git branch feature_branch <output of merge-base command>

Switch to feature_branch branch, make the changes and merge it at the end in master and performance_testing.

If you have changed same files in 2 branches you will get a conflict. It's inevitable, even with cherry-picking, but easy to solve.

The advantage of this approach over cherry-picking is that you will get an uniformed log, with the same commit hashes on both branches.

like image 38
Deniz Avatar answered Sep 21 '22 23:09

Deniz