如何将我的远程Git仓库移动到另一个远程Git仓库?

16

我想将我的远程git仓库及其所有分支移动到一个新的远程仓库。

旧的远程仓库 = git@github.com:thunderrabbit/thunderrabbit.github.com.git

新的远程仓库 = git@newhub.example.net:tr/tr.newrepo.git


我知道这是一个自问自答的问题,但问题本身仍然非常低质量。也许在提供你的答案之前,可以尝试添加一些你尝试过的想法或查阅的文档。 - user456814
FYI,umläute的回答并不完全正确,请参见我的评论 - user456814
4个回答

13

在本地终端上执行:

cd ~
git clone <old-remote> unique_local_name
cd unique_local_name

for remote in `git branch -r | grep -v master `; \
do git checkout --track $remote ; done

git remote add neworigin <new-remote>
git push --all neworigin

最后一行(git push --all gitlab)是一个打字错误吗?不应该是新的源,而不是gitlab吗? - David Beck
啊,是的,看起来是这样。谢谢! - Thunder Rabbit
1
请注意,如果您想要推送标记,则还需要使用 git push --tags 命令(不能与 --all 命令同时使用)。此外,您也可以使用 git branch 命令来代替 git checkout 命令,因为它不会在您的工作副本中切换文件,所以可能更快。 - user456814

9

这些其他回答都没有很好地解释,如果您想使用Git的push机制将所有远程存储库的分支移动到新的远程存储库中,您需要拥有每个远程分支的本地版本。

您可以使用git branch创建本地分支。这将在.git/refs/heads/目录下创建一个分支引用,其中存储了所有本地分支引用。

然后你可以使用 git push命令,搭配 --all--tags 选项标志一起使用:

git push <new-remote> --all  # Push all branches under .git/refs/heads
git push <new-remote> --tags # Push all tags under .git/refs/tags

请注意,--all--tags不能同时使用,因此您必须推两次。

文档

以下是相关的git push文档
--all

Instead of naming each ref to push, specifies that all refs under refs/heads/ be pushed.

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

--mirror

请注意,--mirror 可用于一次性推送分支和标签引用,但使用此选项的问题在于它会推送 .git/refs/所有引用,而不仅仅是 .git/refs/heads.git/refs/tags,这可能不是您想要推送到远程的内容。

例如,--mirror 可以推送存储在 .git/refs/remotes/<remote>/ 下的旧远程跟踪分支,以及其他引用(如 .git/refs/original/,它是 git filter-branch 的副产品)。


4
整个思路是对于每一个旧的远程分支,执行以下步骤:
  • 检出
  • 拉取
  • 推送到新的远程分支(不要忘记标签!)
就像这样:
#!/bin/bash

new_remote_link=git@newhub.example.net:tr/tr.newrepo.git
new_remote=new_remote
old_remote_link=git@github.com:thunderrabbit/thunderrabbit.github.com.git
old_remote=origin

git remote add ${old_remote} ${old_remote_link}

git pull ${old_remote}

BRANCHES=`git ls-remote --heads ${old_remote}  | sed 's?.*refs/heads/??'`

git remote add ${new_remote} ${new_remote_link}

for branch in ${BRANCHES}; do
    git checkout ${branch}
    git pull ${old_remote} ${branch}
    git push ${new_remote} ${branch} --tags
    printf "\nlatest %s commit\n" ${branch}
    git log --pretty=format:"(%cr) %h: %s%n%n" -n1
done

2

您可以简单地更改您的origin仓库的URL:

git clone <old-remote-url> unique_local_name
cd unique_local_name
git pull --all

git remote set-url origin <new-remote-url>
git push --all

这并不完全正确,如果您没有每个远程分支的本地分支版本,则它们将不会被推送到新的远程。只有在.git/refs/heads/下的本地分支才会被推送。 - user456814

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接