gitgit-amend

git amend: Commit not amended


I see a bit strange behavior with Git.

So I have a feature branch locally, say F1, and I add a commit, C1, to it. I push it to repo, get reviews and finally merge to master. So master has my commit C1 on top.

Then I realized that some changes in C1 are not needed. So I created another feature branch, say F2, from latest in master. Fortunately commit C1 is still at top. So I amended C1 itself, and changed the commit message with

'git commit --amend -m "new message"

pushed the branch, got it reviewed, got it merged to master.

I was expecting C1 to be still at top in master, with amended commit message. But it's not and new commit is on the top with new commit message, with C1 at position 2.

Is this 'amend' behaviour as expected?


Solution

  • The reason this happened is because you amended your commit C1 after you had already merged it into master. Once a commit lands on a remote branch, (in this case master), the only way to remove a commit on master would be to rewrite the master branch and force push it. This is generally frowned upon for shared branches such as master, so instead you need to merge in another commit. Had you amended your commit before merging it into master, then it would have worked as you expected.

    So that answers your question, but as an important side note, I'm concerned about this statement:

    Then I realized that some changes in C1 are not needed.

    I urge you to look at the updated master with your new amended commit to make sure you actually accomplished your goal. The fact that you attempted to "remove" something instead of "adding" more things means it's likely you didn't succeed in doing it. Here's why:

    Suppose you added things A and B in commit C1, but then decided you only wanted to add A. The master branch has C1 which has both A and B. Now locally, you amended commit C1 to make C1' which only has A. When you merge that into master it might just do nothing, since master already has A, and there is nothing in C1' that says to "delete B". If you discover this is what happened, then make sure to start with the latest master and "delete B" in another, new, (third) commit.