如何将一个分支目录中的文件合并到另一个分支?

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

简单的例子。这是 'master':

root
    - index.html
    - readme.md

这是一个名为 'dev' 的分支:

root
    src
        - index.jade
    dist
        - index.html

我想获取 'dev' 分支的 'dist' 文件夹中的 index.html 文件(或所有文件),并将其替换或合并到我的主分支的根目录。我试过了,来自大师:

git checkout dev dist/

但它产生了这个结果:

root
    dist
        - index.html
    - index.html

显然不是我想要的。 git 是否能够执行我希望它执行的操作,还是我只需要编写一个脚本?谢谢!

这可以使用 subtree 合并策略或 recursive 合并策略的 subtree[=<path>] 选项来完成。

来自git-merge documentation,对subtree策略的描述:

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.

以及 subtree[=<path>] 选项对 recursive 合并策略的描述:

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.

在您的情况下,如果 master 是当前分支,则以下命令会将 dist/ 目录的内容从 dev 分支合并到根目录中(您将拥有有机会解决冲突):

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

如果您希望将更改合并到 dist/ 目录中,请检出 dev 分支,然后 运行:

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

subtree 策略计算出如何“移动”树木。然后您可以签出 master 并快进到 dev 分支上的新合并提交。