GIT之Submodule的使用

當(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

示例項目

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容