IntelliJ provides a built-in feature called "Before Commit" Actions to perform certain actions before committing changes. This feature enables developers to format their code, optimize imports, and more. However, sometimes you may want to execute a Gradle task before committing the changes. In such cases, you can use the Gradle Plugin Spotless to enforce consistent code formatting and style to ensure readability and maintainability across the codebase. But it can be tedious to manually execute the Gradle task before each commit.
Fortunately, we found a way to run the Gradle task before each commit using the "Before Commit - Run" Configuration in IntelliJ. You can select a Gradle task that will be executed automatically before each commit using this configuration, which is really useful while developing Web-Apps.
Unfortunately, only Gradle tasks are supported, and it's not possible to use this feature for other tasks, such as npm.
Here's how you can run Gradle tasks before each commit:
Open IntelliJ and click on "Run" in the top menu bar.
Select "Edit Configurations" from the drop-down menu.
Click on the "+" button in the top left corner and select "Gradle."
In the "Name" field, enter a name for your configuration (e.g., "Before Commit Task").
In the "Tasks" field, enter the Gradle task that you want to run before each commit (e.g., "spotlessApply").
Click on "OK."
Now go to "Version Control" -> "Before Commit".
Select the configuration you just created from the "Run" drop-down list.
Now every time you commit the changes, the specified Gradle task will be executed automatically:
This feature can save you a lot of time and hassle in preventing failed builds due to coding standards issues, such as inconsistencies in code formatting that violate Spotless requirements. By using the "Before Commit - Run" Configuration, you can ensure that your codebase adheres to the required coding standards.