11

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?

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
ejay
  • 1,114
  • 3
  • 14
  • 26

3 Answers3

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
sgargel
  • 986
  • 2
  • 11
  • 29
  • 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.0 – ejay May 23 '17 at 15:40
  • 2
    @ejay you can simply delete the `"` characters using **tr**: `v=$(cat build.gradle | grep versionName | awk '{print $3}' | tr -d \" )` – sgargel May 23 '17 at 16:06
  • Perfect! Thanks! – ejay May 23 '17 at 19:35
  • 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"` – 11m0 Mar 23 '18 at 04:44
  • In my `build.gradle` there is `=` between variable and value. – sgargel Mar 23 '18 at 06:41
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}" ; 
   }
closure
  • 123
  • 2
  • 6
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