我有一个分支主机,它跟踪远程分支源/主机。

我想在本地和远程将它们重命名为master old。这可能吗?

对于跟踪origin/master(并且总是通过git pull更新本地主分支)的其他用户,在我重命名远程分支后会发生什么?他们的git pull是否仍然有效,或者它是否会抛出一个错误,即无法再找到原始/主文件?

接下来,我想创建一个新的主分支(本地和远程)。再次,在我这样做之后,如果其他用户执行git pull,现在会发生什么?

我想这一切都会带来很多麻烦。有没有一种干净的方法可以得到我想要的东西?还是我应该让master保持原样,创建一个新的分支master,然后继续工作?


当前回答

这是我所知道的最简单、最“可读”的方式:

使用-m“移动”本地分支

git branch -m my_old_branch_name my_new_branch_name

将“已移动”分支推到远程,使用-u设置“上游”

git push origin -u my_new_branch_name

设置“upstream”实际上是将本地分支“连接”到远程,这样像fetch、pull和push这样的操作就可以工作了。

从远程删除旧分支

git push origin -D <old_name>

您的本地分支已经不存在了,因为您在第一步中“移动”了它。

其他回答

在Git v1.7中,我认为这一点略有改变。现在很容易将本地分支机构的跟踪参考更新到新的远程设备。

git branch -m old_branch new_branch         # Rename branch locally    
git push origin :old_branch                 # Delete the old branch    
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote
git update-ref newref oldref
git update-ref -d oldref newref

有很多方法可以重命名分支机构,但我将重点放在更大的问题上:“如何让客户快速前进,而不必在本地处理分支机构”。

首先是一张快速图片:

这实际上很容易做到;但不要滥用它。整个想法取决于合并提交;因为它们允许快进,并将分支的历史与另一分支的历史联系起来。

重命名分支:

# rename the branch "master" to "master-old"
# this works even if you are on branch "master"
git branch -m master master-old

创建新的“主”分支:

# create master from new starting point
git branch master <new-master-start-point>

创建合并提交以具有父子历史记录:

# now we've got to fix the new branch...
git checkout master

# ... by doing a merge commit that obsoletes
# "master-old" hence the "ours" strategy.
git merge -s ours master-old

瞧。

git push origin master

这是因为创建合并提交允许将分支快速转发到新修订。

使用合理的合并提交消息:

renamed branch "master" to "master-old" and use commit ba2f9cc as new "master"
-- this is done by doing a merge commit with "ours" strategy which obsoletes
   the branch.

these are the steps I did:

git branch -m master master-old
git branch master ba2f9cc
git checkout master
git merge -s ours master-old

您可以执行以下操作:

git -m master master-old #rename current master
git checkout -b master   #create a new branch master
git push -f origin master #force push to master

但如果其他人共享这个存储库,强行推送是个坏主意。强制推送将导致其修订历史与新的修订历史冲突。

2022年更新的解决方案

GitHub现在正式支持其用户重命名分支机构,并在GitHub Docs上提供指导。

我已经按照他们的步骤成功地重命名了我的本地和远程分支。

如果URL断开,下面是解决方案。

重命名远程分支

在GitHub.com上,导航到存储库的主页面。在文件列表上方,单击“分支”。在分支列表中,在要重命名的分支的右侧,单击编辑符号。键入分支的新名称并查看信息,然后单击“重命名分支”

在分支名称更改后更新本地克隆

根据GitHub文档:

在GitHub上重命名存储库中的分支后,任何具有存储库本地克隆的合作者都需要更新该克隆。

从计算机上存储库的本地克隆中,运行以下命令用于更新默认分支的名称:

$ git branch -m OLD-BRANCH-NAME NEW-BRANCH-NAME
$ git fetch origin
$ git branch -u origin/NEW-BRANCH-NAME NEW-BRANCH-NAME
$ git remote set-head origin -a

(可选)运行以下命令以删除对旧分支名称的跟踪引用:

$ git remote prune origin