美文网首页
基于 GIt Submodule 来做代码共享

基于 GIt Submodule 来做代码共享

作者: 张朔源 | 来源:发表于2020-07-14 17:56 被阅读0次

代码共享一直是比较头痛的地方,尤其是共享的代码还不稳定,但多个代码仓库同时引用的时候。

我自己常用的方案是使用Git Submodule 同步最新的分支,但在协同开发中,发现还是会有很多因为对 Git认知不同步 导致的问题,本打算用 rust/python 做个工具来解决这个问题,但搜了搜,用 Git 指令组合一下就解决了。下面便列一些相关指令,方便掌握。并给出一个终极指令,用来一键更新代码,并切换submodule分支。

# 给现有 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 指针指向设定分支的最新提交,但该指针并不会关联分支
git submodule update --remote

# 根据 .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;'

上面两个指令,建议使用第二个,会更保险一些,第一个比较激进一些。 (指令可能在 windows 下不太支持)。

参考:

相关文章

网友评论

      本文标题:基于 GIt Submodule 来做代码共享

      本文链接:https://www.haomeiwen.com/subject/gsvfhktx.html