Why does git diff produce different results based on commit changes?

I am new to the world of version control and have just started using git. I have the following output when I run the commandgit log

commit 3b33318e20a64f4395bba416fe60f50f9e0002d1
Author: pm
Date:   Thu Jan 24 08:42:24 2013 +1300

    added fourth line to test1

commit 37f2ce409cdc971958add1fcf6585064f5c0d61d
Author: pm
Date:   Thu Jan 24 08:41:24 2013 +1300

    first commit

      

I understand that it git log

shows the last commit followed by the previous commit. Now if I run the command git diff HEAD HEAD~

, which I understand is "Show me the difference between the last commit and the previous commit", I get the following output:

diff --git a/test1 b/test1
index c6f02c2..e41a5e4 100644
--- a/test1
+++ b/test1
@@ -1,4 +1,3 @@
 This is a test document
 This is the second line in the document
 And the third
-Added a fourth line

      

It shows a minus symbol when I added a new line, when I changed the file test1, however, if I run the command like git diff HEAD~ HEAD

, which I understand is "Show me the difference between the second last commit and the last commit", it shows me the following output:

diff --git a/test1 b/test1
index e41a5e4..c6f02c2 100644
--- a/test1
+++ b/test1
@@ -1,3 +1,4 @@
 This is a test document
 This is the second line in the document
 And the third
+Added a fourth line

      

This shows that I have added a fourth line with a plus sign.

Doesn't matter how the files are compared? I would have thought that the way to compare files would be "compare last to previous", i.e.git diff HEAD HEAD~

+3


source to share


2 answers


git diff A B

lists the changes required to go from A to B. If you replace the arguments, you get the reverse changes, as in your example.

You could argue that Git can know that A happened before B, and then produce the same output for git diff A B

and git diff B A

. However, IMHO this is not a good idea for two reasons:



  • Mapping changes to get left to right is more consistent. This can also come in handy, especially if you are scripting on top of it.

  • Sometimes it is not clear which commit is in front of the other, for example:

      C
     / \
    A   B
    
          

    git diff A B

    : A to B or B to A?

+5


source


Order really matters when passing links to git diff. To see the difference in the past for the future, you need:

git diff HEAD~ HEAD

      



Git doesn't make any guesswork for you.

0


source







All Articles