gitgit-commitgit-amend

How to amend last commit without losing commit tag


I have a commit with a tag, but when I amend any changes to it, it loses the tag. I am not new to git, but still can't understand how it works

I've tried:

git commit --amend --no-edit
git commit --amend --no-post-rewrite
git commit --reuse-message=HEAD -C HEAD

Solution

  • Commits cannot be rewritten. You can only make new commits and replace the old. See my answer to What is a Git commit ID? to understand why.

    If you have this...

    A - B - C [HEAD][tag]
    

    After you commit amend, you have this.

    A - B - C [tag]
         \
          C1 [HEAD]
    

    A brand new commit with its own commit ID. Git does not move the tag for you.

    You could write a little script which checks if the current commit has any tags (git tag --points-at), amends, and then moves the tag to the new commit for you (git tag -f <tag>). You can then call this git-commit-amend (so long as it's git-something), place it in your PATH, and it will be available as git commit-amend.