|
| 1 | +""" |
| 2 | +Copied from old sentry-raven integration. |
| 3 | +""" |
| 4 | +import os.path |
| 5 | + |
| 6 | + |
| 7 | +class InvalidGitRepository(Exception): |
| 8 | + pass |
| 9 | + |
| 10 | + |
| 11 | +def fetch_git_sha(path, head=None): |
| 12 | + """ |
| 13 | + >>> fetch_git_sha(os.path.dirname(__file__)) |
| 14 | + """ |
| 15 | + if not head: |
| 16 | + head_path = os.path.join(path, '.git', 'HEAD') |
| 17 | + if not os.path.exists(head_path): |
| 18 | + raise InvalidGitRepository( |
| 19 | + 'Cannot identify HEAD for git repository at %s' % (path,)) |
| 20 | + |
| 21 | + with open(head_path, 'r') as fp: |
| 22 | + head = str(fp.read()).strip() |
| 23 | + |
| 24 | + if head.startswith('ref: '): |
| 25 | + head = head[5:] |
| 26 | + revision_file = os.path.join( |
| 27 | + path, '.git', *head.split('/') |
| 28 | + ) |
| 29 | + else: |
| 30 | + return head |
| 31 | + else: |
| 32 | + revision_file = os.path.join(path, '.git', 'refs', 'heads', head) |
| 33 | + |
| 34 | + if not os.path.exists(revision_file): |
| 35 | + if not os.path.exists(os.path.join(path, '.git')): |
| 36 | + raise InvalidGitRepository( |
| 37 | + '%s does not seem to be the root of a git repository' % (path,)) |
| 38 | + |
| 39 | + # Check for our .git/packed-refs' file since a `git gc` may have run |
| 40 | + # https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery |
| 41 | + packed_file = os.path.join(path, '.git', 'packed-refs') |
| 42 | + if os.path.exists(packed_file): |
| 43 | + with open(packed_file) as fh: |
| 44 | + for line in fh: |
| 45 | + line = line.rstrip() |
| 46 | + if line and line[:1] not in ('#', '^'): |
| 47 | + try: |
| 48 | + revision, ref = line.split(' ', 1) |
| 49 | + except ValueError: |
| 50 | + continue |
| 51 | + if ref == head: |
| 52 | + return str(revision) |
| 53 | + |
| 54 | + raise InvalidGitRepository( |
| 55 | + 'Unable to find ref to head "%s" in repository' % (head,)) |
| 56 | + |
| 57 | + with open(revision_file) as fh: |
| 58 | + return str(fh.read()).strip() |
0 commit comments