在实际项目开发中,分支管理常常是让人头疼的问题。尤其是当我们“先干了再说”,后面才发现分支规划不合理,就容易出现“乱七八糟”的历史记录。

这篇文章记录了我在一个项目里遇到的真实情况:原本想在 main 分支上直接开发 Vue 版本,后来又想要保持 main 干净,把 Vue 独立出来。于是就有了“历史修复”的一系列操作。下面我会一步步讲解,如何从混乱的分叉整理出清晰的三条线。


1. 问题背景

最初的提交历史长这样:

* bf4b504 chore: initialize project with Vue 3 and Vite
| * 85093cd feat(ui): implement site under construction page
|/
* e9a3ade feat(branding): initialize project with Tootaio Studio branding
* af429eb refactor(ui): migrate from custom CSS to Tailwind CSS
* f0a0ac1 Initial commit

问题在于:

  • Vue 方向bf4b504 开始)本不该在 main 上。
  • 纯 HTML 方向feat-construction)却是基于 main 的,和 Vue 没有关系。
  • 结果是 main 同时承担了两条路线,历史交织在一起。

2. 目标分支结构

我最终想要的状态是这样的:

main
* e9a3ade feat(branding)
* af429eb refactor(ui)
* f0a0ac1 Initial commit

feat-construction (基于 main,纯 HTML)
* 4a33800 refactor(structure)
* b380b08 feat(contact)
* 46bd726 feat(security)
* 85093cd feat(ui)

vue (基于 bf4b504,Vue + Vite)
* ad4167b feat: scaffold initial application structure
* d9d8d32 ci(gitea)
* 3a379b4 ci(deploy)
* 24a7177 ci(gitea)
* bf4b504 chore: initialize project with Vue 3 and Vite

可以看到,最终我们得到三条清晰的主线:

  • main:品牌与基础结构
  • feat-construction:从 main 分支出来的实验性 HTML 方向
  • vue:从 bf4b504 开始的 Vue 前端方向

3. 整理分支的步骤

Step 1:修正 main

把 main 重置回 branding 那条线:

git checkout main
git reset --hard e9a3ade
git push origin main --force

Step 2:修正 vue

bf4b504 的位置新建 vue 分支,然后 cherry-pick 需要的提交:

git checkout -b vue bf4b504
git cherry-pick 7ccb119 fe05773 9e46704 8273e4e
git push origin vue --force

这样 vue 分支就从正确的起点开始了。

Step 3:确认 feat-construction

feat-construction 是从 main 分出来的,保持现状即可。如果之前它误跟了旧的 main,可以用 rebase 修正:

git checkout feat-construction
git rebase main
git push origin feat-construction --force

4. vue 分支要不要重命名?

这里有一个小问题:vue 分支的命名是否合适?

  • 如果你打算长期维护 Vue 方向,vue 这个名字显得有点局限。未来换成 React 或别的框架,就不太合适了。
  • 建议改成更语义化的名字,比如:

    • frontend
    • web
    • app

这样不绑定具体框架,分支命名会更通用。

重命名方法:

# 在 vue 分支上
git branch -m vue frontend
git push origin :vue # 删除远程 vue
git push origin frontend
git push origin -u frontend

5. 最终效果

经过整理后,分支结构变得清晰可控:

  • main:核心与品牌方向
  • feat-construction:实验性的纯 HTML 方向
  • frontend(原来的 vue):Vue 应用主线

这样一来,每条分支都有明确的职责,历史也干净整洁,再也不会出现“乱七八糟”的情况了。


结语 ✨

Git 的灵活性是一把双刃剑。随意开发时很爽,但后期维护就容易让人抓狂。
我的经验是:

  • 一开始就想清楚分支的语义(main 是什么,frontend 是什么)。
  • 不要怕重写历史reset / cherry-pick / rebase 用好了,能让项目清爽无比。
  • 命名要有前瞻性,避免未来改一次分支名牵一发而动全身。

希望这篇文章能帮你少踩坑,也欢迎分享你的分支整理故事~ 🚀