amphibient
amphibient

Reputation: 31278

Amending commit that's been pushed to remote already

Steps to reproduce:

  1. Make a change locally and commit it. A new SHA1 hash is assigned to the commit.
  2. Push to the remote. At this time, the local and remote are fully in sync and the HEAD SHA1 is the same in both places.
  3. Now make a new change that functionally belongs in the same change as 1. above and git commit --amend it rather than make it its own commit. This changes the local SHA1.

At this point, git status reports that that the local and the remote are both ahead of each other by one commit because it can't tell that the latest local commit built on top of the one that's HEAD on the remote. For delta purposes, the HEADs on the local and remote are two distinct commits (as opposed to knowing that the local was built on top of what is on the remote) and the common ancestor is HEAD~1. This causes a great deal of hassle as it (AFAIK) requires merging.

Is there a way to make git keep track of different commits on the same change (which I think should be easy to record to know the history when you do git commit --amend) so that it is possible to push just the incremental change to the remote without needing to merge first?

Upvotes: 0

Views: 504

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522244

From the official Git documentation for git commit --amend:

You need to be careful with this technique because amending changes the SHA-1 of the commit. It’s like a very small rebase – don’t amend your last commit if you’ve already pushed it.

The makers of Git are warning us to avoid amending commits once they have been pushed, so we would be wise to follow suit.

As the previous answer already mentioned, if you insist on amending your commit, then you are compelled to use git push --force to update the remote. But if you do so, you run the risk of causing problems for anyone who has already pulled the remote.

As an alternative to amending a commit which has been pushed, you can simply make a new separate commit for the change. It may not be as sexy as doing an amend, but it will keep things much clearer.

Upvotes: 0

Marcus Müller
Marcus Müller

Reputation: 36442

if you mess with the local commit history (which is exactly what --amend does), your local and remote history will diverge and be incompatible. The only sensible way to fix this is git push --force.

It's generally considered to be good practice to avoid changing commits, especially after pushing them. If you want to have a proper tree of differences that you can incrementally push, you'll have to use branches and commit in these, pushing them individually, and merging them only when you need a merged version. Amending a commit effectively deletes the old and inserts a new one, so this is not something traceable; it's very un-git-like.

Upvotes: 2

Related Questions