"""The git commit this process is running, read once at startup (gandalf#55). /health reports it so CI can wait until production runs the commit it tested. Read straight from .git (no subprocess): a detached HEAD holds the sha itself; a branch HEAD points at a loose ref or a line in packed-refs. Anything unreadable gives '' rather than an error. """ import os import re _SHA = re.compile(r'^[0-9a-f]{40}$') def running_sha(root: str = '') -> str: """The 40-character commit sha checked out in *root* (default: this file's folder), or ''.""" git = os.path.join(root or os.path.dirname(os.path.abspath(__file__)), '.git') try: with open(os.path.join(git, 'HEAD')) as f: head = f.read().strip() if _SHA.match(head): return head if not head.startswith('ref: '): return '' ref = head[5:].strip() loose = os.path.join(git, *ref.split('/')) if os.path.isfile(loose): with open(loose) as f: sha = f.read().strip() return sha if _SHA.match(sha) else '' with open(os.path.join(git, 'packed-refs')) as f: for line in f: parts = line.split() if len(parts) == 2 and parts[1] == ref and _SHA.match(parts[0]): return parts[0] except OSError: pass return '' SHA = running_sha()