A handy pre-commit hook which will run Google's java code style formatter for you on your code!
Here's how to set up this pre-commit hook:
-
Install
pre-commit:pip install pre-commit==4.2.0
-
Create a file named
.pre-commit-config.yamlat the top of your repository with the following content:repos: - repo: https://github.com/nexla/google-style-precommit-hook rev: 0f5e77a35ebf7b5a1ace7d15a7d1c21b14d6da81 hooks: - id: google-style-java files: \.java$
-
Add
.cache/to your project's.gitignorefile. -
Install the pre-commit hooks in your repository:
pre-commit install
Now, every time you attempt to commit changes, the google-style-java hook will automatically format your Java files according to the Google Java Style Guide. If any changes are made by the formatter, the commit will fail. This ensures that developers review the formatted code and manually stage the changes using git add before attempting to commit again.
For IntelliJ users who want their IDE to format code consistently with the pre-commit hook, follow these steps to import the Google Java Style scheme:
- Download Google Java Format plugin version 1.24.0 from here.
- Navigate to the IntelliJ settings:
IntelliJ IDEA->Settings->Plugins. - Click on
Gear Icon, SelectInstall PLugin From Diskand Select the downloaded Plugin in the previous step. - Add the below JRE config under
Help→Edit Custom VM Optionsfrom Intellij Top Menu--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED - Restart Intellij.
- Under
IntelliJ IDEA->Settings->google-java-style-Settingsverifygoogle-java-formatisEnabledwithDefault Google Java Style. - It is also recommended to do
Tools->Actions on Save& then select bothReformat CodeandOptimize Imports
This will configure IntelliJ to use the same Google Java Style Guide for formatting your code.
Each repository must place the java-code-format-check.yml[./java-code-format-check.yml] file under its .github/workflows directory to enable a GitHub Actions check that prevents malformed Java files from being merged via pull requests.
NOTE- The upstream repo is not maintained and is not accepting PR to move to the latest versions of Google Java format. So a fork is being done.