Git - 分支管理



在前面的章节中,我们学习了如何添加和删除分支,本章将讨论分支管理。

git branch 命令的用途远不止添加和删除分支。

不带任何参数运行 git branch 命令时,它将显示所有当前分支。

$ git branch auth-module * master feature-x

当前签出的分支(即 HEAD 指向的分支)用星号 (*) 表示。

此状态的提交将推进签出的分支。

分支的最近提交

使用 git branch -v 查看每个分支的最新提交。

$ git branch -v auth-module abcd123 Latest commit on auth-module * master 7a1b2c3d Latest commit on master feature-x e4f5g6h7 Latest commit on feature-x

分支筛选

使用 git branch 命令,我们可以使用 --merged--no-merged 参数根据分支是否已合并到当前分支来过滤分支列表。

例如,我们可以执行以下命令来查找哪些分支以前已合并到我们当前所在的 master 分支。

$ git branch --merged auth-module * master
  • 使用 git branch --merged 查看在将其合并到主分支 (master) 后,已合并的分支中是否列出了 auth-module

  • 使用 git branch -d,我们可以安全地删除没有 *(星号)符号的分支。

  • 这表明它们的修改已合并到另一个分支中,保证删除后不会丢失工作。

使用 git branch --no-merged 查看仍有未合并到当前分支的更改的分支。例如:

$ git branch --no-merged feature-x

此命令显示具有未合并更改的分支,例如 feature-x。此类分支无法使用 git branch -d 删除,因为会显示一个错误,指出该分支未完全合并。

$ git branch -d feature-x error: The branch 'feature-x' is not fully merged. If you are sure you want to delete it, run 'git branch -D feature-x'

使用 git branch -D feature-x 强制删除此类分支,确保所有更改都永久删除。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

更改分支名称

要更改分支名称,例如将名为 fix-typos 的分支重命名为 typo-fixes,同时保持其完整历史记录不变,请使用 git branch --move。这将本地重命名分支。

$ git branch --move fix-typos typo-fixes

我们本地仓库中的 fix-typos 现在称为 typo-fixes

要更新远程仓库,请推送重命名的分支。

$ git push --set-upstream origin typo-fixes

使用此命令在远程仓库中更新新的分支名称 typo-fixes

检查本地和远程的分支名称

$ git branch --all * typo-fixes main remotes/origin/fix-typos remotes/origin/typo-fixes remotes/origin/main

我们当前正在本地处理的分支是 typo-fixes,也可以从远程仓库访问。

在远程仓库中,分支 fix-typos 仍以之前的名称列出。请按如下方式从远程仓库中删除分支的旧名称:

$ git push origin --delete fix-typos

使用此命令删除远程仓库中分支的旧名称 fix-typos,只保留 typo-fixes

现在,本地和远程仓库中的分支 fix-typos 都已成功重命名为 typo-fixes

更改 master 分支名称

请按照以下步骤更新远程仓库中的本地 master 分支并将其重命名为 feature-new

使用 git branch --move 重命名本地分支

$ git branch --move master feature-new

上述命令将本地 master 分支重命名为 feature-new

要更新远程仓库,请推送重命名的分支。

$ git push --set-upstream origin feature-new

使用新的分支 feature-new 更新远程仓库。

使用以下命令检查本地和远程的分支名称

$ git branch --all * feature-new remotes/origin/HEAD -> origin/master remotes/origin/feature-new remotes/origin/master
  • 我们当前的本地分支现在称为 feature-new,它也存在于远程仓库中。

  • 但是,在远程仓库中,之前的分支名称 master 仍然存在。

  • 在远程更新并将其本地 master 分支重命名为 feature-new 后。

  • 其他协作者仍然可以继续使用之前的 master 分支。

  • 要完成此转换,我们需要执行更多任务。这些任务包括合并和关闭指向旧分支的拉取请求,以及升级依赖项、配置、脚本、仓库主机设置和文档引用。

  • 一旦所有必要任务都已完成,并且我们确定 feature-new 分支与之前的 master 分支的功能相同,我们就可以安全地删除 master 分支。

使用以下命令从远程删除分支的旧名称

$ git push origin --delete master

远程仓库中的 master 分支已删除,只保留 feature-new

分支 master 现在已成功重命名为 feature-new,本地和远程仓库均已更改。

广告