实例
buid.gradle文件如下
import org.yaml.snakeyaml.Yaml
/*
* This file was generated by the Gradle 'init' task.
*/
buildscript {
repositories {
jcenter()
}
dependencies {
classpath group: 'org.yaml', name: 'snakeyaml', version: '1.19'
}
}
plugins {
id 'java'
id 'war'
}
apply plugin:'org.hidetake.ssh'
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:2.3.1.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.3.1.RELEASE'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.1'
}
group = 'com.hongshi'
version = '0.0.1-SNAPSHOT'
description = 'hs-device-platform'
sourceCompatibility = '1.8'
war {
archiveName 'hs-device-platform.war'
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
//获取git版本号信息
def static getGitCommitVersion() {
return gitCommit = 'git log --pretty=format:%h -1'.execute().text.trim()
}
//获取git时间
def static getGitCommitTime(){
return 'git log --pretty=format:“%cd” HEAD -1'.execute().text.trim()
}
/**
更多信息
%H 提交对象(commit)的完整哈希字串
%h 提交对象的简短哈希字串
%T 树对象(tree)的完整哈希字串
%t 树对象的简短哈希字串
%P 父对象(parent)的完整哈希字串
%p 父对象的简短哈希字串
%an 作者(author)的名字
%ae 作者的电子邮件地址
%ad 作者修订日期(可以用 -date= 选项定制格式)
%ar 作者修订日期,按多久以前的方式显示
%cn 提交者(committer)的名字
%ce 提交者的电子邮件地址
%cd 提交日期
%cr 提交日期,按多久以前的方式显示
%s 提交说明
*/
//获取当前时间
static def packageTime() {
return new Date().format("yyyy-MM-dd HH:mm", TimeZone.getTimeZone("GMT+08:00"))
}
task updateYml{
doLast {
//获取yml文件
Map<String,Map<String, String>> resmap = new Yaml().load( new File("${rootDir}/build/resources/main/application-appconfig.yml").newInputStream() )
def gitVersion = getGitCommitVersion()
def version = resmap.get("hs-device-platform").get("version")
resmap.get("hs-device-platform").put("version", version + "." + gitVersion)
resmap.get("hs-device-platform").put("package-time", packageTime())
//写入版本信息
Yaml wyaml = new Yaml();
File dumpfile = new File("${rootDir}/build/resources/main/application-appconfig.yml")
FileWriter writer = new FileWriter(dumpfile)
wyaml.dump(resmap, writer)
}
}
//classes任务执行完之后修改yml文件
classes.finalizedBy(readYml)
效果
完成后的yml文件如下
hs-device-platform:
version: 1.0.0
package-time: 2020-10-20 09:10
后记
实现此功能主要是利用任务,在编译完成后 - 打成war包前:修改即将要打进war包的yml文件;仅此而已,但是很实用!maven中见git-generator (应该是这个名字吧)目测上也是这个原理。