如何恢复到旧提交并将其推回云端

How to revert to an old commit and push it back to cloud

我已经做了 4 次错误的提交,想回到原来的状态。因此尝试了这样的事情 (reference)

    # Resets index to former commit; replace '56e05fced' with your commit code
git reset 56e05fced 

# Moves pointer back to previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

# Updates working copy to reflect the new commit
git reset --hard

我收到一条消息

HEAD is now at 56e05fced

在此之后,我尝试 git push origin master 以确保将上述更改移至 master 分支。但它向我抛出一个错误

  ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'xxxxxxxxxxxx.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

我该如何解决这里的问题。 (不想按照上面留言的建议再拉老夫子了)

在将本地分支重置为旧提交后将本地分支推送到原点是一种破坏性操作,因为它会删除原点中的这些提交。因此,除非使用 git push --force,否则会出现此错误。但是,请谨慎使用武力,因为即使它具有破坏性,您也可以推动。在使用 --force.

之前,请确保您完全了解后果

例如,如果自 56e05fced 以来有其他人推送到 master 分支,您也将删除这些提交。

考虑使用 git revert 而不是 git resetrevert 创建一个与错误提交相反的新提交。最终结果与删除提交相同,但更安全,因为它不会删除历史记录中的任何内容。但是,您需要一次还原一个提交并从最近的提交开始以避免冲突。还原提交也会在历史记录中留下痕迹,其中每个错误的提交都将保留在历史记录中,以及由还原创建的反向提交。