2015
Mar
05

什麼是 Git Submodule

Submodule 可以讓我們的 git repository 裡內嵌多個外部的 remote repository,並將這個 remote repository 下載回你指定的目錄,這個 repository 不一定要是最新的內容,我們也可以指定一個 "Git commit object",每次 git clone 時,都會 clone 到 commit object 當下的內容, 確保程式不會因為第三方的修改而被影響。

Submodule 跟 Remote Repository 是不一樣的定義,使用 Remote Repository 的時機點,是當兩個 repository 屬於同一個 Project,而 Submodule 則是指兩個 repository 是不同的 project ,例如 A ,B 是兩個不同的 Project ,但是 A 會用到 B 的功能,所以我可以將 B 以 submodule 的方式放進 A,讓 B 成為 A 的一部分,但是 A 與 B 仍然是獨立的兩個 Project ,所以我不能去修改 B 的程式碼。

如果你想將兩個 Project 的程式碼,整合成同一個,而且有共同的 git commit log ,那麼你可以使用 Remote Repository 來取代 submodule ,再使用 subtree merge 的方式來 Merge 另一個 repository,這樣操作這兩個 Repository 時,就像是在操作同一個 Repository, 並且可以用 git clone, git checkout 等指令,同時操作兩個 Repository。

Gitlink tree

Gitlink tree 是一個很重要的觀念,如果你想使用 submodule ,那麼你一定要學懂 Gitlink tree,Gitlink 是連結 git repository 中的某一個 commit object ( 例如 70460b4b4aece5915caf5c68d12f56xxxx),每一個 submodule 都會連結一個 Gitlink,當你 checkout 這個 submodule 時,只會 checkout commit object 當下的資料,而不會是 repository 最新的 commit 資料, 等同於我們可以鎖死 submodule 某一個時間點的資料。

當你在 Git 中加入了一個 submodule ,那麼你的 Project 根目錄會有一個檔案 .gitmodules,裡面會記錄 submodule 的 git repository 路徑與對應的目錄。


Submodule 操作指令

git submodule add

如何加入一個 submodule

git submodule add [email protected]:user/third-party-project.git ./lib/third-party

git clone --recursive

clone project code 並且 clone 這個 project 內的所有 submodule

git clone --recursive git://github.com/user/myProject.git

git submodule update

預設 git 不會自動 checked out submodule 的資料,你可以用這個指令來 checked out submodule

git submodule update --init --recursive

git submodule init

git submodule init 這個指令會將 .gitmodules 檔案裡面的資料,復製一份到 .git/config 。


git submodule deinit

git submodule deinit 這個指令會將 submodule 的資料從 .git/config 中移除,當 submodule 沒有定義在 .git/config ,則以下三個指令將無法使用。

  • git submodule update
  • git submodule foreach
  • git submodule sync

參考資料


回應 (Leave a comment)