當一個項目須要包含其餘支持項目源碼時使用的功能,做用是兩個項目是獨立的,且主項目可使用另外一個支持項目。git
git submodule add <submodule_url> # 添加子項目
添加子項目後會出現.gitmodules的文件,這是一個配置文件,記錄mapping between the project's URL and the local subdirectory。且.gitmodules在git版本控制中,這樣其餘參與項目的人才能知道submodule projects的狀況。shell
git submodule init # 初始化本地.gitmodules文件 git submodule update # 同步遠端submodule源碼
若是獲取的項目包含submodules,pull main project的時候不會同時獲取submodules的源碼,須要執行本地.gitmodules初始化的命令,再同步遠端submodule源碼。若是但願clone main project的時候包含全部submodules,可使用下面的命令vim
git clone --recurse-submodules <main_project_url> # 獲取主項目和全部子項目源碼
操做submodules源碼:先進入submodule的direcotry,再執行下述命令bash
git fetch # 獲取submodule遠端源碼
git merge origin/<branch_name> # 合併submodule遠端源碼
git pull # 獲取submodule遠端源碼合併到當前分支
git checkout <branch_name> # 切換submodule的branch
git commit -am "change_summary" # 提交submodule的commit
# or # 更新submodule源碼,默認更新的branch是master,若是要修改branch,在.gitmodule中設置 git submodule update --remote <submodule_name> # 更新全部submodule源碼,默認更新.gitmodule中設置的跟蹤分支,未設置則跟蹤master git submodule update --remote # 當submodule commits提交有問題的時候放棄整個push git push --recurse-submodules=check # 分開提交submodule和main project git push --recurse-submodules=on-demand
.gitmodule內容大體以下app
[submodule <submodule_name>] path = <local_directory> url = <remote_url> branch = <remote_update_branch_name>
用'foreach'關鍵字同時管理多個submodules,以下fetch
# stash全部submodules git submodule foreach 'git stash' # 全部submodules建立新分支 git submodule foreach 'git checkout -b <branch_name>'
submodules的命令很長,爲提高效率,能夠建立alias,記錄在.git/config路徑下。以下:url
git config alias.spush 'push --recurse-submodules=on-demand' git config alias.supdate 'submodule update --remote --merge'
這樣,可使用下面的命令來提升效率spa
git supdate git spush