尽管我的回答超出了您的要求,但我认为这实际上是您打算做的。
您曾经git reset --soft HEAD^
撤消所做的提交。这会将工作副本返回到您提交之前的状态(因为HEAD
指向您当前的提交,并HEAD^
指向它之前的提交(假设只有一个父提交)。
但是现在,当git push
您被告知类似以下内容时:
! [rejected] <branch> -> <branch>e (non-fast-forward)
error: failed to push some refs to 'ssh://<remote server>/<remote path>'
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.
这就是说提交没有对齐,它可以防止你犯错误。错误消息有点误导,您不想按照它的建议去做(拉动以使您的分支同步)。由于您的意图,您只能知道不要这样做。
你可以简单地用--force
(或-f
)(*)来解决这个问题:
git push --force
您可能需要再次设置上游:
git push --force --set-upstream origin <branch>
请注意,如果其他人已经取消了您的工作,这将产生后果,因为会有不同的提交进行相同的更改(可能)。请参阅https://www.kernel.org/pub/software/scm/git/docs/user-manual.html#problems-With-rewriting-history。
为防止出现任何问题,请只推送到您的分支(而不是某个公共分支 - 例如development
开发人员将所有功能分支合并到的分支),并确保在您的团队中进行开放式沟通。
开发人员通常会将此模式用于我所说的周五下午提交,您希望在周末之前保存您的工作以防硬件故障(但在周一返回到预提交状态)。
*Friday*
git add --all # To add all files whether they are tracked or not
git commit -m "Friday afternoon commit"
git --set-upstream push # --set-upstream is for if the branch doesn't exist on the remote server
*Monday*
git reset --soft HEAD^
git push -f --set-upstream origin <branch>
与另一个答案中讨论的相比,这样做的好处git revert
是避免额外的提交。重置将有 2 次提交,这种方式将没有(没有额外的)。优点git reset
是它不会重写历史,因此更安全,尤其是在您不确定自己在做什么的情况下。
(*) 通常存储库被配置为不允许您这样做以掌握 - 修复分支并创建拉取请求。因为如果您已经阅读了上面的链接,在 master 上重写历史将会产生严重的后果(除非您是唯一一个克隆该代码的人)。