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

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

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

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

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


当前回答

我相信关键是你意识到你正在执行一个双重重命名:从主到主,从主到新。

从所有其他答案中,我综合了这一点:

doublerename master-new master master-old

我们首先要定义doublerename Bash函数:

# doublerename NEW CURRENT OLD
#   - arguments are branch names
#   - see COMMIT_MESSAGE below
#   - the result is pushed to origin, with upstream tracking info updated
doublerename() {
  local NEW=$1
  local CUR=$2
  local OLD=$3
  local COMMIT_MESSAGE="Double rename: $NEW -> $CUR -> $OLD.

This commit replaces the contents of '$CUR' with the contents of '$NEW'.
The old contents of '$CUR' now lives in '$OLD'.
The name '$NEW' will be deleted.

This way the public history of '$CUR' is not rewritten and clients do not have
to perform a Rebase Recovery.
"

  git branch --move $CUR $OLD
  git branch --move $NEW $CUR

  git checkout $CUR
  git merge -s ours $OLD -m $COMMIT_MESSAGE

  git push --set-upstream --atomic origin $OLD $CUR :$NEW
}

这类似于更改历史的git rebase,因为分支内容非常不同,但不同之处在于客户端仍然可以安全地使用git pull master快速前进。

其他回答

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

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

您可以执行以下操作:

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

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

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

使用-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 update-ref newref oldref
git update-ref -d oldref newref