代碼共享一直是比較頭痛的地方,尤其是共享的代碼還不穩(wěn)定,但多個代碼倉庫同時引用的時候。
我自己常用的方案是使用Git Submodule 同步最新的分支,但在協(xié)同開發(fā)中,發(fā)現(xiàn)還是會有很多因為對 Git認(rèn)知不同步 導(dǎo)致的問題,本打算用 rust/python 做個工具來解決這個問題,但搜了搜,用 Git 指令組合一下就解決了。下面便列一些相關(guān)指令,方便掌握。并給出一個終極指令,用來一鍵更新代碼,并切換submodule分支。
# 給現(xiàn)有 submodule 添加跟蹤的 branch 信息,需要 Git 版本 Git 2.22, Q2 2019。
git submodule set-branch --branch <branch_name> -- <submodule_path>
# 新增 submodules 時,指定跟蹤 branch 信息
git submodule add [-b <branch>] [--name <name>] -- <repository> [<path>]
# 更新 submodule 的 tracking 指針指向設(shè)定分支的最新提交,但該指針并不會關(guān)聯(lián)分支
git submodule update --remote
# 根據(jù) .gitmodules 里面的 分支跟蹤信息,切換各個 submodule 的分支
git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch'
通過以上基本指令,我們可以組合出如下:
# 更新代碼,更新 submodule 代碼到跟蹤分支的最新代碼
git pull && git submodule update --remote && git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch;'
# 更新代碼,更新 submodule 代碼到指定 commit,并切換分支
git pull && git submodule update && git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git checkout $branch;'
上面兩個指令,建議使用第二個,會更保險一些,第一個比較激進(jìn)一些。 (指令可能在 windows 下不太支持)。