我们要在MANIFEST.MF
中插入当前的git commit哈希。不幸的是,我们不允许使用maven-git-commit-id-plugin
,因此我们采用了以下方法:
exec-maven-plugin
MANIFEST.MF
中的maven-jar-plugin
的同时读取属性但是,这无法正常工作。由于哈希显示的标签末尾为空白。它甚至没有我们开始时设置的默认值。
相关课程:
public class GetGitHash {
public static void main(String... args) {
String gitHash = "ZUFALL";
System.out.println("1. Git Hash: " + System.getProperty("githash"));
try{
ProcessBuilder pb = new ProcessBuilder("git", "rev-parse", "--short", "HEAD");
pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
gitHash = new BufferedReader(new InputStreamReader(p.getInputStream()))
.lines().collect(Collectors.joining(" "));
}
catch (Exception e){
e.printStackTrace();
}
finally {
System.setProperty("githash", gitHash);
}
System.out.println("2. Git Hash: " + System.getProperty("githash"));
}
}
pom文件中的maven-exec
配置:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<id>git-hash</id>
<configuration>
<mainClass>PACKAGE.GetGitHash</mainClass>
<systemProperties>
<systemProperty>
<key>githash</key>
<value>ZUFALL</value>
</systemProperty>
</systemProperties>
</configuration>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
</plugin>
pom文件中的jar插件配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
<manifestEntries>
<Library-Version>${project.version}</Library-Version>
<Build-Timestamp>${maven.build.timestamp}</Build-Timestamp>
<Build-ID>${githash}</Build-ID>
</manifestEntries>
</archive>
</configuration>
</plugin>
在控制台输出中,可以看到该属性已设置:
[INFO] --- exec-maven-plugin:1.6.0:java (git-hash) @ PROJECT ---
1. Git Hash: ZUFALL
2. Git Hash: 0003dfa9
但是MANIFEST
看起来像这样:
Manifest-Version: 1.0
Created-By: Apache Maven 3.3.9
Built-By: USER
Build-Jdk: 11
Build-ID:
Build-Timestamp: 2019-07-19T09:49:36Z
Library-Version: 0.9.2