I would like to include the current git hash in the output of a Python script (as a the version number of the code that generated that output).
How can I access the current git hash in my Python script?
git describe command is a good way of creating a human-presentable "version number" of the code. From the examples in the documentation:
With something like git.git current tree, I get:
[torvalds@g5 git]$ git describe parent v1.0.4-14-g2414721
i.e. the current head of my "parent" branch is based on v1.0.4, but since it has a few commits on top of that, describe has added the number of additional commits ("14") and an abbreviated object name for the commit itself ("2414721") at the end.
From within Python, you can do something like the following:
import subprocess label = subprocess.check_output(["git", "describe"]).strip()
No need to hack around getting data from the
git command yourself. GitPython is a very nice way to do this and a lot of other
git stuff. It even has "best effort" support for Windows.
pip install gitpython you can do
import git repo = git.Repo(search_parent_directories=True) sha = repo.head.object.hexsha