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

其他回答

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

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

如果您知道没有人撤回您未修改的承诺,请使用gitpush的--forcewithlease选项。

在TortoiseGit中,您可以在“推送…”选项“强制:可能丢弃”和检查“已知更改”下执行相同的操作。

强制(可能放弃已知的更改)允许远程存储库接受更安全的非快进推送。这可能会导致远程存储库丢失提交;小心使用。这可以防止丢失来自远程用户的未知更改。它检查服务器分支是否指向与远程跟踪分支相同的提交(已知更改)。如果是,将执行强制推压。否则将被拒绝。由于git没有远程跟踪标记,因此无法使用此选项覆盖标记。

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

简言之:不要将修改后的承诺推至公开回购。

长篇大论:一些Git命令,比如gitcommit--modify和gitrebase,实际上重写了历史图。只要你还没有发布你的更改,这是很好的,但一旦你发布了,你就真的不应该玩弄历史,因为如果有人已经得到了你的更改的话,那么当他们再次尝试时,可能会失败。您不应该修改提交,而应该使用更改进行新的提交。

但是,如果您真的、真的想推动修改的提交,可以这样做:

$ git push origin +master:master

前导+符号将迫使推送发生,即使它不会导致“快进”提交。(当您推送的更改是公共回购中已存在更改的直接后代时,会发生快速提交。)