How Can I Selectively Merge Changes Between Two Branches While Retaining Both?

I am in the midst of a major refactor of a collection of scripts, which have to remain active and functional while I perform the refactor (which will take quite a while).  I’ve split off a new branch to perform the refactor, but…

  • I’m still maintaining the master branch (correcting bugs, etc).  So, I would like to be able to periodically compare the master branch to my refactor branch, and selectively merge any fixes I’ve made to the master branch into the refactor branch to keep it as up-to-date as possible while I continue refactoring.
  • At the same time, while working on the refactor branch, I occasionally notice things or make corrections that should also be applied to the master branch.  So, I would also like to be able to periodically compare both branches and merge some of the changes in the opposite direction, from my refactor-in-progress branch to master.
  • While all of this is going on, I still need both the master branch and the refactor branch to remain separate, since the master branch should (obviously) only contain fixes or other changes I’ve confirmed function as intended.

I’m somewhat familiar with the process of merging a branch back into master once I’m finished and ready to apply all of the changes, but how can I merge changes selectively between two branches as described above?  (I’m using Visual Studio Code and a few GitHub extensions to manage my repository, in case that happens to be relevant.)

Thanks in advance for any help you can provide!

If you want to apply individual commits from one branch to another (either way around) you can do that with git cherry-pick. Note that cherry-pick does not merge, it applies an existing change to another branch.

Otherwise there are two things that might be helpful:

  • If you make small changes on the master branch, it might be possible to just merge them into the refactoring branch.
  • Depending on what you’re refactoring it may be possible to do it in small stages, and after completing one stage you can test it and (if everything works) merge to master. Keeping the difference small makes merges easier.
1 Like