jerryshao commented on code in PR #14939:
URL: https://github.com/apache/gravitino/pull/14939#discussion_r4560578497


##########
common/build.gradle.kts:
##########
@@ -59,89 +60,143 @@ dependencies {
   testFixturesImplementation(libs.commons.lang3)
 }
 
-fun getGitCommitId(): String {
-  var gitCommitId: String
-  try {
-    val gitPath = File(rootDir.path, ".git")
-    val gitFolder = if (gitPath.isDirectory) {
-      gitPath
-    } else {
-      val content = gitPath.readText().trim()
-      File(rootDir.path, content.substringAfter("gitdir: ").trim())
-    }
+val gitCommitIdPattern = Regex("[0-9a-fA-F]{40}")
 
-    val head = File(gitFolder, "HEAD").readText().split(":")
-    val isCommit = head.size == 1
-    gitCommitId = if (isCommit) {
-      head[0].trim()
-    } else {
-      val refHead = File(gitFolder, head[1].trim())
-      refHead.readText().trim()
+// Ask git itself first: it handles linked worktrees, packed refs and detached 
HEAD.
+// Only trust git when rootDir has its own .git, so a source tarball extracted 
inside another
+// repository does not pick up that repository's commit id.
+fun getGitCommitIdFromGit(): String? {
+  if (!File(rootDir, ".git").exists()) {
+    return null
+  }
+  return try {
+    val process = ProcessBuilder("git", "rev-parse", "HEAD")
+      .directory(rootDir)
+      .redirectError(ProcessBuilder.Redirect.DISCARD)
+      .start()
+    if (!process.waitFor(30, TimeUnit.SECONDS)) {
+      process.destroyForcibly()
+      return null
     }
+    val output = process.inputStream.bufferedReader().use { 
it.readText().trim() }
+    if (process.exitValue() == 0 && gitCommitIdPattern.matches(output)) output 
else null
   } catch (e: Exception) {
-    println("WARN: Unable to get Git commit id : ${e.message}")
-    gitCommitId = ""
+    null
+  }
+}
+
+// Fallback that parses the .git directory by hand, used when the git command 
is unavailable.
+fun getGitCommitIdFromFiles(): String {
+  val gitPath = File(rootDir.path, ".git")
+  val gitFolder = if (gitPath.isDirectory) {
+    gitPath
+  } else {
+    // Linked worktrees have a ".git" file holding an absolute (or relative) 
"gitdir:" path.
+    rootDir.resolve(gitPath.readText().trim().substringAfter("gitdir: 
").trim())
+  }
+
+  val head = File(gitFolder, "HEAD").readText().split(":")
+  if (head.size == 1) {
+    return head[0].trim()
+  }
+  val refName = head[1].trim()
+  // Branch refs of linked worktrees live in the common git dir.
+  val commonDir = File(gitFolder, "commondir")
+  val refFolders = if (commonDir.exists()) {
+    listOf(gitFolder, gitFolder.resolve(commonDir.readText().trim()))
+  } else {
+    listOf(gitFolder)
+  }
+  for (folder in refFolders) {
+    val refFile = File(folder, refName)
+    if (refFile.exists()) {
+      return refFile.readText().trim()
+    }
+    val packed = File(folder, "packed-refs")
+    if (packed.exists()) {
+      packed.readLines().firstOrNull { it.endsWith(" $refName") }?.let {
+        return it.substringBefore(" ").trim()
+      }
+    }
   }
-  return gitCommitId
+  throw GradleException("Unable to resolve ref $refName")
 }
 
-val propertiesFile = "src/main/resources/gravitino-build-info.properties"
-fun writeProjectPropertiesFile() {
-  val propertiesFile = file(propertiesFile)
-  if (propertiesFile.exists()) {
-    propertiesFile.delete()
+fun getGitCommitId(): String {
+  getGitCommitIdFromGit()?.let { return it }
+  return try {
+    val commitId = getGitCommitIdFromFiles()
+    if (!gitCommitIdPattern.matches(commitId)) {
+      throw GradleException("Invalid Git commit id: $commitId")
+    }
+    commitId
+  } catch (e: Exception) {
+    println("WARN: Unable to get Git commit id : ${e.message}")
+    ""
   }
+}
 
-  val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
+// The build info file is generated into the build directory by a dedicated 
task. Its inputs are
+// the project version and the git commit id, so it (and everything 
downstream, including the
+// jar and the build cache) is only redone when the commit changes.
+val gitCommitIdValue: String by lazy { getGitCommitId() }
+val buildInfoFileName = "gravitino-build-info.properties"
+val buildInfoDir = layout.buildDirectory.dir("generated/build-info")
 
-  val compileDate = dateFormat.format(Date())
+val generateBuildInfo by tasks.registering {

Review Comment:
   Added in 72d39eaae9: the logic now lives in `gradle/build-info.gradle.kts`, 
and `TestBuildInfoGeneration` (Gradle TestKit) applies that real script to 
temporary projects. It covers linked worktrees (named and detached), packed 
refs, the file fallback (`-PgitExecutable` override), no `.git`, a stale 
`src/main/resources` copy, UP-TO-DATE on an unchanged build, and a refresh on a 
HEAD-only change. It asserts both the generated resource and the single 
build-info entry in the JAR match HEAD. I also checked the tests fail when the 
packed-refs lookup or the stale-copy exclusion is removed.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to