Read android's versionName from build.gradle in Jenkins pipeline
Asked Answered
J

1

7

I have a (Windows) Jenkins pipeline for my Android project and I'm trying to get the versionName defined in build.gradle file. According to https://mcmap.net/q/928972/-read-versionname-of-build-gradle-from-jenkins and https://mcmap.net/q/542492/-read-versionname-from-build-gradle-in-bash I have the setup below:

build.gradle

android {
  defaultConfig {
    versionCode 71
    versionName "2.3.0.Beta10"
  }
}

task versionName{
  doLast {
    println android.defaultConfig.versionName
  }
}

Jenkinsfile

pipeline {
  environment {
    SERVER_PATH = '\\\\ARK_SRV\\Android\\'
  }
  agent any

  stages {

    stage('Create Directory') {
      steps {
        script {
          def VERSION_NAME = bat (script: "./gradlew -q versionName", returnStdout: true).trim()
          echo "Version Name: ${VERSION_NAME}"
          def FINAL_DIR = SERVER_PATH + VERSION_NAME
          echo "Final Directoy: ${FINAL_DIR}"
          // ...
        }
      }
    }

  }

}

However I'm getting both the whole batch command and its output into VERSION_NAME variable, so the printouts look like this:

Actual Values

Version Name: C:\Program Files (x86)\Jenkins\workspace\AndroidTest>./gradlew -q versionName 
2.3.0.Beta10

Final Directoy: \\ARK_SRV\Android\C:\Program Files (x86)\Jenkins\workspace\AndroidTest>./gradlew -q versionName 
2.3.0.Beta10

Expected Values

Version Name: 2.3.0.Beta10

Final Directoy: \\ARK_SRV\Android\2.3.0.Beta10

What am I doing wrong? Is there a better way to retrieve defaultConfig values from my build.gradle?

Judithjuditha answered 20/12, 2018 at 16:40 Comment(0)
B
5

you can split the output and take the required portion of the output in your case you can try below lines:

def output = bat (script: "./gradlew -q versionName", returnStdout: true).trim()
def  VERSION_NAME = output.split('\n')[1]
echo "Version Name: ${VERSION_NAME}"
Beaux answered 21/12, 2018 at 6:39 Comment(1)
This can also help in fetching the version detail from product flavours. Nice!Wanonah

© 2022 - 2024 — McMap. All rights reserved.