Fetch the git SHA, with packed-refs support, and fallback to HEAD based on https://github.com/getsentry/raven-python/blob/25728c8190a7f008cdb00b1664cd4fd479060eaf/raven/versioning.py#L17
Created
October 8, 2019 15:52
-
-
Save zerolab/fe9a8b1e5325fc2513470cee077f9615 to your computer and use it in GitHub Desktop.
fetch_git_sha for Sentry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fetch_git_sha(path): | |
head_path = os.path.join(path, '.git', 'HEAD') | |
if not os.path.exists(head_path): | |
return '' | |
with open(head_path) as f: | |
head = f.read().strip() | |
head = head[5:] | |
revision_file = os.path.join(path, '.git', *head.split('/')) | |
if not os.path.exists(revision_file): | |
# Check for our .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, 'r') as f: | |
for line in f: | |
line = line.rstrip() | |
if not line: | |
continue | |
if line[:1] in ('#', '^'): | |
continue | |
try: | |
revision, ref = line.split(' ', 1) | |
except ValueError: | |
continue | |
if ref == head: | |
return revision | |
else: | |
with open(revision_file) as f: | |
return f.read().strip() | |
# default to HEAD | |
return head |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment