Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I selectively merge or pick changes from another branch in Git?

I'm using Git on a new project that has two parallel -- but currently experimental -- development branches:

  • master: import of existing codebase plus a few modifications that I'm generally sure of
  • exp1: experimental branch #1
  • exp2: experimental branch #2

exp1 and exp2 represent two very different architectural approaches. Until I get further along I have no way of knowing which one (if either) will work. As I make progress in one branch I sometimes have edits that would be useful in the other branch and would like to merge just those.

What is the best way to merge selective changes from one development branch to another while leaving behind everything else?

Approaches I've considered:

  1. git merge --no-commit followed by manual unstaging of a large number of edits that I don't want to make common between the branches.

  2. Manual copying of common files into a temporary directory followed by git checkout to move to the other branch and then more manual copying out of the temporary directory into the working tree.

  3. A variation on the above. Abandon the exp branches for now and use two additional local repositories for experimentation. This makes the manual copying of files much more straightforward.

All three of these approaches seem tedious and error-prone. I'm hoping there is a better approach; something akin to a filter path parameter that would make git-merge more selective.

like image 858
David Joyner Avatar asked Jan 16 '09 04:01

David Joyner


People also ask

Can I merge specific commit from another branch?

Go to either the git log or the GitHub UI and grab the unique commit hashes for each of the commits that you want. "Cherry pick" the commits you want into this branch. Run this command: git cherry-pick super-long-hash-here . That will pull just this commit into your current branch.

How do I merge files from one branch to another in git?

We can simply give git checkout the name of the feature branch 1 and the paths to the specific files that we want to add to our master branch. Boom.


1 Answers

I had the exact same problem as mentioned by you above. But I found this clearer in explaining the answer.

Summary:

  • Check out the path(s) from the branch you want to merge,

     $ git checkout source_branch -- <paths>...  Hint: It also works without `--` like seen in the linked post. 
  • or to selectively merge hunks

     $ git checkout -p source_branch -- <paths>... 

Alternatively, use reset and then add with the option -p,

    $ git reset <paths>...     $ git add -p <paths>... 
  • Finally commit

     $ git commit -m "'Merge' these changes" 
like image 72
12 revs, 10 users 28% Avatar answered Sep 30 '22 11:09

12 revs, 10 users 28%