gitpushcommit-messagegit-amend

Amending a pushed commit message


I just made pushed a commit, then realized I needed to change the commit message.

So on my local repo I did:

git commit --amend -m "New commit message"

But when I then tried to push this, I got loads of error messages saying

Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull') and try again

Was this the wrong way to amend my message? In the end I ended up having to reset all my repos and then do the commits again with a fresh message.

So my question is, what is the proper way to amend the commit message of something that has already been pushed?


Solution

  • Short answer: there is no proper way.

    What git commit --amend does is to "replace" the previous commit with a similar, but altered, commit. You haven't really altered the original commit. It is still there, but nothing references it anymore and it will eventually be garbage collected unless something starts referencing it.

    This is transparent when done locally. But when you have pushed the commit it is essentially too late. You have already shared the commit with others that may have pulled it and based work on that commit. You cannot replace that commit with another commit.

    Lets say you made a commit A (after a commit B):

    B - A    <- master
    

    Then you change your mind and amend A, that will actually create a new commit A'. The current branch will point to this new commit. The original commit A is still there, but no branch is pointing to it

    B - A
      \ 
        A'  <- master
      
    

    If you first pushed A

    local                            remote
    B - A   <-master                 B - A    <- origin/master
    

    and then amend, you won't be allowed to make a normal push, since that push would not be a fast forward merge

    local                            remote
    B - A                            B - A    <- origin/master
      \ 
        A'  <- master
    

    Excacerbating the problem: others may have already used your commit

    local                            remote
    B - A                            B - A - C   <- origin/master
      \ 
        A'  <- master
    

    You could do your amend and then do a force push git push -f. But that will cause problems for other developers who have based their work on the original commit. It is the same problem as with rebasing (a commit --amend is sort of like a mini-rebase). See "The Perils of Rebasing" section of the Git Pro book for further explanation.

    Bad state on remote after force push:
    
    local                            remote
    B - A                            B - A - C
      \                                \
        A'  <- master                    A'   <- origin/master