简体   繁体   English

如何在 Android Studio 中使用 Git 命令恢复和删除提交?

[英]How to revert and delete a commit using Git commands in Android Studio?

For Example, I have made commit 1 and commit 2 on a branch.例如,我在一个分支上做了提交 1 和提交 2。 I want to revert commit 2 and delete it so I cannot see it in Git Tab in Android Studio and on GitHub.我想恢复提交 2 并将其删除,因此在 Android Studio 和 GitHub 的 Git 选项卡中看不到它。 Please let me know how can I do that?请让我知道我该怎么做? I am very new to Git and GitHub.我对 Git 和 GitHub 很陌生。 I have also tried following command我也尝试过以下命令

git reset HEAD~1

You're close.你很近。 You need to specify the reset mode .您需要指定重置模式 The command you ran without specifying the mode will use the default, which would be equivalent to:您在未指定模式的情况下运行的命令将使用默认值,相当于:

git reset --mixed HEAD~1

I assume you were unhappy with this because even though it removed (or more accurately hid) commit 2, all of the changes in commit 2 remained on your drive as pending changes.我假设您对此不满意,因为即使它删除(或更准确地说是隐藏)提交 2,提交 2 中的所有更改仍作为待处理更改保留在您的驱动器上。 At that point, you could just undo all of those pending changes to get where you want to be, which is back at commit 1 as if you never made commit 2 at all.那时,您可以撤消所有这些待处理的更改以到达您想要的位置,这又回到了提交 1,就好像您根本没有提交 2 一样。 If you still have commit 2, the command you wanted to run was:如果您仍然有提交 2,那么您要运行的命令是:

git reset --hard HEAD~1

Note that HEAD~1 is identical to the parent of the commit you're currently on.请注意, HEAD~1与您当前正在进行的提交的父级相同。 So if you're currently on commit 2, then HEAD~1 would be commit 1. Alternatively, you could also do:因此,如果您当前处于提交 2,那么 HEAD~1 将是提交 1。或者,您也可以这样做:

git reset --hard commit-1-ID # commit-1-ID is the hash, e.g. a1b2c3d4

If you already pushed out commit 2 to GitHub, then after you've done the reset, you need to force push your branch back out to replace the copy of the branch on GitHub, like this:如果您已经将提交 2 推送到 GitHub,那么在您完成重置后,您需要强制推送您的分支以替换 GitHub 上的分支副本,如下所示:

git push --force-with-lease

Side note: you said, "I want to revert commit 2...", and in Git, there is actually a command called revert which you use to undo changes from a specific commit in a brand new commit.旁注:您说,“我想恢复提交 2...”,在 Git 中,实际上有一个名为revert的命令,您可以使用它来撤消全新提交中特定提交的更改。 (So in your example you make commit 3 which is the reverse of commit 2, effectively putting your state back to commit 1, but with 2 extra commits in your history.) I can tell that you want reset instead because you don't want to be able to see commit 2 anymore, but realize the option to revert does exist if you prefer that. (因此在您的示例中,您进行了提交 3,这与提交 2 相反,有效地将您的 state 放回提交 1,但在您的历史记录中有 2 个额外的提交。)我可以告诉您,您想要reset ,因为您不想要能够再看到提交 2,但如果您愿意,请意识到确实存在revert选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM