20

This is what happens:

  1. After a recent commit to remote master, I make a small trivial change to my local repo
  2. I add git commit --amend and leave the same commit message as HEAD
  3. I try to push the repo to master with git push

And now I get

On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
nothing to commit, working directory clean

I want to understand:

  1. Why this exactly happens?
  2. What can I do to prevent this?
  3. How do I reconcile master with local after a git amend?
Amit Erandole
  • 11,995
  • 23
  • 65
  • 103

2 Answers2

21

You changed an existing pushed commit, creating your own version (since its content has changed)

 --x---Y (master: that is the X amended)
    \
     --X (origin/master)

That is why you have 1 and 1 different commit each between master and origin/master

What can I do to prevent this?

Don't "amend" an existing pushed commit (only local not-yet-pushed one)

How do I reconcile master with local after a git amend?

Simply rebase on top of origin/master, then push

git rebase origin/master

 --x--X---Y' (master)
      |
(origin/master)

git push

 --x--X---Y' (master, origin/master)

However, jwinn notes in the comments that it can mean your amend goes away ("warning: skipped previously applied commit"), and would not be the way to get your local amend (on an already pushed commit) to origin/master.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Important to note that answer #3 can mean that you amend goes away ("warning: skipped previously applied commit"), and would not be the way to get your local amend (on an already pushed commit) to origin/master. – jwinn Jun 30 '22 at 14:30
  • @jwinn Good point. I have included your comment in the answer for more visibility – VonC Jun 30 '22 at 19:56
4

If you are the only one working on the project after your amend you could have run

git push -f origin master

If you are not the only one working on the project be carefull of what you do because it's rewriting history.

Here is a great article about amend :
https://medium.com/@igor_marques/git-basics-adding-more-changes-to-your-last-commit-1629344cb9a8