当我使用了一点源代码后,我做了我通常的事情提交,然后推送到远程存储库。但后来我注意到我忘记在源代码中组织导入。因此,我执行modify命令以替换先前的commit:

> git commit --amend

不幸的是,无法将提交推回到存储库。它是这样被拒绝的:

> git push origin
To //my.remote.repo.com/stuff.git/
 ! [rejected]        master -> master (non-fast forward)
error: failed to push some refs to '//my.remote.repo.com/stuff.git/'

我该怎么办?(我可以访问远程存储库。)


当前回答

我通过放弃本地修改的提交并在顶部添加新的更改来解决这个问题:

# Rewind to commit before conflicting
git reset --soft HEAD~1

# Pull the remote version
git pull

# Add the new commit on top
git add ...
git commit
git push

其他回答

我也有同样的问题。

意外修改了已推送的最后一个提交在本地做了很多更改,提交了大约五次尝试推送,出现错误,恐慌,合并远程,得到很多不是我的文件,推送,失败等。

作为一个Git新手,我认为这是完全的FUBAR。

解决方案:@bara建议+创建一个本地备份分支

# Rewind to commit just before the pushed-and-amended one.
# Replace <hash> with the needed hash.
# --soft means: leave all the changes there, so nothing is lost.
git reset --soft <hash>

# Create new branch, just for a backup, still having all changes in it.
# The branch was feature/1234, new one - feature/1234-gone-bad
git checkout -b feature/1234-gone-bad

# Commit all the changes (all the mess) not to lose it & not to carry around
git commit -a -m "feature/1234 backup"

# Switch back to the original branch
git checkout feature/1234

# Pull the from remote (named 'origin'), thus 'repairing' our main problem
git pull origin/feature/1234

# Now you have a clean-and-non-diverged branch and a backup of the local changes.
# Check the needed files from the backup branch
git checkout feature/1234-gone-bad -- the/path/to/file.php

也许这不是一个快速而干净的解决方案,我失去了我的历史(1次提交而不是5次),但它节省了一天的工作。

在更改提交的作者和提交人时,以下内容对我有效。

git push-f原始主机

Git非常聪明,能够发现这些都是相同delta的提交,只是在元信息部分有所不同。

本地和远程负责人都指出了有问题的提交。

在这里,我如何修复以前提交中的编辑:

保存您的工作到目前为止。如果做了更改,现在就暂时保存:git Stash现在您的工作副本在上次提交时是干净的。进行编辑和修复。在“修改”模式下提交更改:gitcommit--all--modify您的编辑器将显示一条日志消息(默认情况下,是旧的日志消息)。保存并在满意时退出编辑器。新的更改将添加到旧的提交中。使用git log和git diff HEAD自行查看^重新应用隐藏的更改(如果有):git stash apply

您正在看到Git安全功能。Git拒绝用您的分支更新远程分支,因为您的分支的头部提交不是您要推送的分支的当前头部提交的直接后代。

如果不是这样的话,那么两个同时推到同一个存储库的人就不会知道同时有一个新的提交,而最后推的人都会失去前一个推的人的工作,而他们中的任何一个都没有意识到这一点。

如果你知道你是唯一一个推送的人,并且你想推送一个修改后的提交或推送一条返回分支的提交,你可以使用-f开关“强制”Git更新远程分支。

git push -f origin master

即使这样也可能不起作用,因为Git允许远程存储库通过使用配置变量receive.denynonfastforwards在远端拒绝非fastforward推送。如果是这种情况,拒绝原因如下(注意“远程拒绝”部分):

 ! [remote rejected] master -> master (non-fast forward)

为了解决这个问题,您需要更改远程存储库的配置,或者作为一个肮脏的黑客,您可以删除并重新创建分支,从而:

git push origin :master
git push origin master

通常,git push的最后一个参数使用格式<local_ref>:<remote_ref>,其中local_ref是本地存储库上分支的名称,remote_ref是远程存储库上的分支的名称。此命令对使用两个短手。:master有一个空的localref,这意味着将一个空分支推送到远程端master,即删除远程分支。没有:的分支名称表示将具有给定名称的本地分支推送到具有相同名称的远程分支。在这种情况下,master是master:master的缩写。

您收到此错误,因为Git远程已经有这些提交文件。您必须强制推动分支才能使其工作:

git push -f origin branch_name

还要确保您从远程获取代码,因为团队中的其他人可能已经将代码推到了同一分支。

git pull origin branch_name

这是我们必须强制将提交推到远程的情况之一。