Home > other >  In Gradle, how can I append Jenkins build number to artifact version in a Jenkins pipeline?
In Gradle, how can I append Jenkins build number to artifact version in a Jenkins pipeline?

Time:01-30

Gradle v7.3.3

In my gradle.properties file, I have the artifact version set to 2.0

gradle.properties
-----------------

version=2.0

Now when I do a Jenkins build, I want to append the build number to that version, and publish the subsequent artifact. That is, I want the artifact to be

com.company.com:myproject:2.0.<build_number>

I tried

sh "./gradlew :myproject:clean :myproject:build -x test -PartifactBuildNumber=$env.BUILD_NUMBER -p myproject"
sh "./gradlew publish -x build -x test -PartifactBuildNumber=$env.BUILD_NUMBER -p myproject"

But of course that only has the Jenkins build number in the artifact version, instead of the desired 2.0.<BUILD_NUMBER>. Is there an elegant way to do this

CodePudding user response:

You have two easy options to achieve what you want:
First options is to read the gradle.properties (using readProperties), into a local map in your pipeline, update the version to the new value, and write back the file.
For example:

// Read the properties file and update the version
def props = readProperties file: 'gradle.properties'
props.version = "${props.version}.${env.BUILD_NUMBER}"

// Write back the updated properties file
def content = props.collect{ "${it.key}=${it.value}".join('\n')
writeFile file: 'gradle.properties', text: content

// Run your commands

You can now run all you regular shell commands and the updated version will be used.

The second option is to read the gradle.properties, extract the version from it and construct a new version variable in your pipeline that will be passed to the shell commands.
For example:

// Read the properties file and update the version
def props = readProperties file: 'gradle.properties'
def newVersion =  "${props.version}.${env.BUILD_NUMBER}"

// Use the newVersion parameter in your shell steps
sh "./gradlew :myproject:clean :myproject:build -x test -PartifactBuildNumber=${newVersion} -p myproject"
sh "./gradlew publish -x build -x test -PartifactBuildNumber=${newVersion} -p myproject"

If you have other steps that relay on the version for which you cannot pass the updated version, than the first option will probably suite you well, however if you can pass the version, the second option is easier and doesn't require any tempering with files.

  •  Tags:  
  • Related