Automatic versioning of Android build using git describe with Gradle

后端 未结 10 1989
醉酒成梦
醉酒成梦 2020-11-30 18:18

I have searched extensively, but likely due to the newness of Android Studio and Gradle. I haven\'t found any description of how to do this. I want to do basically exactly

10条回答
  •  日久生厌
    2020-11-30 19:11

    After seeing moveaway00's answer and Avinash R's comment on that answer, I've ended up using this:

    apply plugin: 'android'
    
    def getVersionCode = { ->
        try {
            def stdout = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'rev-list', '--first-parent', '--count', 'master'
                standardOutput = stdout
            }
            return Integer.parseInt(stdout.toString().trim())
        }
        catch (ignored) {
            return -1;
        }
    }
    
    def getVersionName = { ->
        try {
            def stdout = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'describe', '--tags', '--dirty'
                standardOutput = stdout
            }
            return stdout.toString().trim()
        }
        catch (ignored) {
            return null;
        }
    }
    
    android {
        defaultConfig {
            versionCode getVersionCode()
            versionName getVersionName()
        }
    }
    

    I've edited moveaway00's code to also include Avinash R's comment: the version code is now the number of commits since master, as this is what the version code is supposed to be.

    Note that I didn't need to specify the version code and the version name in the manifest, Gradle took care of it.

提交回复
热议问题