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


##########
common/build.gradle.kts:
##########
@@ -59,30 +59,66 @@ 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())
-    }
+// Ask git itself first: it handles linked worktrees, packed refs and detached 
HEAD.
+fun getGitCommitIdFromGit(): String? {
+  return try {
+    val process = ProcessBuilder("git", "rev-parse", "HEAD")

Review Comment:
   git rev-parse HEAD run from rootDir will return the parent repo's commit if 
the source is an unpacked tarball inside another git checkout. Consider 
checking that git rev-parse --show-toplevel equals rootDir before trusting the 
result.



##########
common/build.gradle.kts:
##########
@@ -129,11 +165,21 @@ fun writeProjectPropertiesFile() {
 
 tasks {
   jar {
+    // The build info (commit id, compile date) is regenerated on every run, 
so never skip the jar.
+    outputs.upToDateWhen { false }

Review Comment:
   outputs.upToDateWhen { false } makes the common jar re-run on every build 
and invalidates up-to-date checks and caching for all downstream modules. 
Prefer declaring the commit id as a task input (e.g. via a provider) so the jar 
reruns only when HEAD changes.



##########
clients/client-python/scripts/generate_version.py:
##########
@@ -28,22 +30,71 @@
 VERSION_PATTERN = r"version\s*=\s*['\"]([^'\"]+)['\"]"
 
 
-def get_git_commit_id():
+COMMIT_ID_PATTERN = re.compile(r"[0-9a-fA-F]{40}")
+
+
+def _read_commit_id_from_git():
+    """Ask git itself, which handles worktrees, packed refs and detached 
HEAD."""
+    try:
+        result = subprocess.run(
+            ["git", "rev-parse", "HEAD"],
+            cwd=PROJECT_ROOT,
+            capture_output=True,
+            text=True,
+            check=False,
+            timeout=30,
+        )
+    except (OSError, subprocess.SubprocessError):
+        return ""
+    output = result.stdout.strip()
+    if result.returncode == 0 and COMMIT_ID_PATTERN.fullmatch(output):
+        return output
+    return ""
+
+
+def _read_commit_id_from_files():
+    """Fallback that parses the .git directory by hand when git is 
unavailable."""
     try:
-        commit_id = ""
-        git_path = f"{PROJECT_ROOT}/.git/"
-        with open(git_path + "HEAD", "r", encoding="utf-8") as file:
-            ref = file.readline().strip()
-
-        if ref.startswith("ref:"):
-            ref_path = ref.split(" ")[1]
-            with open(git_path + ref_path, "r", encoding="utf-8") as file:
-                commit_id = file.readline().strip()
-        return commit_id
-    except (FileNotFoundError, IOError):
+        git_path = Path(PROJECT_ROOT) / ".git"
+        if git_path.is_file():
+            # Linked worktrees have a ".git" file holding a "gitdir:" path
+            # (absolute, or relative to the root).
+            content = git_path.read_text(encoding="utf-8").strip()
+            gitdir = content.split("gitdir:", 1)[1].strip()
+            git_dir = (Path(PROJECT_ROOT) / gitdir).resolve()
+        else:
+            git_dir = git_path
+
+        head = (git_dir / "HEAD").read_text(encoding="utf-8").strip()
+        if not head.startswith("ref:"):
+            return head

Review Comment:
   A detached HEAD value is returned without validating it is a 40-char hex id, 
so a malformed HEAD ends up in the version file. Validate with 
COMMIT_ID_PATTERN before returning.



##########
common/build.gradle.kts:
##########
@@ -129,11 +165,21 @@ fun writeProjectPropertiesFile() {
 
 tasks {
   jar {
+    // The build info (commit id, compile date) is regenerated on every run, 
so never skip the jar.
+    outputs.upToDateWhen { false }
+
     doFirst() {
       writeProjectPropertiesFile()
       if (!file(propertiesFile).exists()) {
         throw GradleException("Failed to generate $propertiesFile.")
       }
+      // processResources may have copied a stale file (e.g. empty commit id) 
into the main
+      // resources output, which wins over the fresh one below; refresh it.
+      val processed = 
layout.buildDirectory.file("resources/main/gravitino-build-info.properties")
+        .get().asFile
+      if (processed.parentFile.exists()) {
+        file(propertiesFile).copyTo(processed, overwrite = true)

Review Comment:
   Copying over build/resources/main inside the jar doFirst mutates another 
task's output after the fact, which can confuse incremental builds. Would it be 
cleaner to make processResources depend on the generated file instead?



-- 
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