当我使用了一点源代码后,我做了我通常的事情提交,然后推送到远程存储库。但后来我注意到我忘记在源代码中组织导入。因此,我执行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将中止。
如果您还没有将代码推送到远程分支(GitHub/Bitbucket),可以在命令行上更改提交消息,如下所示。
git commit --amend -m "Your new message"
如果您正在处理特定分支,请执行以下操作:
git commit --amend -m "BRANCH-NAME: new message"
如果您已经用错误的消息推送了代码,那么在更改消息时需要小心。即,在您更改提交消息并再次尝试推送后,您最终会遇到问题。要使其平滑,请执行以下步骤。
请在做之前阅读整个答案
git commit --amend -m "BRANCH-NAME : your new message"
git push -f origin BRANCH-NAME # Not a best practice. Read below why?
重要提示:当您直接使用强制推送时,您可能会遇到其他开发人员正在同一分支上工作的代码问题。因此,为了避免这些冲突,您需要在强制推送之前从分支中提取代码:
git commit --amend -m "BRANCH-NAME : your new message"
git pull origin BRANCH-NAME
git push -f origin BRANCH-NAME
如果提交消息已经被推送,这是更改提交消息时的最佳做法。