git 如何恢复两次提交并只提交好东西?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7932222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 12:12:03  来源:igfitidea点击:

How to revert two commits back and commit only good stuff?

git

提问by Damir

I commited something wrong twice. How to revert two commits back and commit only good stuff ?

我犯了两次错误。如何恢复两次提交并只提交好东西?

回答by Emil Sit

First, git reset HEAD~2to discard the top two commits, while leaving your working tree exactly as it is. Then, simply create a new commit with what you want (e.g., with git adds and then git commit).

首先,git reset HEAD~2丢弃前两个提交,同时让您的工作树完全保持原样。然后,简单地用你想要的东西创建一个新的提交(例如,用git adds 和 then git commit)。

See Reset Demystifiedby Scott Chacon for the details on the often confusing git resetcomamnd.

有关经常令人困惑的命令的详细信息,请参阅Scott Chacon 的Reset Demystifiedgit reset

回答by Noufal Ibrahim

You can do a git rebase -i HEAD~2and then use the interface to discard the "bad commits" that are there since then and clean up your history. This however alters the project history and if you've already pushed (and others pulled) your changes, there are some social issues to work out.

您可以执行 agit rebase -i HEAD~2然后使用该界面丢弃从那时起就存在的“错误提交”并清理您的历史记录。然而,这会改变项目历史,如果您已经推动(和其他人撤回)您的更改,则有一些社会问题需要解决。

The other option is to git revertthose changes. Then 2 new commits will get added to the history that makes the fact that you don't want these two commits explicit in the project history. Less clean but easier to work with.

另一种选择是进行git revert这些更改。然后 2 个新提交将添加到历史记录中,这使得您不希望在项目历史记录中明确这两个提交。不太干净,但更容易使用。

回答by Sheharyar

Revert changes in a new Commit

还原新提交中的更改

If you want to completely undo the commits and delete them, use rebaseor resetlike other answers suggest.

如果您想完全撤消提交并删除它们,请使用rebasereset喜欢其他建议的答案。

But sometimes, you can't modify git history(for example after pushing to a protected branch on remote). In that case, your best bet is git revert:

但有时,您无法修改 git 历史记录(例如在推送到远程受保护分支之后)。在这种情况下,您最好的选择是git revert

git revert --no-commit HEAD~1^..HEAD

This will revert all changes in the last two commits (from HEADto HEAD~1). You can make sure everything looks good by checking the status or diff and commit the revert:

这将恢复最近两次提交中的所有更改(从HEADHEAD~1)。您可以通过检查状态或差异并提交还原来确保一切正常:

git status # or git diff
git commit -m "Reverted the last two commits"