Skip to content

Instantly share code, notes, and snippets.

@dkirkby
Last active March 6, 2021 21:40
Show Gist options
  • Save dkirkby/fbc0b981f4fa2b98e4658476e139e579 to your computer and use it in GitHub Desktop.
Save dkirkby/fbc0b981f4fa2b98e4658476e139e579 to your computer and use it in GitHub Desktop.
Get a git description of a package
# Put this anywhere within the package then call it at runtime to get a git description
# of the package version being used. This only works when the package is being imported
# from a directory checked out directly from github, which is generally not the case
# for pip- or conda-installed packages.
def git_describe():
"""Return a string describing the git origin of the package where this function is defined.
The result is usually <tag>-<n>-g<hash> where <tag> is the last tag, <n> is the number of
subsequent commits, and <hash> is the current git hash. When n=0, only <hash> is returned.
Details on git-describe are at https://git-scm.com/docs/git-describe
"""
try:
path = pathlib.Path(__file__).parent
process = subprocess.Popen(
['git', 'describe', '--tags', '--always'],
cwd=path, shell=False, stdout=subprocess.PIPE)
return process.communicate()[0].strip().decode()
except Exception as e:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment