git - 如何在 Git 中 merge 子目录?

标签 git

是否可以仅将本地 Git 分支的子目录更改 merge 到远程 Git 分支,还是“全有或全无”?

例如,我有:

branch-a
 - content-1
 - dir-1
   - content-2

branch-b
 - content-1
 - dir-1
   - `content-2

我只想将 branch-a dir-1 的内容与 branch-b dir-1 的内容 merge 。

最佳答案

作为 SO 问题“How do you merge selective files with git-merge?”的替代方案,我刚刚找到了this GitHub thread这可能更适合 merge 整个子目录,基于 git read-tree :

  • My repository => cookbooks
    My repository target directory => cookbooks/cassandra

  • Remote repository => infochimps
    Remote repository source I want merged into cookbooks/cassandra => infochimps/cookbooks/cassandra

Here are the commands I used to merge them

  • Add the repository and fetch it

    git remote add -f infochimps git://github.com/infochimps cluster_chef.git
    
  • Perform the merge

    git merge --allow-unrelated-histories -s ours --no-commit infochimps/master
    

(this performs a merge by using the 'ours' strategy (-s ours), which discards changes from the source branch.
This records the fact that infochimps/master has been merged, without actually modifying any file in the target branch)

  • Merge only infochimps/cookbooks/cassandra into cassandra

    git read-tree --prefix=cassandra/ -u infochimps/master:cookbooks/cassandra
    

This reads the tree for only the required source subdirectory i.e. cookbooks/cassandra, on the upstream branch of the source repository.

Note that the target subdirectory name should also be cookbooks/cassandra, or you would see:

fatal: Not a valid object name
  • Commit the change

    git commit -m 'merging in infochimps cassandra'
    

附录

这很奇怪,[edit me] — 但是 read-tree 这一步可能会像这样失败:

error: Entry 'infochimps/cookbooks/cassandra/README' overlaps with 'cookbooks/cassandra/README'. Cannot bind.

...即使两个文件相同。这可能会有所帮助:

git rm -r cassandra
git read-tree --prefix=cassandra/ -u infochimps/master:cookbooks/cassandra

当然,手动验证这是否符合您的要求。

关于git - 如何在 Git 中 merge 子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1214906/

相关文章:

git - 如何让 Git 提交历史显示在 Redmine 问题跟踪器上

git - 在 OSX 上将远程 CVS 迁移到本地 Git

linux - Git 符号链接(symbolic link) - Windows 工作站 - Linux 服务器

java - 如何使用 JGit 找到提交的分支?

git - 有没有办法仅在至少两次 Github 批准后才配置 merge pull 请求?

git - 我可以将 .gitmodules 文件放在子目录中吗?

git - 如何列出将受 `git add .` 影响的所有文件?

git - 在分支 checkout 之间保留 git --assume-unchanged 文件

git - 无效的对象名称 'C'

git merge --no-commit 编辑