Automatically format your Apex on every commit
If you aren’t already using Prettier for Apex, I highly recommend you try it out. Even though it doesn’t always format exactly as I would, the consistency and convenience of auto-formatting makes it more than worth it.

It’s easy enough to set up vscode to format on save, but we can take this a step further by running prettier
on the pre-commit hook. This will ensure that code is always formatted before being committed.
And since we already have a package.json
in our project, setup is extremely simple:
Steps
npm i -D husky pretty-quick
- In
package.json
add the following: - Add
“apexInsertFinalNewline”: false,
to your.prettierrc
config. (explanation)
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
}
That’s it, We’re done!
husky
is a tool that makes git hooks dead simple (as you can see) and pretty-quick
allows you to run prettier
on only staged files.
One more thing…
In order to keep a bunch of formatting changes out of your pull requests, I recommend running prettier
one time for everything.
You can easily do so by running: npx prettier — write 'src/**/*.{trigger,cls}'
.
Keep in mind, this will likely change a bunch of lines in every single apex file. It’s probably best to wait until you don’t have any divergent branches, otherwise you might have a tough time dealing with merge conflicts.
Once you’ve done this, you will very rarely see a “formatting only” change in git again!
-Happy coding
`