在軟件開發過程中,通常我們會遇到有一些通用的部分希望抽取出來做成一個公共庫的情況,比如安卓和IOS都通用的H5頁面。而公共代碼庫的版本管理是個麻煩的事情。幸運的是,萬能的Git有個叫子模組(git submodule)的命令完美地幫我們解決了這個問題。
添加子模塊
為當前工程添加submodule,命令如下:
git submodule add 倉庫地址 路徑
其中,倉庫地址是指子模塊倉庫地址,路徑指將子模塊放置在當前工程下的路徑。
注意:路徑不能以 / 結尾(會造成修改不生效)、不能是現有工程已有的目錄(不能順利 Clone)
命令執行完成,會在當前工程根路徑下生成一個名為“.gitmodules”的文件,其中記錄了子模塊的信息。添加完成以后,再將子模塊所在的文件夾添加到工程中即可。
下載的工程帶有submodule
當使用git clone下來的工程中帶有submodule時,初始的時候,submodule的內容並不會自動下載下來的,此時,只需執行如下命令:
git submodule init
git submodule update
或者是執行以下命令(該命令效果等同於上面兩個命令):
git submodule update --init --recursive
即可將子模塊內容下載下來后工程才不會缺少相應的文件。
更新submodule的URL
1.更新.gitsubmodule中對應submodule的條目URL
2.更新 .git/config 中對應submodule的條目的URL
3.執行 git submodule sync
刪除子模塊
1. 使用vim編輯.gitmodules(vim .gitmodule), 刪除對應要刪除的submodule的行.
2. 使用vim編輯.git/config,刪除有對應要刪除的submodule的行.
3.執行 git rm --cached {submodule_path}。注意,路徑不要加后面的“/”。例如:你的submodule保存在 supports/libs/websocket/ 目錄。執行命令為: git rm --cached supports/libs/websocket
手冊
usage: git submodule [--quiet] [--cached] or: git submodule [--quiet] add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--] <repository> [<path>] or: git submodule [--quiet] status [--cached] [--recursive] [--] [<path>...] or: git submodule [--quiet] init [--] [<path>...] or: git submodule [--quiet] deinit [-f|--force] (--all| [--] <path>...) or: git submodule [--quiet] update [--init] [--remote] [-N|--no-fetch] [-f|--force] [--checkout|--merge|--rebase] [--[no-]recommend-shallow] [--reference <repository>] [--recursive] [--] [<path>...] or: git submodule [--quiet] set-branch (--default|--branch <branch>) [--] <path> or: git submodule [--quiet] summary [--cached|--files] [--summary-limit <n>] [commit] [--] [<path>...] or: git submodule [--quiet] foreach [--recursive] <command> or: git submodule [--quiet] sync [--recursive] [--] [<path>...] or: git submodule [--quiet] absorbgitdirs [--] [<path>...]