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

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

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

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

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


当前回答

关于:

git checkout old-branch-name
git push remote-name new-branch-name
git push remote-name :old-branch-name
git branch -m new-branch-name

其他回答

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
git checkout -b new-branch-name
git push remote-name new-branch-name :old-branch-name

在删除旧分支名称之前,您可能必须手动切换到新分支名称

可以将以下内容保存到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自定义操作中使用。

git update-ref newref oldref
git update-ref -d oldref newref

关于:

git checkout old-branch-name
git push remote-name new-branch-name
git push remote-name :old-branch-name
git branch -m new-branch-name