Improving Git Diffs
Word-wise diffs with colors and syntax highlighting.
Default git
The default git diff
is rather lackluster since it only displays which lines changed, not how they changed:
This is especially bad when the lines are long, or there are a lot of very similar lines:
One solution is looking at diffs using GitHub or GitLab, both of which highlight the specific words that changed. This is a lot nicer, but it obviously doesn’t run in the terminal, requires you to be online, and only works with repos that are hosted on the website (and up to date).
Thankfully, there is a way to get the same behavior without any of the negatives.
Diff Highlighters
Here is the “long lines” example from before, word-colored by a command line tool, compared to the default diff:
This output was produced by diffr
, which is most likely available from your operating system’s package manager of choice.
There are other, more powerful options below, but diffr
gives the cleanest output by default.
To make Git use diffr
, edit your .gitconfig
to include the following:
# .gitconfig
[pager]
# Use `diffr` (make sure it is installed).
log = diffr | less
show = diffr | less
diff = diffr | less
Syntax Highlighting
One thing is still missing when compared to GitHub — Syntax highlighting.
Using delta
gives you that and much more. The defaults do not look very good, which is why delta
is not the first option I suggested, but it is incredibly customizable.
Here is what it looks like using default settings:
Here is a diff using my custom settings:
Delta also supports side-by-side diffs:
To make Git use delta
, edit your .gitconfig
to include the following:
# .gitconfig
[pager]
# Use `delta`.
log = delta
show = delta
diff = delta
Other Alternatives
For the sake of being thorough, here are some other diff highlighters. These rely on a less accurate algorithm for generating the highlights, so they are generally not recommended.
Git is actually bundled a tool — diff-highlight
(except on Mac, which thus ships an incomplete Git installation. Sighhh, Apple🤦) (brew install git
solves this).
You can usually find and add it to $PATH
at /usr/local/share/git/contrib/diff-highlight/
.
Then, edit your .gitconfig:
# .gitconfig
[pager]
# Use `diff-highlight` (make sure it is in `$PATH`).
log = diff-highlight | less
show = diff-highlight | less
diff = diff-highlight | less
Finally, you can check out diff-so-fancy
(which uses diff-highlight
under the hood):
Final Words
Hope this was useful.
Please feel free to reach out on Twitter for any reason.