6

I would like to access versionCode and versionName in defaultConfig from a gradle task. I am using the experimental gradle plugin. I tried model.android.defaultConfig.versionCode but it doesn't recognise android...

apply plugin: 'com.android.model.application'

apply from: "../config.gradle"
apply from: "../gitversion.gradle"
def config = ext.configuration

model {
    android {
        compileSdkVersion = config.compileSdkVersion
        buildToolsVersion = config.buildToolsVersion

        defaultConfig {
            applicationId = 'eu.tss.apitest'
            minSdkVersion.apiLevel = config.minimumSdkVersion
            targetSdkVersion.apiLevel = config.targetSdkVersion
            defaultConfig {

            versionCode = 1
            versionName = '1.0'
            ext.printVersions(versionCode,versionName)
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles.add(file('proguard-android.txt'))
            }
        }

    }
   android.lintOptions {

        abortOnError false
    }
}

dependencies {
    println rootProject.getName()
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile project(':tssapiandroid')
    compile project(path: ':tssuielements')
}

task printVersions{

    //I would like to access versionCode here:)
}
emKaroly
  • 756
  • 1
  • 10
  • 22

1 Answers1

11

Create method in your build.gradle:

def getVersionCode = { ->
    // calculate versionCode code or use hardcoded value
    return 1
}

Use this method in defaultConfig:

android {
    defaultConfig {
        versionCode getVersionCode()
    }
}

Use the same method in your custom task:

task printVersions{
    print "Version code is " + getVersionCode()
}

Alternative solution is to access versionCode property directly:

task printVersions{
    print "Version code is $project.android.defaultConfig.versionCode"
}
Veaceslav Gaidarji
  • 4,261
  • 3
  • 38
  • 61
  • I want to access what is actually in android.defaultConfig.versionCode from that printVersion task. – emKaroly Dec 01 '16 at 09:58
  • check "alternative solution" in this case. – Veaceslav Gaidarji Dec 01 '16 at 10:35
  • Doesn't work i get: Error:(65, 0) Could not get unknown property 'android' for project ':app' of type org.gradle.api.Project. I am using experimental plugin so there is model before android but projeect.model.android.defaultConfig.versionCode not working either. – emKaroly Dec 01 '16 at 11:11
  • I've investigated a lot with experimental plugin (0.9.0-alpha2), but have no solution yet. – Veaceslav Gaidarji Dec 01 '16 at 15:37
  • I do that whole day:) I asked how to migrate to stable gradle but i got just few down votes... – emKaroly Dec 01 '16 at 15:43