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

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

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

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

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


当前回答

好的,在本地和远程重命名分支非常简单!。。。

如果你在分支机构,你可以很容易地做到:

gitbranch-m<branch>

否则,您需要执行以下操作:

git分支-m<your_old_branch><your_new_branch>

然后,将删除推送到远程,如下所示:

git推送原点<your_old_branch>

现在你完成了。

如果在尝试推送时遇到上游错误,只需执行以下操作:

git push--设置上游原点<your_new_branch>

我还创建了下图,以显示实际命令行上的步骤。只要按照步骤操作,你就会很好:

其他回答

最接近重命名的方法是删除,然后在远程设备上重新创建。例如:

git branch -m master master-old
git push remote :master         # Delete master
git push remote master-old      # Create master-old on remote

git checkout -b master some-ref # Create a new local master
git push remote master          # Create master on remote

然而,这有很多警告。首先,没有现有的签出会知道重命名-Git不会尝试跟踪分支重命名。如果新的master还不存在,git pull将出错。如果已创建新主控形状。拉将尝试合并master和master old。因此,除非您与之前签出存储库的所有人合作,否则这通常是一个坏主意。

注意:默认情况下,更新版本的Git不允许您远程删除主分支。您可以通过在远程存储库上将receive.denyDeleteCurrent配置值设置为警告或忽略来覆盖此设置。否则,如果您准备立即创建一个新的master,请跳过gitpushremote:master步骤,并将--force传递给gitpushremotemaster步骤。请注意,如果无法更改远程的配置,则无法完全删除主分支!

此警告仅适用于当前分支(通常是主分支);任何其他分支都可以如上所述被删除和重新创建。

在服务器上登录,转到Git目录并在裸存储库中重命名分支。

这并没有与重新加载同一分支相关的所有问题。实际上,“客户端”将自动识别修改后的名称并更改其远程引用。

之后(或之前)还可以修改分支的本地名称。

在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

可以将以下内容保存到shell脚本中以执行该作业:

例如:

remote="origin"

if [ "$#" -eq 0 ] # if there are no arguments, just quit
then
    echo "Usage: $0 oldName newName or $0 newName" >&2
    exit 1
elif
    [ "$#" -eq 1 ] # if only one argument is given, rename current branch
then
    oldBranchName="$(git branch | grep \* | cut -d ' ' -f2)" #save current branch name
    newBranchName=$1
else
    oldBranchName=$1
    newBranchName=$2
fi

git branch -m $oldBranchName $newBranchName

git push $remote :$oldBranchName # Delete old branch on remote
git push --set-upstream $remote $newBranchName # Add new branch name on remote and track it

请注意,这里的默认远程名称“origin”是硬编码的。您可以扩展脚本以使其可配置!

然后,该脚本可以与Bash别名、Git别名一起使用,或者在Sourcetree自定义操作中使用。

当我尝试时,所选答案失败。它抛出一个错误:拒绝删除当前分支:refs/heads/master。我想我会发布适合我的内容:

git checkout master             # If not in master already

git branch placeholder          # Create placeholder branch
git checkout placeholder        # Check out to placeholder
git push remote placeholder     # Push placeholder to remote repository

git branch -d master            # Remove master in local repository
git push remote :master         # Remove master from remote repository.

诀窍是在将占位符推送到远程存储库之前立即检出占位符。其余部分不言自明;删除主分支并将其推送到远程存储库现在应该可以工作了。摘自此处。