/
JavaCompile.java
396 lines (352 loc) · 15.3 KB
/
JavaCompile.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
/*
* Copyright 2012 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.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import org.gradle.api.JavaVersion;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.file.ProjectLayout;
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.CommandLineJavaCompileSpec;
import org.gradle.api.internal.tasks.compile.CompilationSourceDirs;
import org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler;
import org.gradle.api.internal.tasks.compile.CompilerForkUtils;
import org.gradle.api.internal.tasks.compile.DefaultJavaCompileSpec;
import org.gradle.api.internal.tasks.compile.DefaultJavaCompileSpecFactory;
import org.gradle.api.internal.tasks.compile.HasCompileOptions;
import org.gradle.api.internal.tasks.compile.JavaCompileExecutableUtils;
import org.gradle.api.internal.tasks.compile.JavaCompileSpec;
import org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory;
import org.gradle.api.internal.tasks.compile.incremental.recomp.JavaRecompilationSpecProvider;
import org.gradle.api.jvm.ModularitySpec;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.tasks.CacheableTask;
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.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.DefaultModularitySpec;
import org.gradle.internal.jvm.JavaModuleDetector;
import org.gradle.internal.operations.BuildOperationExecutor;
import org.gradle.jvm.toolchain.JavaCompiler;
import org.gradle.jvm.toolchain.JavaInstallationMetadata;
import org.gradle.jvm.toolchain.JavaToolchainService;
import org.gradle.jvm.toolchain.internal.DefaultToolchainJavaCompiler;
import org.gradle.jvm.toolchain.internal.JavaExecutableUtils;
import org.gradle.language.base.internal.compile.CompileSpec;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.work.Incremental;
import org.gradle.work.InputChanges;
import org.gradle.work.NormalizeLineEndings;
import javax.inject.Inject;
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Compiles Java source files.
*
* <pre class='autoTested'>
* plugins {
* id 'java'
* }
*
* tasks.withType(JavaCompile).configureEach {
* //enable compilation in a separate daemon process
* options.fork = true
* }
* </pre>
*/
@CacheableTask
public abstract class JavaCompile extends AbstractCompile implements HasCompileOptions {
private final CompileOptions compileOptions;
private final FileCollection stableSources = getProject().files((Callable<FileTree>) this::getSource);
private final ModularitySpec modularity;
private File previousCompilationDataFile;
private final Property<JavaCompiler> javaCompiler;
public JavaCompile() {
ObjectFactory objectFactory = getObjectFactory();
compileOptions = objectFactory.newInstance(CompileOptions.class);
modularity = objectFactory.newInstance(DefaultModularitySpec.class);
JavaToolchainService javaToolchainService = getJavaToolchainService();
Provider<JavaCompiler> javaCompilerConvention = getProviderFactory()
.provider(() -> JavaCompileExecutableUtils.getExecutableOverrideToolchainSpec(this, objectFactory))
.flatMap(javaToolchainService::compilerFor)
.orElse(javaToolchainService.compilerFor(it -> {}));
javaCompiler = objectFactory.property(JavaCompiler.class).convention(javaCompilerConvention);
javaCompiler.finalizeValueOnRead();
compileOptions.getIncrementalAfterFailure().convention(true);
CompilerForkUtils.doNotCacheIfForkingViaExecutable(compileOptions, getOutputs());
}
/**
* {@inheritDoc}
*/
@Override
@Internal("tracked via stableSources")
public FileTree getSource() {
return super.getSource();
}
/**
* Configures the java compiler to be used to compile the Java source.
*
* @see org.gradle.jvm.toolchain.JavaToolchainSpec
* @since 6.7
*/
@Nested
public Property<JavaCompiler> getJavaCompiler() {
return javaCompiler;
}
/**
* Compile the sources, taking into account the changes reported by inputs.
*
* @since 6.0
*/
@TaskAction
protected void compile(InputChanges inputs) {
DefaultJavaCompileSpec spec = createSpec();
if (!compileOptions.isIncremental()) {
performFullCompilation(spec);
} else {
performIncrementalCompilation(inputs, spec);
}
}
private void performIncrementalCompilation(InputChanges inputs, DefaultJavaCompileSpec spec) {
boolean isUsingCliCompiler = isUsingCliCompiler(spec);
if (isUsingCliCompiler) {
spec.getCompileOptions().setSupportsIncrementalCompilationAfterFailure(false);
}
spec.getCompileOptions().setSupportsCompilerApi(!isUsingCliCompiler);
spec.getCompileOptions().setSupportsConstantAnalysis(!isUsingCliCompiler);
spec.getCompileOptions().setPreviousCompilationDataFile(getPreviousCompilationData());
Compiler<JavaCompileSpec> compiler = createCompiler();
compiler = makeIncremental(inputs, (CleaningJavaCompiler<JavaCompileSpec>) compiler, getStableSources());
performCompilation(spec, compiler);
}
private Compiler<JavaCompileSpec> makeIncremental(InputChanges inputs, CleaningJavaCompiler<JavaCompileSpec> compiler, FileCollection stableSources) {
FileTree sources = stableSources.getAsFileTree();
return getIncrementalCompilerFactory().makeIncremental(
compiler,
sources,
createRecompilationSpec(inputs, sources)
);
}
private JavaRecompilationSpecProvider createRecompilationSpec(InputChanges inputs, FileTree sources) {
return new JavaRecompilationSpecProvider(
getDeleter(),
getServices().get(FileOperations.class),
sources,
inputs.isIncremental(),
() -> inputs.getFileChanges(getStableSources()).iterator()
);
}
private boolean isUsingCliCompiler(DefaultJavaCompileSpec spec) {
return CommandLineJavaCompileSpec.class.isAssignableFrom(spec.getClass());
}
private void performFullCompilation(DefaultJavaCompileSpec spec) {
Compiler<JavaCompileSpec> compiler;
spec.setSourceFiles(getStableSources());
compiler = createCompiler();
performCompilation(spec, compiler);
}
CleaningJavaCompiler<JavaCompileSpec> createCompiler() {
Compiler<JavaCompileSpec> javaCompiler = createToolchainCompiler();
return new CleaningJavaCompiler<>(javaCompiler, getOutputs(), getDeleter());
}
private <T extends CompileSpec> Compiler<T> createToolchainCompiler() {
return spec -> {
DefaultToolchainJavaCompiler compiler = (DefaultToolchainJavaCompiler) getJavaCompiler().get();
return compiler.execute(spec);
};
}
/**
* 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 performCompilation(JavaCompileSpec spec, Compiler<JavaCompileSpec> compiler) {
WorkResult result = new CompileJavaBuildOperationReportingCompiler(this, compiler, getServices().get(BuildOperationExecutor.class)).execute(spec);
setDidWork(result.getDidWork());
}
@VisibleForTesting
DefaultJavaCompileSpec createSpec() {
validateForkOptionsMatchToolchain();
List<File> sourcesRoots = CompilationSourceDirs.inferSourceRoots((FileTreeInternal) getStableSources().getAsFileTree());
JavaModuleDetector javaModuleDetector = getJavaModuleDetector();
boolean isModule = JavaModuleDetector.isModuleSource(modularity.getInferModulePath().get(), sourcesRoots);
boolean isSourcepathUserDefined = compileOptions.getSourcepath() != null && !compileOptions.getSourcepath().isEmpty();
DefaultJavaCompileSpec spec = new DefaultJavaCompileSpecFactory(compileOptions, getToolchain()).create();
spec.setDestinationDir(getDestinationDirectory().getAsFile().get());
spec.setWorkingDir(getProjectLayout().getProjectDirectory().getAsFile());
spec.setTempDir(getTemporaryDir());
spec.setCompileClasspath(ImmutableList.copyOf(javaModuleDetector.inferClasspath(isModule, getClasspath())));
spec.setModulePath(ImmutableList.copyOf(javaModuleDetector.inferModulePath(isModule, getClasspath())));
if (isModule && !isSourcepathUserDefined) {
compileOptions.setSourcepath(getProjectLayout().files(sourcesRoots));
}
spec.setAnnotationProcessorPath(compileOptions.getAnnotationProcessorPath() == null ? ImmutableList.of() : ImmutableList.copyOf(compileOptions.getAnnotationProcessorPath()));
configureCompileOptions(spec);
spec.setSourcesRoots(sourcesRoots);
if (!isToolchainCompatibleWithJava8()) {
spec.getCompileOptions().setHeaderOutputDirectory(null);
}
return spec;
}
private void validateForkOptionsMatchToolchain() {
if (!getOptions().isFork()) {
return;
}
JavaCompiler javaCompilerTool = getJavaCompiler().get();
File toolchainJavaHome = javaCompilerTool.getMetadata().getInstallationPath().getAsFile();
ForkOptions forkOptions = getOptions().getForkOptions();
File customJavaHome = forkOptions.getJavaHome();
if (customJavaHome != null) {
JavaExecutableUtils.validateMatchingFiles(
customJavaHome, "Toolchain from `javaHome` property on `ForkOptions`",
toolchainJavaHome, "toolchain from `javaCompiler` property"
);
}
String customExecutablePath = forkOptions.getExecutable();
if (customExecutablePath != null) {
// We do not match the custom executable against the compiler executable from the toolchain (javac),
// because the custom executable can be set to the path of another tool in the toolchain such as a launcher (java).
File customExecutableJavaHome = JavaExecutableUtils.resolveJavaHomeOfExecutable(customExecutablePath);
JavaExecutableUtils.validateMatchingFiles(
customExecutableJavaHome, "Toolchain from `executable` property on `ForkOptions`",
toolchainJavaHome, "toolchain from `javaCompiler` property"
);
}
}
private boolean isToolchainCompatibleWithJava8() {
return getToolchain().getLanguageVersion().canCompileOrRun(8);
}
@Input
JavaVersion getJavaVersion() {
return JavaVersion.toVersion(getToolchain().getLanguageVersion().asInt());
}
private void configureCompileOptions(DefaultJavaCompileSpec spec) {
if (compileOptions.getRelease().isPresent()) {
spec.setRelease(compileOptions.getRelease().get());
} else {
String toolchainVersion = JavaVersion.toVersion(getToolchain().getLanguageVersion().asInt()).toString();
String sourceCompatibility = getSourceCompatibility();
// Compatibility can be null if no convention was configured, e.g. when JavaBasePlugin is not applied
if (sourceCompatibility == null) {
sourceCompatibility = toolchainVersion;
}
String targetCompatibility = getTargetCompatibility();
if (targetCompatibility == null) {
targetCompatibility = sourceCompatibility;
}
spec.setSourceCompatibility(sourceCompatibility);
spec.setTargetCompatibility(targetCompatibility);
}
spec.setCompileOptions(compileOptions);
}
private JavaInstallationMetadata getToolchain() {
return getJavaCompiler().get().getMetadata();
}
private File getTemporaryDirWithoutCreating() {
// Do not create the temporary folder, since that causes problems.
return getServices().get(TemporaryFileProvider.class).newTemporaryFile(getName());
}
/**
* Returns the module path handling of this compile task.
*
* @since 6.4
*/
@Nested
public ModularitySpec getModularity() {
return modularity;
}
/**
* Returns the compilation options.
*
* @return The compilation options.
*/
@Nested
public CompileOptions getOptions() {
return compileOptions;
}
@Override
@CompileClasspath
@Incremental
public FileCollection getClasspath() {
return super.getClasspath();
}
/**
* The sources for incremental change detection.
*
* @since 6.0
*/
@SkipWhenEmpty
@IgnoreEmptyDirectories
@NormalizeLineEndings
@PathSensitive(PathSensitivity.RELATIVE)
@InputFiles
protected FileCollection getStableSources() {
return stableSources;
}
@Inject
protected ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException();
}
@Inject
protected JavaToolchainService getJavaToolchainService() {
throw new UnsupportedOperationException();
}
@Inject
protected ProviderFactory getProviderFactory() {
throw new UnsupportedOperationException();
}
@Inject
protected IncrementalCompilerFactory getIncrementalCompilerFactory() {
throw new UnsupportedOperationException();
}
@Inject
protected JavaModuleDetector getJavaModuleDetector() {
throw new UnsupportedOperationException();
}
@Inject
protected Deleter getDeleter() {
throw new UnsupportedOperationException();
}
@Inject
protected ProjectLayout getProjectLayout() {
throw new UnsupportedOperationException();
}
}