Error: Undo last git commit on both local and remote

Error: Undo last git commit on both local and remote

假设我在本地 A 上有一个分支,这在远程 origin/A 中也存在。我的本地和远程分支都是同步的。例如,在本地我有类似的提交 - C1C2C3C4,在我的远程也一样。

现在我想恢复为 C4 提交的更改。我已经将其推送到远程,所以我也想在远程执行此操作。

NOTE: I found lot of question in Whosebug for this. Here is one. But it's not working for me!

按照这个我试过:

git reset --hard HEAD~1
git push -f origin A

第一个命令工作正常,我的本地版本现在没有 C4 提交。

第二个命令有问题。它显示 remote: error: denying non-fast-forward refs/heads/A (you should pull first).

如何解决这个问题?

您当前删除最近提交的方法是完全正确的:

git reset --hard HEAD~1
git push -f origin A

不幸的是,GitHub 似乎不允许您进行强制推送。但是,还有另一种选择。您可以改为 git revert 最近的提交。这将在分支顶部添加一个 new 提交,这将撤消最近提交所做的任何事情。据推测,在 GitHub 中添加新提交不会有任何问题。如果您想走这条路,请尝试以下操作:

git revert HEAD
git push origin A

您的新分支图将如下所示:

remote: C1 -- C2 -- C3 -- C4 -- R
local:  C1 -- C2 -- C3 -- C4 -- R

其中 R 是还原提交 C4 的提交。从功能上讲,这两个分支的行为就好像 C4R 提交都不存在一样,即:

local/remote: C1 -- C2 -- C3