对此有两种选择:一种是安全的,一种是给你留下肮脏的 git 历史,另一种是不安全,给你留下干净的 git 历史。你选择:
选项 1:还原
你可以告诉 git “恢复提交”。这意味着它将引入一个更改,该更改会还原您在提交中所做的每个更改。您需要执行两次(每次提交一次):
git revert 98y65r4
git revert 987xcrt
此解决方案将像这样留下您的 git 历史记录(您可以执行 gitk --all 以查看您的 repo 状态的图形表示):
2222222 revert of 987xcrt: this commit is not required
1111111 revert of 98y65r4: this commit is not required
abcd123 some message
xyze456 another commit message
98y65r4 this commit is not required
987xcrt this commit is not required
bl8976t initial commit
然后你可以将新的 2 个提交推送到你的远程仓库:
git push
此解决方案是安全的,因为它不会对您的远程仓库进行破坏性操作。
选项 2:交互式变基
您也可以为此使用交互式变基。命令是:
git rebase -i bl8976t
在其中,您告诉 git 让您选择要混合在一起的提交,重新排序或 删除。
当你执行命令时,一个编辑器会打开一个类似下面的文本:
pick bl8976t initial commit
pick 987xcrt this commit is not required
pick 98y65r4 this commit is not required
pick xyze456 another commit message
pick abcd123 some message
继续删除你不想要的行,像这样:
pick bl8976t initial commit
pick xyze456 another commit message
pick abcd123 some message
保存文件并关闭编辑器。
到目前为止,这仅修改了您存储库的本地副本(您可以使用gitk --all 看到提交树)。
现在您需要将更改推送到您的仓库,这是通过“推力”完成的,但在执行命令之前请记住,推力是一种破坏性操作,它将覆盖您的远程存储库,并且可能会给其他使用它的人带来合并麻烦。如果你没问题,想做推力,命令是:
git push -f