iTranslated by AI
Embedding Git Tags and Hashes as Version Information (Gradle)
This article describes how to embed Git tag and hash information as version info in a Java Gradle project.
The versions used for verification are as follows:
- Java 8
- Gradle 7.3.2
The project used for verification is available here:
Information to Embed
To make it clear under what state the artifact was generated, we will configure it as follows:
-
versionproperty (used for the JAR filename or as a library version):
Based on Git tag information.- If the tag is
v1.1.2, it becomes1.1.2. - If the tag is
v1.0.0-beta1, it becomes1.0.0-beta1. (It is fine to include the-beta1suffix.)
- If the tag is
-
Implementation-VersioninMETA-INF/MANIFEST.MF:
Append the Git tag plus the commit hash value.- If the tag is
v1.1.2, append the hash (8 digits) to make it1.1.2.f15325d3. - If the tag is
v1.0.0-beta1, it becomes1.1.2-beta1.f15325d3.
- If the tag is
com.palantir.git-version Plugin
We use the com.palantir.git-version plugin to retrieve various Git information.
This plugin allows you to obtain information similar to git describe --tags --always --first-parent.
build.gradle Configuration
The configuration details for build.gradle are described below.
For the complete file, please refer to the following:
Adding the Plugin
Specify com.palantir.git-version as the plugin to be used.
plugins {
id 'java'
id 'com.palantir.git-version' version '0.12.3'
}
Configuring version Property and Implementation-Version
Set the Gradle version property based on the tag information.
Also, set the Implementation-Version in META-INF/MANIFEST.MF with the tag and hash information.
def gitInfo = versionDetails()
version = gitInfo.lastTag.substring(1)
def implementationVersion = version + '.' + gitInfo.gitHash[0..7]
jar {
manifest {
attributes(
'Implementation-Version' : implementationVersion
)
}
}
This completes the configuration.
(Bonus) Retrieving Implementation-Version Information Programmatically
The Implementation-Version in META-INF/MANIFEST.MF can be retrieved programmatically.
package com.github.onozaty.embed;
public class Main {
public static void main(String[] args) {
String implementationVersion = getImplementationVersion();
System.out.println("implementationVersion: " + implementationVersion);
}
private static String getImplementationVersion() {
return Main.class.getPackage().getImplementationVersion();
}
}
Including this in the logs at application startup makes it easier to identify which version the application was running when the logs were generated.
Incidentally, Spring Boot reads the Implementation-Version information at startup and outputs it in the startup logs.
2022-01-07 00:10:11.145 INFO 11772 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication v1.0.0-beta1.86ea7f27 using Java 1.8.0_222 on PCXX with PID 11772 (F:\demo\demo-1.0.0-beta1.jar started by onozaty in F:\demo)
Discussion