当我使用了一点源代码后,我做了我通常的事情提交,然后推送到远程存储库。但后来我注意到我忘记在源代码中组织导入。因此,我执行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/'

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


当前回答

我也有同样的问题。

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

作为一个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 commit --amend -m "New message"

git push --force repository-name branch-name

注意:除非您确信在最近一次提交后没有其他人克隆过您的存储库,否则不建议使用--force。

更安全的选择是使用:

git push --force-with-lease repository-name branch-name

与-force不同,-force将销毁其他人推送到分支的任何更改,如果存储库有上游更改,-forcewithlease将中止。

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

git push -f origin branch_name

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

git pull origin branch_name

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

快速咆哮:没有人在这里发布简单的答案,这表明了Git CLI显示出的绝望的用户敌意。

无论如何,如果你没有试图强行推动,那么“显而易见”的方法就是先拉动。这将拉动您修改的更改(因此不再具有),以便您再次拥有它。

一旦解决了任何冲突,就可以再次推送。

So:

git pull

如果在pull中出现错误,可能是本地存储库配置有问题(我在.git/config分支部分中有一个错误的ref)。

之后

git push

也许你会得到一个额外的承诺,主题讲述一个“琐碎的合并”。

我一直在做Git让我做的事。所以:

无法推送,因为修改了提交。我按照建议拉了一下。合并失败。所以我手动修复。创建新提交(标记为“merge”)并将其推送。它似乎起作用了!

注:修改后的承诺是最新的承诺。