HomeThe Classics

Why I Used diff-index Before the Commit

Published:

This is also a video [2:39]

When I had the video making some bad code the other day, I, copied some old code and I couldn’t explain it. Well now I can.

The offending code:

git diff-index HEAD --quiet || (git commit -m "Added new data")

What’s happening is that I’m trying to prevent git from making a commit with nothing to commit because it would result in an error, halting the CI run. Running diff-index checks if there’s anything to commit and if there is, it would make the commit.

Whenever a command is run, it returns an error code on completion. Any number above 0 is considered an error. diff-index finding changed files would return a 1 error code. The code basically asks to return either result and evaluates it lazily as shown by the || operator. That means that if diff-index has nothing, it will move on to making the commit. Were it a | instead, it would run both commands.

Note that you don’t have to use diff-index and can use diff instead. The --quiet prevents the scroll buffer which will hand the CI build since you can’t do anything, but it still returns the appropriate error code!

I hope I’ve explained it better now.