关于 Git 子树合并
如果需要管理单一仓库中的多个项目,可以使用子树合并来处理所有引用。
通常,子树合并用于在仓库中包含仓库。 “子仓库”存储在主仓库的文件夹中。
解释子树合并的最佳方式是举例说明。 我们将:
- 创建一个名为
test
的空仓库,表示我们的项目 - 将另一个仓库
Spoon-Knife
作为子树合并到其中。 - 如果该子项目属于同一仓库,
test
项目会使用它。 - 从
Spoon-Knife
提取更新到test
项目。
创建用于子树合并的空仓库
-
Open TerminalTerminalGit Bashthe terminal.
-
创建一个新目录并找到它。
$ 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" > [master (root-commit) 3146c2a] initial commit > 0 files changed, 0 insertions(+), 0 deletions(-) > create mode 100644 .gitignore
Adding a new repository as a subtree
-
新增指向我们感兴趣的单独项目的远程 URL。
$ git remote add -f spoon-knife git@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 git://github.com/octocat/Spoon-Knife > * [new branch] master -> Spoon-Knife/master
-
Merge the
Spoon-Knife
project into the local Git project. 这不会在本地更改任何文件,但会为下一步准备 Git。If you're using Git 2.9 or above:
$ git merge -s ours --no-commit --allow-unrelated-histories spoon-knife/master > Automatic merge went well; stopped before committing as requested
If you're using Git 2.8 or below:
$ git merge -s ours --no-commit spoon-knife/master > Automatic merge went well; stopped before committing as requested
-
Create a new directory called spoon-knife, and copy the Git history of the
Spoon-Knife
project into it.$ git read-tree --prefix=spoon-knife/ -u spoon-knife/master
-
提交更改以确保其安全。
$ git commit -m "Subtree merged in spoon-knife" > [master fe0ca25] Subtree merged in spoon-knife
Although we've only added one subproject, any number of subprojects can be incorporated into a Git repository.
Tip: If you create a fresh clone of the repository in the future, the remotes you've added will not be created for you. You will have to add them again using the git remote add
command.
Synchronizing with updates and changes
When a subproject is added, it is not automatically kept in sync with the upstream changes. You will need to update the subproject with the following command:
$ git pull -s subtree remotename branchname
对于上述示例,将是:
$ git pull -s subtree spoon-knife master