Automatic versioning of Android build using git describe with Gradle

后端 未结 10 1964
醉酒成梦
醉酒成梦 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:16

    Put the following in your build.gradle file for the project. There's no need to modify the manifest directly: Google provided the necessary hooks into their configuration.

    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', '--tags', '--dirty'
                standardOutput = stdout
            }
            return stdout.toString().trim()
        }
        catch (ignored) {
            return null;
        }
    }
    android {
        defaultConfig {
            versionCode getVersionCode()
            versionName getVersionName()
        }
    }
    

    Note that if git is not installed on the machine, or there is some other error getting the version name/code, it will default to what is in your android manifest.

提交回复
热议问题