Gradle打包构建携带版本等信息的Jar包原创
942次浏览
编辑于2023年03月07日 16:28:28
随着产品开发的不断迭代和产品应用的范围越来越广,不光要在源码的版本管理上下功夫,也要确保给客户的部署版本随时可追溯。Jar包携带版本等信息是十分必要的。可以利用Gradle构建工具的便利,来完成这一功能。
Gradle的基础知识参考 实战Gradle 这本书,当然也可以参考 吴锐雄:Gradle使用教程 (强烈推荐),如果在初步构建工程上有疑问,移步如何构建一个苍穹Gradle工程
实现上述功能的代码我写在下面了,大家可以参考
group 'kd.cosmic' version '1.0-SNAPSHOT' apply plugin: 'java' apply from: "config.gradle" def trd = ext.path.trd def biz = ext.path.biz def bos = ext.path.bos def cus = ext.path.cus def outputDir = './out' def artifactDir = '/artifacts' def jarPackage = '/package' # 打包时间 static def releaseTime() { return new Date().format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("GMT+08:00")) } # GIT版本号 git rev-parse --short HEAD 获取短版本号 static def getGitSHA() { return 'git rev-parse HEAD'.execute().text.trim() } # GIT分支 static def getGitBranch() { return 'git rev-parse --abbrev-ref HEAD'.execute().text.trim() } # GIT用户 static def getGitUser() { return 'git config user.name'.execute().text.trim() } sourceCompatibility = 1.8 subprojects { apply plugin: 'java' dependencies { compile fileTree(dir: bos, include: '*.jar') compile fileTree(dir: trd, include: '*.jar') compile fileTree(dir: biz, include: '*.jar') compile fileTree(dir: cus, include: '*.jar') } sourceSets { main { java.srcDirs = ["src/main/java"] resources.srcDirs = ['src/main/resources'] } } tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } # 打包指令,必须依赖于build等指令,否则不会进行java文件和资源文件的编译 task makeJar (type: Jar, dependsOn: build, compileJava, processResources) { archiveName project.name + ".jar" from ([sourceSets.main.output.classesDir, sourceSets.main.output.resourcesDir]) destinationDir = file('build/libs') # 通过清单文件记录相关信息 manifest { attributes( 'JarName': project.name, 'User': getGitUser(), 'Branch': getGitBranch(), 'CommitId': getGitSHA(), 'BuildDate': releaseTime() ) } ext.deleteDirFiles = {File file -> if(file.isDirectory()) { file.listFiles().each { subFile -> deleteDirFiles(subFile) } } else { if (file.name.endsWith(".jar")){ file.delete() } } } doFirst { if (!project.getBuildDir().exists()){ project.getBuildDir().mkdirs() } file(project.getBuildDir().path).listFiles().each { buildFile -> if(buildFile.isDirectory()){ deleteDirFiles(buildFile) } else { buildFile.delete() } } # 也可以生成资源文件,供jar包直接获取 def filePath = "src/main/resources/jar.properties" def resourceFile = file(filePath) if (resourceFile.exists()) { resourceFile.delete() } else { if (!resourceFile.getParentFile().exists()) { resourceFile.getParentFile().mkdir() } resourceFile.createNewFile() } resourceFile.withWriter { BufferedWriter writer -> def jarStatus = "JarName: " + project.name + "\nUser: " + getGitUser() + "\nBranch: " + getGitBranch() + "\nCommitId: " + getGitSHA() + "\nBuildDate: " + releaseTime() writer.append(jarStatus) } } } } project.beforeEvaluate { } project.afterEvaluate { } tasks.withType(JavaCompile) { options.encoding = 'UTF-8' } # 在root project执行所有子module的打包指令 task makeJar { doFirst { project.childProjects.each { name, cp -> cp.tasks.withType(Jar).matching { task -> task.name.equals('makeJar') }.each { task -> task.execute() } } } doLast { } } clean { doFirst { project.childProjects.each { name, cp -> delete cp.buildDir } } doLast { } } # 压缩指定文件夹下的所有JAR包为一个压缩包 task zipJar (type: Zip) { doFirst { file("out").listFiles().each { buildFile -> if(!buildFile.isDirectory()){ buildFile.delete() } } } archiveName project.name + '.zip' destinationDir file(outputDir + artifactDir) into("/") { from outputDir + artifactDir + jarPackage include '*.jar' } } # 复制编译好的JAR包到指定的目录 task copyJar (type: Copy) { doFirst { File outFile = file(outputDir + artifactDir + jarPackage) if (!outFile.exists()) { outFile.mkdirs() } else { outFile.listFiles().each { file -> file.delete() } } } doLast { } project.childProjects.each { name, cp -> from fileTree(dir: cp.getBuildDir().path).filter { subFile -> !subFile.isDirectory() } from cp.getBuildDir().path.replace(project.rootDir.path, '.') into outputDir + artifactDir + jarPackage include "**/*.jar" exclude { FileTreeElement detail -> detail.isDirectory() } rename(name + '.+jar', name + ".jar") } file(outputDir).listFiles().each { file -> file.delete() } } zipJar.dependsOn (copyJar) copyJar.dependsOn (makeJar) //makeJar.dependsOn (compileJava, processResources)
最后在project下执行gradle -> other -> zipJar即可