Skip to content

Commit

Permalink
Support configuration cache for getting git commit (#1494)
Browse files Browse the repository at this point in the history
  • Loading branch information
Luna712 authored Jan 21, 2025
1 parent 1436c15 commit 578eb48
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile
import java.io.ByteArrayOutputStream

plugins {
id("com.android.application")
Expand All @@ -13,22 +12,24 @@ val javaTarget = JvmTarget.fromTarget(libs.versions.jvmTarget.get())
val tmpFilePath = System.getProperty("user.home") + "/work/_temp/keystore/"
val prereleaseStoreFile: File? = File(tmpFilePath).listFiles()?.first()

fun String.execute(): String? {
val output = ByteArrayOutputStream()

val process = ProcessBuilder()
.command(this.split(" "))
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.start()

val exitValue = process.inputStream.use { input ->
input.copyTo(output)
process.waitFor()
fun getGitCommitHash(): String {
return try {
val headFile = file("${project.rootDir}/.git/HEAD")

// Read the commit hash from .git/HEAD
if (headFile.exists()) {
val headContent = headFile.readText().trim()
if (headContent.startsWith("ref:")) {
val refPath = headContent.substring(5) // e.g., refs/heads/main
val commitFile = file("${project.rootDir}/.git/$refPath")
if (commitFile.exists()) commitFile.readText().trim() else ""
} else headContent // If it's a detached HEAD (commit hash directly)
} else {
"" // If .git/HEAD doesn't exist
}.take(7) // Return the short commit hash
} catch (_: Throwable) {
"" // Just return an empty string if any exception occurs
}

return if (exitValue == 0) {
output.toString().trim()
} else null
}

android {
Expand Down Expand Up @@ -62,7 +63,7 @@ android {
versionName = "4.4.2"

resValue("string", "app_version", "${defaultConfig.versionName}${versionNameSuffix ?: ""}")
resValue("string", "commit_hash", "git rev-parse --short HEAD".execute() ?: "")
resValue("string", "commit_hash", getGitCommitHash())
resValue("bool", "is_prerelease", "false")

// Reads local.properties
Expand Down

0 comments on commit 578eb48

Please sign in to comment.