利用 rebase 删除 git 历史纪录


使用 rebase 方式来清理 Git 历史,并保留当前文件状态,步骤如下:


🌟 方法: 使用交互式 Rebase (git rebase -i) 清理历史

🛠️ 步骤 1: 创建测试分支

main 分支上,创建一个新的测试分支,确保你不会直接影响 main

git checkout -b test-clean-rebase

这样,即使操作出错,你的 main 还是安全的。


🛠️ 步骤 2: 交互式 Rebase

你想要删除所有旧的 commit,只保留当前的文件。最直接的方法是 rebase 到最早的提交,进行一次 压缩提交 (Squash)

  1. 找到最早的 commit(根提交)

    git log --reverse --oneline
    • 这会列出所有 commit,并按时间从旧到新排序。
    • 记下最早的 commit 的哈希值,例如 abc1234
  2. 执行 Rebase

    git rebase -i --root
    • 这里 --root 允许我们修改最早的提交
  3. 在编辑界面选择 “squash” (压缩)

    • Git 会打开一个编辑窗口,里面列出所有 commit:
      pick abc1234 init
      pick def5678 add feature 1
      pick ghi9101 remove old code
      pick jkl1121 update theme
    • 把除了第一个以外的所有 pick 改成 squash(或 s):
      pick abc1234 init
      squash def5678 add feature 1
      squash ghi9101 remove old code
      squash jkl1121 update theme
    • 这样,所有 commit 都会合并成一个提交。
  4. 编辑提交信息

    • Git 让你编辑新的 commit message,把它改成合适的描述,比如:
      Clean history - retain current files
    • 保存并退出,Git 会重新创建一个干净的提交。

🛠️ 步骤 3: 强制推送 (⚠️ 慎用)

如果 rebase 成功,你可以查看 git log,确认历史是否干净。

如果一切正确,并且你想把清理后的历史推送到远程:

git push --force origin test-clean-rebase

⚠️ 注意

  • --force 会覆盖远程分支,请确保远程仓库的其他人不会受影响。
  • 如果你要替换 main 分支,请执行:
    git checkout main
    git reset --hard test-clean-rebase
    git push --force origin main

🎯 总结

✅ 使用 git rebase -i --root 交互式 rebase,可以压缩所有历史到一个新的提交。
✅ 这个方法不会影响当前文件,但会清理掉所有 commit 记录。
git push --force 需要谨慎使用,以免影响团队协作。



文章作者: 赵阳
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 赵阳 !
  目录