11package org .scip_code .scip_java .gradle ;
22
33import java .util .ArrayList ;
4+ import java .util .HashSet ;
45import java .util .List ;
56import java .util .Map ;
7+ import java .util .Set ;
68import org .gradle .api .Plugin ;
79import org .gradle .api .Project ;
810import org .gradle .api .Task ;
911import org .gradle .api .artifacts .Configuration ;
1012import org .gradle .api .initialization .Settings ;
1113import org .gradle .api .internal .GradleInternal ;
1214import 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 ;
1319import org .gradle .api .tasks .compile .JavaCompile ;
20+ import org .gradle .process .CommandLineArgumentProvider ;
1421
1522public 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}
0 commit comments