Skip to main content

Gradle plugin configuration

The OpenRewrite Gradle Plugin is the fastest way to apply OpenRewrite recipes to your code as part of your Gradle build. The OpenRewrite Gradle Plugin is compatible with all versions of Gradle since 4.0.

Plugin configuration​

The Gradle plugin is distributed through the Code Genome Project rather than the Gradle Plugin Portal, so start by declaring that repository in pluginManagement. Gradle resolves plugins before it evaluates any project, which is why this belongs in settings.gradle rather than build.gradle.

settings.gradle
pluginManagement {
repositories {
maven {
url = "https://artifacts.codegenomeproject.org/maven"
credentials {
username = providers.gradleProperty("codegenomeUsername").get()
password = providers.gradleProperty("codegenomePassword").get()
}
}
// Keep the portal for any other plugins your build applies
gradlePluginPortal()
}
}

Then apply the org.openrewrite.rewrite plugin to your build. The repositories block is separate and still required: the plugin resolves the rewrite core libraries and any recipe modules at runtime from the project's repositories.

build.gradle
plugins {
id("java")
id("org.openrewrite.rewrite") version("latest.release")
}

rewrite {
// OpenRewrite Extension Configuration
}

// Ensure a repository is declared that the rewrite core libraries can be resolved from
repositories {
mavenCentral()
maven {
url = "https://artifacts.codegenomeproject.org/maven"
credentials {
username = providers.gradleProperty("codegenomeUsername").get()
password = providers.gradleProperty("codegenomePassword").get()
}
}
}
Info

The Gradle plugin, the rewrite core libraries, and recipe modules are all distributed through the Code Genome Project repository, which requires authentication. Sign in there to create a download token, then put your credentials in ~/.gradle/gradle.properties so they are not committed alongside your build:

~/.gradle/gradle.properties
codegenomeUsername=you@example.com
codegenomePassword=your-download-token

In CI, set the ORG_GRADLE_PROJECT_codegenomeUsername and ORG_GRADLE_PROJECT_codegenomePassword environment variables instead. See the quickstart guide for details.

With the plugin applied, the rewrite DSL is available for configuration.

Multi-module Gradle projects​

When applied to a multi-project build, plugin behavior differs depending on whether the plugin is applied to the root project or to a sub-project. Applied to the root project, the plugin will parse and refactor all sources from all projects. Applied to any project other than the root project, the plugin will parse and refactor only sources from that project.

The rewrite Gradle plugin resolves the rewrite core libraries and any recipe modules added to the rewrite configuration at runtime. It will attempt to resolve them from whatever repositories are available to the project. This is accomplished by adding the Code Genome Project repository, or an internal repository that mirrors it, to your project's repositories:

repositories {
mavenCentral()
maven {
url = "https://artifacts.codegenomeproject.org/maven"
credentials {
username = providers.gradleProperty("codegenomeUsername").get()
password = providers.gradleProperty("codegenomePassword").get()
}
}
}

Configuring the 'rewrite' DSL​

It generally makes sense to apply the plugin to the root build.gradle in a repository so that the configuration applies to each project in a multi-module project. The table below lists the properties of the rewrite DSL, with their type listed below their name. The auto-generated Gradle plugin Javadoc describes them in more detail.

PropertyDescription
activeRecipes
List<String>
Fully qualified class names of recipes to activate. Recipes will only run when explicitly activated here or in a rewrite.yml file. Defaults to empty list.
activeStyles
List<String>
Fully qualified class names of styles to activate. Styles will only be applied when explicitly activated here or in a rewrite.yml file. Defaults to empty list.
configFile
File
Path to the OpenRewrite YAML configuration file. Defaults to rewrite.yml in the project directory.
checkstyleConfigFile
File
Optional path to a Checkstyle configuration file. When set, OpenRewrite will use it to inform Java code style decisions. If not set explicitly, the plugin will attempt to auto-detect a Checkstyle configuration from the Checkstyle Gradle plugin. Defaults to null.
enableExperimentalGradleBuildScriptParsing
boolean
Whether to parse Gradle build scripts (build.gradle) as part of the source set. Defaults to true.
exportDatatables
boolean
Whether to export data tables to <build directory>/reports/rewrite/datatables/<timestamp>. Defaults to false.
exclusions
List<String>
Glob patterns for files to exclude from processing. For example: "src/generated/**". Defaults to empty list.
plainTextMasks
List<String>
Glob patterns for files that should be parsed as plain text. Exclusions take precedence over plain text masks. Defaults to built-in list.
sizeThresholdMb
int
Maximum file size in megabytes. Source files larger than this threshold are skipped during parsing. Defaults to 10.
rewriteVersion
String
Override the version of rewrite core libraries to be used. When null, the version bundled with the plugin is used. Defaults to null.
logCompilationWarningsAndErrors
boolean
Whether to log Java compilation warnings and errors encountered during parsing. Defaults to false.
failOnInvalidActiveRecipes
boolean
Whether to throw an exception if an activeRecipe fails configuration validation. This may happen if the activeRecipe is improperly configured, or any downstream recipes are improperly configured. For now, this defaults to false to prevent one improperly configured recipe from failing the build. In the future, the default may change to true to be more restrictive.
failOnDryRunResults
boolean
Whether rewriteDryRun should fail the build when it detects that changes would be made. Useful in CI to enforce that all recipes have already been applied. Defaults to false.
throwOnParseFailures
boolean
Whether to throw an exception when source file parsing fails. Can also be enabled via the project property -Prewrite.throwOnParseFailures. Defaults to false.
pomCacheEnabled
boolean
Whether to cache resolved Maven POMs to a RocksDB-backed on-disk cache to speed up subsequent recipe runs. When enabled, a two-layer cache is used: an in-memory L1 cache backed by a RocksDB L2 cache. When disabled, only an in-memory cache is used. Defaults to true.
pomCacheDirectory
String
Directory in which to store the RocksDB-backed Maven POM cache. Defaults to ~/.rewrite-cache.
build.gradle
plugins {
id("java")
id("org.openrewrite.rewrite") version("latest.release")
}

repositories {
mavenCentral()
maven {
url = "https://artifacts.codegenomeproject.org/maven"
credentials {
username = providers.gradleProperty("codegenomeUsername").get()
password = providers.gradleProperty("codegenomePassword").get()
}
}
}

rewrite {
activeRecipe("com.yourorg.ExampleRecipe", "com.yourorg.ExampleRecipe2")
activeStyle("com.yourorg.ExampleStyle", "com.yourorg.ExampleStyle2")

exclusion(
// Excludes a particular yaml file
"subproject-a/src/main/resources/generated.yaml",
// Exclude all json files
"**/*.json"
)
plainTextMask("**/*.txt")

// These are default values, shown for example. It isn't necessary to supply these values manually:
configFile = project.getRootProject().file("rewrite.yml")
failOnDryRunResults = false
sizeThresholdMb = 10
}

Activating OpenRewrite recipes​

Info

OpenRewrite libraries and modules are published to the Code Genome Project. Use the repositories Gradle DSL to ensure that your build can resolve dependencies from there, or from an internal repository that mirrors it. Keep mavenCentral() alongside it: the Code Genome Project hosts only OpenRewrite and Moderne artifacts, not the third-party libraries they depend on.

Access depends on your account. OpenRewrite's Apache-licensed recipes are available to any authenticated user, while source-available and proprietary recipes require a Moderne subscription.

No recipe is ever run on your codebase without being explicitly activated in the plugin's configuration. To make pre-packaged OpenRewrite recipes available for activation, add Rewrite's bill of materials along with the specific rewrite dependencies:

build.gradle
dependencies {
rewrite(platform("org.openrewrite.recipe:rewrite-recipe-bom:latest.release"))
rewrite("org.openrewrite.recipe:rewrite-jackson")
}

Once a pre-packaged recipe has been added to the rewrite dependency configuration, you can tell the Gradle plugin to activate it the rewrite DSL. For example, here is how you would activate the org.openrewrite.java.jackson.UpgradeJackson_2_3 recipe that comes with rewrite-jackson in a single-project Gradle build:

build.gradle
plugins {
id("java")
id("org.openrewrite.rewrite") version("latest.release")
}

repositories {
mavenCentral()
maven {
url = "https://artifacts.codegenomeproject.org/maven"
credentials {
username = providers.gradleProperty("codegenomeUsername").get()
password = providers.gradleProperty("codegenomePassword").get()
}
}
}

dependencies {
implementation("com.fasterxml.jackson.core:jackson-databind:2.18.2")
rewrite(platform("org.openrewrite.recipe:rewrite-recipe-bom:latest.release"))
rewrite("org.openrewrite.recipe:rewrite-jackson")
}

rewrite {
activeRecipe("org.openrewrite.java.jackson.UpgradeJackson_2_3")
}

The "Run" task​

Execute gradle rewriteRun to run the active recipes and apply the changes. This will write changes locally to your source files on disk. Afterward, review the changes, and when you are comfortable with the changes, commit them. The run goal generates warnings in the build log wherever it makes changes to source files.

Showing which files were changed and by what visitors

After the goal finishes executing, run git diff (or your VCS system's equivalent) to see what changes were made, review, and commit them.

Example of changes made to netflix conductor by the rewriteRun task

JVM args that can be added to the Gradle command line​

It is possible to control the active recipe and style using JVM arguments in the command line.

  • To change the active recipe, you can specify either rewrite.activeRecipe or rewrite.activeRecipes (both do the same thing and take the same input).
  • To change the style, you can specify either rewrite.activeStyle or rewrite.activeStyles (both do the same thing and take the same input).

Here's an example of what this might look like if you were to use rewriteRun with an init script:

gradle rewriteRun --init-script init.gradle -Drewrite.activeRecipe=org.openrewrite.FindSpringUses 

In general, it's best to default to not passing in any styles and to allow rewrite to detect the styles itself. If you need to, though, you can always append -Drewrite.activeStyle to the end of the command:

-Drewrite.activeStyle=com.yourorg.YesTabsNoStarImports

The "dryRun" task​

Execute gradle rewriteDryRun to dry-run the active recipes and print which visitors would make changes to which files in the build log. This does not alter your source files on disk at all. This goal can be used to preview the changes that would be made by the active recipes.

rewriteDryRun outputs a report in the form of a patch file, by default under build/reports/rewrite/rewrite.patch, containing changes that would be made if you were to run rewriteRun. This patch file can be used with git or diff to view or apply the potential changes. For example, git diff . build/reports/rewrite/rewrite.patch.

Listing of source files that would be changed if rewriteRun were run

rewriteDryRun can be used as a "gate" in a continuous integration environment by failing the build if rewriteDryRun detects changes to be made and failOnDryRunResults is set to true:

rewrite {
// ...
failOnDryRunResults = true
}

If desired, rewriteDryRun can be configured so that when check runs, rewriteDryRun does too:

tasks.named("check").configure {
dependsOn(tasks.named("rewriteDryRun"))
}

The "Discover" task​

Execute gradle rewriteDiscover to list the recipes available on your classpath.