Skip to main content

Command Palette

Search for a command to run...

Setup Laravel Pint in Git Pre-Commit Hook without using any dependencies

Without even needing to depend upon Husky and npm to setup

Updated
2 min read
Setup Laravel Pint in Git Pre-Commit Hook without using any dependencies
K

Former Full-stack Engineer at Nexlabs

Undergrad SE @ CAMT - Chiang Mai University

Logo Laravel Pint

Laravel Pint is an opinionated automated code styling fixer. It is based on PHP-CS Fixer, but you don't need to worry about anything about what is going underneath.

You just need to install Pint, run ./vendor/bin/pint, and boom; your project is now fixed with Laravel's code styling. It's that simple.

But what is not simple is that we need to ensure every developer in the project team uses Pint. However, it is not an easy job to enforce that every developer runs it manually each time they commit a change.

So what about using a node package like Husky to add Pint to the pre-commit?

It might work, but it needs to run npm install on each developer's machine to setup the hook.

So what if the project doesn't use npm or even javascript at all?

That's when we have to think about alternatives. In this tutorial, I will use the bare-bone pre-commit hook to setup Pint.

Setup

Install Laravel Pint

Laravel Pint now comes out of the box with all new Laravel Applications.

If you are working on an old project, run the following:

composer require laravel/pint --dev
  1. Create a folder called .hooks in the project root

  2. Then create a file called pre-commit and give appropriate execute permission by running the below command.

     cd .hooks/
     sudo chmod 754 pre-commit
    
  3. Add the following bash script to the pre-commit file. This script will run whenever you and anyone try to commit this project with git.

     #!/bin/sh
    
     # Run Laravel Pint
     # This script will run Laravel Pint on newly staged PHP Files. 
    
     files=$(git diff --cached --name-only --diff-filter=AMCR | grep "\.php$")
     if echo "$files" | grep --quiet "\.php$"; then
         echo "Running Laravel Pint..."
         ./vendor/bin/pint $files && git add $files
     fi
    
  4. Then, we will register with the composer's post-autoload-dump hook to register this git hook when someone setup the project. Add this line to the composer.json file's scripts.post-autoload-dump of your project.

     git config core.hooksPath .hooks
    

    It should look something like this in your composer.json file:

  5. Just run the composer install command again, and the pre-commit hook will be registered. This should also automatically install this git hook in your teammates' machines whenever they run composer install or anything that triggers the post-autoload-dump hook such as composer dump-autoload command.

  6. Now, you have successfully configured pre-commit hook when you see Laravel Pint running when committing something. :)

My one bit

Part 1 of 1