如何在Git中将master分支重命名为main

长期以来,大多数 Git 仓库的默认分支都被命名为“master”。幸运的是,许多人已经意识到这个术语(在“主/从”中更为明显)应该被替换!科技行业应该走向一种更加包容、开放的文化——而移除“主/从”这样的术语是这一进程中的重要一步。

在公开讨论中,出现了一些“master”的不同替代词,其中包括“default”和“primary”。但最受欢迎的似乎是“main”。

这篇短文将帮助您将自己的 Git 存储库中的“master”重命名为“main”(或您的团队选择的任何其他术语)。

将本地主分支重命名为main

第一步是重命名本地Git 存储库中的“master”分支:

$ git branch -m master main

让我们快速检查一下这是否按预期工作:

$ git status
On branch main
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

到目前为止一切顺利!本地分支已重命名 – 但现在我们也需要在远程仓库上进行一些更改!

重命名远程主分支

第二步,我们需要在远程仓库中创建一个名为“main”的新分支——因为 Git 不允许简单地“重命名”远程分支。我们需要创建一个新的“main”分支,然后删除旧的“master”分支。

首先,输入以下命令:

$ git push -u origin main

git push -u origin main命令将把本地“主”分支推送到远程,无论当前检出哪个分支(即,无论 HEAD 指向哪里)。

现在我们在远程仓库上有一个名为“main”的新分支。让我们继续删除远程仓库中旧的“master”分支:

$ git push origin --delete master

根据您的具体设置,此操作可能有效,重命名成功。然而,在很多情况下,您会看到类似以下的错误消息:

To https://github.com/test/git-test.git
! [remote rejected]   master (refusing to delete the current branch: refs/heads/master)
error: failed to push some refs to 'https://[email protected]/test/git-test.git'

与其他代码托管平台一样,GitHub 也要求您定义一个“默认”分支,并且不允许删除该分支。此外,您的旧“主分支”可能被设置为“受保护”。您需要先解决此问题才能继续操作。如果你远程仓库不在GitHub,是一个本地bare仓库,那么可以去到bare仓库下,将其“默认”分支改为main(这个分支不必存在,修改为其他任何非master都行):

# Login to the remote host and enter the remote bare repository directory with login shell
$ ssh -t remote-host 'cd /git/test/git-test.git; exec bash -l'
$ git branch
  main
* master
$ git symbolic-ref HEAD refs/heads/main
$ git branch
* main
  master

回到本地仓库,如果您现在再试一次,从远程存储库中删除“master”应该会成功:

$ git push origin --delete master
To https://github.com/test/git-test.git
 - [deleted]           master

你的队友必须做什么

如果您团队中的其他人有存储库的本地克隆,他们也必须在他们的终端执行一些步骤:

# Switch to the "master" branch:
$ git checkout master

# Rename it to "main":
$ git branch -m master main

# Get the latest commits (and branches!) from the remote:
$ git fetch

# Remove the existing tracking connection with "origin/master":
$ git branch --unset-upstream

# Create a new tracking connection with the new "origin/main" branch:
$ git branch -u origin/main

# Remove all such stale branches 
# see more: https://stackoverflow.com/questions/5094293/git-remote-branch-deleted-but-still-it-appears-in-branch-a
$ git remote prune origin
$ git fetch -p
$ git fetch --prune
$ git pull --prune
$ git branch -d -r origin/master

需要注意的事情

正如您所见,将“master”重命名为“main”的过程并不十分复杂。

不过,需要注意的一点是你的工具链:如果你正在使用 CI/CD 工具、GitHub Actions、Azure DevOps / Atlassian Bamboo / GitLab CI 流水线或类似的工具,你应该彻底检查这些工具。如果它们依赖于特定的“origin/master”分支,你可能也需要更改它们的设置。

更改初始化仓库的默认分支为main

通常新版git初始化仓库的默认分支为main,如果不是,可以通过以下命令设置

$ git config --global init.defaultBranch main

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注