5

More specifically I have a few build configs:

signingConfigs {
    debug {
        keyAlias ''
        keyPassword ''
        storeFile file('') 
    }
    release {
        keyAlias ''
        keyPassword ''
        storeFile file('')
        storePassword ''
    }
}
....
defaultConfig {
    applicationId ""
    minSdkVersion 21
    targetSdkVersion 23
    versionCode code
}

I want the gradle to autoincrement code version every time the 'release' is run.

What I have so far:

def code = 1;

//Get all the gradle task names being run
List<String> runTasks = gradle.startParameter.getTaskNames();

for (String item : runTasks) {

    //Get the version.properties file. Its our custom file for storing a code version, please don't remove it
    def versionPropsFile = file('version.properties')

    def Properties versionProps = new Properties()

    //This will prevent the gradle from exploding when there's no file yet created
    if (versionPropsFile.exists())
        versionProps.load(new FileInputStream(versionPropsFile))

    //It will insert the "0" version in case the file does not exist
    code = (versionProps['VERSION_CODE'] ?: "0").toInteger()

    if (item.contains("release")) {
        // If we're building up on Jenkins, increment the version strings
        code++

        versionProps['VERSION_CODE'] = code.toString()

        //It will overwrite the file even if it doesn't exist
        versionProps.store(versionPropsFile.newWriter(), null)
    }
}

The problem:

I can't seem to get inside if (item.contains("release")). Its always false but I definitely see that gradle runs this taks. How can I fix it or at least output in console all the tasks (their names) being run by gradle?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ross Stepaniak
  • 877
  • 1
  • 6
  • 22
  • 1
    is this a duplicate of http://stackoverflow.com/questions/23516090/android-studio-gradle-version-increment?rq=1 ? – k3b Feb 15 '16 at 12:35
  • @k3b thanks for pointing this. The accepted solution in this post doesn't work for me. Let me check once again. – Ross Stepaniak Feb 15 '16 at 12:40

4 Answers4

1

My implementation of this problem:

I have a version file which contains the version number. From this file we get the version. When the build contains the task "publishRelease" (it can be any other task) we increase the version in the version file. I like this sollution because it keeps the defaultConfig clean of coding logic.

The version.properties

VERSION_CODE=45

and in the android config part

 defaultConfig {
    applicationId "..."
    minSdkVersion 16
    targetSdkVersion 23
    versionCode getVersion()
    versionName "0.2." + versionCode
}

and the getVersion()

def getVersion() {
    def versionPropertiesFile = file('version.properties')
    def appVersion = -1;

    if (versionPropertiesFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropertiesFile))

        appVersion = versionProps['VERSION_CODE'].toInteger()

        def runTasks = gradle.startParameter.taskNames
        if ('publishRelease' in runTasks) {
            print("Increase version to " + appVersion + '\n')

            appVersion += 1

            versionProps['VERSION_CODE'] = appVersion.toString()
            versionProps.store(versionPropertiesFile.newWriter(), null)
        }

    } else {
        throw new GradleException("Could not read version.properties!")
    }

    return appVersion;
}
jbarat
  • 2,382
  • 21
  • 23
0

Try this. I use this in all my application and works fine.First, create a version.properties file in your /app/ folder. This file should look like below. Here VERSION_CODE indicates versionCode field in your app. This should be incremented always while VERSION_NAME indicates minor patch in your version name. (e.g. x.x.12).

/app/version.properties

VERSION_NAME=0      
VERSION_CODE=0

Then in your module level, build.Gradle file add following code in defaultConfig block. This will increment the version code and version name by 1 after every release build. (Basically, when assambleRelease gradle task executes. If you have different build type change task name according to your requirement.)

/app/build.gradle

//Version code increment
    def versionPropsFile = file('version.properties')
    if (versionPropsFile.canRead()) {
        //load the version.properties file
        def Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))

        /**
         * get the name of currently running task
         */
        def runTasks = gradle.startParameter.taskNames

        /**
         * Value to increment in minor version & version code.
         */
        def incrementCount = 0

        //Build version code and build type logic.
        if (':storeFinder:assembleRelease' in runTasks) {

            //if it is Production build package increment the version code by 1.
            incrementCount = 1;
        }

        //generate new version code
        def code = versionProps['VERSION_CODE'].toInteger() + incrementCount
        def minorPatch = versionProps['VERSION_NAME'].toInteger() + incrementCount

        //write new versionCode/version name suffix back to version.properties
        versionProps['VERSION_CODE'] = code.toString()
        versionProps['VERSION_NAME'] = minorPatch.toString()
        versionProps.store(versionPropsFile.newWriter(), null)

        //here version code is decided by above code.
        //noinspection GroovyAssignabilityCheck
        versionCode code
        versionName "1.0." + minorPatch;  //e.g. 1.0.61

    } else {
        //version.properties file not found.
        throw new GradleException("Could not read version.properties! Copy that to /app folder from version control.")
    }
Keval Patel
  • 592
  • 3
  • 13
0

I take following code from Plaid app from googler Nick Butcher It's really clean.

apply plugin: 'com.android.application'

// query git for the SHA, Tag and commit count. Use these to automate versioning.
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def gitTag = 'git describe --tags'.execute([], project.rootDir).text.trim()
def gitCommitCount = 100 + Integer.parseInt('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId 'net.hadifar.dope'
        minSdkVersion 14
        targetSdkVersion 23
        versionName gitTag
        versionCode gitCommitCount
        buildConfigField "String", "GIT_SHA", "\"${gitSha}\""

    }

    lintOptions {
        abortOnError false
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    buildTypes {
        release {
            minifyEnabled false
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {}
}
ext {
    supportLibVersion = '23.3.0'
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    compile "com.android.support:appcompat-v7:${supportLibVersion}"
}
Amir
  • 16,067
  • 10
  • 80
  • 119
  • This code not increase version by each release build. it increase with each commit. but you can modify to adopt your needs. – Amir May 04 '16 at 07:53
-2

git can helpful, follow this link: Automatic versioning and increment using Git tags and Gradle

android {
    defaultConfig {
    ...
        // Fetch the version according to git latest tag and "how far are we from last tag"
        def longVersionName = "git -C ${rootDir} describe --tags --long".execute().text.trim()
        def (fullVersionTag, versionBuild, gitSha) = longVersionName.tokenize('-')
        def(versionMajor, versionMinor, versionPatch) = fullVersionTag.tokenize('.')

        // Set the version name
        versionName "$versionMajor.$versionMinor.$versionPatch($versionBuild)"

        // Turn the version name into a version code
        versionCode versionMajor.toInteger() * 100000 +
                versionMinor.toInteger() * 10000 +
                versionPatch.toInteger() * 1000 +
                versionBuild.toInteger()

        // Friendly print the version output to the Gradle console
        printf("\n--------" + "VERSION DATA--------" + "\n" + "- CODE: " + versionCode + "\n" + 
               "- NAME: " + versionName + "\n----------------------------\n")
    ...
    }
}
laomo
  • 436
  • 4
  • 12
  • 1
    Instead of posting links, post the actual content here. Links may go down. Links should be used for references only. – Mangesh Mar 26 '16 at 04:52