如果你和我一样:
- 多平台,因此子进程可能有一天会崩溃
- 使用 Python 2.7,所以 GitPython 不可用
- 不想仅仅为此使用 Numpy
- 已经在使用 Sentry(旧版本:raven)
然后(这在 shell 上不起作用,因为 shell 没有检测到当前文件路径,请将 BASE_DIR 替换为您当前的文件路径):
import os
import raven
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(raven.fetch_git_sha(BASE_DIR))
就是这样。
我一直在寻找另一种解决方案,因为我想迁移到 sentry_sdk 并离开 raven,但也许你们中的一些人想继续使用 raven 一段时间。
Here was the discussion that get me into this stackoverflow issue
所以在没有 raven 的情况下使用 raven 的代码也是可能的(见讨论):
from __future__ import absolute_import
import os.path
__all__ = 'fetch_git_sha'
def fetch_git_sha(path, head=None):
"""
>>> fetch_git_sha(os.path.dirname(__file__))
"""
if not head:
head_path = os.path.join(path, '.git', 'HEAD')
with open(head_path, 'r') as fp:
head = fp.read().strip()
if head.startswith('ref: '):
head = head[5:]
revision_file = os.path.join(
path, '.git', *head.split('/')
)
else:
return head
else:
revision_file = os.path.join(path, '.git', 'refs', 'heads', head)
if not os.path.exists(revision_file):
# Check for Raven .git/packed-refs' file since a `git gc` may have run
# https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery
packed_file = os.path.join(path, '.git', 'packed-refs')
if os.path.exists(packed_file):
with open(packed_file) as fh:
for line in fh:
line = line.rstrip()
if line and line[:1] not in ('#', '^'):
try:
revision, ref = line.split(' ', 1)
except ValueError:
continue
if ref == head:
return revision
with open(revision_file) as fh:
return fh.read().strip()
我将此文件命名为 versioning.py 并在我需要它的地方导入“fetch_git_sha”,并将文件路径作为参数传递。
希望对你们中的一些人有所帮助;)