World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14857] fix(build): resolve git commit id correctly in worktrees and packed refs (#14939)
Jerry Shao0cb237af6fb8
diff --git a/clients/client-python/scripts/generate_version.py b/clients/client-python/scripts/generate_version.pyindex 63e32f5f0e..cb7d9bbef2 100644--- a/clients/client-python/scripts/generate_version.py+++ b/clients/client-python/scripts/generate_version.py@@ -19,7 +19,9 @@import reimport configparser+import subprocessfrom datetime import datetime+from pathlib import Pathfrom gravitino.constants.root import PROJECT_ROOTfrom gravitino.constants.version import Version, VERSION_INI, SETUP_FILE@@ -28,22 +30,78 @@ from gravitino.exceptions.base import GravitinoRuntimeExceptionVERSION_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.ktsindex 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.ktsnew file mode 100644index 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.ktsindex 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)