asArguments() {
27 | ["-D${PROPERTY_NAME}=${getVersions().join("|")}".toString()]
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #
2 |
--------------------------------------------------------------------------------
/gradle/licenseHeader.txt:
--------------------------------------------------------------------------------
1 | Copyright ${year} the original author or authors.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | https://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/openrewrite/rewrite-gradle-plugin/e973f1ccc7d87e60c08f32c82be052ba26e11167/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip
4 | distributionSha256Sum=7197a12f450794931532469d4ff21a59ea2c1cd59a3ec3f89c035c3c420a6999
5 | networkTimeout=10000
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | if ! command -v java >/dev/null 2>&1
137 | then
138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
139 |
140 | Please set the JAVA_HOME variable in your environment to match the
141 | location of your Java installation."
142 | fi
143 | fi
144 |
145 | # Increase the maximum file descriptors if we can.
146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
147 | case $MAX_FD in #(
148 | max*)
149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
150 | # shellcheck disable=SC2039,SC3045
151 | MAX_FD=$( ulimit -H -n ) ||
152 | warn "Could not query maximum file descriptor limit"
153 | esac
154 | case $MAX_FD in #(
155 | '' | soft) :;; #(
156 | *)
157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
158 | # shellcheck disable=SC2039,SC3045
159 | ulimit -n "$MAX_FD" ||
160 | warn "Could not set maximum file descriptor limit to $MAX_FD"
161 | esac
162 | fi
163 |
164 | # Collect all arguments for the java command, stacking in reverse order:
165 | # * args from the command line
166 | # * the main class name
167 | # * -classpath
168 | # * -D...appname settings
169 | # * --module-path (only if needed)
170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
171 |
172 | # For Cygwin or MSYS, switch paths to Windows format before running java
173 | if "$cygwin" || "$msys" ; then
174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
176 |
177 | JAVACMD=$( cygpath --unix "$JAVACMD" )
178 |
179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
180 | for arg do
181 | if
182 | case $arg in #(
183 | -*) false ;; # don't mess with options #(
184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
185 | [ -e "$t" ] ;; #(
186 | *) false ;;
187 | esac
188 | then
189 | arg=$( cygpath --path --ignore --mixed "$arg" )
190 | fi
191 | # Roll the args list around exactly as many times as the number of
192 | # args, so each arg winds up back in the position where it started, but
193 | # possibly modified.
194 | #
195 | # NB: a `for` loop captures its iteration list before it begins, so
196 | # changing the positional parameters here affects neither the number of
197 | # iterations, nor the values presented in `arg`.
198 | shift # remove old arg
199 | set -- "$@" "$arg" # push replacement arg
200 | done
201 | fi
202 |
203 |
204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
206 |
207 | # Collect all arguments for the java command:
208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
209 | # and any embedded shellness will be escaped.
210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
211 | # treated as '${Hostname}' itself on the command line.
212 |
213 | set -- \
214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
215 | -classpath "$CLASSPATH" \
216 | org.gradle.wrapper.GradleWrapperMain \
217 | "$@"
218 |
219 | # Stop when "xargs" is not available.
220 | if ! command -v xargs >/dev/null 2>&1
221 | then
222 | die "xargs is not available"
223 | fi
224 |
225 | # Use "xargs" to parse quoted args.
226 | #
227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
228 | #
229 | # In Bash we could simply go:
230 | #
231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
232 | # set -- "${ARGS[@]}" "$@"
233 | #
234 | # but POSIX shell has neither arrays nor command substitution, so instead we
235 | # post-process each arg (as a line of input to sed) to backslash-escape any
236 | # character that might be a shell metacharacter, then use eval to reverse
237 | # that process (while maintaining the separation between arguments), and wrap
238 | # the whole thing up as a single "set" statement.
239 | #
240 | # This will of course break if any of these variables contains a newline or
241 | # an unmatched quote.
242 | #
243 |
244 | eval "set -- $(
245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
246 | xargs -n1 |
247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
248 | tr '\n' ' '
249 | )" '"$@"'
250 |
251 | exec "$JAVACMD" "$@"
252 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/plugin/build.gradle.kts:
--------------------------------------------------------------------------------
1 | @file:Suppress("UnstableApiUsage")
2 |
3 | import nl.javadude.gradle.plugins.license.LicenseExtension
4 | import org.gradle.rewrite.build.GradleVersionData
5 | import org.gradle.rewrite.build.GradleVersionsCommandLineArgumentProvider
6 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
7 | import java.util.*
8 |
9 | plugins {
10 | id("org.jetbrains.kotlin.jvm") version "1.9.0"
11 | id("com.gradle.plugin-publish") version "1.1.0"
12 | id("com.github.hierynomus.license") version "0.16.1"
13 | id("nebula.maven-apache-license")
14 | }
15 |
16 | gradlePlugin {
17 | website.set("https://github.com/openrewrite/rewrite-gradle-plugin")
18 | vcsUrl.set("https://github.com/openrewrite/rewrite-gradle-plugin.git")
19 |
20 | plugins {
21 | create("rewrite") {
22 | id = "org.openrewrite.rewrite"
23 | displayName = "Rewrite"
24 | description = "Automatically eliminate technical debt"
25 | implementationClass = "org.openrewrite.gradle.RewritePlugin"
26 | tags.set(listOf("rewrite", "refactoring", "remediation", "security", "migration", "java", "checkstyle"))
27 | }
28 | }
29 | }
30 |
31 | repositories {
32 | if (!project.hasProperty("releasing")) {
33 | mavenLocal {
34 | mavenContent {
35 | excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*")
36 | }
37 | }
38 |
39 | maven {
40 | url = uri("https://oss.sonatype.org/content/repositories/snapshots")
41 | }
42 | }
43 |
44 | mavenCentral {
45 | mavenContent {
46 | excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*")
47 | }
48 | }
49 | gradlePluginPortal()
50 | google()
51 | }
52 |
53 | val latest = if (project.hasProperty("releasing")) {
54 | "latest.release"
55 | } else {
56 | "latest.integration"
57 | }
58 |
59 | configurations.all {
60 | resolutionStrategy {
61 | cacheChangingModulesFor(0, TimeUnit.SECONDS)
62 | cacheDynamicVersionsFor(0, TimeUnit.SECONDS)
63 | if (name.startsWith("test")) {
64 | eachDependency {
65 | if (requested.name == "groovy-xml") {
66 | useVersion("3.0.9")
67 | }
68 | }
69 | }
70 | }
71 | }
72 |
73 | java {
74 | toolchain {
75 | languageVersion.set(JavaLanguageVersion.of(17))
76 | }
77 | }
78 |
79 | tasks.withType().configureEach {
80 | options.release.set(8)
81 | options.encoding = "UTF-8"
82 | options.compilerArgs.add("-parameters")
83 | options.isFork = true
84 | }
85 |
86 | tasks.withType().configureEach {
87 | compilerOptions {
88 | jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8)
89 | }
90 | }
91 |
92 | val rewriteDependencies = configurations.create("rewriteDependencies")
93 | configurations.named("compileOnly").configure {
94 | extendsFrom(rewriteDependencies)
95 | }
96 |
97 | dependencies {
98 | "rewriteDependencies"(platform("org.openrewrite:rewrite-bom:$latest"))
99 | "rewriteDependencies"("org.openrewrite:rewrite-core")
100 | "rewriteDependencies"("org.openrewrite:rewrite-hcl")
101 | "rewriteDependencies"("org.openrewrite:rewrite-java")
102 | "rewriteDependencies"("org.openrewrite:rewrite-java-21")
103 | "rewriteDependencies"("org.openrewrite:rewrite-java-17")
104 | "rewriteDependencies"("org.openrewrite:rewrite-java-11")
105 | "rewriteDependencies"("org.openrewrite:rewrite-java-8")
106 | "rewriteDependencies"("org.openrewrite:rewrite-json")
107 | "rewriteDependencies"("org.openrewrite:rewrite-kotlin")
108 | "rewriteDependencies"("org.openrewrite:rewrite-xml")
109 | "rewriteDependencies"("org.openrewrite:rewrite-yaml")
110 | "rewriteDependencies"("org.openrewrite:rewrite-properties")
111 | "rewriteDependencies"("org.openrewrite:rewrite-protobuf")
112 | "rewriteDependencies"("org.openrewrite:rewrite-groovy")
113 | "rewriteDependencies"("org.openrewrite:rewrite-gradle")
114 | "rewriteDependencies"("org.openrewrite:rewrite-polyglot:$latest")
115 | "rewriteDependencies"("org.openrewrite.gradle.tooling:model:$latest")
116 | "rewriteDependencies"("org.openrewrite:rewrite-maven")
117 | "rewriteDependencies"("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.2")
118 | "rewriteDependencies"("com.google.guava:guava:latest.release")
119 | implementation(platform("org.openrewrite:rewrite-bom:$latest"))
120 | compileOnly("com.android.tools.build:gradle:7.0.4")
121 | compileOnly("org.jetbrains.kotlin:kotlin-gradle-plugin:latest.release")
122 | compileOnly("com.google.guava:guava:latest.release")
123 |
124 | testImplementation(platform("org.junit:junit-bom:latest.release"))
125 | testImplementation("org.junit.jupiter:junit-jupiter-api")
126 | testImplementation("org.junit.jupiter:junit-jupiter-params")
127 | testImplementation("org.openrewrite.tools:jgit:latest.release")
128 | testImplementation("org.openrewrite:rewrite-test")
129 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
130 | testImplementation("org.assertj:assertj-core:3.+")
131 |
132 | modules {
133 | module("com.google.guava:listenablefuture") {
134 | replacedBy("com.google.guava:guava", "listenablefuture is part of guava")
135 | }
136 | module("com.google.collections:google-collections") {
137 | replacedBy("com.google.guava:guava", "google-collections is part of guava")
138 | }
139 | }
140 | }
141 |
142 | project.rootProject.tasks.getByName("postRelease").dependsOn(project.tasks.getByName("publishPlugins"))
143 |
144 | tasks.register("testGradleReleases") {
145 | jvmArgumentProviders.add(GradleVersionsCommandLineArgumentProvider(GradleVersionData::getReleasedVersions))
146 | }
147 |
148 | tasks.register("testGradleNightlies") {
149 | jvmArgumentProviders.add(GradleVersionsCommandLineArgumentProvider(GradleVersionData::getNightlyVersions))
150 | }
151 |
152 | tasks.withType {
153 | useJUnitPlatform()
154 | // Remove this once we've fixed https://github.com/openrewrite/rewrite-gradle-plugin/issues/132
155 | setForkEvery(1)
156 | }
157 |
158 | val gVP = tasks.register("generateVersionsProperties") {
159 | val outputFile = file("${project.layout.buildDirectory.get().asFile}/rewrite/versions.properties")
160 | description = "Creates a versions.properties in $outputFile"
161 | group = "Build"
162 |
163 | inputs.files(rewriteDependencies)
164 | inputs.property("releasing", project.hasProperty("releasing"))
165 |
166 | outputs.file(outputFile)
167 |
168 | doLast {
169 | if (outputFile.exists()) {
170 | outputFile.delete()
171 | } else {
172 | outputFile.parentFile.mkdirs()
173 | }
174 | val resolvedModules = rewriteDependencies.resolvedConfiguration.firstLevelModuleDependencies
175 | val props = Properties()
176 | for (module in resolvedModules) {
177 | props["${module.moduleGroup}:${module.moduleName}"] = module.moduleVersion
178 | }
179 | outputFile.outputStream().use {
180 | props.store(it, null)
181 | }
182 | }
183 | }
184 |
185 | tasks.named("processResources") {
186 | into("rewrite/") {
187 | from(gVP)
188 | }
189 | }
190 |
191 | tasks.named("test") {
192 | systemProperty(
193 | "org.openrewrite.test.gradleVersion", project.findProperty("testedGradleVersion") ?: gradle.gradleVersion
194 | )
195 | }
196 |
197 | val testGradle4 = tasks.register("testGradle4") {
198 | systemProperty("org.openrewrite.test.gradleVersion", "4.10")
199 | systemProperty("jarLocationForTest", tasks.named("jar").get().archiveFile.get().asFile.absolutePath)
200 | // Gradle 4 predates support for Java 11
201 | javaLauncher.set(javaToolchains.launcherFor {
202 | languageVersion.set(JavaLanguageVersion.of(8))
203 | })
204 | }
205 | tasks.named("check").configure {
206 | dependsOn(testGradle4)
207 | }
208 |
209 | configure {
210 | ext.set("year", Calendar.getInstance().get(Calendar.YEAR))
211 | skipExistingHeaders = true
212 | header = project.rootProject.file("gradle/licenseHeader.txt")
213 | mapping(mapOf("kt" to "SLASHSTAR_STYLE", "java" to "SLASHSTAR_STYLE"))
214 | strictCheck = true
215 | exclude("**/versions.properties")
216 | exclude("**/*.txt")
217 | }
218 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/AbstractRewriteTask.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.api.DefaultTask;
19 | import org.gradle.api.file.ProjectLayout;
20 | import org.gradle.api.provider.Provider;
21 | import org.gradle.api.tasks.Input;
22 | import org.gradle.api.tasks.Internal;
23 | import org.gradle.api.tasks.options.Option;
24 | import org.gradle.util.GradleVersion;
25 |
26 | import javax.inject.Inject;
27 | import java.io.File;
28 | import java.nio.file.Path;
29 | import java.util.Collections;
30 | import java.util.List;
31 | import java.util.Set;
32 | import java.util.stream.Collectors;
33 |
34 | public abstract class AbstractRewriteTask extends DefaultTask {
35 | protected Provider> resolvedDependencies;
36 | protected boolean dumpGcActivity;
37 | protected GradleProjectParser gpp;
38 | protected RewriteExtension extension;
39 |
40 | protected AbstractRewriteTask() {
41 | if (GradleVersion.current().compareTo(GradleVersion.version("7.4")) >= 0) {
42 | notCompatibleWithConfigurationCache("org.openrewrite.rewrite needs to parse the whole project");
43 | }
44 | }
45 |
46 | public T setExtension(RewriteExtension extension) {
47 | this.extension = extension;
48 | //noinspection unchecked
49 | return (T) this;
50 | }
51 |
52 | public T setResolvedDependencies(Provider> resolvedDependencies) {
53 | this.resolvedDependencies = resolvedDependencies;
54 | //noinspection unchecked
55 | return (T) this;
56 | }
57 |
58 | @Option(description = "Dump GC activity related to parsing.", option = "dumpGcActivity")
59 | public void setDumpGcActivity(boolean dumpGcActivity) {
60 | this.dumpGcActivity = dumpGcActivity;
61 | }
62 |
63 | @Input
64 | public boolean isDumpGcActivity() {
65 | return dumpGcActivity;
66 | }
67 |
68 | @Inject
69 | public ProjectLayout getProjectLayout() {
70 | throw new AssertionError("unexpected; getProjectLayout() should be overridden by Gradle");
71 | }
72 |
73 | @Internal
74 | protected T getProjectParser() {
75 | if (gpp == null) {
76 | if (extension == null) {
77 | throw new IllegalArgumentException("Must configure extension");
78 | }
79 | if (resolvedDependencies == null) {
80 | throw new IllegalArgumentException("Must configure resolvedDependencies");
81 | }
82 | Set deps = resolvedDependencies.getOrNull();
83 | if (deps == null) {
84 | deps = Collections.emptySet();
85 | }
86 | Set classpath = deps.stream()
87 | .map(File::toPath)
88 | .collect(Collectors.toSet());
89 | gpp = new DelegatingProjectParser(getProject(), extension, classpath);
90 | }
91 | //noinspection unchecked
92 | return (T) gpp;
93 | }
94 |
95 | @Input
96 | public List getActiveRecipes() {
97 | return getProjectParser().getActiveRecipes();
98 | }
99 |
100 | @Input
101 | public List getActiveStyles() {
102 | return getProjectParser().getActiveStyles();
103 | }
104 |
105 | protected void shutdownRewrite() {
106 | getProjectParser().shutdownRewrite();
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/DelegatingProjectParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.api.Project;
19 | import org.gradle.internal.service.ServiceRegistry;
20 | import org.jspecify.annotations.Nullable;
21 |
22 | import java.lang.reflect.InvocationTargetException;
23 | import java.net.MalformedURLException;
24 | import java.net.URI;
25 | import java.net.URL;
26 | import java.nio.file.Path;
27 | import java.nio.file.Paths;
28 | import java.util.Arrays;
29 | import java.util.Collection;
30 | import java.util.List;
31 | import java.util.Set;
32 | import java.util.concurrent.Callable;
33 | import java.util.function.Consumer;
34 | import java.util.stream.Collectors;
35 |
36 | public class DelegatingProjectParser implements GradleProjectParser {
37 | @Nullable
38 | protected static List rewriteClasspath;
39 | @Nullable
40 | protected static RewriteClassLoader rewriteClassLoader;
41 | protected final GradleProjectParser gpp;
42 |
43 | public DelegatingProjectParser(Project project, RewriteExtension extension, Set classpath) {
44 | try {
45 | List classpathUrls = classpath.stream()
46 | .map(Path::toUri)
47 | .map(uri -> {
48 | try {
49 | return uri.toURL();
50 | } catch (MalformedURLException e) {
51 | throw new RuntimeException(e);
52 | }
53 | })
54 | .collect(Collectors.toList());
55 |
56 | @SuppressWarnings("ConstantConditions")
57 | URL currentJar = jarContainingResource(getClass()
58 | .getResource("/org/openrewrite/gradle/isolated/DefaultProjectParser.class")
59 | .toString());
60 | classpathUrls.add(currentJar);
61 |
62 | ClassLoader pluginClassLoader = getPluginClassLoader(project);
63 |
64 | if (rewriteClassLoader == null ||
65 | !classpathUrls.equals(rewriteClasspath) ||
66 | rewriteClassLoader.getPluginClassLoader() != pluginClassLoader) {
67 | if (rewriteClassLoader != null) {
68 | rewriteClassLoader.close();
69 | }
70 | rewriteClassLoader = new RewriteClassLoader(classpathUrls, pluginClassLoader);
71 | rewriteClasspath = classpathUrls;
72 | }
73 |
74 | Class> gppClass = Class.forName("org.openrewrite.gradle.isolated.DefaultProjectParser", true, rewriteClassLoader);
75 | assert (gppClass.getClassLoader() == rewriteClassLoader) : "DefaultProjectParser must be loaded from RewriteClassLoader to be sufficiently isolated from Gradle's classpath";
76 | gpp = (GradleProjectParser) gppClass.getDeclaredConstructor(Project.class, RewriteExtension.class)
77 | .newInstance(project, extension);
78 |
79 | } catch (Exception e) {
80 | throw new RuntimeException(e);
81 | }
82 | }
83 |
84 | @Override
85 | public List getActiveRecipes() {
86 | return unwrapInvocationException(gpp::getActiveRecipes);
87 | }
88 |
89 | @Override
90 | public List getActiveStyles() {
91 | return unwrapInvocationException(gpp::getActiveStyles);
92 | }
93 |
94 | @Override
95 | public List getAvailableStyles() {
96 | return unwrapInvocationException(gpp::getAvailableStyles);
97 | }
98 |
99 | @Override
100 | public void discoverRecipes(ServiceRegistry serviceRegistry) {
101 | unwrapInvocationException(() -> {
102 | gpp.discoverRecipes(serviceRegistry);
103 | return null;
104 | });
105 | }
106 |
107 | @Override
108 | public Collection listSources() {
109 | return unwrapInvocationException(gpp::listSources);
110 | }
111 |
112 | @Override
113 | public void run(Consumer onError) {
114 | unwrapInvocationException(() -> {
115 | gpp.run(onError);
116 | return null;
117 | });
118 | }
119 |
120 | @Override
121 | public void dryRun(Path reportPath, boolean dumpGcActivity, Consumer onError) {
122 | unwrapInvocationException(() -> {
123 | gpp.dryRun(reportPath, dumpGcActivity, onError);
124 | return null;
125 | });
126 | }
127 |
128 | @Override
129 | public void shutdownRewrite() {
130 | unwrapInvocationException(() -> {
131 | gpp.shutdownRewrite();
132 | return null;
133 | });
134 | }
135 |
136 | protected URL jarContainingResource(String resourcePath) {
137 | try {
138 | if (resourcePath.startsWith("jar:")) {
139 | resourcePath = resourcePath.substring(4);
140 | int indexOfBang = resourcePath.indexOf("!");
141 | if (indexOfBang != -1) {
142 | resourcePath = resourcePath.substring(0, indexOfBang);
143 | }
144 | return new URI(resourcePath).toURL();
145 | } else if (resourcePath.startsWith("file:")) {
146 | return new URI(resourcePath.substring(0, resourcePath.lastIndexOf("/main/") + 6)).toURL();
147 | }
148 | // This code path only gets taken when running the tests against older versions of Gradle
149 | // In all other circumstances, "path" will point at a jar file
150 | return Paths.get(System.getProperty("jarLocationForTest")).toUri().toURL();
151 | } catch (Exception e) {
152 | throw new RuntimeException(e);
153 | }
154 | }
155 |
156 | /**
157 | * Bloating stack traces with reflection errors isn't generally helpful for understanding what went wrong.
158 | *
159 | * This highlights the actual cause of a problem, allowing Gradle's console to display something useful like
160 | * "Recipe validation errors detected ..." rather than only "InvocationTargetException ..."
161 | */
162 | private T unwrapInvocationException(Callable supplier) {
163 | try {
164 | return supplier.call();
165 | } catch (InvocationTargetException e) {
166 | if (e.getTargetException() instanceof RuntimeException) {
167 | throw (RuntimeException) e.getTargetException();
168 | } else {
169 | throw new RuntimeException(e.getTargetException());
170 | }
171 | } catch (Exception e) {
172 | throw new RuntimeException(e);
173 | }
174 | }
175 |
176 | private ClassLoader getPluginClassLoader(Project project) {
177 | ClassLoader pluginClassLoader = getAndroidPluginClassLoader(project);
178 | if (pluginClassLoader == null) {
179 | pluginClassLoader = getClass().getClassLoader();
180 | }
181 | return pluginClassLoader;
182 | }
183 |
184 | private @Nullable ClassLoader getAndroidPluginClassLoader(Project project) {
185 | List pluginIds = Arrays.asList(
186 | "com.android.application",
187 | "com.android.library",
188 | "com.android.feature",
189 | "com.android.dynamic-feature",
190 | "com.android.test");
191 |
192 | for (String pluginId : pluginIds) {
193 | if (project.getPlugins().hasPlugin(pluginId)) {
194 | Object plugin = project.getPlugins().getPlugin(pluginId);
195 | return plugin.getClass().getClassLoader();
196 | }
197 | }
198 | return null;
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/GradleProjectParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.internal.service.ServiceRegistry;
19 |
20 | import java.nio.file.Path;
21 | import java.util.Collection;
22 | import java.util.List;
23 | import java.util.function.Consumer;
24 |
25 | public interface GradleProjectParser {
26 | List getActiveRecipes();
27 |
28 | List getActiveStyles();
29 |
30 | List getAvailableStyles();
31 |
32 | Collection listSources();
33 |
34 | void discoverRecipes(ServiceRegistry serviceRegistry);
35 |
36 | /**
37 | * @deprecated Use {@link #discoverRecipes(ServiceRegistry)} instead.
38 | */
39 | @Deprecated
40 | default void discoverRecipes(boolean interactive, ServiceRegistry serviceRegistry) {
41 | discoverRecipes(serviceRegistry);
42 | }
43 |
44 | void run(Consumer onError);
45 |
46 | void dryRun(Path reportPath, boolean dumpGcActivity, Consumer onError);
47 |
48 | void shutdownRewrite();
49 | }
50 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/RewriteClassLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import java.net.URL;
19 | import java.net.URLClassLoader;
20 | import java.util.Arrays;
21 | import java.util.Collection;
22 | import java.util.List;
23 |
24 | /**
25 | * Rewrite uses jackson for serialization/deserialization. So do lots of other build plugins.
26 | * Gradle plugins all share the same classpath at runtime.
27 | *
28 | * This classloader exists to isolate rewrite's use of jackson from the rest of the build.
29 | */
30 | public class RewriteClassLoader extends URLClassLoader {
31 |
32 | private static final List PARENT_LOADED_PACKAGES = Arrays.asList(
33 | "org.openrewrite.gradle.GradleProjectParser",
34 | "org.openrewrite.gradle.DefaultRewriteExtension",
35 | "org.openrewrite.gradle.RewriteExtension",
36 | "org.slf4j",
37 | "org.gradle",
38 | "groovy",
39 | "org.codehaus.groovy");
40 | private static final List PLUGIN_LOADED_PACKAGES = Arrays.asList("com.android");
41 | private final ClassLoader pluginClassLoader;
42 |
43 | public RewriteClassLoader(Collection artifacts) {
44 | this(artifacts, RewriteClassLoader.class.getClassLoader());
45 | }
46 |
47 | public RewriteClassLoader(Collection artifacts, ClassLoader pluginClassLoader) {
48 | super(artifacts.toArray(new URL[0]), RewriteClassLoader.class.getClassLoader());
49 | this.pluginClassLoader = pluginClassLoader;
50 | setDefaultAssertionStatus(true);
51 | }
52 |
53 | public ClassLoader getPluginClassLoader() {
54 | return pluginClassLoader;
55 | }
56 |
57 | /**
58 | * Load the named class. We want classes that extend org.openrewrite.Recipe
to be loaded
59 | * by this ClassLoader only. But we want classes required to run recipes to continue
60 | * to be loaded by their parent ClassLoader to avoid ClassCastException
s. In the case
61 | * of Android Gradle plugin classes, we use the ClassLoader of the plugin.
62 | */
63 | protected Class> loadClass(String name, boolean resolve) throws ClassNotFoundException {
64 | Class> foundClass = findLoadedClass(name);
65 | if (foundClass == null) {
66 | try {
67 | if (shouldBeParentLoaded(name)) {
68 | foundClass = super.loadClass(name, resolve);
69 | } else if (shouldBePluginLoaded(name)) {
70 | foundClass = Class.forName(name, resolve, pluginClassLoader);
71 | } else {
72 | foundClass = findClass(name);
73 | }
74 | } catch (ClassNotFoundException e) {
75 | foundClass = super.loadClass(name, resolve);
76 | }
77 | }
78 | if (resolve) {
79 | resolveClass(foundClass);
80 | }
81 | return foundClass;
82 | }
83 |
84 | protected boolean shouldBeParentLoaded(String name) {
85 | return shouldBeLoaded(name, PARENT_LOADED_PACKAGES);
86 | }
87 |
88 | protected boolean shouldBePluginLoaded(String name) {
89 | return shouldBeLoaded(name, PLUGIN_LOADED_PACKAGES);
90 | }
91 |
92 | private boolean shouldBeLoaded(String name, List packagesToLoad) {
93 | for (String pkg : packagesToLoad) {
94 | if (name.startsWith(pkg)) {
95 | return true;
96 | }
97 | }
98 | return false;
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/RewriteDiscoverTask.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.api.tasks.TaskAction;
19 |
20 | import javax.inject.Inject;
21 |
22 | public class RewriteDiscoverTask extends AbstractRewriteTask {
23 |
24 | @Inject
25 | public RewriteDiscoverTask() {
26 | setGroup("rewrite");
27 | setDescription("Lists all available recipes and their visitors");
28 | }
29 |
30 | @TaskAction
31 | public void run() {
32 | getProjectParser().discoverRecipes(getServices());
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/RewriteDryRunTask.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.api.logging.Logger;
19 | import org.gradle.api.logging.Logging;
20 | import org.gradle.api.specs.Specs;
21 | import org.gradle.api.tasks.OutputFile;
22 | import org.gradle.api.tasks.TaskAction;
23 |
24 | import javax.inject.Inject;
25 | import java.nio.file.Path;
26 |
27 | public class RewriteDryRunTask extends AbstractRewriteTask {
28 |
29 | private static final Logger logger = Logging.getLogger(RewriteDryRunTask.class);
30 |
31 | @OutputFile
32 | public Path getReportPath() {
33 | return getProjectLayout()
34 | .getBuildDirectory()
35 | .get()
36 | .getAsFile()
37 | .toPath()
38 | .resolve("reports")
39 | .resolve("rewrite")
40 | .resolve("rewrite.patch");
41 | }
42 |
43 | @Inject
44 | public RewriteDryRunTask() {
45 | setGroup("rewrite");
46 | setDescription("Run the active refactoring recipes, producing a patch file. No source files will be changed.");
47 | getOutputs().upToDateWhen(Specs.SATISFIES_NONE);
48 | }
49 |
50 | @TaskAction
51 | public void run() {
52 | getProjectParser().dryRun(getReportPath(), dumpGcActivity, throwable -> logger.info("Error during rewrite dry run", throwable));
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/plugin/src/main/java/org/openrewrite/gradle/RewriteExtension.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2025 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * https://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.openrewrite.gradle;
17 |
18 | import org.gradle.api.Project;
19 |
20 | import javax.annotation.Nullable;
21 | import javax.inject.Provider;
22 | import java.io.File;
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.util.*;
26 |
27 | import static java.util.Arrays.asList;
28 | import static java.util.Collections.emptyMap;
29 |
30 | @SuppressWarnings("unused")
31 | public class RewriteExtension {
32 |
33 | private final List activeRecipes = new ArrayList<>();
34 | private final List activeStyles = new ArrayList<>();
35 | private boolean configFileSetDeliberately;
36 |
37 | protected final Project project;
38 | private File configFile;
39 |
40 | @Nullable
41 | private Provider checkstyleConfigProvider;
42 |
43 | @Nullable
44 | private Provider