How to review diffs between commits

hustnzj發表於2022-09-07

Up until now, we’ve been using git log --stat to view the changes introduced by new commits. However, this doesn’t show us which lines have been changed in any given file. For this level of detail, we need the git diff command.

For the sake of brevity, only three common case will be described.

Case One

git diff <commit>..<commit> or git diff <commit> <commit>

This is to view the changes between two arbitrary <commit>.

For example, we can view the differences between the grandparent and the parent of HEAD.

gif diff HEAD~2..HEAD~1

The result as below:

diff --git a/pink.html b/pink.html
index c349233..6d0e147 100644
--- a/pink.html
+++ b/pink.html
@@ -4,10 +4,17 @@
   <title>The Pink Page</title>
   <link rel="stylesheet" href="style.css" />
   <meta charset="utf-8" />
+               <style>
+                       div {
+                               width: 300px;
+                               height: 50px;
+                       }
+               </style>
 </head>
 <body>
   <h1 style="color: #F0F">The Pink Page</h1>
   <p>Only <span style="color: #F0F">real men</span> wear pink!</p>
+  <div style="background-color: #F0F"></div>
   <p><a href="index.html">Return to home page</a></p>
 </body>
 </html>

The diff pinpoints that 7 lines had been added in pink.html.

Case Two

git diff

This form is to view our uncommitted changes.

Open up blue.html, make any kind of change, and save the file. Then, run git diff without any arguments:

git diff

We can see the changes in the blue.html:

diff --git a/blue.html b/blue.html
index 4e38c74..d46efb0 100644
--- a/blue.html
+++ b/blue.html
@@ -1,6 +1,6 @@
 <!DOCTYPE html>
 <html lang="en">
-
+d1
 <head>
   <title>The Blue Page</title>
   <link rel="stylesheet" href="style.css" />
@@ -14,4 +14,4 @@

 </body>

-</html>
\ No newline at end of file
+</html>

Case Three

git diff --cached

We can use the --cached flag to generate a diff between the staged snapshot and the most recent commit:

git add blue.html
git diff --cached

The diffs as below:

diff --git a/blue.html b/blue.html
index 4e38c74..d46efb0 100644
--- a/blue.html
+++ b/blue.html
@@ -1,6 +1,6 @@
 <!DOCTYPE html>
 <html lang="en">
-
+d1
 <head>
   <title>The Blue Page</title>
   <link rel="stylesheet" href="style.css" />
@@ -14,4 +14,4 @@

 </body>

-</html>
\ No newline at end of file
+</html>

We can also see the d1 characters have been added into blue.html.

Conclusions

These are the three main configurations of the git diff command:

  1. git diff <commit>..<commit> or git diff <commit> <commit>
  2. git diff
  3. git diff --cached

References

Ry’s Git Tutorial

本作品採用《CC 協議》,轉載必須註明作者和本文連結
日拱一卒

相關文章