A git diff with all changed and new unstaged files
When reviewing what I’m about to commit, I want to see a colorful diff of my changes including the new files I’m adding to the repo which have never been committed before.
Annoyingly, git only shows changes to existing files, so to review
all of my code, I have to manually open all new files. This has been an
irritation of mine for years. I finally did something about it today.
Behold, my "review" diff, a small Bash script:
#!/bin/bash
# Show changed *and new* unstaged files in diff.
TEMPFILE='/tmp/gdiff.ansi'
# Normal diff, force control seq. colors to temp file
git diff --color HEAD > $TEMPFILE
# Loop through all *new* files
for FILE in $(git ls-files --others --exclude-standard)
do
# Append to temp file.
# Compare with /dev/null or no changes to show.
git diff --color /dev/null $FILE >> $TEMPFILE
done
# -R ("raw") allows control sequences through to tty
less -R $TEMPFILE
As you can see, the "magic" parts are using git ls-files --others --exclude-standard to list new,
untracked files and diffing them with /dev/null so that the entire file is
styled as new, added lines.
Explanation of options from man git-ls-files:
-o, --others
Show other (i.e. untracked) files in the output
--exclude-standard
Add the standard Git exclusions: .git/info/exclude, .gitignore in each
directory, and the user's global exclusion file.
I already had the aliases s='git status' and d='git diff' since I use these
commands so often, so I replaced d with this script and I only wish I’d done
it sooner!