适用场景

  • 生产环境的 master 分支出现紧急 bug,需要立即修复。
  • develop 分支比 master 超前很多,不能直接合并到 master
  • 需要发布一个新的版本,只包含紧急修复内容。

1️⃣ 准备工作

  1. 确认本地仓库已经更新:
# 切换到 master
git checkout master
# 拉取远程最新 master
git pull origin master
  1. 检查当前分支状态,确保没有未提交的修改:
git status

2️⃣ 创建 hotfix 分支

master 分支新建一个 hotfix 分支,命名建议使用 hotfix/描述

git checkout -b hotfix/fix-critical-bug
分支名可根据修复内容具体命名,比如 hotfix/login-error

此时分支基于 master,不会包含 develop 的新功能。


3️⃣ 修复问题

  1. 在 hotfix 分支上修改代码,完成 bug 修复。
  2. 提交修改:
git add .
git commit -m "fix: 修复生产环境紧急 bug 描述"
注意 commit message 尽量简洁、清晰,推荐使用 Conventional Commits 规范。

4️⃣ 测试

  • 本地测试、单元测试、集成测试确保 bug 已修复。
  • 可以在临时或 staging 环境验证。

5️⃣ 合并 hotfix 到 master

  1. 切换到 master 分支:
git checkout master
  1. 合并 hotfix 分支:
git merge --no-ff hotfix/fix-critical-bug
--no-ff 可以保留单独的 merge commit,方便追踪 hotfix。
  1. 推送 master:
git push origin master

6️⃣ 发布新版本

  1. 创建 tag,标记新版本(比如 v1.0.1):
git tag -a v1.0.1 -m "hotfix: 修复紧急 bug"
  1. 推送 tag 到远程仓库:
git push origin v1.0.1
至此,生产环境可以基于最新 tag 部署 hotfix。

7️⃣ 将 hotfix 合并回 develop(可选,但推荐)

为了保持 develop 分支也包含修复,避免重复修复:

git checkout develop
git pull origin develop
git merge --no-ff hotfix/fix-critical-bug
git push origin develop
如果 develop 分支与 hotfix 有冲突,需要手动解决。

8️⃣ 删除 hotfix 分支(可选)

修复完成并合并后,可以删除本地和远程 hotfix 分支:

# 删除本地分支
git branch -d hotfix/fix-critical-bug

# 删除远程分支
git push origin --delete hotfix/fix-critical-bug

🔹 流程示意图

develop
    \
     *----*----* (未来功能)
      \
master ---*---* (生产版本)
             \
              hotfix/fix-critical-bug
                   *
                    \
master <-----------* (合并 hotfix, 发布新版本 v1.0.1)
develop <-----------* (可选合并 hotfix)
  • * 表示 commit
  • hotfix 分支只包含 master 的内容 + 修复

9️⃣ 注意事项

  1. hotfix 只修复紧急 bug,不引入新功能
  2. commit message 规范,方便生成 changelog。
  3. 发布新版本时,只用 hotfix 分支内容,避免将 develop 的未完成功能带入生产。
  4. 修复完成后,务必合并回 develop,保持代码一致。