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!

  • How to remove files from wrongly merged branch?
  • Using git, how do a merge a tracked branch back into the remote origin/HEAD?
  • Merge codes from different authors on github
  • Keeping up to date a subtree of other project
  • Git - coworker somehow overwrote my entire commit while resolving a conflict
  • Modifying a merge commit after another commits before push
  • Why do I need the “master” in git merge origin/master?
  • Git Merge Recursive Ours - Command Syntax Example
  • One Solution collect form web for “How to merge files from one branch's directory into another branch?”

    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.

    Git Baby is a git and github fan, let's start git clone.