Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commit a change to more than one branch in Git

Typical usage scenario:

I have master, branch_foo and branch_bar. All are up to date. Now, I do a "git checkout master" and work on a bug fix.

Lets say that fix was on a tracked file that is in the same state on all branches - ie. before the fix, a diff of the file from each branch results in no differences.

Is there a way to commit this fix to all branches?

like image 738
Carl Avatar asked Oct 06 '09 19:10

Carl


People also ask

How do I commit to all branches?

If you use git branches a lot, you'll often push each branch after each commit. Instead of pushing every single branch you can do git push --all origin . This will push all commits of all branches to origin.

Can two branches refer to same commit?

Yes, two branches can point to the same commits.


2 Answers

The common approach to this is "merging upwards". From man gitworkflows:

Always commit your fixes to the oldest supported branch that require them. Then (periodically) merge the integration branches upwards into each other.

This gives a very controlled flow of fixes. If you notice that you have applied a fix to e.g. master that is also required in maint, you will need to cherry-pick it (using git-cherry-pick(1)) downwards. This will happen a few times and is nothing to worry about unless you do it very frequently.

The first method is of course preferred - it's good to have a commit in your repo only once, and to be able to see the history of how it got into each branch. Life isn't perfect, though, and you'll sometimes find yourself in the second category. If that situation becomes common enough, you could perhaps write a script like

multi-cherry-pick <commit> <branch> [<branch>...]

which checks out each branch in turn and cherry-picks the given commit.

like image 99
Cascabel Avatar answered Oct 05 '22 14:10

Cascabel


I expect git cherry-pick is what you want.

After committing the fix to the first branch, you can use git cherry-pick to merge it into each of the other branches.

This related question on SO may be of interest: Git & Working on multiple branches

like image 44
Tim Henigan Avatar answered Oct 05 '22 14:10

Tim Henigan