当我使用了一点源代码后,我做了我通常的事情提交,然后推送到远程存储库。但后来我注意到我忘记在源代码中组织导入。因此,我执行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 reset --soft HEAD^
git stash
git push -f origin master
git stash pop
git commit -a
git push origin master

它执行以下操作:

将分支头重置为父提交。停止这最后的承诺。强制推至远程。远程现在没有最后一次提交。打开你的储藏室。干净地提交。按下遥控器。

如果将此应用于其他分支或远程,请记住更改原点和主控点。

其他回答

我也有同样的问题。

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

作为一个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让我做的事。所以:

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

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

我必须通过从远程回购中提取来解决这个问题,并处理出现的合并冲突,提交然后推送。但我觉得还有更好的方法。

为了避免强制推送,在远程裸存储库中,使用以下命令删除最后一次提交(要修改的提交):

git update-ref HEAD HEAD^

然后在没有冲突的情况下推送修改后的提交。

注意:这假设在此期间没有人做出错误的承诺。如果有,他们将不得不同样地倒带并再次拉动,可能会合并自己的更改。

如果要更改的消息是针对存储库的最新提交,则将执行以下命令:

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将中止。