Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge files from one branch's directory into another branch?

Simple example. This is 'master':

root
    - index.html
    - readme.md

This is a branch called 'dev':

root
    src
        - index.jade
    dist
        - index.html

I'd like to take the index.html file (or all files, really) in the 'dist' folder of the 'dev' branch and replace or merge it with the one in the root directory of my master branch. I've tried, from master:

git checkout dev dist/

But it produces this result:

root
    dist
        - index.html
    - index.html

Clearly not what I want. Is git capable of doing what I want it to do or will I just have to whip up a script? Thanks!

like image 364
user41997 Avatar asked Apr 16 '15 21:04

user41997


People also ask

How do I merge files from another branch in Sourcetree?

Click Show to expand the list of branches. Under Branches, double-click the feature branch that is behind to switch to that branch. Click the Merge button. From the popup that appears, select the commit you want to merge into your feature branch.

Can you merge master into another branch?

The steps to merge master into any branch are: Open a Terminal window on the client machine. Switch to the feature branch. Use git to merge master into the branch.


1 Answers

This can be accomplished using the subtree merge strategy, or the subtree[=<path>] option to the recursive merge strategy.

From the git-merge documentation, the description of the subtree strategy:

subtree

This is a modified recursive strategy. When merging trees A and B, if B corresponds to a subtree of A, B is first adjusted to match the tree structure of A, instead of reading the trees at the same level. This adjustment is also done to the common ancestor tree.

And the description of the subtree[=<path>] option to the recursive merge strategy:

subtree[=<path>]

This option is a more advanced form of subtree strategy, where the strategy makes a guess on how two trees must be shifted to match with each other when merging. Instead, the specified path is prefixed (or stripped from the beginning) to make the shape of two trees to match.

In your case, if master is the current branch the following command will merge the contents of the dist/ directory from the dev branch into the root directory (you will have the opportunity to resolve conflicts should there be any):

git merge --no-ff -s recursive -X subtree=dist dev

If, instead, you wish to merge changes into the dist/ directory, checkout the dev branch then run:

git merge --no-ff -s recursive -X subtree=dist master

The subtree strategy figures out how to "shift" the trees. You can then checkout master and fast-forward to the new merge commit on the dev branch.

like image 165
frasertweedale Avatar answered Sep 20 '22 13:09

frasertweedale