Spaces:
Runtime error
Runtime error
| # Copyright (c) 2025 SandAI. All Rights Reserved. | |
| # | |
| # Licensed 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. | |
| from __future__ import annotations | |
| import subprocess | |
| from pathlib import Path | |
| def get_git_version(short: bool = True, length: int = 7) -> str: | |
| """ | |
| 获取当前仓库的 Git 提交 ID。默认返回短 SHA。 | |
| 当无法通过 git 命令获取时,回退读取 .git/HEAD/packed-refs。 | |
| """ | |
| # 以本文件为锚点推断仓库根目录:.../magi_compiler/magi_compiler/utils/version.py → .../magi_compiler | |
| repo_root = Path(__file__).resolve().parents[2] | |
| git_dir = repo_root / ".git" | |
| # 优先通过 git 命令获取 | |
| try: | |
| sha = subprocess.check_output( | |
| ["git", "-C", str(repo_root), "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL | |
| ).strip() | |
| return sha[:length] if short else sha | |
| except Exception: | |
| pass | |
| # 回退:解析 .git/HEAD | |
| try: | |
| head = (git_dir / "HEAD").read_text().strip() | |
| if head.startswith("ref:"): | |
| ref_path = head.split(" ", 1)[1].strip() | |
| ref_file = git_dir / ref_path | |
| if ref_file.exists(): | |
| sha = ref_file.read_text().strip() | |
| else: | |
| # 可能被打包到 packed-refs | |
| packed = git_dir / "packed-refs" | |
| sha = "" | |
| if packed.exists(): | |
| with packed.open() as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line or line.startswith("#") or line.startswith("^"): | |
| continue | |
| parts = line.split(" ") | |
| if len(parts) == 2 and parts[1] == ref_path: | |
| sha = parts[0] | |
| break | |
| if not sha: | |
| return "unknown" | |
| else: | |
| # detached HEAD,HEAD 文件直接保存 SHA | |
| sha = head | |
| return sha[:length] if short else sha | |
| except Exception: | |
| return "unknown" | |