Formatting in pre-commit hook

Posted on by  
Christophe Hesters

Many projects force their code to be formatted. We use spotless for this purpose. It can check for propper formatting, and also format the code for you. Then build pipeline checks if the code is properly formatted. Failing pipelines due to formatting errors are annoying and cost a lot of time and money. This blog proposes a solution.

Git has some hooks that you can install. Hooks are scripts that are run at specific events such as pre-commit, post-commit, pre-push, prepare-commit-msg, pre-rebase, etc. I created a script that formats the code in the pre-commit hook. It does:

  1. This scripts tracks any of the java or kotlin files in the staging area.

  2. Formats the code using spotless if there are any java/kotlin files.

  3. It adds the files from step 1 again to the staging area, to pick up the re-formatted changes.

The commit now contains formatted code. This saves a lot of time, instead of finding out that the build failed 5 minutes later.

The pre-commit hook looks like:

If you use another formatter, you can easily update the script.

You can install it by running the following command in your repository root:

Continue reading →