【Maven 插件】为 jar 包添加代码版本信息 —— git-commit-id-plugin

背景

在软件包中添加代码版本信息是许多组织使用的管理技巧。

这些信息在很多场景中可以发挥重要作用。

对于一些尚处于混沌状态的萌芽组织来说,这些信息几乎可以在排障过程中发挥灯塔的作用。

组织管理不善会引发很多“人祸”。

软件包覆盖版本发布?代码分支管理方法混乱?代码 tag 覆盖打?系统出了问题,不知道软件包是哪个分支、哪次提交构建的?

一个真实的项目

该项目基于 git 管理代码版本。

之前一直是通过自研的 CI 系统构建;

此 CI 系统会自动获取当前所构建代码的 git 信息,写入文件,添加到最终构建出的软件包中。

后来因为某些外部非技术原因,需要在另一套系统中构建软件包。

为了让最终的软件包包含相关 git 信息,就使用了 Maven 插件 git-commit-id-plugin。

快速使用 git-commit-id-plugin

此 Maven 插件可以从代码目录中的 .git 目录获取相关信息,写入文件。

该文件可以在Maven打包(package)过程中被包含到 jar 包内。

为了方便获取信息,我们可以开放一个接口来呈现此信息文件中的内容。如,一个 HTTP API。

配置 git-commit-id-plugin

在工程的 POM 文件中添加对此插件的引用,并添加一些自定义的配置。

(通常是在程序入口所在 jar包 的 POM 中配置。)

以下示例只是一种常用的快速配置样例,它使用了很多默认值。

如:生成的 git 信息文件路径为:${project.build.outputDirectory}/git.properties

可参考官方文档实现自定义配置。

Xml代码

 

  1. <project>  

  2.   ...  

  3.   <build>  

  4.     ...  

  5.     <plugins>  

  6.       ...  

  7.       <plugin>  

  8.         <groupId>pl.project13.maven</groupId>  

  9.         <artifactId>git-commit-id-plugin</artifactId>  

  10.         <version>3.0.1</version>  

  11.         <configuration>  

  12.           <generateGitPropertiesFile>true</generateGitPropertiesFile>  

  13.           <includeOnlyProperties>  

  14.             <includeOnlyProperty>^git.branch$</includeOnlyProperty>  

  15.             <includeOnlyProperty>^git.commit.id$</includeOnlyProperty>  

  16.             <includeOnlyProperty>^git.dirty$</includeOnlyProperty>  

  17.             <includeOnlyProperty>^git.build.time$</includeOnlyProperty>  

  18.           </includeOnlyProperties>  

  19.         </configuration>  

  20.       </plugin>  

  21.     </plugins>  

  22.   </build>  

  23. </project>  

添加信息获取接口

上述软件包中的 git 信息获取/发布方式可以有多种实现方案。此处仅提供一种常见的 HTTP API 方式:

Java代码

 

  1. @RestController  

  2. public class InfoController {  

  3.   @GetMapping("/git_info")  

  4.   public String getGitInfo() throws Exception {  

  5.     // 直接将 git 信息文件的内容返回给客户端  

  6.     return IOUtils.toString(new URI("classpath:git.properties"), StandardCharsets.UTF_8);  

  7.   }  

  8. }  

发布了228 篇原创文章 · 获赞 3 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/hchaoh/article/details/103907827