How to format code with Laravel Pint automatically on Git Commit
1 min read

How to format code with Laravel Pint automatically on Git Commit

Automatic code format with Laravel Pint

I have been using Laravel Pint for a while now. Initially, I ran pint to format my code manually and across all files. Recently, I have been making use of Git pre-commit hooks to apply code format changes to only files that have been modified. I use this both for Arbeitnow with Laravel and the blog with Statamic.

To do this, you will need to install Laravel pint:

composer require laravel/pint --dev

Then, go to your root directory, find .git/hooks and create a copy of the pre-commit.sample hook file. I named mine as pre-commit and made it executable using chmod +x pre-commit

Open that pre-commit file on your editor and paste this:

#!/bin/sh
files=$(git diff --cached --name-only --diff-filter=ACM -- '*.php');
vendor/bin/pint $files
Laravel Pint formatting the files
Laravel Pint formatting the files

This fetches the list of files that have been Added, Copied or Modified (ACM in diff-filter) and passes that as the argument for pint to format only those files.

If you want to include files that were renamed, you can use the additional flag R in diff-filter. Additionally, if you want to disable the output of pint, you can pass in the flag -q for quiet output like this:

vendor/bin/pint $files -q