Skip to content

Commit c468612

Browse files
authored
Replace getProject() references with injected services in task implementations where possible (#81681)
- Rework task implementations to avoid project usage at execution time - In general usages of getProject() within a task should be avoided as it is not compatible with gradle configuration cache. Related to #57918
1 parent 76691bc commit c468612

23 files changed

+445
-248
lines changed

build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/precommit/LicenseHeadersTask.java

Lines changed: 41 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
import org.gradle.api.DefaultTask;
2424
import org.gradle.api.GradleException;
2525
import org.gradle.api.file.FileCollection;
26+
import org.gradle.api.file.ProjectLayout;
27+
import org.gradle.api.file.RegularFileProperty;
2628
import org.gradle.api.provider.ListProperty;
2729
import org.gradle.api.tasks.CacheableTask;
2830
import org.gradle.api.tasks.IgnoreEmptyDirectories;
@@ -55,12 +57,42 @@
5557
import javax.inject.Inject;
5658
import java.io.Serializable;
5759

60+
import javax.inject.Inject;
61+
5862
/**
5963
* Checks files for license headers..
6064
*/
6165
@CacheableTask
6266
public abstract class LicenseHeadersTask extends DefaultTask {
63-
public LicenseHeadersTask() {
67+
68+
private final RegularFileProperty reportFile;
69+
70+
private static List<License> conventionalLicenses = Arrays.asList(
71+
// Dual SSPLv1 and Elastic
72+
new License("DUAL", "SSPL+Elastic License", "the Elastic License 2.0 or the Server")
73+
);
74+
75+
/**
76+
* Allowed license families for this project.
77+
*/
78+
@Input
79+
private List<String> approvedLicenses = new ArrayList<String>(Arrays.asList("SSPL+Elastic License", "Generated", "Vendored", "Apache LZ4-Java"));
80+
/**
81+
* Files that should be excluded from the license header check. Use with extreme care, only in situations where the license on the
82+
* source file is compatible with the codebase but we do not want to add the license to the list of approved headers (to avoid the
83+
* possibility of inadvertently using the license on our own source files).
84+
*/
85+
@Input
86+
private List<String> excludes = new ArrayList<String>();
87+
88+
private ListProperty<License> additionalLicenses;
89+
90+
@Inject
91+
public LicenseHeadersTask(ObjectFactory objectFactory, ProjectLayout projectLayout) {
92+
additionalLicenses = objectFactory.listProperty(License.class).convention(conventionalLicenses);
93+
reportFile = objectFactory.fileProperty().convention(
94+
projectLayout.getBuildDirectory().file("reports/licenseHeaders/rat.xml")
95+
);
6496
setDescription("Checks sources for missing, incorrect, or unacceptable license headers");
6597
}
6698

@@ -79,14 +111,11 @@ public List<FileCollection> getJavaFiles() {
79111
@Internal
80112
public abstract ListProperty<FileCollection> getSourceFolders();
81113

82-
public File getReportFile() {
114+
@OutputFile
115+
public RegularFileProperty getReportFile() {
83116
return reportFile;
84117
}
85118

86-
public void setReportFile(File reportFile) {
87-
this.reportFile = reportFile;
88-
}
89-
90119
public List<String> getApprovedLicenses() {
91120
return approvedLicenses;
92121
}
@@ -103,29 +132,6 @@ public void setExcludes(List<String> excludes) {
103132
this.excludes = excludes;
104133
}
105134

106-
@OutputFile
107-
private File reportFile = new File(getProject().getBuildDir(), "reports/licenseHeaders/rat.xml");
108-
109-
private static List<License> conventionalLicenses = Arrays.asList(
110-
// Dual SSPLv1 and Elastic
111-
new License("DUAL", "SSPL+Elastic License", "the Elastic License 2.0 or the Server")
112-
);
113-
114-
/**
115-
* Allowed license families for this project.
116-
*/
117-
@Input
118-
private List<String> approvedLicenses = new ArrayList<String>(Arrays.asList("SSPL+Elastic License", "Generated", "Vendored", "Apache LZ4-Java"));
119-
/**
120-
* Files that should be excluded from the license header check. Use with extreme care, only in situations where the license on the
121-
* source file is compatible with the codebase but we do not want to add the license to the list of approved headers (to avoid the
122-
* possibility of inadvertently using the license on our own source files).
123-
*/
124-
@Input
125-
private List<String> excludes = new ArrayList<String>();
126-
127-
private ListProperty<License> additionalLicenses;
128-
129135
/**
130136
* Additional license families that may be found. The key is the license category name (5 characters),
131137
* followed by the family name and the value list of patterns to search for.
@@ -151,11 +157,6 @@ public void additionalLicense(final String categoryName, String familyName, Stri
151157
additionalLicenses.add(new License(categoryName, familyName, pattern));
152158
}
153159

154-
@Inject
155-
public LicenseHeadersTask(ObjectFactory objectFactory) {
156-
additionalLicenses = objectFactory.listProperty(License.class).convention(conventionalLicenses);
157-
}
158-
159160
@TaskAction
160161
public void runRat() {
161162
ReportConfiguration reportConfiguration = new ReportConfiguration();
@@ -186,13 +187,15 @@ public void runRat() {
186187
return simpleLicenseFamily;
187188
}).toArray(SimpleLicenseFamily[]::new));
188189

189-
ClaimStatistic stats = generateReport(reportConfiguration, getReportFile());
190+
File repFile = getReportFile().getAsFile().get();
191+
ClaimStatistic stats = generateReport(reportConfiguration, repFile);
190192
boolean unknownLicenses = stats.getNumUnknown() > 0;
191193
boolean unApprovedLicenses = stats.getNumUnApproved() > 0;
192194
if (unknownLicenses || unApprovedLicenses) {
193195
getLogger().error("The following files contain unapproved license headers:");
194-
unapprovedFiles(getReportFile()).stream().forEachOrdered(unapprovedFile -> getLogger().error(unapprovedFile));
195-
throw new GradleException("Check failed. License header problems were found. Full details: " + reportFile.getAbsolutePath());
196+
unapprovedFiles(repFile).stream().forEachOrdered(unapprovedFile -> getLogger().error(unapprovedFile));
197+
throw new GradleException("Check failed. License header problems were found. Full details: " +
198+
repFile.getAbsolutePath());
196199
}
197200
}
198201

@@ -208,7 +211,7 @@ private IHeaderMatcher subStringMatcher(String licenseFamilyCategory, String lic
208211

209212
private ClaimStatistic generateReport(ReportConfiguration config, File xmlReportFile) {
210213
try {
211-
Files.deleteIfExists(reportFile.toPath());
214+
Files.deleteIfExists(reportFile.get().getAsFile().toPath());
212215
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(xmlReportFile));
213216
return toXmlReportFile(config, bufferedWriter);
214217
} catch (IOException | RatException exception) {

build-conventions/src/main/java/org/elasticsearch/gradle/internal/conventions/precommit/PomValidationTask.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import org.elasticsearch.gradle.internal.conventions.precommit.PrecommitTask;
1414
import org.gradle.api.GradleException;
1515
import org.gradle.api.file.RegularFileProperty;
16+
import org.gradle.api.model.ObjectFactory;
1617
import org.gradle.api.tasks.InputFile;
1718
import org.gradle.api.tasks.TaskAction;
1819

@@ -21,12 +22,19 @@
2122
import java.util.function.Consumer;
2223
import java.util.function.Predicate;
2324

25+
import javax.inject.Inject;
26+
2427
public class PomValidationTask extends PrecommitTask {
2528

26-
private final RegularFileProperty pomFile = getProject().getObjects().fileProperty();
29+
private final RegularFileProperty pomFile;
2730

2831
private boolean foundError;
2932

33+
@Inject
34+
public PomValidationTask(ObjectFactory objects) {
35+
pomFile = objects.fileProperty();
36+
}
37+
3038
@InputFile
3139
public RegularFileProperty getPomFile() {
3240
return pomFile;

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesGraphTask.java

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import org.apache.http.impl.client.CloseableHttpClient;
1515
import org.apache.http.impl.client.HttpClients;
1616
import org.apache.http.util.EntityUtils;
17+
import org.gradle.StartParameter;
1718
import org.gradle.api.DefaultTask;
1819
import org.gradle.api.GradleException;
1920
import org.gradle.api.artifacts.Configuration;
@@ -27,6 +28,10 @@
2728
import java.util.HashSet;
2829
import java.util.Set;
2930

31+
import javax.inject.Inject;
32+
33+
import static org.elasticsearch.gradle.util.GradleUtils.projectPath;
34+
3035
/**
3136
* A task to generate a dependency graph of our runtime dependencies and push that via
3237
* an API call to a given endpoint of a SCA tool/service.
@@ -43,6 +48,7 @@ public class DependenciesGraphTask extends DefaultTask {
4348
private Configuration runtimeConfiguration;
4449
private String token;
4550
private String url;
51+
private StartParameter startParameter;
4652

4753
@Input
4854
public String getUrl() {
@@ -71,10 +77,14 @@ public void setRuntimeConfiguration(Configuration runtimeConfiguration) {
7177
this.runtimeConfiguration = runtimeConfiguration;
7278
}
7379

80+
@Inject
81+
public DependenciesGraphTask(StartParameter startParameter) {
82+
this.startParameter = startParameter;
83+
}
84+
7485
@TaskAction
7586
void generateDependenciesGraph() {
76-
77-
if (getProject().getGradle().getStartParameter().isOffline()) {
87+
if (startParameter.isOffline()) {
7888
throw new GradleException("Must run in online mode in order to submit the dependency graph to the SCA service");
7989
}
8090

@@ -102,7 +112,7 @@ void generateDependenciesGraph() {
102112
}
103113
// We add one package and one node for each dependency, it suffices to check packages.
104114
if (packages.size() > 0) {
105-
final String projectName = "elastic/elasticsearch" + getProject().getPath();
115+
final String projectName = "elastic/elasticsearch" + projectPath(getPath());
106116
final String output = """
107117
{
108118
"depGraph": {
@@ -138,4 +148,5 @@ void generateDependenciesGraph() {
138148
}
139149
}
140150
}
151+
141152
}

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/DependenciesInfoTask.java

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
import org.gradle.api.artifacts.DependencySet;
1616
import org.gradle.api.artifacts.ModuleVersionIdentifier;
1717
import org.gradle.api.artifacts.ProjectDependency;
18+
import org.gradle.api.file.DirectoryProperty;
19+
import org.gradle.api.file.ProjectLayout;
1820
import org.gradle.api.internal.ConventionTask;
21+
import org.gradle.api.model.ObjectFactory;
1922
import org.gradle.api.tasks.Input;
2023
import org.gradle.api.tasks.InputDirectory;
2124
import org.gradle.api.tasks.InputFiles;
@@ -33,6 +36,8 @@
3336
import java.util.regex.Pattern;
3437
import java.util.stream.Collectors;
3538

39+
import javax.inject.Inject;
40+
3641
/**
3742
* A task to gather information about the dependencies and export them into a csv file.
3843
* <p>
@@ -45,17 +50,12 @@
4550
* </ul>
4651
*/
4752
public class DependenciesInfoTask extends ConventionTask {
48-
/**
49-
* Directory to read license files
50-
*/
51-
@Optional
52-
@InputDirectory
53-
private File licensesDir = new File(getProject().getProjectDir(), "licenses").exists()
54-
? new File(getProject().getProjectDir(), "licenses")
55-
: null;
53+
54+
private final DirectoryProperty licensesDir;
5655

5756
@OutputFile
58-
private File outputFile = new File(getProject().getBuildDir(), "reports/dependencies/dependencies.csv");
57+
private File outputFile;
58+
5959
private LinkedHashMap<String, String> mappings;
6060

6161
public Configuration getRuntimeConfiguration() {
@@ -74,12 +74,17 @@ public void setCompileOnlyConfiguration(Configuration compileOnlyConfiguration)
7474
this.compileOnlyConfiguration = compileOnlyConfiguration;
7575
}
7676

77-
public File getLicensesDir() {
77+
/**
78+
* Directory to read license files
79+
*/
80+
@Optional
81+
@InputDirectory
82+
public DirectoryProperty getLicensesDir() {
7883
return licensesDir;
7984
}
8085

8186
public void setLicensesDir(File licensesDir) {
82-
this.licensesDir = licensesDir;
87+
this.licensesDir.set(licensesDir);
8388
}
8489

8590
public File getOutputFile() {
@@ -101,13 +106,16 @@ public void setOutputFile(File outputFile) {
101106
@InputFiles
102107
private Configuration compileOnlyConfiguration;
103108

104-
public DependenciesInfoTask() {
109+
@Inject
110+
public DependenciesInfoTask(ProjectLayout projectLayout, ObjectFactory objectFactory) {
111+
this.licensesDir = objectFactory.directoryProperty();
112+
this.licensesDir.set(projectLayout.getProjectDirectory().dir("licenses"));
113+
this.outputFile = projectLayout.getBuildDirectory().dir("reports/dependencies").get().file("dependencies.csv").getAsFile();
105114
setDescription("Create a CSV file with dependencies information.");
106115
}
107116

108117
@TaskAction
109118
public void generateDependenciesInfo() throws IOException {
110-
111119
final DependencySet runtimeDependencies = runtimeConfiguration.getAllDependencies();
112120
// we have to resolve the transitive dependencies and create a group:artifactId:version map
113121

@@ -203,8 +211,9 @@ protected String getLicenseType(final String group, final String name) throws IO
203211
}
204212

205213
protected File getDependencyInfoFile(final String group, final String name, final String infoFileSuffix) {
206-
java.util.Optional<File> license = licensesDir != null
207-
? Arrays.stream(licensesDir.listFiles((dir, fileName) -> Pattern.matches(".*-" + infoFileSuffix + ".*", fileName)))
214+
File licenseDirFile = licensesDir.getAsFile().get();
215+
java.util.Optional<File> license = licenseDirFile.exists()
216+
? Arrays.stream(licenseDirFile.listFiles((dir, fileName) -> Pattern.matches(".*-" + infoFileSuffix + ".*", fileName)))
208217
.filter(file -> {
209218
String prefix = file.getName().split("-" + infoFileSuffix + ".*")[0];
210219
return group.contains(prefix) || name.contains(prefix);
@@ -221,7 +230,7 @@ protected File getDependencyInfoFile(final String group, final String name, fina
221230
+ ":"
222231
+ name
223232
+ " in "
224-
+ getLicensesDir().getAbsolutePath()
233+
+ licenseDirFile.getAbsolutePath()
225234
)
226235
);
227236
}

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/EmptyDirTask.java

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,6 @@ public void setDir(File dir) {
5656
this.dir = dir;
5757
}
5858

59-
/**
60-
* @param dir The path of the directory to create. Takes a String and coerces it to a file.
61-
*/
62-
public void setDir(String dir) {
63-
this.dir = getProject().file(dir);
64-
}
65-
6659
@Input
6760
public int getDirMode() {
6861
return dirMode;

build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/ExportElasticsearchBuildResourcesTask.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.gradle.api.file.DirectoryProperty;
1313
import org.gradle.api.logging.Logger;
1414
import org.gradle.api.logging.Logging;
15+
import org.gradle.api.model.ObjectFactory;
1516
import org.gradle.api.tasks.Classpath;
1617
import org.gradle.api.tasks.Input;
1718
import org.gradle.api.tasks.OutputDirectory;
@@ -28,6 +29,8 @@
2829
import java.util.HashSet;
2930
import java.util.Set;
3031

32+
import javax.inject.Inject;
33+
3134
/**
3235
* Export Elasticsearch build resources to configurable paths
3336
* <p>
@@ -43,8 +46,9 @@ public class ExportElasticsearchBuildResourcesTask extends DefaultTask {
4346

4447
private DirectoryProperty outputDir;
4548

46-
public ExportElasticsearchBuildResourcesTask() {
47-
outputDir = getProject().getObjects().directoryProperty();
49+
@Inject
50+
public ExportElasticsearchBuildResourcesTask(ObjectFactory objects) {
51+
outputDir = objects.directoryProperty();
4852
}
4953

5054
@OutputDirectory

0 commit comments

Comments
 (0)