在Git中切换到不同的代码库

4

Git中我仍然感到困惑的一种情况是:

$ git clone https://github.com/dude1/project

糟糕,那不是正确的版本。我会切换到另一个版本:

$ git remote add dude2 https://github.com/dude2/project
$ git fetch dude2
$ git checkout dude2/master

Note: checking out 'dude2/master'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at f3o845a... 

嗯,我希望 master 指的是dude2/master。

$ git checkout -b master dude2/master

fatal: A branch named 'master' already exists.

除了删除整个目录并重新开始,我应该如何干净地切换存储库?


1
当你想放弃之前所引用的分支时,尝试使用-B而不是-b - jthill
非常感谢。有趣的是,-B选项会给出关于不同分支如何发散的信息。 - Steve Bennett
1
@SteveBennett然后两个远程仓库的主分支内容不相同。你第一次clone时复制了第一个远程仓库的内容。当你将主分支切换到第二个远程仓库时,差异被视为你自己创建的提交,从而"分叉"了主分支和远程仓库的关系。 - Klas Mellbourn
2个回答

3
在git中,你不应该在远程分支上提交工作(应该在本地分支上完成工作),这就是为什么当你checkout dude2/master时会进入“分离头指针”状态。远程分支应该包含来自远程的提交副本,而不是本地创建的提交。
正如jthill建议的那样,强制切换master的最佳方法是:
git checkout -B master dude2/master

输出应包括:
Branch master set up to track remote branch master from dude2.

表示您的主分支现在正在跟踪不同的远程主分支的更改。

0
仔细思考后,显而易见的答案是:
首先执行上述命令git checkout dude2/master。然后:
$ git branch -d master
warning: deleting branch 'master' that has been merged to
     'refs/remotes/dude1/master', but not yet merged to HEAD.
Deleted branch master (was f30845a).

$ git checkout -b master dude2/master
Branch master set up to track remote branch master from dude2.
Switched to a new branch 'dude2'

我对删除主文件时的警告含义一无所知。

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