Spring Boot 使用Maven git-commit-id插件

场景分析: 现在我们想知道线上运行的应用程序jar包是属于哪个版本分支的代码, 且具体到这个jar包的代码最后一次提交的commitId是?

硬编码方式

@Slf4j
@RestController
public class VersionController {

    @GetMapping("/version")
    public String versionInformation() {
		return "dev_1.1-30f7304c03d0567c23e6a636fa40d786629d0d18";
    }
}

这种方式的弊端: 每次部署的时候都要手动修改版本信息。

 

使用git-commit-id方式

pom引入插件

<plugin>
    <groupId>pl.project13.mavengroupId>
    <artifactId>git-commit-id-pluginartifactId>
    <version>2.2.4version>
    <executions>
        <execution>
            <id>get-the-git-infosid>
            <goals>
                <goal>revisiongoal>
            goals>
        execution>
    executions>
    <configuration>
        <dotGitDirectory>${project.basedir}/.gitdotGitDirectory>
        <prefix>gitprefix>
        <verbose>trueverbose>
        <dateFormat>yyyy-MM-dd'T'HH:mm:ssZdateFormat>
        
        <generateGitPropertiesFile>truegenerateGitPropertiesFile>
        
        <generateGitPropertiesFilename>${project.build.outputDirectory}/git.propertiesgenerateGitPropertiesFilename>
        <format>jsonformat>
        
        <gitDescribe>
            
            <skip>falseskip>
            
            <always>falsealways>
            
        	<abbrev>7abbrev>
            
            <dirty>-dirtydirty>
        gitDescribe>
    configuration>
plugin>
  • target/classes下生成git.properties文件
  • target\***.jar\BOOT-INF\classes下生成git.properties文件

 

读取git.properties版本信息文件

@Slf4j
@RestController
public class VersionController {

    @GetMapping("/version")
    public String versionInformation() {
        return readGitProperties();
    }

    private String readGitProperties() {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("git.properties");
        try {
            return readFromInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return "Version information could not be retrieved.";
        }
    }

    private String readFromInputStream(InputStream inputStream)
            throws IOException {
        StringBuilder result = new StringBuilder();
        try (
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8.name()))
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line).append(System.lineSeparator());
            }
        }
        return result.toString();
    }

}

 

@Slf4j
@RestController
public class VersionController {

    @Value("classpath:git.json")
    private Resource gitJson;

    @GetMapping("/version")
    public String versionInformation() {
        try {
            return IOUtils.toString(
                    gitJson.getInputStream(), StandardCharsets.UTF_8.name()
            );
        } catch (IOException ex) {
            log.error("读取文件异常", ex);
            return "Version information could not be retrieved.";
        }
    }

}

使用Maven git-commit-id插件,版本信息可以随时检索并始终保持最新,无需每次都手动去修改版本信息。

 

插件目标、参数

  • git-commit-id:revision:将构建时的信息保存到指定文件中或maven的属性中,默认绑定生命周期的阶段(phase):initialize
  • git-commit-id:validateRevision:校验属性是否符合预期值,默认绑定阶段:verify

 

git-commit-id:revision目标

将构建时的信息保存到指定文件中或maven的属性中,默认绑定生命周期的阶段(phase):initialize

相关参数如下:

参数 默认值 描述
abbrevLength 7 git.commit.id.abbrev属性的长度,取值范围在[2, 40],即打印的object id的长度
commitIdGenerationMode flat git.commit.id属性的生成模式,可选值:flat、full
dateFormat yyyy-MM-dd’T’HH:mm:ssZ 定义这个插件的使用日期的格式
dateFormatTimeZone 定义日期时区,如:America/Los_Angeles、GMT+10、PST
dotGitDirectory ${project.basedir}/.git 需要检查的仓库根目录
evaluateOnCommit HEAD 告诉插件生成属性参考哪次提交
failOnNoGitDirectory true 没有 .git 目录时则构建失败,false:继续构建
failOnUnableToExtractRepoInfo true 获取不到足够数据则构建失败,false:继续构建
format properties 保存属性的格式:properties 或 json
generateGitPropertiesFile false true:生成git.properties文件,默认只是将属性添加到maven项目属性中
generateGitPropertiesFilename ${project.build.outputDirectory}/git.properties) git.properties文件的位置,在generateGitPropertiesFile=true时有效
gitDescribe 配置git-describe命令,可以修改dirty标志、abbrev长度、其他可选项
excludeProperties 需要隐藏的属性列表,如:仓库地址git.remote.origin.url、用户信息git.commit.user.*
includeOnlyProperties 需要保存到文件中的属性列表,该列表会被excludeProperties属性配置的值覆盖
injectAllReactorProjects false true:将git属性注入所有项目
prefix git 属性的前缀,如生成的属性都是:git.xxx
replacementProperties 在生成的git属性中通过表达式替换字符或字符串
runOnlyOnce false true:在多模块构建中只执行一次
skip false true:跳过插件执行
skipPoms true false:执行以pom方式打包的项目
skipViaCommandLine false true:通过命令行方式跳过插件执行,属性:maven.gitcommitid.skip
useNativeGit false true:使用原生git去获取仓库信息
verbose false true:扫描路径时打印更多信息

 

git-commit-id:validateRevision目标

校验属性是否符合预期值,默认绑定阶段:verify

相关参数如下:

参数 默认值 描述
validationProperties 需要校验的属性
validationShouldFailIfNoMatch true true:不匹配时则构建失败

 

总结

在Maven的git的承诺ID插件是必不可少的,应该被添加到每个Maven项目。它会在构建期间自动创建版本信息,以便在部署应用程序时验证版本信息。不再讨论在环境中运行软件的哪个版本。

 

References

  • Spring Boot 2.0 使用Maven git-commit-id插件
  • Maven构建生成的文件加上commit-id
  • Maven学习笔记 - git-commit-id-plugin插件

你可能感兴趣的:(Maven,Git)