Allow build info properties to be excluded

Update Maven and Gradle plugins to allow build info properties to be
excluded.

Prior to this commit, the `BuildPropertiesWriter` would fail with an
NPE if the group, artifact, name or version properties were `null`.

This was specifically problematic with the Gradle plugin, since its
DSL allows `null` properties which would either be passed to the writer
or, in the case of `artifact`, converted into a string value of
"unspecified".

See gh-27412
This commit is contained in:
Vedran Pavic 2021-07-16 21:57:57 +02:00 committed by Phillip Webb
parent 2034ad4827
commit ea9faf8690
13 changed files with 355 additions and 26 deletions

View File

@ -30,8 +30,7 @@ By default, the generated build information is derived from the project:
| Property | Default value
| `build.artifact`
| The base name of the `bootJar` or `bootWar` task, or `unspecified` if no such task
exists
| The base name of the `bootJar` or `bootWar` task
| `build.group`
| The group of the project
@ -61,6 +60,8 @@ include::../gradle/integrating-with-actuator/build-info-custom-values.gradle[tag
include::../gradle/integrating-with-actuator/build-info-custom-values.gradle.kts[tags=custom-values]
----
NOTE: To omit any of the default properties from the generated build information, set its value to `null`.
The default value for `build.time` is the instant at which the project is being built.
A side-effect of this is that the task will never be up-to-date.
As a result, builds will take longer as more tasks, including the project's tests, will have to be executed.

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2020 the original author or authors.
* Copyright 2012-2021 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.
@ -60,12 +60,9 @@ public class BuildInfo extends ConventionTask {
public void generateBuildProperties() {
try {
new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties"))
.writeBuildProperties(
new ProjectDetails(this.properties.getGroup(),
(this.properties.getArtifact() != null) ? this.properties.getArtifact()
: "unspecified",
this.properties.getVersion(), this.properties.getName(), this.properties.getTime(),
coerceToStringValues(this.properties.getAdditional())));
.writeBuildProperties(new ProjectDetails(this.properties.getGroup(), this.properties.getArtifact(),
this.properties.getVersion(), this.properties.getName(), this.properties.getTime(),
coerceToStringValues(this.properties.getAdditional())));
}
catch (IOException ex) {
throw new TaskExecutionException(this, ex);

View File

@ -39,6 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* Integration tests for the {@link BuildInfo} task.
*
* @author Andy Wilkinson
* @author Vedran Pavic
*/
@GradleCompatibility(configurationCache = true)
class BuildInfoIntegrationTests {
@ -50,8 +51,8 @@ class BuildInfoIntegrationTests {
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
Properties buildInfoProperties = buildInfoProperties();
assertThat(buildInfoProperties).containsKey("build.time");
assertThat(buildInfoProperties).containsEntry("build.artifact", "unspecified");
assertThat(buildInfoProperties).containsEntry("build.group", "");
assertThat(buildInfoProperties).doesNotContainKey("build.artifact");
assertThat(buildInfoProperties).doesNotContainKey("build.group");
assertThat(buildInfoProperties).containsEntry("build.name", this.gradleBuild.getProjectDir().getName());
assertThat(buildInfoProperties).containsEntry("build.version", "unspecified");
}
@ -122,6 +123,26 @@ class BuildInfoIntegrationTests {
assertThat(firstHash).isEqualTo(secondHash);
}
@TestTemplate
void removePropertiesUsingNulls() {
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
Properties buildInfoProperties = buildInfoProperties();
assertThat(buildInfoProperties).doesNotContainKey("build.group");
assertThat(buildInfoProperties).doesNotContainKey("build.artifact");
assertThat(buildInfoProperties).doesNotContainKey("build.version");
assertThat(buildInfoProperties).doesNotContainKey("build.name");
}
@TestTemplate
void removePropertiesUsingEmptyStrings() {
assertThat(this.gradleBuild.build("buildInfo").task(":buildInfo").getOutcome()).isEqualTo(TaskOutcome.SUCCESS);
Properties buildInfoProperties = buildInfoProperties();
assertThat(buildInfoProperties).doesNotContainKey("build.group");
assertThat(buildInfoProperties).doesNotContainKey("build.artifact");
assertThat(buildInfoProperties).doesNotContainKey("build.version");
assertThat(buildInfoProperties).doesNotContainKey("build.name");
}
private Properties buildInfoProperties() {
File file = new File(this.gradleBuild.getProjectDir(), "build/build-info.properties");
assertThat(file).isFile();

View File

@ -38,6 +38,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* Tests for {@link BuildInfo}.
*
* @author Andy Wilkinson
* @author Vedran Pavic
*/
@ClassPathExclusions("kotlin-daemon-client-*")
class BuildInfoTests {
@ -49,8 +50,8 @@ class BuildInfoTests {
void basicExecution() {
Properties properties = buildInfoProperties(createTask(createProject("test")));
assertThat(properties).containsKey("build.time");
assertThat(properties).containsEntry("build.artifact", "unspecified");
assertThat(properties).containsEntry("build.group", "");
assertThat(properties).doesNotContainKey("build.artifact");
assertThat(properties).doesNotContainKey("build.group");
assertThat(properties).containsEntry("build.name", "test");
assertThat(properties).containsEntry("build.version", "unspecified");
}
@ -62,6 +63,20 @@ class BuildInfoTests {
assertThat(buildInfoProperties(task)).containsEntry("build.artifact", "custom");
}
@Test
void artifactCanBeRemovedFromPropertiesUsingNull() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setArtifact(null);
assertThat(buildInfoProperties(task)).doesNotContainKey("build.artifact");
}
@Test
void artifactCanBeRemovedFromPropertiesUsingEmptyString() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setArtifact("");
assertThat(buildInfoProperties(task)).doesNotContainKey("build.artifact");
}
@Test
void projectGroupIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
@ -76,6 +91,20 @@ class BuildInfoTests {
assertThat(buildInfoProperties(task)).containsEntry("build.group", "com.example");
}
@Test
void groupCanBeRemovedFromPropertiesUsingNull() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setGroup(null);
assertThat(buildInfoProperties(task)).doesNotContainKey("build.group");
}
@Test
void groupCanBeRemovedFromPropertiesUsingEmptyString() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setGroup("");
assertThat(buildInfoProperties(task)).doesNotContainKey("build.group");
}
@Test
void customNameIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
@ -83,6 +112,20 @@ class BuildInfoTests {
assertThat(buildInfoProperties(task)).containsEntry("build.name", "Example");
}
@Test
void nameCanBeRemovedFromPropertiesUsingNull() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setName(null);
assertThat(buildInfoProperties(task)).doesNotContainKey("build.name");
}
@Test
void nameCanBeRemovedFromPropertiesUsingEmptyString() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setName("");
assertThat(buildInfoProperties(task)).doesNotContainKey("build.name");
}
@Test
void projectVersionIsReflectedInProperties() {
BuildInfo task = createTask(createProject("test"));
@ -97,6 +140,20 @@ class BuildInfoTests {
assertThat(buildInfoProperties(task)).containsEntry("build.version", "2.3.4");
}
@Test
void versionCanBeRemovedFromPropertiesUsingNull() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setVersion(null);
assertThat(buildInfoProperties(task)).doesNotContainKey("build.version");
}
@Test
void versionCanBeRemovedFromPropertiesUsingEmptyString() {
BuildInfo task = createTask(createProject("test"));
task.getProperties().setVersion("");
assertThat(buildInfoProperties(task)).doesNotContainKey("build.version");
}
@Test
void timeIsSetInProperties() {
BuildInfo task = createTask(createProject("test"));

View File

@ -0,0 +1,16 @@
plugins {
id 'org.springframework.boot' version '{version}' apply false
}
group = 'foo'
version = '0.1.0'
task buildInfo(type: org.springframework.boot.gradle.tasks.buildinfo.BuildInfo) {
destinationDir project.buildDir
properties {
group = ''
artifact = ''
version = ''
name = ''
}
}

View File

@ -0,0 +1,16 @@
plugins {
id 'org.springframework.boot' version '{version}' apply false
}
group = 'foo'
version = '0.1.0'
task buildInfo(type: org.springframework.boot.gradle.tasks.buildinfo.BuildInfo) {
destinationDir project.buildDir
properties {
group = null
artifact = null
version = null
name = null
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2021 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.
@ -25,6 +25,7 @@ import java.util.Map;
import java.util.Properties;
import org.springframework.core.CollectionFactory;
import org.springframework.util.StringUtils;
/**
* A {@code BuildPropertiesWriter} writes the {@code build-info.properties} for
@ -32,6 +33,7 @@ import org.springframework.core.CollectionFactory;
*
* @author Andy Wilkinson
* @author Stephane Nicoll
* @author Vedran Pavic
* @since 1.0.0
*/
public final class BuildPropertiesWriter {
@ -71,10 +73,18 @@ public final class BuildPropertiesWriter {
protected Properties createBuildInfo(ProjectDetails project) {
Properties properties = CollectionFactory.createSortedProperties(true);
properties.put("build.group", project.getGroup());
properties.put("build.artifact", project.getArtifact());
properties.put("build.name", project.getName());
properties.put("build.version", project.getVersion());
if (StringUtils.hasText(project.getGroup())) {
properties.put("build.group", project.getGroup());
}
if (StringUtils.hasText(project.getArtifact())) {
properties.put("build.artifact", project.getArtifact());
}
if (StringUtils.hasText(project.getName())) {
properties.put("build.name", project.getName());
}
if (StringUtils.hasText(project.getVersion())) {
properties.put("build.version", project.getVersion());
}
if (project.getTime() != null) {
properties.put("build.time", DateTimeFormatter.ISO_INSTANT.format(project.getTime()));
}

View File

@ -35,6 +35,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* Integration tests for the Maven plugin's build info support.
*
* @author Andy Wilkinson
* @author Vedran Pavic
*/
@ExtendWith(MavenBuildExtension.class)
class BuildInfoIntegrationTests {
@ -63,6 +64,14 @@ class BuildInfoIntegrationTests {
.hasBuildTime("2019-07-08T08:00:00Z")));
}
@TestTemplate
void generatedBuildInfoUsesCustomBuildProperties(MavenBuild mavenBuild) {
mavenBuild.project("build-info-custom-build-properties")
.execute(buildInfo((buildInfo) -> assertThat(buildInfo).hasBuildGroup("test-group")
.hasBuildArtifact("test-artifact").hasBuildName("test-name").hasBuildVersion("test-version")
.containsBuildTime()));
}
@TestTemplate
void generatedBuildInfoReproducible(MavenBuild mavenBuild) {
mavenBuild.project("build-info-reproducible")
@ -89,6 +98,13 @@ class BuildInfoIntegrationTests {
.doesNotContainBuildTime()));
}
@TestTemplate
void whenBuildPropertiesAreEmptyTheyDoNotAppearInGeneratedBuildInfo(MavenBuild mavenBuild) {
mavenBuild.project("build-info-disable-build-properties").execute(
buildInfo((buildInfo) -> assertThat(buildInfo).doesNotContainBuildGroup().doesNotContainBuildArtifact()
.doesNotContainBuildName().doesNotContainBuildVersion().containsBuildTime()));
}
private ProjectCallback buildInfo(Consumer<AssertProvider<BuildInfoAssert>> buildInfo) {
return buildInfo("target/classes/META-INF/build-info.properties", buildInfo);
}
@ -130,18 +146,34 @@ class BuildInfoIntegrationTests {
return containsEntry("build.group", expected);
}
BuildInfoAssert doesNotContainBuildGroup() {
return doesNotContainKey("build.group");
}
BuildInfoAssert hasBuildArtifact(String expected) {
return containsEntry("build.artifact", expected);
}
BuildInfoAssert doesNotContainBuildArtifact() {
return doesNotContainKey("build.artifact");
}
BuildInfoAssert hasBuildName(String expected) {
return containsEntry("build.name", expected);
}
BuildInfoAssert doesNotContainBuildName() {
return doesNotContainKey("build.name");
}
BuildInfoAssert hasBuildVersion(String expected) {
return containsEntry("build.version", expected);
}
BuildInfoAssert doesNotContainBuildVersion() {
return doesNotContainKey("build.version");
}
BuildInfoAssert containsBuildTime() {
return containsKey("build.time");
}

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.boot.maven.it</groupId>
<artifactId>build-info-custom-build-properties</artifactId>
<version>0.0.1.BUILD-SNAPSHOT</version>
<name>Generate build info with custom build properties</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>@java.version@</maven.compiler.source>
<maven.compiler.target>@java.version@</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
<executions>
<execution>
<configuration>
<group>test-group</group>
<artifact>test-artifact</artifact>
<version>test-version</version>
<name>test-name</name>
</configuration>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,24 @@
/*
* Copyright 2012-2021 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
*
* https://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.test;
public class SampleApplication {
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.boot.maven.it</groupId>
<artifactId>build-info-disable-build-properties</artifactId>
<version>0.0.1.BUILD-SNAPSHOT</version>
<name>Generate build info with disabled build properties</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>@java.version@</maven.compiler.source>
<maven.compiler.target>@java.version@</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>@project.groupId@</groupId>
<artifactId>@project.artifactId@</artifactId>
<version>@project.version@</version>
<executions>
<execution>
<configuration>
<group>off</group>
<artifact>off</artifact>
<version>off</version>
<name>off</name>
</configuration>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,24 @@
/*
* Copyright 2012-2021 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
*
* https://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.test;
public class SampleApplication {
public static void main(String[] args) {
}
}

View File

@ -41,6 +41,7 @@ import org.springframework.boot.loader.tools.BuildPropertiesWriter.ProjectDetail
* {@link MavenProject}.
*
* @author Stephane Nicoll
* @author Vedran Pavic
* @since 1.4.0
*/
@Mojo(name = "build-info", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, threadSafe = true)
@ -55,18 +56,48 @@ public class BuildInfoMojo extends AbstractMojo {
@Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
/**
* The Maven project.
*/
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
/**
* The location of the generated {@code build-info.properties} file.
*/
@Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/build-info.properties")
private File outputFile;
/**
* The value used for the {@code build.group} property. Defaults to
* {@code project.groupId}. To disable the {@code build.group} property entirely, use
* {@code 'off'}.
* @since 2.6.0
*/
@Parameter(defaultValue = "${project.groupId}")
private String group;
/**
* The value used for the {@code build.artifact} property. Defaults to
* {@code project.artifactId}. To disable the {@code build.artifact} property
* entirely, use {@code 'off'}.
* @since 2.6.0
*/
@Parameter(defaultValue = "${project.artifactId}")
private String artifact;
/**
* The value used for the {@code build.version} property. Defaults to
* {@code project.version}. To disable the {@code build.version} property entirely,
* use {@code 'off'}.
* @since 2.6.0
*/
@Parameter(defaultValue = "${project.version}")
private String version;
/**
* The value used for the {@code build.name} property. Defaults to
* {@code project.name}. To disable the {@code build.name} property entirely, use
* {@code 'off'}.
* @since 2.6.0
*/
@Parameter(defaultValue = "${project.name}")
private String name;
/**
* The value used for the {@code build.time} property in a form suitable for
* {@link Instant#parse(CharSequence)}. Defaults to
@ -88,8 +119,8 @@ public class BuildInfoMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
ProjectDetails details = new ProjectDetails(this.project.getGroupId(), this.project.getArtifactId(),
this.project.getVersion(), this.project.getName(), getBuildTime(), this.additionalProperties);
ProjectDetails details = new ProjectDetails(getGroup(), getArtifact(), getVersion(), getName(),
getBuildTime(), this.additionalProperties);
new BuildPropertiesWriter(this.outputFile).writeBuildProperties(details);
this.buildContext.refresh(this.outputFile);
}
@ -101,6 +132,34 @@ public class BuildInfoMojo extends AbstractMojo {
}
}
private String getGroup() {
if ("off".equalsIgnoreCase(this.group)) {
return null;
}
return this.group;
}
private String getArtifact() {
if ("off".equalsIgnoreCase(this.artifact)) {
return null;
}
return this.artifact;
}
private String getVersion() {
if ("off".equalsIgnoreCase(this.version)) {
return null;
}
return this.version;
}
private String getName() {
if ("off".equalsIgnoreCase(this.name)) {
return null;
}
return this.name;
}
private Instant getBuildTime() {
if (this.time == null || this.time.isEmpty()) {
Date startTime = this.session.getRequest().getStartTime();