如何从Gradle读取应用版本、实现版本自增并将变更推送至代码仓库
实现方案:Gradle版本自动递增+变更推回代码仓库
前置准备(Gradle侧配置)
建议把版本号独立存放在gradle.properties文件中,方便直接修改,文件内容示例:
version=1.0.0 name=your-app-name
之后在build.gradle中添加版本递增任务,下方示例默认递增补丁版本(版本号第三位),你可以按需调整递增规则:
task incrementVersion { doLast { def versionFile = file('gradle.properties') def versionPattern = /version=(\d+)\.(\d+)\.(\d+)/ def content = versionFile.text def matcher = (content =~ versionPattern) if (matcher.find()) { def major = matcher[0][1] as int def minor = matcher[0][2] as int def patch = matcher[0][3] as int // 要递增次版本就修改为minor +=1、patch=0,递增主版本同理调整 patch += 1 def newVersion = "${major}.${minor}.${patch}" content = content.replaceAll(versionPattern, "version=${newVersion}") versionFile.write(content) // 输出新版本号供Jenkins读取 println newVersion } else { throw new GradleException("未找到合法的版本号格式") } } }
Jenkinsfile修改方案
先确认Jenkins配置了拥有代码仓库写入权限的Git凭证,修改后的完整Jenkinsfile如下:
pipeline { agent any stages { stage("拉取最新代码") { steps { // 拉取最新代码避免提交冲突 git branch: 'main', credentialsId: 'git-repo-credentials', url: '你的代码仓库地址' // 配置Git提交人信息 sh 'git config user.name "jenkins-bot"' sh 'git config user.email "jenkins@your-domain.com"' } } stage("递增版本号") { steps { script { // 执行Gradle递增版本任务,读取新版本号 newBuildVersion = sh(returnStdout: true, script: './gradlew -q incrementVersion').trim() // 读取应用名 buildName = sh(returnStdout: true, script: './gradlew -q properties | grep name: | awk \'{print $2}\'').trim() } } } stage("构建应用") { steps { sh './gradlew clean build -x test' } } stage("构建并推送Docker镜像") { steps { script { echo 'building the docker image' withCredentials([ usernamePassword(credentialsId: 'docker-hub-repo', usernameVariable: 'USER', passwordVariable: 'PASSWORD') ]) { sh "docker build -t somename/${buildName}:${newBuildVersion} ." sh "echo $PASSWORD | docker login -u $USER --password-stdin" sh "docker push somename/${buildName}:${newBuildVersion}" } } } } stage("推送版本变更到代码仓库") { steps { withCredentials([ usernamePassword(credentialsId: 'git-repo-credentials', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PWD') ]) { // 提交版本变更,[ci skip]标识避免触发重复构建 sh 'git add gradle.properties' sh 'git commit -m "chore: 自动递增版本号到${newBuildVersion} [ci skip]"' // HTTPS仓库推送示例,SSH协议仓库直接执行git push origin main即可 sh "git push https://${GIT_USER}:${GIT_PWD}@去掉https前缀的代码仓库地址 main" } } } } }
注意事项
- 把代码中的占位符(仓库地址、凭证ID)替换为你实际的配置
- 版本号递增规则可以通过修改Gradle的
incrementVersion任务自定义 - 如果使用SSH协议拉取代码,只要Jenkins的SSH凭证有推送权限,不需要在push地址中携带账号密码
[ci skip]是主流CI系统通用的跳过构建标识,避免版本提交触发新的流水线导致死循环
内容的提问来源于stack exchange,提问作者Carlos Gonzalez
相关产品推荐
相关产品推荐

