关于子树合并
通常,子树合并用于在仓库中包含另一个仓库。 “子仓库” 存放在主仓库的一个文件夹中。
解释子树合并的最佳方式是通过示例展示。我们将
- 创建一个名为
test的空仓库,代表我们的项目。 - 将另一个仓库合并为名为
Spoon-Knife的子树。 test项目将使用该子项目,就像它是同一仓库的一部分一样。- 从
Spoon-Knife拉取更新到我们的test项目。
为子树合并设置空仓库
-
打开 终端终端Git Bash。
-
创建一个新目录并进入该目录。
mkdir test cd test -
初始化一个新的 Git 仓库。
$ git init > Initialized empty Git repository in /Users/octocat/tmp/test/.git/ -
创建并提交一个新文件。
$ touch .gitignore $ git add .gitignore $ git commit -m "initial commit" > [main (root-commit) 3146c2a] initial commit > 0 files changed, 0 insertions(+), 0 deletions(-) > create mode 100644 .gitignore
将新仓库添加为子树
-
添加指向我们感兴趣的独立项目的新远程 URL。
$ git remote add -f spoon-knife https://github.com/octocat/Spoon-Knife.git > Updating spoon-knife > warning: no common commits > remote: Counting objects: 1732, done. > remote: Compressing objects: 100% (750/750), done. > remote: Total 1732 (delta 1086), reused 1558 (delta 967) > Receiving objects: 100% (1732/1732), 528.19 KiB | 621 KiB/s, done. > Resolving deltas: 100% (1086/1086), done. > From https://github.com/octocat/Spoon-Knife > * [new branch] main -> Spoon-Knife/main -
将
Spoon-Knife项目合并到本地 Git 项目中。这不会在本地更改任何文件,但会为下一步做好 Git 的准备。如果您使用的是 Git 2.9 及以上版本
$ git merge -s ours --no-commit --allow-unrelated-histories spoon-knife/main > Automatic merge went well; stopped before committing as requested如果您使用的是 Git 2.8 及以下版本
$ git merge -s ours --no-commit spoon-knife/main > Automatic merge went well; stopped before committing as requested -
创建一个名为 spoon-knife 的新目录,并将
Spoon-Knife项目的 Git 历史复制到其中。$ git read-tree --prefix=spoon-knife/ -u spoon-knife/main > fatal: refusing to merge unrelated histories -
提交更改以确保安全。
$ git commit -m "Subtree merged in spoon-knife" > [main fe0ca25] Subtree merged in spoon-knife
虽然我们只添加了一个子项目,但可以在 Git 仓库中合并任意数量的子项目。
提示
如果您以后创建该仓库的全新克隆,之前添加的远程不会自动创建。您需要使用 git remote add 命令 再次添加它们。
同步更新和更改
添加子项目后,它不会自动与上游更改保持同步。您需要使用以下命令更新子项目
git pull -s subtree REMOTE-NAME BRANCH-NAME
上述示例对应的命令是
git pull -s subtree spoon-knife main