6

I open for some correction of my understanding of this, but I am not sure why this happens.

When using git, I understand that if I make a change to a file and then commit it I get a new hash because the file has changed.

My understanding of git commit --amend is that I can make changes to the last commit.

Now I can understand that if I change the commit message, the hash will change.

But when I do not make any changes and just save and exit out of the editor (I may have changed my mind on needing a change) why does the hash change? All my files and everything is the same, but I have saved it. When I of a git log the time of the commit hasn't changed, it just appears twice in the log with the same time, the same message, same files except a different commit hash.

Why does it change if no alterations have been done??

jwknz
  • 6,598
  • 16
  • 72
  • 115

1 Answers1

7

Git hashes are calculated using a number of items, including the author name/date, commit name/date commit message, tree, and parent SHA, among others. When you amend a commit, the commit name and date are updated. (You generally don't see the commit name and date unless you pass additional formatting options to git log.) Because that has been updated, the commit hash will change when a commit is amended.

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • mipadi is totally right. You just created a new commit itself and added the previous commit's changes to it, supplanting the previous commit. – gran_profaci Sep 08 '15 at 22:56
  • Ah that makes sense, thank you for the update. So just to clarify is there anyway that no changes are made and the hash isn't altered?? – jwknz Sep 08 '15 at 23:01
  • @JeffKranenburg: There is, in fact. If you keep the committer author and date the same when you amend a commit, and make no other relevant changes, the hash will stay the same. You can override the committer author and date using the `GIT_COMMITTER_NAME` and `GIT_COMMITTER_DATE` environment variables. – mipadi Sep 08 '15 at 23:16
  • @JeffKranenburg: However, if you simply want to abort a `git commit --amend`, it's probably easier to just delete the entire commit message when Git prompts you to edit it. Git won't accept an empty message and will abort the commit instead. – mipadi Sep 08 '15 at 23:17
  • Awesome I will have a play around with that. – jwknz Sep 08 '15 at 23:51
  • Just did some more playing around and if I do not make any changes to anything at all, including the date and author, but safe the file the commit hash changes. I am not sure why, but that is how it is on my system. – jwknz Sep 09 '15 at 00:19
  • @JeffKranenburg: Hm, I don't know. I tested it and it worked. Here's a rough log of what I did: https://gist.github.com/mdippery/2d9b4245c12fa615e935 – mipadi Sep 09 '15 at 00:52