Pre-commit hooks: what are those? {Outreachy}

Pre-commit hooks: what are those? {Outreachy}

Git is an amazing version control system for many reasons. The main one - you can customize its behavior to your liking, so that your workflow can be smoother and simpler. Wouldn't it be nice if every time your code went sideways with commit recommendations, someone would kindly note that and recommend to look at [this line] before pushing your changes into the history?

If [git event]: execute script

We're talking about automation and optimization of the work. That's where Git hooks come in - the scripts that are triggered if a particular event happens in a Git repository. You can "hook" certain actions to the key points in the development life cycle. For example, imagine you're writing a commit message. Using hooks you can customize its default contents, as shown in this article. So that every time you open the message editor, your script writes a handy guide right there in the commented lines:

Tip 1: Great commit summaries should be 50 characters or less. Use description for the extra information.

pre-commit

The thing to keep in mind is that the hooks are local for the particular repository, in other words, git clone doesn't copy them to the new repository. .git/hooks directory isn't even under version control. For big projects though you want to organize them all neatly and share with the team, so that code reviewers can skip suggesting adding an empty line at the end of the file. And in general with a "project's hook set" it's easier for contributors to follow the commit policy your project encourages. One solution is to store the hooks in another directory that is version-controlled and update it. The other one is to use packages.

For my project with Sktime I use pre-commit hooks framework . It helps to highlight simple issues before committing the code, such as: missing semicolons, trailing whitespace, and debug statements. These checks save a lot of time, because all these little "mistakes" are easy to miss, yet they are important: if left overlooked, they make code less readable.

photo_2021-06-20_23-04-00.jpg

After installation pre-commit hooks are run automatically and if at least one fails, then the changes won't be committed. You can see the error messages to fix the files. Some of the mistakes, like trailing whitespaces, are even fixed for you (as you can see in the picture, - files were modified by this hook). Of course after the file is changed, you need to stage and commit it again. Like other hooks, you can modify or disable pre-commit scripts.

Hooks are a very powerful feature and I'm looking forward to exploring them and optimizing my Git workflow. Have you used them in your project?

To learn more you can visit:

git-scm.com/book/en/v2/Customizing-Git-Git-..

pre-commit.com/#intro

atlassian.com/git/tutorials/git-hooks

Cheers

Photo by Bradyn Trollip on Unsplash