How to Read a git diff
March 11, 2016
When I learned how to read a git diff/patch, I felt like my understanding of the internal mechanics of git improved. Here's a little tid bit I'm going to use as an example to illustrate some of the different components:
01. diff --git a/bootstrap.sh b/bootstrap.sh02. index e98ae1c..9073c4d 10064403. --- a/bootstrap.sh04. +++ b/bootstrap.sh05. @@ -1,6 +1,6 @@06. #!/usr/bin/env bash07.08. -apt-get update09. +sudo apt-get update10.11. wget -qO- https://raw.githubusercontent.com/...12.13. @@ -9,3 +9,4 @@ echo "source /home/vagrant/.nvm/...14. source /home/vagrant/.profile15.16. nvm install node17. +nvm alias default node
This is from a git diff associated with a commit on my lets-learn-vagrant repository on GitHub.
Lines 1 through 4 have some information about the diff, including file names of the original files and modified/new files.
On line 5,
@@ indicates the start of a new hunk, which lasts from lines 5 to 12.
- Ln 5
-1,6means: "the original file, starting on line 1, had 6 lines before this diff was applied."
- Ln 5
+1,6means: "the modified/new file, starting on line 1, has 6 lines after this diff is applied."
- Ln 6
#1/usr/bin/env bashis part of the original file and remains unchanged because the beginning of the line starts with a space.
- Ln 7 is also whitespace that remains unchanged.
- Ln 8
apt-get updateis removed as shown by its leading
- Ln 9
sudo apt-get updateis added, per the
+at the beginning of the line.
Because this hunk has 1 line removal and 1 line addition, the total number of lines before and after the patch is applied remains unchanged, as per line 5's
@@ -1,6 +1,6 @@.
Now let's take a look at the second hunk in this git diff/patch on lines 13 to 17.
- Ln 13
-9,3 +9,4indicates that the following information shows the original file, starting on line 9, had 3 lines of code, and the modified/new file, starting on line 9, has 4 lines of code.
- Lns 14–16 all lead with a whitespace (aka there are no changes)
- Ln 17
nvm alias default nodehas a
+, so it's a new addition!
A random observation I made: Each hunk is buffered at the beginning and end (for context) by 3 unchanged lines for
git diff and 7 unchanged lines for
git add --edit for my current git configuration.