TL;DR: If you can, use ext {} with constants (hash). You can do call pointer things too!

In the past days I've been trying to add some functionality to my Gradle build file so the version would be determined from the git tag. I've found this excellent entry showing how to get the actual string. My code ended up being like this:

// versions.gradle

def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}
def getVersionBaseName = { ->
    String result = getVersionName()
    String version = result.split('\\-')[0]
    if (!version)
        version = result
    return version
}

Long build file

The problem I have is that with every custom thing, the build file increases. Then, finding an error of a particular thing becomes more and more difficult. So, I've been looking for a way to modularise the build system and I found something.

My versions.gradle looks like this now:

def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}
def getVersionBaseName = { ->
    String result = getVersionName()
    String version = result.split('\\-')[0]
    if (!version)
        version = result
    return version
}

ext{
    VERConsts = [:]
    // a call result
    VERConsts['NAME'] = getVersionName()
    // a function call
    VERConsts['NAME_CALL'] = getVersionName
    VERConsts['BASE_NAME'] = getVersionBaseName()
}

Then, in my build.gradle I can use:

apply from: './versions.gradle'

// ...

android {
    // ...
    defaultConfig {
        applicationId project.GROUP + ".fallpaper"
        minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
        targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
        versionCode 1
        versionName VERConsts['NAME'] + " (b" + VERConsts['COUNT'] + ")"
    }
}

// ...

See how it uses VERConsts[] hash. Using the VERConsts['NAME_CALL']() will do the same.

I guess this doesn't work every time, but if you can manage to call your functions etc. in their own file (like calling getVersionName() in versions.gradle), you can place the result in a hash and export it :)

HTH,