Skip to content

Commit 1841b93

Browse files
authored
Keep the SCIP javac plugin attached when builds replace compiler arguments (#1047)
1 parent d828f26 commit 1841b93

13 files changed

Lines changed: 251 additions & 53 deletions

File tree

‎scip-gradle-plugin/src/main/java/org/scip_code/scip_java/gradle/ScipGradlePlugin.java‎

Lines changed: 114 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
package org.scip_code.scip_java.gradle;
22

33
import java.util.ArrayList;
4+
import java.util.HashSet;
45
import java.util.List;
56
import java.util.Map;
7+
import java.util.Set;
68
import org.gradle.api.Plugin;
79
import org.gradle.api.Project;
810
import org.gradle.api.Task;
911
import org.gradle.api.artifacts.Configuration;
1012
import org.gradle.api.initialization.Settings;
1113
import org.gradle.api.internal.GradleInternal;
1214
import org.gradle.api.invocation.Gradle;
15+
import org.gradle.api.tasks.Input;
16+
import org.gradle.api.tasks.SourceSet;
17+
import org.gradle.api.tasks.SourceSetContainer;
18+
import org.gradle.api.tasks.compile.CompileOptions;
1319
import org.gradle.api.tasks.compile.JavaCompile;
20+
import org.gradle.process.CommandLineArgumentProvider;
1421

1522
public class ScipGradlePlugin implements Plugin<Project> {
1623

@@ -67,7 +74,10 @@ private void configureProject(Project project) {
6774
}
6875

6976
Object javacPluginDep = project.files(requiredExtra(extraProperties, "javacPluginJar"));
70-
boolean pluginAdded = tryAddJavacPlugin(project, javacPluginDep, isAndroid);
77+
// Android compile tasks belong to variants rather than source sets, so
78+
// there the plugin is added to all of them or to none.
79+
boolean androidPluginAdded = isAndroid && tryAddAndroidJavacPlugin(project, javacPluginDep);
80+
Set<String> pluginTasks = isAndroid ? Set.of() : addJavacPlugin(project, javacPluginDep);
7181

7282
project
7383
.getTasks()
@@ -79,36 +89,27 @@ private void configureProject(Project project) {
7989
// SCIP state.
8090
task.getOptions().setIncremental(false);
8191

82-
if (pluginAdded) {
83-
// Groovy build scripts can append interpolated strings
84-
// (GString) to compilerArgs, so despite the List<String>
85-
// signature the list may hold non-String elements. Iterate
86-
// through a wildcard reference so elements are not implicitly
87-
// cast to String, which throws ClassCastException (issue
88-
// #801).
89-
List<?> args = task.getOptions().getCompilerArgs();
90-
91-
// It's important we don't add the plugin configuration more
92-
// than once, as javac considers that an error.
93-
boolean alreadyAdded =
94-
args.stream()
95-
.anyMatch(arg -> String.valueOf(arg).startsWith("-Xplugin:scip"));
96-
if (!alreadyAdded) {
97-
// The random timestamp ensures the sources are _always_
98-
// recompiled, so Gradle doesn't cache any state.
99-
// TODO: before this plugin is published to Maven Central, we
100-
// will need to revert this change - as it can have
101-
// detrimental effect on people's builds.
102-
task.getOptions()
103-
.getCompilerArgs()
104-
.add(
105-
"-Xplugin:scip -targetroot:"
106-
+ targetRoot
107-
+ " -sourceroot:"
108-
+ sourceRoot
109-
+ " -randomtimestamp="
110-
+ System.nanoTime());
111-
}
92+
if (androidPluginAdded || pluginTasks.contains(task.getName())) {
93+
// An argument provider rather than compilerArgs, because builds
94+
// may replace compilerArgs after we run (Spring's conventions
95+
// call setCompilerArgs in afterEvaluate), which would silently
96+
// drop the plugin.
97+
// The random timestamp ensures the sources are _always_
98+
// recompiled, so Gradle doesn't cache any state.
99+
// TODO: before this plugin is published to Maven Central, we
100+
// will need to revert this change - as it can have
101+
// detrimental effect on people's builds.
102+
task.getOptions()
103+
.getCompilerArgumentProviders()
104+
.add(
105+
new JavacPluginArgument(
106+
task.getOptions(),
107+
"-Xplugin:scip -targetroot:"
108+
+ targetRoot
109+
+ " -sourceroot:"
110+
+ sourceRoot
111+
+ " -randomtimestamp="
112+
+ System.nanoTime()));
112113
}
113114
});
114115
}
@@ -146,40 +147,32 @@ private void configureProject(Project project) {
146147
/**
147148
* javac discovers {@code -Xplugin:} plugins from the annotation processor path when {@code
148149
* -processorpath} is set, and only falls back to the classpath when it isn't. Gradle populates
149-
* {@code -processorpath} from the {@code annotationProcessor} (main) and {@code
150-
* testAnnotationProcessor} (test) configurations, so whenever one of them declares a processor we
151-
* must add the SCIP javac plugin to that same configuration or the corresponding compile task
152-
* fails with "plug-in not found: scip". The two configurations are independent (test does not
153-
* extend main), so each is checked separately.
150+
* {@code -processorpath} from each source set's annotation processor configuration ({@code
151+
* annotationProcessor} for main, {@code testAnnotationProcessor} for test), so whenever one of
152+
* them declares a processor we must add the SCIP javac plugin to that same configuration or the
153+
* corresponding compile task fails with "plug-in not found: scip". The configurations are
154+
* independent (test does not extend main), so each is checked separately.
154155
*/
155156
private static boolean hasAnnotationProcessors(Project project, String configurationName) {
156157
try {
157158
Configuration config = project.getConfigurations().getByName(configurationName);
158-
return config.isCanBeResolved() && !config.getDependencies().isEmpty();
159+
// All dependencies, including inherited ones: the Error Prone Gradle
160+
// plugin makes annotationProcessor extend its own configuration.
161+
return config.isCanBeResolved() && !config.getAllDependencies().isEmpty();
159162
} catch (Exception exc) {
160163
return false;
161164
}
162165
}
163166

164-
private static boolean tryAddJavacPlugin(
165-
Project project, Object javacPluginDep, boolean isAndroid) {
167+
private static boolean tryAddAndroidJavacPlugin(Project project, Object javacPluginDep) {
166168
try {
167169
project.getDependencies().add("compileOnly", javacPluginDep);
168170
project.getDependencies().add("testCompileOnly", javacPluginDep);
169-
if (isAndroid) {
170-
// AGP always passes -processorpath, so javac only finds the plugin there.
171-
for (String name : ANDROID_ANNOTATION_PROCESSORS) {
172-
if (project.getConfigurations().findByName(name) != null) {
173-
project.getDependencies().add(name, javacPluginDep);
174-
}
171+
// AGP always passes -processorpath, so javac only finds the plugin there.
172+
for (String name : ANDROID_ANNOTATION_PROCESSORS) {
173+
if (project.getConfigurations().findByName(name) != null) {
174+
project.getDependencies().add(name, javacPluginDep);
175175
}
176-
return true;
177-
}
178-
if (hasAnnotationProcessors(project, "annotationProcessor")) {
179-
project.getDependencies().add("annotationProcessor", javacPluginDep);
180-
}
181-
if (hasAnnotationProcessors(project, "testAnnotationProcessor")) {
182-
project.getDependencies().add("testAnnotationProcessor", javacPluginDep);
183176
}
184177
return true;
185178
} catch (Exception exc) {
@@ -201,6 +194,44 @@ private static boolean tryAddJavacPlugin(
201194
}
202195
}
203196

197+
/**
198+
* Adds the SCIP javac plugin to each source set and returns the names of the compile tasks of the
199+
* source sets it was added to. A failure only skips that source set, because the other source
200+
* sets' configurations may still accept new dependencies.
201+
*/
202+
private static Set<String> addJavacPlugin(Project project, Object javacPluginDep) {
203+
Set<String> pluginTasks = new HashSet<>();
204+
for (SourceSet sourceSet : project.getExtensions().getByType(SourceSetContainer.class)) {
205+
try {
206+
project.getDependencies().add(sourceSet.getCompileOnlyConfigurationName(), javacPluginDep);
207+
String processors = sourceSet.getAnnotationProcessorConfigurationName();
208+
if (hasAnnotationProcessors(project, processors)) {
209+
project.getDependencies().add(processors, javacPluginDep);
210+
}
211+
pluginTasks.add(sourceSet.getCompileJavaTaskName());
212+
} catch (Exception exc) {
213+
// The source set's configurations have likely already been resolved by
214+
// another plugin or buildscript, so we can no longer add new
215+
// dependencies to them. The source set will be skipped (no SCIP output)
216+
// and, if no source set is indexed, the post-build check in
217+
// `GradleBuildTool` will surface a clearer error.
218+
project
219+
.getLogger()
220+
.warn(
221+
"scip-java: failed to attach SCIP compiler plugin to source set '"
222+
+ sourceSet.getName()
223+
+ "' of project '"
224+
+ project.getName()
225+
+ "' ("
226+
+ exc.getClass().getSimpleName()
227+
+ ": "
228+
+ exc.getMessage()
229+
+ "). This source set will not be indexed.");
230+
}
231+
}
232+
return pluginTasks;
233+
}
234+
204235
private static void configureKotlinCompileTask(
205236
Task task, Object scipKotlinc, String sourceRoot, String targetRoot) {
206237
if (!task.getClass().getSimpleName().contains("KotlinCompile")) {
@@ -244,4 +275,35 @@ private static Object requiredExtra(Map<String, Object> extraProperties, String
244275
}
245276
return value;
246277
}
278+
279+
/** Passes the SCIP javac plugin argument, unless the build already passes one itself. */
280+
private static class JavacPluginArgument implements CommandLineArgumentProvider {
281+
private final CompileOptions options;
282+
private final String argument;
283+
284+
JavacPluginArgument(CompileOptions options, String argument) {
285+
this.options = options;
286+
this.argument = argument;
287+
}
288+
289+
@Input
290+
public String getArgument() {
291+
return argument;
292+
}
293+
294+
@Override
295+
public Iterable<String> asArguments() {
296+
// Groovy build scripts can append interpolated strings (GString) to
297+
// compilerArgs, so despite the List<String> signature the list may hold
298+
// non-String elements. Iterate through a wildcard reference so elements
299+
// are not implicitly cast to String, which throws ClassCastException
300+
// (issue #801).
301+
List<?> args = options.getCompilerArgs();
302+
303+
// javac rejects the plugin configuration if it's given more than once.
304+
boolean alreadyAdded =
305+
args.stream().anyMatch(arg -> String.valueOf(arg).startsWith("-Xplugin:scip"));
306+
return alreadyAdded ? List.of() : List.of(argument);
307+
}
308+
}
247309
}

‎scip-java/src/main/kotlin/org/scip_code/scip_java/buildtools/GradleBuildTool.kt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,16 @@ This means our SCIP compiler plugin was not attached to one or more JavaCompile
4242
4343
1. The 'compileOnly' configuration was already resolved before our init script ran.
4444
Check the Gradle output above for warnings of the form:
45+
"scip-java: failed to attach SCIP compiler plugin to source set '<name>' of project '<name>'"
46+
or, for Android projects:
4547
"scip-java: failed to attach SCIP compiler plugin to project '<name>'"
4648
Workaround: apply the SCIP plugin earlier (e.g. via a settings plugin),
4749
or restructure the build so that 'compileOnly' is not resolved at evaluation time.
4850
4951
2. Another Gradle plugin is replacing the compiler arguments we add (rather than appending).
5052
Verify with: ./gradlew compileJava --info | grep -- '-Xplugin:scip'
5153
If '-Xplugin:scip' is missing from the printed javac command, another plugin
52-
is overwriting JavaCompile.options.compilerArgs.
54+
is overwriting JavaCompile.options.compilerArgumentProviders.
5355
"""
5456
)
5557
return 1

‎scip-java/src/test/kotlin/tests/GradleBuildToolTest.kt‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,15 @@ class GradleBuildToolTest : BuildToolHarness() {
6868
expectedScipFiles = 2,
6969
)
7070
)
71+
// Regression test: processors inherited from another configuration (as
72+
// with the Error Prone Gradle plugin) also make Gradle pass -processorpath.
73+
add(
74+
checkGradleBuild(
75+
"inherited-annotation-path",
76+
"gradle/inherited-annotation-path",
77+
expectedScipFiles = 2,
78+
)
79+
)
7180
add(
7281
checkGradleBuild("build-with-Werror", "gradle/build-with-Werror", expectedScipFiles = 2)
7382
)
@@ -82,6 +91,30 @@ class GradleBuildToolTest : BuildToolHarness() {
8291
expectedScipFiles = 1,
8392
)
8493
)
94+
// Regression test: a build that replaces compilerArgs after the plugin
95+
// ran must still load the SCIP javac plugin.
96+
add(
97+
checkGradleBuild(
98+
"replaced-compiler-args",
99+
"gradle/replaced-compiler-args",
100+
expectedScipFiles = 1,
101+
)
102+
)
103+
// Regression test: source sets other than main and test need the SCIP
104+
// javac plugin on their classpath too.
105+
add(
106+
checkGradleBuild("custom-source-set", "gradle/custom-source-set", expectedScipFiles = 2)
107+
)
108+
// Regression test: a source set whose configurations were resolved before
109+
// the plugin ran is compiled without the SCIP javac plugin, and the other
110+
// source sets are still indexed.
111+
add(
112+
checkGradleBuild(
113+
"resolved-source-set",
114+
"gradle/resolved-source-set",
115+
expectedScipFiles = 1,
116+
)
117+
)
85118
add(
86119
checkGradleBuild(
87120
"publishing",
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
plugins {
2+
id 'java'
3+
}
4+
repositories {
5+
mavenCentral()
6+
}
7+
// compileJava depends on compileExtraJava, which also needs the SCIP javac
8+
// plugin on its classpath.
9+
sourceSets {
10+
extra
11+
}
12+
dependencies {
13+
implementation sourceSets.extra.output
14+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package example;
2+
3+
public class Greeting {
4+
public static String of(String name) {
5+
return "Hello, " + name + "!";
6+
}
7+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package example;
2+
3+
public class Example {
4+
public String greet(String name) {
5+
return Greeting.of(name);
6+
}
7+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
plugins {
2+
id 'java'
3+
}
4+
repositories {
5+
mavenCentral()
6+
}
7+
// The processor is only inherited by annotationProcessor, like the Error Prone
8+
// Gradle plugin's 'errorprone' configuration.
9+
configurations {
10+
processors
11+
annotationProcessor.extendsFrom(processors)
12+
}
13+
dependencies {
14+
compileOnly 'org.immutables:value:2.9.2'
15+
processors 'org.immutables:value:2.9.2'
16+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package test;
2+
import org.immutables.value.Value;
3+
import java.util.Optional;
4+
@Value.Immutable
5+
public abstract class WorkflowOptions {
6+
public abstract Optional<String> getWorkflowIdReusePolicy();
7+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
plugins {
2+
id 'java'
3+
}
4+
repositories {
5+
mavenCentral()
6+
}
7+
// Replaces compilerArgs after the SCIP plugin has configured the task, like
8+
// Spring Framework's JavaConventions.
9+
afterEvaluate {
10+
tasks.withType(JavaCompile).configureEach {
11+
options.compilerArgs = ["-Xlint:serial"]
12+
}
13+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package example;
2+
3+
public class Example {
4+
public String greet(String name) {
5+
return "Hello, " + name + "!";
6+
}
7+
}

0 commit comments

Comments
 (0)