在根项目的gradle子项目中设置android版本代码/名称

时间:2019-09-12 12:59:36

标签: android gradle

在构建Android应用程序的子项目中,我试图根据根build.gradle中的变量设置版本代码/名称。

子项目build.gradle

apply plugin: 'com.android.application'

repositories {
    google()
    mavenCentral()
    jcenter()
}

android {
    compileSdkVersion 24

    // current atak build tools version"
    buildToolsVersion "28.0.3"
    defaultConfig {
        multiDexEnabled true
        versionCode project.commit_head_count
        versionName project.full_version
    }

    lintOptions {
        abortOnError false
    }
}

// set the build info prior to building
build.dependsOn rootProject.setBuildInfo

root build.gradle:

// gathers git / build information and dumps it to VERSION files to be read by web app and data analysis program
task setBuildInfo() {
    doLast {
        // read the core version file and store in variable
        def coreVersionFile = new File("$projectDir/VERSION.txt")
        def coreVersion = coreVersionFile.readLines().get(0)

        // get the git hash value (short)
        def getShortGitHashCmd = "git rev-parse --short HEAD"
        def getShortGitHashProcess = getShortGitHashCmd.execute()

        // get the count of commits on this branch at HEAD
        def getCommitCountCmd = "git rev-list HEAD --count"
        def getCommitCountProcess = getCommitCountCmd.execute()

        ext.commit_head_count = getCommitCountProcess.text.trim()
        ext.git_hash = getShortGitHashProcess.text.trim()
        ext.full_version = "$coreVersion.$ext.commit_head_count"
        ext.build_date = new Date().format('yyyy-MM-dd HH:mm:ss')

        // assigns the full_version for global use in other task
        // https://stackoverflow.com/a/29597784/680268
        project.ext.$full_version = ext.full_version
        project.ext.$commit_head_count = ext.commit_head_count


        def fileContent =
                "Short Version:$coreVersion\n" +
                        "Long Version:$ext.full_version\n" +
                        "Git hash:$ext.git_hash\n" +
                        "Commit count:$ext.commit_head_count\n" +
                        "Build date:$ext.build_date\n"
        print fileContent
    }
}

// set the build info prior to building
compileJava.dependsOn setBuildInfo

执行此操作时,android app子项目说它不知道commit_head_count变量指的是什么。我觉得如果我真的可以让setBuildInfo首先运行,那会起作用,但不能使它起作用

1 个答案:

答案 0 :(得分:0)

在执行某些其他任务时,使用以下代码片段执行自定义任务:

tasks.matching { it.name == 'name of dependent task (i.e build)' }.all { Task task ->
    task.dependsOn setBuildInfo
}

这将使所有其他匹配任务强制依赖于您的自定义任务。

否则,在评估项目时,其他解决方案将成为您的构建信息。

将此代码放在您的根目录 build.gradle 中,并检查结果:

project.afterEvaluate {
    print("This line prints every single time")
}