Read versionName of build.gradle from Jenkins
Asked Answered
C

3

12

I'm using Jenkins for my Android app builds. On every build, I get some info, like build number, etc...

I'm searching a way to read the versionName value of in the build.gradle when Jenkins build the job. I know we can get the buildNumber with the $BUILD_NUMBERenv variable, but how to get the versionName?

Cleghorn answered 5/11, 2016 at 19:59 Comment(0)
H
8

You could do this by adding an Execute Shell step which determines the versionName, and exporting it as an environment variable using the EnvInject Plugin.

Assuming your build.gradle contains:

versionName = myname

You can add this script:

v=$(cat build.gradle  | grep versionName | awk '{print $3}')
echo MY_VERSION_NAME=${v} > env.properties
Hoashis answered 20/4, 2017 at 11:8 Comment(5)
Yeah, really great!. What's the trick if I just wanna get the version which is between "". For example versionName = "1.0.0", just wanna 1.0.0Cleghorn
@Cleghorn you can simply delete the " characters using tr: v=$(cat build.gradle | grep versionName | awk '{print $3}' | tr -d \" )Hoashis
Perfect! Thanks!Cleghorn
Shouldn't this be '{print $2}' since we're trying to print the version name which is the second part of the string. Kinda like versionName "3.0.0"Ausgleich
In my build.gradle there is = between variable and value.Hoashis
G
7

A better way to do this is add a "printVersion" task in build.gradle. app/build.gradle

task printVersion{
  doLast {
    print android.defaultConfig.versionName + '-' + android.defaultConfig.versionCode
  }
}

Test it with: ./gradlew -q printVersion

1.8-13

Then in jenkins pipeline, add a stage after git:

   stage('printVersion') {
        def versionInfo = sh (
            script: './gradlew -q printVersion',
            returnStdout: true
        ).trim()
        echo "VersionInfo: ${versionInfo}"
//set the current build to versionInfo plus build number.
        currentBuild.displayName = "${versionInfo}-${currentBuild.number}" ; 
   }
Gust answered 27/6, 2018 at 16:2 Comment(0)
D
2

Example: gradle properties | grep "version" | awk '{print $2}'

On jenkins:

def versionInfo = sh (
  script: "gradle properties | grep 'version' | awk '{print $2}'",
  returnStdout: true
).trim()
println versionInfo
Delaminate answered 1/4, 2020 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.