/
GroovyCompile.java
424 lines (382 loc) · 17.2 KB
/
GroovyCompile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks.compile;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.JavaVersion;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.internal.FeaturePreviews;
import org.gradle.api.internal.file.FileOperations;
import org.gradle.api.internal.file.FileTreeInternal;
import org.gradle.api.internal.file.temp.TemporaryFileProvider;
import org.gradle.api.internal.tasks.compile.CleaningJavaCompiler;
import org.gradle.api.internal.tasks.compile.CompilationSourceDirs;
import org.gradle.api.internal.tasks.compile.CompilerForkUtils;
import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpec;
import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpecFactory;
import org.gradle.api.internal.tasks.compile.GroovyCompilerFactory;
import org.gradle.api.internal.tasks.compile.GroovyJavaJointCompileSpec;
import org.gradle.api.internal.tasks.compile.HasCompileOptions;
import org.gradle.api.internal.tasks.compile.MinimalGroovyCompileOptions;
import org.gradle.api.internal.tasks.compile.MinimalJavaCompilerDaemonForkOptions;
import org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory;
import org.gradle.api.internal.tasks.compile.incremental.recomp.GroovyRecompilationSpecProvider;
import org.gradle.api.internal.tasks.compile.incremental.recomp.RecompilationSpecProvider;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.CompileClasspath;
import org.gradle.api.tasks.IgnoreEmptyDirectories;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Nested;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.SkipWhenEmpty;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.WorkResult;
import org.gradle.internal.file.Deleter;
import org.gradle.internal.jvm.Jvm;
import org.gradle.internal.jvm.inspection.JvmMetadataDetector;
import org.gradle.jvm.toolchain.JavaInstallationMetadata;
import org.gradle.jvm.toolchain.JavaLauncher;
import org.gradle.jvm.toolchain.internal.InstallationLocation;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.util.internal.GFileUtils;
import org.gradle.util.internal.IncubationLogger;
import org.gradle.work.Incremental;
import org.gradle.work.InputChanges;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
import static com.google.common.base.Preconditions.checkState;
import static org.gradle.api.internal.FeaturePreviews.Feature.GROOVY_COMPILATION_AVOIDANCE;
/**
* Compiles Groovy source files, and optionally, Java source files.
*/
@CacheableTask
public class GroovyCompile extends AbstractCompile implements HasCompileOptions {
private FileCollection groovyClasspath;
private final ConfigurableFileCollection astTransformationClasspath;
private final CompileOptions compileOptions;
private final GroovyCompileOptions groovyCompileOptions = getProject().getObjects().newInstance(GroovyCompileOptions.class);
private final FileCollection stableSources = getProject().files((Callable<FileTree>) this::getSource);
private final Property<JavaLauncher> javaLauncher;
private File previousCompilationDataFile;
public GroovyCompile() {
ObjectFactory objectFactory = getObjectFactory();
CompileOptions compileOptions = objectFactory.newInstance(CompileOptions.class);
compileOptions.setIncremental(false);
compileOptions.getIncrementalAfterFailure().convention(true);
this.compileOptions = compileOptions;
this.javaLauncher = objectFactory.property(JavaLauncher.class);
this.astTransformationClasspath = objectFactory.fileCollection();
if (!experimentalCompilationAvoidanceEnabled()) {
this.astTransformationClasspath.from((Callable<FileCollection>) this::getClasspath);
}
CompilerForkUtils.doNotCacheIfForkingViaExecutable(compileOptions, getOutputs());
}
@Override
@CompileClasspath
@Incremental
public FileCollection getClasspath() {
// Note that @CompileClasspath here is an approximation and must be fixed before de-incubating getAstTransformationClasspath()
// See https://github.com/gradle/gradle/pull/9513
return super.getClasspath();
}
/**
* The classpath containing AST transformations and their dependencies.
*
* @since 5.6
*/
@Classpath
public ConfigurableFileCollection getAstTransformationClasspath() {
return astTransformationClasspath;
}
private boolean experimentalCompilationAvoidanceEnabled() {
return getFeaturePreviews().isFeatureEnabled(GROOVY_COMPILATION_AVOIDANCE);
}
@TaskAction
protected void compile(InputChanges inputChanges) {
checkGroovyClasspathIsNonEmpty();
warnIfCompileAvoidanceEnabled();
GroovyJavaJointCompileSpec spec = createSpec();
WorkResult result = getCompiler(spec, inputChanges).execute(spec);
setDidWork(result.getDidWork());
}
/**
* The previous compilation analysis. Internal use only.
*
* @since 7.1
*/
@OutputFile
protected File getPreviousCompilationData() {
if (previousCompilationDataFile == null) {
previousCompilationDataFile = new File(getTemporaryDirWithoutCreating(), "previous-compilation-data.bin");
}
return previousCompilationDataFile;
}
private void warnIfCompileAvoidanceEnabled() {
if (experimentalCompilationAvoidanceEnabled()) {
IncubationLogger.incubatingFeatureUsed("Groovy compilation avoidance");
}
}
private Compiler<GroovyJavaJointCompileSpec> getCompiler(GroovyJavaJointCompileSpec spec, InputChanges inputChanges) {
GroovyCompilerFactory groovyCompilerFactory = getGroovyCompilerFactory();
Compiler<GroovyJavaJointCompileSpec> delegatingCompiler = groovyCompilerFactory.newCompiler(spec);
CleaningJavaCompiler<GroovyJavaJointCompileSpec> cleaningGroovyCompiler = new CleaningJavaCompiler<>(delegatingCompiler, getOutputs(), getDeleter());
if (spec.incrementalCompilationEnabled()) {
IncrementalCompilerFactory factory = getIncrementalCompilerFactory();
return factory.makeIncremental(
cleaningGroovyCompiler,
getStableSources().getAsFileTree(),
createRecompilationSpecProvider(inputChanges)
);
} else {
return cleaningGroovyCompiler;
}
}
@Inject
protected GroovyCompilerFactory getGroovyCompilerFactory() {
throw new UnsupportedOperationException();
}
private RecompilationSpecProvider createRecompilationSpecProvider(InputChanges inputChanges) {
FileCollection stableSources = getStableSources();
return new GroovyRecompilationSpecProvider(
getDeleter(),
getServices().get(FileOperations.class),
stableSources.getAsFileTree(),
inputChanges.isIncremental(),
() -> inputChanges.getFileChanges(stableSources).iterator()
);
}
/**
* The sources for incremental change detection.
*
* @since 5.6
*/
@SkipWhenEmpty
@IgnoreEmptyDirectories
// Java source files are supported, too. Therefore, we should care about the relative path.
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
protected FileCollection getStableSources() {
return stableSources;
}
/**
* Injects and returns an instance of {@link IncrementalCompilerFactory}.
*
* @since 5.6
*/
@Inject
protected IncrementalCompilerFactory getIncrementalCompilerFactory() {
throw new UnsupportedOperationException();
}
@Inject
protected Deleter getDeleter() {
throw new UnsupportedOperationException("Decorator takes care of injection");
}
@Inject
protected ProjectLayout getProjectLayout() {
throw new UnsupportedOperationException();
}
@Inject
protected ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException();
}
private FileCollection determineGroovyCompileClasspath() {
if (experimentalCompilationAvoidanceEnabled()) {
return astTransformationClasspath.plus(getClasspath());
} else {
return getClasspath();
}
}
private static void validateIncrementalCompilationOptions(List<File> sourceRoots, boolean annotationProcessingConfigured) {
if (sourceRoots.isEmpty()) {
throw new InvalidUserDataException("Unable to infer source roots. Incremental Groovy compilation requires the source roots. Change the configuration of your sources or disable incremental Groovy compilation.");
}
if (annotationProcessingConfigured) {
throw new InvalidUserDataException("Enabling incremental compilation and configuring Java annotation processors for Groovy compilation is not allowed. Disable incremental Groovy compilation or remove the Java annotation processor configuration.");
}
}
@Nullable
private JavaInstallationMetadata getToolchain() {
return javaLauncher.map(JavaLauncher::getMetadata).getOrNull();
}
private GroovyJavaJointCompileSpec createSpec() {
validateConfiguration();
DefaultGroovyJavaJointCompileSpec spec = new DefaultGroovyJavaJointCompileSpecFactory(compileOptions, getToolchain()).create();
assert spec != null;
FileTreeInternal stableSourcesAsFileTree = (FileTreeInternal) getStableSources().getAsFileTree();
List<File> sourceRoots = CompilationSourceDirs.inferSourceRoots(stableSourcesAsFileTree);
spec.setSourcesRoots(sourceRoots);
spec.setSourceFiles(stableSourcesAsFileTree);
spec.setDestinationDir(getDestinationDirectory().getAsFile().get());
spec.setOriginalDestinationDir(spec.getDestinationDir());
spec.setWorkingDir(getProjectLayout().getProjectDirectory().getAsFile());
spec.setTempDir(getTemporaryDir());
spec.setCompileClasspath(ImmutableList.copyOf(determineGroovyCompileClasspath()));
configureCompatibilityOptions(spec);
spec.setAnnotationProcessorPath(Lists.newArrayList(compileOptions.getAnnotationProcessorPath() == null ? getProjectLayout().files() : compileOptions.getAnnotationProcessorPath()));
spec.setGroovyClasspath(Lists.newArrayList(getGroovyClasspath()));
spec.setCompileOptions(compileOptions);
spec.setGroovyCompileOptions(new MinimalGroovyCompileOptions(groovyCompileOptions));
spec.getCompileOptions().setSupportsCompilerApi(true);
if (getOptions().isIncremental()) {
validateIncrementalCompilationOptions(sourceRoots, spec.annotationProcessingConfigured());
spec.getCompileOptions().setPreviousCompilationDataFile(getPreviousCompilationData());
}
if (spec.getGroovyCompileOptions().getStubDir() == null) {
File dir = new File(getTemporaryDir(), "groovy-java-stubs");
GFileUtils.mkdirs(dir);
spec.getGroovyCompileOptions().setStubDir(dir);
}
configureExecutable(spec.getCompileOptions().getForkOptions());
return spec;
}
private void configureCompatibilityOptions(DefaultGroovyJavaJointCompileSpec spec) {
JavaInstallationMetadata toolchain = getToolchain();
if (toolchain != null) {
boolean isSourceOrTargetConfigured = false;
if (super.getSourceCompatibility() != null) {
spec.setSourceCompatibility(getSourceCompatibility());
isSourceOrTargetConfigured = true;
}
if (super.getTargetCompatibility() != null) {
spec.setTargetCompatibility(getTargetCompatibility());
isSourceOrTargetConfigured = true;
}
if (!isSourceOrTargetConfigured) {
String languageVersion = toolchain.getLanguageVersion().toString();
spec.setSourceCompatibility(languageVersion);
spec.setTargetCompatibility(languageVersion);
}
} else {
spec.setSourceCompatibility(getSourceCompatibility());
spec.setTargetCompatibility(getTargetCompatibility());
}
}
private void configureExecutable(MinimalJavaCompilerDaemonForkOptions forkOptions) {
if (javaLauncher.isPresent()) {
forkOptions.setExecutable(javaLauncher.get().getExecutablePath().getAsFile().getAbsolutePath());
} else {
forkOptions.setExecutable(Jvm.current().getJavaExecutable().getAbsolutePath());
}
}
private void validateConfiguration() {
if (javaLauncher.isPresent()) {
checkState(getOptions().getForkOptions().getJavaHome() == null, "Must not use `javaHome` property on `ForkOptions` together with `javaLauncher` property");
checkState(getOptions().getForkOptions().getExecutable() == null, "Must not use `executable` property on `ForkOptions` together with `javaLauncher` property");
}
}
private void checkGroovyClasspathIsNonEmpty() {
if (getGroovyClasspath().isEmpty()) {
throw new InvalidUserDataException("'" + getName() + ".groovyClasspath' must not be empty. If a Groovy compile dependency is provided, "
+ "the 'groovy-base' plugin will attempt to configure 'groovyClasspath' automatically. Alternatively, you may configure 'groovyClasspath' explicitly.");
}
}
/**
* We need to track the Java version of the JVM the Groovy compiler is running on, since the Groovy compiler produces different results depending on it.
*
* This should be replaced by a property on the Groovy toolchain as soon as we model these.
*
* @since 4.0
*/
@Input
protected String getGroovyCompilerJvmVersion() {
if (javaLauncher.isPresent()) {
return javaLauncher.get().getMetadata().getLanguageVersion().toString();
}
final File customHome = getOptions().getForkOptions().getJavaHome();
if (customHome != null) {
return getServices().get(JvmMetadataDetector.class).getMetadata(new InstallationLocation(customHome, "JVM for Groovy compiler")).getLanguageVersion().getMajorVersion();
}
return JavaVersion.current().getMajorVersion();
}
/**
* {@inheritDoc}
*/
@Override
@Internal("tracked via stableSources")
public FileTree getSource() {
return super.getSource();
}
/**
* Gets the options for the Groovy compilation. To set specific options for the nested Java compilation, use {@link
* #getOptions()}.
*
* @return The Groovy compile options. Never returns null.
*/
@Nested
public GroovyCompileOptions getGroovyOptions() {
return groovyCompileOptions;
}
/**
* Returns the options for Java compilation.
*
* @return The Java compile options. Never returns null.
*/
@Nested
public CompileOptions getOptions() {
return compileOptions;
}
/**
* Returns the classpath containing the version of Groovy to use for compilation.
*
* @return The classpath.
*/
@Classpath
public FileCollection getGroovyClasspath() {
return groovyClasspath;
}
/**
* Sets the classpath containing the version of Groovy to use for compilation.
*
* @param groovyClasspath The classpath. Must not be null.
*/
public void setGroovyClasspath(FileCollection groovyClasspath) {
this.groovyClasspath = groovyClasspath;
}
/**
* The toolchain {@link JavaLauncher} to use for executing the Groovy compiler.
*
* @return the java launcher property
* @since 6.8
*/
@Nested
@Optional
public Property<JavaLauncher> getJavaLauncher() {
return javaLauncher;
}
@Inject
protected FeaturePreviews getFeaturePreviews() {
throw new UnsupportedOperationException();
}
private File getTemporaryDirWithoutCreating() {
// Do not create the temporary folder, since that causes problems.
return getServices().get(TemporaryFileProvider.class).newTemporaryFile(getName());
}
}