Using Git to Version Your APK

| Comments

Have you ever wanted to version your Android APKs directly from your Git repository based on tags? I currently use git-flow for all of my release management tasks, and so every release I make has a Git tag associated with it. I was searching around and found a few posts, such as this one and this one. Somewhere, lost in my Google buffer I found this alternate way of accomplishing the same thing by adding the following productFlavors to your android section in build.gradle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
productFlavors {

    def getVersionCode = { ->
        try {
            def code = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'tag', '--list'
                standardOutput = code
            }
            return code.toString().split("\n").size()
        }
        catch (ignored) {
            return -1;
        }
    }

    def getVersionName = { ->
        try {
            def stdout = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'describe', '--match=[^(hudson)].*', '--tags', '--dirty'
                standardOutput = stdout
            }
            return stdout.toString().trim()
        }
        catch (ignored) {
            return null;
        }
    }

    development {
        versionName getVersionName()
        versionCode getVersionCode()
        packageName 'com.acme.app.development'
    }
    production {
        versionName getVersionName()
        versionCode getVersionCode()
        packageName 'com.acme.app'
    }
}

This also gives you a way of having different package names for development and production. Building at the command-line then because as easy as:

1
2
./gradlew assembleDevelopmentDebug
./gradlew assembleProductionRelease

The versionCode will be set as the number of tags found in the branch’s git history, and the versionName will be based on git describe output. Super simple.

Copyright © 2015 - Neal Sanche. Powered by Octopress