初探 Git Submodules

之前一直想將一個 Git 倉庫放到另一個 Git 倉庫,有 Maven 多模塊項目(Maven Multimodule Project)和 Gradle 多項目構建(Gradle Multiproject Build)那味兒。Git 這麼騷,肯定也可以。「掃」了多個開源倉庫,Get 到了 Git submodule 可以做這種操作,水篇文章記錄波。

沒有使用 Git Submodules 之前

沒有使用 submodule 之前,如果在一個 Git 項目追蹤另一個 Git 項目,會報一個 warning「我敲,有暗示用 submodule,之前沒注意」,操作如下:

mkdir git-submodule
cd git-submodule
git init
git clone //github.com/volantis-x/hexo-theme-volantis --depth 1

執行 git add hexo-theme-volantis,會出現如下 warning(adding embedded git repository):

追蹤執行結果

然後使用 git status 查看,雖然 git add 成功了,但是並沒有成功 add 到 hexo-theme-volantis 裏面的內容。提示也說了(will not contain the contents of the embedded repository),提交到 GitHub 後,顯示結果如下, folder 戳也戳不開。

push to GitHub

可以明顯的看到,並不能保證 子目錄/文件 的完整性。就我之前如果想在一個 Git 項目保留另一個 Git 項目,那麼我只能將一個項目的 Git 版本庫去掉,從後續的使用感受來看,此後我追蹤另一個項目的更新會有點麻煩。從 yeshan333/actions-for-hexo-blog 項目的對 volantis 項目追蹤的歷史commit@3ce9316 可以看得出來 actions-for-hexo-blog@3ce9316

Git Submodules 的作用

是時候該見識 submodule 的作用了,從官方文檔可以看到,它可以解決之前上面提到的一些問題。略微概括下就是:

  • Git的 submodule 可以將一個 Git 版本庫作為一個子目錄保存在另一個 Git 版本庫中,並可以保留兩個版本庫之間 commit 的分離,保持父項目和子項目相互獨立,實現更為精確的版本控制。

Git Submodules 的本質

actions-for-hexo-blog 項目來實踐感受下 submodule。操作如下:

git clone [email protected]:yeshan333/actions-for-hexo-blog.git && cd actions-for-hexo-blog
git submodule add [email protected]:volantis-x/hexo-theme-volantis.git themes/volantis

執行上述命令之後,會看到當前項目下生成了個 .gitmodules 文件,內容如下:

[submodule "themes/volantis"]
	path = themes/volantis
	url = [email protected]:volantis-x/hexo-theme-volantis.git

同時,.git/config 文件也會被追加寫入如下內容:

[submodule "themes/volantis"]
	url = [email protected]:volantis-x/hexo-theme-volantis.git
	active = true

再看看 theme/volantis 目錄,發現該項目的 Git 版本庫不見了,之前提到 git submodule 可以保留兩個版本庫之間 commit 的分離,那麼項目 volantis 的版本庫放哪了?摸索下當前項目的版本庫可以看到被放在了 .git/modules/themes/volantis 下。嘗試提交到 GitHub 看看。

GitHub 提交結果

emm……,收工,目錄名顯示多個 commit 引用,可以進行跳轉。

更多操作

# 子模塊刪除
- 刪除.gitsubmodule文件中子模塊的相關字段;
- 刪除.git/config文件中子模塊的相關字段;
- 刪除模塊目錄:
- git rm --cached <submodule-path>

參考

Tags: