當(dāng)一個項目需要包含其他支持項目源碼時使用的功能,作用是兩個項目是獨立的,且主項目可以使用另一個支持項目。
git submodule add <submodule_url> # 添加子項目
添加子項目后會出現(xiàn).gitmodules的文件,這是一個配置文件,記錄mapping between the project's URL and the local subdirectory。且.gitmodules在git版本控制中,這樣其他參與項目的人才能知道submodule projects的情況。
git submodule init # 初始化本地.gitmodules文件
git submodule update # 同步遠(yuǎn)端submodule源碼
如果獲取的項目包含submodules,pull main project的時候不會同時獲取submodules的源碼,需要執(zhí)行本地.gitmodules初始化的命令,再同步遠(yuǎn)端submodule源碼。如果希望clone main project的時候包含所有submodules,可以使用下面的命令
git clone --recurse-submodules <main_project_url> # 獲取主項目和所有子項目源碼
操作submodules源碼:先進(jìn)入submodule的direcotry,再執(zhí)行下述命令
git fetch # 獲取submodule遠(yuǎn)端源碼
git merge origin/<branch_name> # 合并submodule遠(yuǎn)端源碼
git pull # 獲取submodule遠(yuǎn)端源碼合并到當(dāng)前分支
git checkout <branch_name> # 切換submodule的branch
git commit -am "commit" # 提交submodule的commit
# or
# 更新submodule源碼,默認(rèn)更新的branch是master,如果要修改branch,在.gitmodule中設(shè)置
git submodule update --remote <submodule_name>
# 更新所有submodule源碼,默認(rèn)更新.gitmodule中設(shè)置的跟蹤分支,未設(shè)置則跟蹤master
git submodule update --remote
# 當(dāng)submodule commits提交有問題的時候放棄整個push
git push --recurse-submodules=check
# 分開提交submodule和main project
git push --recurse-submodules=on-demand
.gitmodule內(nèi)容大致如下
[submodule <submodule_name>]
path = <local_directory>
url = <remote_url>
branch = <remote_update_branch_name>
用'foreach'關(guān)鍵字同時管理多個submodules,如下
# stash所有submodules
git submodule foreach 'git stash'
# 所有submodules創(chuàng)建新分支
git submodule foreach 'git checkout -b <branch_name>'
submodules的命令很長,為提升效率,可以創(chuàng)建alias,記錄在.git/config路徑下。如下:
git config alias.spush 'push --recurse-submodules=on-demand'
git config alias.supdate 'submodule update --remote --merge'
這樣,可以使用下面的命令來提高效率
git supdate
git spush