Git hooks are scripts that will run when a certain event occurs in git like git push, git pull, git commit, etc…
We can find git hooks at .git/hooks in a particular git repository.
Pre-commit is a git hook, that triggers custom scripts or commands during the execution of a git commit.
In this article, we will format PHP code using prettier at the time of committing code to git.
We will use:
npm install --save-dev prettier @prettier/plugin-php husky
npx husky install
npx husky add .husky/pre-commit ""
This will create a pre-commit file in the .husky directory in the project’s root.
Then add the following script to the .husky/pre-commit at the end of the file.
prettier — write $(git diff — name-only — diff-filter=ACMR — cached ) && git add .
What will the above script do?
A
), Copied (C
), Modified (M
), Renamed (R
).During formatting code, we do not need to format some files like, node_modules files, .env, .sh, .json, or .yml files.
We need to add those files in .prettierignore. Prettier will ignore those files at the time of formatting.
Here is an example of .prettierignore. You can add any file you want to.
/node_modules
*.json
*.sh
.env.*
*.yml
That’s it. Let’s format the code.
Nope!! let’s commit the code.
git add . && git commit -m "Added pre-commit hook"
In the output, you will see that prettier had formatted changed(staged) files and committed changes to git.
You do not need to use any extra plugins for formatting PHP code. Also now onwards, you do not have to format files whenever you push changes to git and can spend your time on other tasks.