处理Git子存储库的简单方法

在这篇文章中,我描述了发现管理Git子存储库的最简单方法。

警告:此帖子过时,可能无法反映当前的最新状态

假设在您的项目中有一个要在单独的Git存储库中管理的文件夹。

或者,假设您想开源应用程序的一部分,但又不想管理单独的文件夹,符号链接和单独的Git推送。

你能做什么?

输入子树

首先,创建一个新的存储库,该存储库将托管您需要的文件。如果使用GitHub,请使用README.md文件对其进行初始化,以便它将自动创建master分支。

接下来,将其添加为项目中的远程对象。

$ git remote add repository-name [email protected]:yourname/repository-name.git
$ git subtree add --prefix=subfolder/path/you/want repository-name master

Change repository-name, subfolder/path/you/want and yourname with your chosen names.

You can add --squash to the last command if the project want to incorporate has already many commits, and you want to pull all changes in one single commit.

You’re done!

Pushing and pulling

Now, suppose someone pushes a PR on that subrepository, or you edit it from another project.

To incorporate the changes inside your project, do:

git subtree pull --prefix=subfolder/path/you/want repository-name master

You can add --squash if you want to incorporate all changes in one single commit.

Now you’ll push to your own project, and the changes made in the subrepository are stored in the Git history of it.

To also push those changes to the subrepository Git history, and to the remote, just do

git subtree push --prefix=subfolder/path/you/want repository-name master

Again, use --squash if you feel it appropriate. Git will cherry-pick the commits that involve the subrepository subdirectory, so you’ll just see those changes in the subrepository history.

You might want to be careful and differentiate the commits that involve the subrepository. In this way you’ll keep things separated.


More git tutorials: