主题模式
Git 历史重置:保留快照并核对远端
普通历史重置可以保留当前文件、重新建立初始提交。它不会让泄漏凭据失效,也不能抹除所有旧副本。下方先给出 Windows PowerShell 的本地裸仓库练习,再保留面向实际远端的 Bash 步骤。两者都只用于没有敏感数据清理需求的普通重置。
在本地副本中重建根提交
本次先完成基本提交及 worktree 练习,把示例 main 推送到 .cache/git-pnpm-walkthrough/remote.git。旧 main 为 197f6ad561a1d6e9bb21915c3b257dba4bec5727。然后在同一练习根目录新建克隆:
powershell
# 在 .cache/git-pnpm-walkthrough/repo 中执行
git push origin main
git fetch origin
git rev-parse HEAD
git rev-parse refs/remotes/origin/main
git clone --no-local ../remote.git ../history-reset
Set-Location ../history-reset
git config --local user.name "Docs Demo"
git config --local user.email "[email protected]"
git status --short
git branch --show-current
git branch history-before-reset main
git checkout --orphan codex/clean-history main
git diff --cached --stat
git diff --cached
git commit -m "chore: start a new history"
git rev-list --count HEAD
git diff --exit-code history-before-reset HEAD --克隆的工作区检查无输出,当前分支为 main。新快照有 5 个文件、9 行内容。提交后 rev-list 输出 1;最后的 diff 无输出,退出码为 0,说明新根提交与原 main 的文件快照相同。
继续只更新这个本地裸仓库的 main:
powershell
$history_expected_main = git rev-parse history-before-reset
git push --force-with-lease="refs/heads/main:$history_expected_main" origin HEAD:refs/heads/main
git ls-remote origin refs/heads/main
git rev-parse HEAD两次查询都得到 208d30df71dcbbcdaaa055ee613b899d58177caa。这里 origin 是练习目录中的裸仓库,不涉及线上分支。history-before-reset 仍引用旧历史,因此重建单个分支不等于从所有引用中删除旧对象。
密码或令牌泄漏:先让凭据失效
先撤销或轮换令牌、密码,再更新应用配置并检查访问日志。按平台指南清理涉及的历史路径和引用;fork、他人克隆、PR 引用及缓存仍需单独处理。不要为方便回滚再上传含秘密的分支、标签或压缩包。
普通历史重置:只保留当前文件快照
先取得维护者同意,与协作者约定暂停更新。无敏感数据时,将旧历史备份到受控位置并验证可恢复;分支保护不允许重写时走既定审核流程。
1. 核对工作区与远端
bash
git remote -v
git branch --show-current
git status --short
git fetch origin
git rev-parse HEAD
git rev-parse refs/remotes/origin/main要求当前是 main、工作区干净、没有合并或变基进行中,而且两个 SHA 一致。任何一项不符都先处理,不进入下一步。
2. 创建并检查新快照
bash
history_expected_main="$(git rev-parse refs/heads/main)"
git checkout --orphan clean-history main
git diff --cached --stat
git diff --cached孤儿分支名必须尚不存在。已跟踪文件已进入暂存区,无需 git add -A。逐项排除秘密和临时文件,再提交:
bash
git commit -m "chore: start a new history"
git rev-list --count HEAD
git diff --exit-code "$history_expected_main" HEAD --第一条应输出 1;最后的快照比较应无输出、退出码为 0,表示新提交与原 main 保存的文件一致。
3. 只更新指定的远端分支
bash
git push --force-with-lease="refs/heads/main:$history_expected_main" origin HEAD:refs/heads/main
git ls-remote origin refs/heads/main
git rev-parse HEAD远端 SHA 应与新 HEAD 一致。lease 拒绝说明远端状态变化,应重新调查;不能刷新预期值后直接覆盖。协作者需重新克隆或迁移未合并工作;不要把保留的旧 main 直接推回新历史。