---
title: "【Maven 插件】为 jar 包添加代码版本信息 —— git-commit-id-plugin"
author: "草料场"
date: "2019-09-04T13:44:03Z"
tags: []
categories: ["开源软件"]
slug: "maven-jar-git-commit-id-plugin"
draft: false
lastmod: "2019-09-05T14:09:19Z"
id: 2444086
url: "https://pre.iteye.com/blog/2444086"
---

# 背景

在软件包中添加代码版本信息是许多组织使用的管理技巧。  
这些信息在很多场景中可以发挥重要作用。  
对于一些尚处于混沌状态的萌芽组织来说，这些信息几乎可以在排障过程中发挥灯塔的作用。  
 

组织管理不善会引发很多“人祸”。  
软件包覆盖版本发布？代码分支管理方法混乱？代码 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**  
可参考[官方文档](https://github.com/git-commit-id/maven-git-commit-id-plugin/blob/master/docs/using-the-plugin.md)实现自定义配置。  
 

```
<project>
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>pl.project13.maven</groupId>
        <artifactId>git-commit-id-plugin</artifactId>
        <version>3.0.1</version>
        <configuration>
          <generateGitPropertiesFile>true</generateGitPropertiesFile>
          <includeOnlyProperties>
            <includeOnlyProperty>^git.branch$</includeOnlyProperty>
            <includeOnlyProperty>^git.commit.id$</includeOnlyProperty>
            <includeOnlyProperty>^git.dirty$</includeOnlyProperty>
            <includeOnlyProperty>^git.build.time$</includeOnlyProperty>
          </includeOnlyProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
```

 

## 添加信息获取接口

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

```
@RestController
public class InfoController {
  @GetMapping("/git_info")
  public String getGitInfo() throws Exception {
    // 直接将 git 信息文件的内容返回给客户端
    return IOUtils.toString(new URI("classpath:git.properties"), StandardCharsets.UTF_8);
  }
}
```