Skip to content

Instantly share code, notes, and snippets.

@bmcfee
Last active January 1, 2016 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcfee/8087049 to your computer and use it in GitHub Desktop.
Save bmcfee/8087049 to your computer and use it in GitHub Desktop.
Just a quick little function to extract the current git revision hash from a filename. This is useful for data-versioning, say, when running a development version of a feature extractor on a fixed sample.
import os
import git
def get_git_revision(filename, default='unversioned'):
'''Walk up a path name until we find a git dir, then grab its current revision.
If the file is not under any git repository, returns ''.
'''
old_filename = None
filename = os.path.realpath(filename)
while filename != old_filename:
try:
g = git.Git(filename)
rev = g.log(['-n 1', '--format=%H'])
return rev
except:
old_filename = filename
filename = os.path.dirname(filename)
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment