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


##########
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:
   Fixed in 6ed7d1a112. The build info is now produced by a dedicated 
`generateBuildInfo` task whose inputs are the project version and the git 
commit id, so the jar and downstream tasks only rerun when the commit changes. 
`upToDateWhen { false }` and `cacheIf { false }` are removed. Verified: a 
second `:server:test` run is fully UP-TO-DATE, and a new commit regenerates the 
jar with the new id.



##########
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:
   Fixed in f2f2ea3612: git is only trusted when `rootDir` has its own `.git`, 
so a source tarball extracted inside another repository yields an empty id with 
the WARN instead of the outer repo commit. The same guard is in the Python 
script, with a unit test.



##########
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:
   Fixed in 6ed7d1a112. The `doFirst` copy into `build/resources/main` is gone. 
`processResources` now takes the generated file from `generateBuildInfo` as an 
input, and the source set ignores a stale copy in `src/main/resources`.



##########
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:
   Fixed in f2f2ea3612: the file-parsing fallback result is now validated as a 
40-hex SHA before use (an invalid value yields an empty id). Covered by 
`test_invalid_head_gives_empty_id` in 6ed7d1a112.



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