When you first started with git, you quickly got up to speed with committing, pushing, pulling, merging, and the like. But then you noticed a gaping hole in your knowledge - how do you find stuff in Git? Can you revert to a version of a file as it stood three weeks ago, or find out when a bug was introduced? Who was the last person to edit this file?
They always tell you that the great thing about Git is that you [almost] never lose any history. So how do you access and utilize that history?
What are Git hooks? Can you do anything useful with them? Also, since Git hooks come from Linux, is there anything special you need to do to get them working on Windows?
What are Git hooks?
Git hooks allow you to run custom scripts whenever certain important events occur in the Git life-cycle, such as committing, merging, and pushing. Git ships with a number of sample hook scripts in the
repo\.git\hooks directory, but they are disabled by default. For instance, if you open that folder you’ll find a file called
pre-commit.sample. To enable it, just rename it to
pre-commit by removing the
.sample extension and make the script executable (
chmod +x pre-commit if you’re on Linux, or just check your NTFS execute rights if you’re on Windows). When you attempt to commit using
git commit, the script is found and executed. If your pre-commit script exits with a 0 (zero), you commit successfully, otherwise the commit fails.
If you take a look at the default sample pre-commit script, it does a few helpful things by default, like disallowing non-ascii filenames since they cause issues on some platforms, and checking for whitespace errors. This means that if you enable this script and have “whitespace errors”, like lines that end in spaces or tabs, you’ll fail to commit and have to remove the whitespace before you can commit.
What cool stuff can I do with Git hooks?
Since you’re working with scripts, you can do pretty much anything with Git hooks. That being said, just because you can do something… Yeah, you know. Git hooks can make the behavior of common Git tasks like committing, pushing and pulling nonstandard, which can annoy people, especially if they’re just trying to get used to the glories of Git. But here are a few examples of what you might accomplish with Git hooks.