This is an automated email from the ASF dual-hosted git repository.
jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new 0cb237af6f [#14857] fix(build): resolve git commit id correctly in
worktrees and packed refs (#14939)
0cb237af6f is described below
commit 0cb237af6fb8d53436820ba8458bb6322ca45cc1
Author: Jerry Shao <[email protected]>
AuthorDate: Fri Nov 13 17:45:22 2026 +0800
[#14857] fix(build): resolve git commit id correctly in worktrees and
packed refs (#14939)
### What changes were proposed in this pull request?
- `common/build.gradle.kts`: resolve the commit id with `git rev-parse
HEAD` (run in `rootDir`, result accepted only if it is a 40-hex SHA).
The previous file-parsing logic is kept as a fallback and now also
handles an absolute `gitdir:` path, `commondir` (branch refs of linked
worktrees) and `packed-refs`. If nothing works, it still prints a `WARN`
and writes an empty value.
- `common/build.gradle.kts`: the jar task now refreshes the copy of
`gravitino-build-info.properties` that `processResources` placed in
`build/resources/main`. Previously that stale copy won over the freshly
generated file, so the JAR could carry an empty commit id even when
`src/main/resources` was correct. The jar task is also no longer skipped
as UP-TO-DATE, so a new commit is always reflected.
- `server/build.gradle.kts`: remove an unused duplicate of
`getGitCommitId()`.
- `clients/client-python/scripts/generate_version.py`: same fix for the
Python client's `version.ini` (it also returned an empty id for a
detached HEAD).
### Why are the changes needed?
`git.commit.id` was empty in `gravitino-build-info.properties`, the
common JAR and the Python `version.ini` for: linked git worktrees
(absolute `gitdir:` path was joined to `rootDir`; branch refs live in
the common git dir), detached HEAD, and checkouts whose refs were packed
by `git gc`/`git pack-refs`.
Fixes #14857
### Does this PR introduce _any_ user-facing change?
No. The commit id shown by the server/client version info is now
populated in the cases above.
### How was this patch tested?
Built `:common:jar` and ran `generate_version.py`, comparing the output
with `git rev-parse HEAD`, both with git available and with git removed
from `PATH` (to exercise the fallback): named-branch linked worktree,
detached linked worktree, normal checkout with loose refs, packed refs,
detached HEAD, linked worktree with packed refs, and a `git archive`
copy without `.git` (build succeeds, `WARN` printed, empty value). All
as expected. No unit tests were added, since this is build-script logic.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
---
clients/client-python/scripts/generate_version.py | 82 +++++++++--
common/build.gradle.kts | 90 +-----------
gradle/build-info.gradle.kts | 162 ++++++++++++++++++++++
server/build.gradle.kts | 19 ---
4 files changed, 233 insertions(+), 120 deletions(-)
diff --git a/clients/client-python/scripts/generate_version.py
b/clients/client-python/scripts/generate_version.py
index 63e32f5f0e..cb7d9bbef2 100644
--- a/clients/client-python/scripts/generate_version.py
+++ b/clients/client-python/scripts/generate_version.py
@@ -19,7 +19,9 @@
import re
import configparser
+import subprocess
from datetime import datetime
+from pathlib import Path
from gravitino.constants.root import PROJECT_ROOT
from gravitino.constants.version import Version, VERSION_INI, SETUP_FILE
@@ -28,22 +30,78 @@ from gravitino.exceptions.base import
GravitinoRuntimeException
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.
+
+ Only trusted when PROJECT_ROOT has its own .git, so a source tarball
extracted
+ inside another repository does not pick up that repository's commit id.
+ """
+ if not (Path(PROJECT_ROOT) / ".git").exists():
+ return ""
+ 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
+
+ ref_name = head.split(":", 1)[1].strip()
+ # Branch refs of linked worktrees live in the common git dir.
+ search_dirs = [git_dir]
+ common_dir = git_dir / "commondir"
+ if common_dir.is_file():
+ common = common_dir.read_text(encoding="utf-8").strip()
+ search_dirs.append((git_dir / common).resolve())
+
+ for folder in search_dirs:
+ ref_file = folder / ref_name
+ if ref_file.is_file():
+ return ref_file.read_text(encoding="utf-8").strip()
+ packed = folder / "packed-refs"
+ if packed.is_file():
+ for line in packed.read_text(encoding="utf-8").splitlines():
+ if line.endswith(" " + ref_name):
+ return line.split(" ", 1)[0].strip()
+ return ""
+ except (OSError, IndexError):
return ""
+def get_git_commit_id():
+ commit_id = _read_commit_id_from_git() or _read_commit_id_from_files()
+ return commit_id if COMMIT_ID_PATTERN.fullmatch(commit_id) else ""
+
+
def main():
with open(SETUP_FILE, "r", encoding="utf-8") as f:
setup_content = f.read()
diff --git a/common/build.gradle.kts b/common/build.gradle.kts
index b71694b4c4..1587b91362 100644
--- a/common/build.gradle.kts
+++ b/common/build.gradle.kts
@@ -17,9 +17,6 @@
* under the License.
*/
-import java.text.SimpleDateFormat
-import java.util.Date
-
plugins {
`maven-publish`
`java-test-fixtures`
@@ -59,89 +56,4 @@ 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 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()
- }
- } catch (e: Exception) {
- println("WARN: Unable to get Git commit id : ${e.message}")
- gitCommitId = ""
- }
- return gitCommitId
-}
-
-val propertiesFile = "src/main/resources/gravitino-build-info.properties"
-fun writeProjectPropertiesFile() {
- val propertiesFile = file(propertiesFile)
- if (propertiesFile.exists()) {
- propertiesFile.delete()
- }
-
- val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
-
- val compileDate = dateFormat.format(Date())
- val projectVersion = project.version.toString()
- val commitId = getGitCommitId()
-
- propertiesFile.parentFile.mkdirs()
- propertiesFile.createNewFile()
- propertiesFile.writer().use { writer ->
- writer.write(
- "#\n" +
- "# Licensed to the Apache Software Foundation (ASF) under one\n" +
- "# or more contributor license agreements. See the NOTICE file\n" +
- "# distributed with this work for additional information\n" +
- "# regarding copyright ownership. The ASF licenses this file\n" +
- "# to you under the Apache License, Version 2.0 (the\n" +
- "# \"License\"); you may not use this file except in compliance\n" +
- "# with the License. You may obtain a copy of the License at\n" +
- "#\n" +
- "# http://www.apache.org/licenses/LICENSE-2.0\n" +
- "#\n" +
- "# Unless required by applicable law or agreed to in writing,\n" +
- "# software distributed under the License is distributed on an\n" +
- "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n" +
- "# KIND, either express or implied. See the License for the\n" +
- "# specific language governing permissions and limitations\n" +
- "# under the License.\n" +
- "#\n"
- )
- writer.write("project.version=$projectVersion\n")
- writer.write("compile.date=$compileDate\n")
- writer.write("git.commit.id=$commitId\n")
- }
-}
-
-tasks {
- jar {
- doFirst() {
- writeProjectPropertiesFile()
- if (!file(propertiesFile).exists()) {
- throw GradleException("Failed to generate $propertiesFile.")
- }
- }
-
- from("src/main/resources") {
- include("gravitino-build-info.properties").duplicatesStrategy =
DuplicatesStrategy.EXCLUDE
- }
- }
-
- clean {
- delete("$propertiesFile")
- }
-}
+apply(from = rootProject.file("gradle/build-info.gradle.kts"))
diff --git a/gradle/build-info.gradle.kts b/gradle/build-info.gradle.kts
new file mode 100644
index 0000000000..bfa1082778
--- /dev/null
+++ b/gradle/build-info.gradle.kts
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// Generates gravitino-build-info.properties (project version, compile date,
git commit id) and
+// wires it into processResources. Applied from common/build.gradle.kts;
requires the java plugin.
+
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.concurrent.TimeUnit
+
+val gitCommitIdPattern = Regex("[0-9a-fA-F]{40}")
+
+// 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) {
+ 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()
+ }
+ }
+ }
+ throw GradleException("Unable to resolve ref $refName")
+}
+
+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}")
+ ""
+ }
+}
+
+// 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 generateBuildInfo by tasks.registering {
+ val projectVersion = project.version.toString()
+ val outputFile = buildInfoDir.map { it.file(buildInfoFileName) }
+
+ inputs.property("projectVersion", projectVersion)
+ inputs.property("gitCommitId", providers.provider { gitCommitIdValue })
+ outputs.file(outputFile)
+
+ doLast {
+ val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
+ val file = outputFile.get().asFile
+ file.parentFile.mkdirs()
+ file.writer().use { writer ->
+ writer.write(
+ "#\n" +
+ "# Licensed to the Apache Software Foundation (ASF) under one\n" +
+ "# or more contributor license agreements. See the NOTICE file\n" +
+ "# distributed with this work for additional information\n" +
+ "# regarding copyright ownership. The ASF licenses this file\n" +
+ "# to you under the Apache License, Version 2.0 (the\n" +
+ "# \"License\"); you may not use this file except in compliance\n" +
+ "# with the License. You may obtain a copy of the License at\n" +
+ "#\n" +
+ "# http://www.apache.org/licenses/LICENSE-2.0\n" +
+ "#\n" +
+ "# Unless required by applicable law or agreed to in writing,\n" +
+ "# software distributed under the License is distributed on an\n" +
+ "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n" +
+ "# KIND, either express or implied. See the License for the\n" +
+ "# specific language governing permissions and limitations\n" +
+ "# under the License.\n" +
+ "#\n"
+ )
+ writer.write("project.version=$projectVersion\n")
+ writer.write("compile.date=${dateFormat.format(Date())}\n")
+ writer.write("git.commit.id=$gitCommitIdValue\n")
+ }
+ }
+}
+
+the<SourceSetContainer>().named("main") {
+ // Ignore a stale copy generated into src/main/resources by older builds.
+ resources.exclude(buildInfoFileName)
+}
+
+tasks.named<ProcessResources>("processResources") {
+ from(generateBuildInfo)
+}
+
+tasks.named<Delete>("clean") {
+ // Remove the stale copy generated into src/main/resources by older builds.
+ delete("src/main/resources/$buildInfoFileName")
+}
diff --git a/server/build.gradle.kts b/server/build.gradle.kts
index 895c64a511..628f6fa5c3 100644
--- a/server/build.gradle.kts
+++ b/server/build.gradle.kts
@@ -70,25 +70,6 @@ dependencies {
testRuntimeOnly(libs.junit.jupiter.engine)
}
-fun getGitCommitId(): String {
- var gitCommitId: String
- try {
- val gitFolder = rootDir.path + "/.git/"
- 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()
- }
- } catch (e: Exception) {
- println("WARN: Unable to get Git commit id : ${e.message}")
- gitCommitId = ""
- }
- return gitCommitId
-}
-
tasks {
test {
environment("GRAVITINO_HOME", rootDir.path)