如何创建 Android Studio 构建脚本以在构建版本中插入 git commit hash?

Ben*_*ueg 3 android-manifest android-studio android-gradle-plugin

我想在我的 AndroidManifest 中插入最后一次 git commit 的哈希值(更具体地说是 versionCode 标签)。

我在 Android Studio 中使用 gradle。

dju*_*nod 5

要回答 OQ,请将以下内容添加到应用程序 build.gradle 的 android 部分

def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}
Run Code Online (Sandbox Code Playgroud)

由于 versionCode 是数字,因此将 defaultConfig versionName 更改为

versionName getGitHash()
Run Code Online (Sandbox Code Playgroud)

更好的实施

我在自己的项目中实际做的是将值注入 BuildConfig 变量并以这种方式访问​​它。

我在 android 部分使用这些方法:

def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', 'HEAD'
        standardOutput = stdout
    }
    return "\"" + stdout.toString().trim() + "\""
}

def getGitBranch = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
        standardOutput = stdout
    }
    return "\"" + stdout.toString().trim() + "\""
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到 BuildConfig 部分:

productFlavors {
    dev {
        ...
        buildConfigField "String", "GIT_HASH", getGitHash()
        buildConfigField "String", "GIT_BRANCH", getGitBranch()
        ...
    }
 }
Run Code Online (Sandbox Code Playgroud)

然后在源代码中,比如Application.java

Log.v(LOG_TAG, "git branch=" + BuildConfig.GIT_BRANCH);
Log.v(LOG_TAG, "git commit=" + BuildConfig.GIT_HASH);
Run Code Online (Sandbox Code Playgroud)