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

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

我会怎么做?

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

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

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

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

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

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

gitcommit—修改git push—力

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

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