To automatically format code using Laravel Pint during Git Commit, you can set up a pre-commit git hook in your Git repository that runs the Laravel Pint command to format your code before it is committed. This simple snippet ensures that your code is consistently formatted and adheres to the Laravel Pint coding standards, which can improve code readability and maintainability.
Also Read: Useful Github Repositories for Developers
Install Laravel Pint
composer require laravel/pint --dev
Automate Laravel Pint on Commits
Then, go to your root directory, find
.git/hooks and create a copy of the
pre-commit.sample hook file and make it executable using the following commands:
cp ./git/hooks/pre-commit.sample ./git/hooks/pre-commit
chmod +x ./git/hooks/pre-commit
pre-commit file in your editor and paste the following bash script
#!/bin/sh files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.php'); vendor/bin/pint $files
filesvariable stores the list of PHP files that have been changed and are ready to be committed.
git diffcommand is used here to retrieve a list of changed files that are staged for commit.
--cachedoption specifies that only staged changes should be considered.
--name-onlyoption is used to output only the file names, without any additional details.
--diff-filter=ACMRoption limits the output to files that are Added, Copied, Renamed or Modified.
- The '--' argument is used to separate the options from the file pattern
*.php, which specifies that only PHP files should be considered.
- Then simply, the code runs the
pintcommand on thees changed files on every Git commit.
Also Read: Laravel Responsables
In summary, this script retrieves the list of changed PHP files that are staged for commit and runs Laravel Pint on each file to automatically format it according to Laravel Pint standards before the changes are committed.
Also Read: Cool projects on Github