问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/29686681/how-to-merge-files-from-one-branchs-directory-into-another-branch