處理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: