Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I force push after changing a commit message?

Tags:

git

git-push

push

I read this about how to amend commit messages. The accepted answer says:

If you've already pushed your commit up to your remote branch, then you'll need to force push the commit with git push <remote> <branch> --force.

It's my understanding (also from the accepted answer) that git push --force will overwrite all data on the remote branch with the local one.

Why is force-pushing after changing a commit message necessary? What happens if I amend a commit message and try to push without -f or --force?

like image 557
MD XF Avatar asked Dec 06 '16 19:12

MD XF


People also ask

Can I change commit message before push?

Commit has not been pushed online If the commit only exists in your local repository and has not been pushed to GitHub.com, you can amend the commit message with the git commit --amend command. On the command line, navigate to the repository that contains the commit you want to amend.

Should I always push after commit?

Typically pushing and pulling a few times a day is sufficient. Like @earlonrails said, more frequent pushes means less likelihood of conflicting changes but typically it isn't that big a deal. Think of it this way, by committing to your local repository you are basically saying "I trust this code. It is complete.

Can you commit without push?

So commiting changes without pushing allow the save-load behaviour done locally during development. Once you are happy with your work, you then commit AND push.


1 Answers

By amending commits, you are changing their SHA1, which means the local and remote history are no longer the same.

If you want to replace the remote history by your (amended) local one, you will need to force push.
If you don't, Git will refuse the push, and ask you to pull (which in this case is not helpful, as you would merge with identical content but different commit messages)

Force pushing can be dangerous as it forces other collaborators to reset their own local history to the new (forced pushed) one.

As commented, --force-with-lease is safer (if the remote branch you are changing was itself changed since your last pull, meaning other were actively using it and pushing it back, then the forced push is denied).
Combine that with a sensible pull policy (where you always rebase what you have not yet pushed), and force pushing becomes less needed.

like image 173
VonC Avatar answered Oct 08 '22 22:10

VonC