合并两个不同远程仓库的Git命令

需求场景描述

同一个项目的代码,在coding上有一份,在GitHub上也有一份。但coding上的代码较新,领先了几个commit,GitHub上的比较旧。这是想要将GitHub上的代码与coding上的代码保持一致。而且最好要能保留commits。

合并步骤

首先拉取旧仓库的代码,这里应该克隆GitHub的代码。

git clone git@github.com:username/xxx.git
cd xxx

之后进入旧仓库的master分支,查看已有的远程仓库

git remote -v //查看远程仓库
origin  git@github.com:username/xxx.git (fetch)
origin  git@github.com:username/xxx.git (push)

添加新仓库的远程地址并命名,这里我添加了coding仓库的远程地址

git remote add coding https://e.coding.net/username/project/xxx.git

拉取coding远程仓库中的所有代码分支到本地,注意使用fetch命令,这样不会自动合并

git fetch coding

根据新拉取的新仓库目标分支的代码(这里是coding/master)在旧仓库中建立一个新分支并命名(如origin/coding),切换到此分支。

git checkout -b coding coding/master //相当于将远程仓库的master分支复制了一份到旧仓库新建的coding分支

查看当前仓库的所有分支,确保切换到了旧仓库中新建的目标分支

* coding
  master
  remotes/coding/beta
  remotes/coding/deepin
  remotes/coding/master
  remotes/coding/spiff
  remotes/origin/HEAD -> origin/master
  remotes/origin/deepin
  remotes/origin/master
  remotes/origin/spiff

切换回旧仓库的master分支

git checkout master

使用git merge命令合并coding分支到主分支master

git merge coding

这一步中可能会有冲突,需要手动解决,并提交到主分支。建议使用IDE(VSCode,IDEA等)的可视化git解决冲突,方便比对代码

如果两个仓库只是版本不同,一个版本靠前一个落后,没有commits记录上的差异时,合并时是不会产生冲突的。没有冲突的话是不需要这一步的

git commit -m "合并来自coding的代码"

经过上一步的操作,我们已经将coding的代码合并到本地GitHub仓库了,接下来只需要将合并后的本地仓库推送到Github

git push origin master --allow-unrelated-histories

参考资料:

合并两个不同远程仓库的Git命令

posted @ 2022-11-28 22:40  因为风的缘故~  阅读(670)  评论(1编辑  收藏  举报