1. 程式人生 > 其它 >Github SubModule 指南

Github SubModule 指南

最近學習使用 Hugo 構建靜態網站。安裝主題時,接觸到git submodule這個命令,踩了些坑,總結一下。

子模組與父模組如何同步更新

子模組是一個單獨的專案,commit push等操作需要在子模組自己的repo目錄下操作。父專案的操作與子模組無關。父專案git add無法新增子模組的changes,當然也就無法commit push

子模組版本升級後,父專案不會自動升級,仍然停留在對之前版本的引用。以下命令可以檢視父模組當前使用子模組的哪個版本:

> git submodule status
f0dc1cf84d7c47dc1625e956f07b37b6c238a3dc themes/hugo-theme-stack (v3.8.0-4-gf0dc1cf)

子模組修改後,父模組雖然無法git add/commit/push,但是git status卻可以顯示:

> git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
modified:   themes/hugo-theme-stack (new commits)

這裡會讓人疑惑,有changes,但是無法add進來。

這是因為,子模組的修改,只能在子模組裡面進行commit & push

子模組commit & push之後,父模組不會自動更新,仍然保持著對子模組上一版本的引用。此時可以使用git add submoduleDir 新增子模組的更新,然後commit & push,將子模組的修改同步到父模組。

如果父模組在尚未add & commit & push子模組更新的情況下,執行了git submoule update,此時子模組會回滾到上一版本(父模組引用的那個版本)。然後去子模組git status

,會提示 HEAD detached at xxxxxx

如果發生了上述情況,可以在子模組git branch -a檢視分支,git checkout到上次提交修改的分支。然後子模組就恢復到working tree clean了。

再去父模組,git add submoduleDir && commit && push

其他命令:

git submodule init
git submodule update
git submodule status

如何修改子模組的 remote url

需求:使用的別人的主題repo作為子模組。然後改了些地方,發現無法提交到父專案,更不能提交到別人的repo。

解決:fork別人的repo,然後使用自己fork的repo作為子模組。後面原作者的repo更新了,再單獨升級fork後的repo。升級時注意別覆蓋了自己的修改。如果使用良好,不升級也可。

那麼,如何將submodule,從引用別人的repo,改為引用自己的。

先刪除

GIT 未提供submodule remove的功能。要刪除一個子模組,需按照下面步驟操作:

  1. git submodule deinit sub/module,執行後模組目錄將被清空。
  2. git rm sub/module,執行後會清除.gitmodules裡的專案。
  3. git commit -m ‘remove sub/module。

第一步不做似乎也沒關係。第二步是關鍵,這裡不能直接rm sub/module,這樣不會同步更新.gitmodules的內容。

再新增

git submodule add https://github.com/whuwangyong/hugo-theme-stack/ themes/hugo-theme-stack

如果遇到如下錯誤:

A git directory for ‘hugo-theme-stack’ is found locally with remote(s): origin https://github.com/CaiJimmy/hugo-theme-stack/ If you want to reuse this local git directory instead of cloning again from https://github.com/CaiJimmy/hugo-theme-stack/ use the ‘–force’ option. If the local git directory is not the correct repo or you are unsure what this means choose another name with the ‘–name’ option.

需刪除本地的快取:

git rm --cached sub/module 

或直接刪除站點根目錄的.git/module/下面對應的子模組:

rm -rf .git/module/hugo-theme-stack

然後再次執行git submodule add

Reference

  1. GIT 的 SUBMODULE - 閱微堂 (zhiqiang.org)
  2. git submodule刪除後重新新增問題_Week Mao的專欄-CSDN部落格
  3. 來說說坑爹的 git submodule - 掘金 (juejin.cn)

本文同步釋出於: