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

其他回答

如果您使用的是Visual Studio代码,可以尝试此扩展以使其更容易。

https://marketplace.visualstudio.com/items?itemName=cimdalli.git-提交修改推力

正如您从其名称中可以理解的,它连续执行命令

gitcommit—修改git push—力

您可以通过以下操作以简单、安全的方式进行操作:

使用gitcommit修改您的上一次提交--修改和需要添加的任何选项git pull将本地回购与远程回购同步。拉动后,您将在本地和远程之间发生冲突。您只需接受当前更改并再次提交即可解决这些问题。数字推送

现在,本地和远程回购已更新,无需更改回购历史记录。

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

git update-ref HEAD HEAD^

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

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

在这种情况下,你应该——用力。

基于:

如果是单个项目,我会这样做:git推送原点<分支名称>-f

如果您正在与您的团队合作,或其他同行正在审查和使用您的代码,则不建议使用强制标志。主要是因为你总是想要一个干净的git历史。

我会怎么做?

如果有更多的人在同一个分支机构工作,或者其他人在审查你的代码,我会gitcommit--modify,然后gitpush-f。。。并让人们知道他们需要获取pull-rebase,以便能够看到您的更改。如果在审查PR或MR时发生类似的情况,请添加新的干净提交,并在结尾处清除历史。

我也有同样的问题。

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

作为一个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次),但它节省了一天的工作。