When I’ve worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit:
> git commit --amend
Unfortunately the commit can’t be pushed back to the repository. It is rejected like this:
> 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/'
What should I do? (I can access the remote repository.)
I actually once pushed with
--forceand.gitrepository and got scolded by Linus BIG TIME. In general this will create a lot of problems for other people. A simple answer is ‘Don’t do it’.I see others gave the recipe for doing so anyway, so I won’t repeat them here. But here is a tip to recover from the situation after you have pushed out the amended commit with –force (or +master).
git reflogto find the old commit that you amended (call itold, and we’ll call the new commit you created by amendingnew).oldandnew, recording the tree ofnew, likegit checkout new && git merge -s ours old.git merge mastergit push . HEAD:masterThen people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor
newoverold. Their later merges will not see the conflicts betweenoldandnewthat resulted from your amending, so they do not have to suffer.