背景
在实际工作中,相信大家都有遇到过需要向两个或两个以上的远端代码仓库提交代码,或者向一个代码仓库拉取代码并同步到另一个代码仓库的情况。比如,我们就遇到过以下两种情况:
- 基于开源项目的二开项目。为了获得开源项目的最新代码(功能),需要时不时的从开源项目的代码仓库(gitee.com、github.com等)拉取新代码,然后提交到本地二开后的代码仓库。
- 我司最近做了一次研发环境的迁移,重新搭建一套新的研发环境,但是短时间内老的那套研发环境还会继续使用,因为进行中的研发任务还继续提交代码到老环境的代码仓库,新的研发任务则迁移到了新的代码仓库上进行开发。此时在老环境上开发的同事就需要将代码提交到老代码仓库的同时,也提交一份到新的代码仓库(当时,不要求实时同步,最终一致就可以了)。
那么我们如何通过Git的多仓库管理能力来轻松搞定同步提交代码到多个远程仓库呢?答案就是利用Git remote的多仓库管理功能来实现。具体的可以有三种方式搞定这个问题。
解决方案
下面以DRM项目为示例,跟着我来一步步体验一下这个过程吧
示例说明
代码仓库原始地址在gitee.com上
https://gitee.com/devon/drm.git
现迁移一份到我司代码仓库(我司用的是Gitea,自带有代码库迁移的功能)
http://code.example.com/devon/drm.git
目前两个代码库的代码是一样的。
方案一
配置两个独立仓库组,然后通过git push命令推送到指定仓库组仓库的方式实现代码同步。
当前仓库配置信息:
drm(master)$ git remote -v
origin https://gitee.com/devon/drm.git (fetch)
origin https://gitee.com/devon/drm.git (push)
添加我司代码仓库
drm(master)$ git remote add gttis http://code.example.com/devon/drm.git
指定代码仓库的别名,此处我使用 gttis 作为我司代码仓库的别名
添加完后查看仓库名称及地址
drm(master)$ git remote -v
origin https://gitee.com/devon/drm.git (fetch)
origin https://gitee.com/devon/drm.git (push)
gttis http://code.example.com/devon/drm.git (fetch)
gttis http://code.example.com/devon/drm.git (push)
可以看到我司的代码仓库已经成功添加了,但是此时你是没办法签出新仓库的代码分支的,因为它的仓库信息还没有被拉取下来。
所以我们需要通过fetch命令拉取新仓库的元数据信息(分支、标签等)
drm(master)$ git fetch gttis
From http://code.example.com/devon/drm
* [new branch] master -> gttis/master
到这里两个远端仓库分支的信息都被拉到本地了。接下来,我们可以在一个分支上做一些代码修改,然后分别向两个仓库提交代码了。
我们修改了README.md文件
drm(master)$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: README.md
提交代码到本地缓冲区
drm(master)$ git commit -a -m 'for testing'
[master ffd788b] for testing
1 file changed, 1 insertion(+), 1 deletion(-)
接下来就到了验证成败关键时刻了
首先,将代码推到原代码仓库(gitee.com)
drm(master)$ git push
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100%