在使用 git 重置后无法推送更改——很难

我犯了一个错误,做了一些我不应该做的改变。 在我做出承诺之后,我推动了我的更改。 然后,我使用以下命令尝试重置我的更改。

 git reset --hard head

现在我想用下面的命令将这个“重置”推到远程存储库:

git push MyBranch

但我得到了这个错误:

remote: error: denying non-fast-forward refs/heads/branch (you should pull first)

我尝试使用这个命令,但没有成功:

git push -f "origin"

知道我能做什么吗?

100932 次浏览

You need to specify what ref you want to push:

git push -f origin MyBranch
git push -f origin myBranch

should work (provided you are aware this can be dangerous if MyBranch was already fetched by others in their own repo)

Since 2012, you also have:

  • git push --force-with-lease (Git 1.8.5+ Q3 2013) which is safer, and
  • git push --force-if-includes (Git 2.30+, Q1 2021), which attempts to ensure that what is being force-pushed was created after examining the commit at the tip of the remote ref that is about to be force-replaced.

Note: if your remote repo ('origin') has its config set with

receive.denyNonFastForwards true

it will deny any non fast-forward push (even when forced).
See "Is there a way to configure git repository to reject 'git push --force'?".


The OP user654019 reports

I managed to solve the problem this time by setting denyNonFastForwards to false and using -f to force the push

If the OP didn't have access to the repo, he/she would have to:

By example:

$ git revert -m 1 [sha_of_C8]
Finished one revert.
[master 88edd6d] Revert "Merge branch 'jk/post-checkout'"
1 files changed, 0 insertions(+), 2 deletions(-)

revert a merge

A complete discussion on how to revert a merge can be found here.

The idea remains to generate only new commits, including one reverting the changes introduced by the merge commit.
You then can push that new commit, as a fast-forward change.