You will need to use the short
argument of rev-parse
here to generate the smallest SHA that can uniquely identify the commit. Basically, the short
will call the internal git API and return the shortest possible length string for the SHA which can uniquely identify the commit, even if you've passed a very small value for short. So effectively, you can do something like below, which will give you the shortest SHA always (I use short=1
to emphasize that):
In [1]: import git
In [2]: repo = git.Repo(search_parent_directories=True)
In [3]: sha = repo.head.object.hexsha
In [4]: short_sha = repo.git.rev_parse(sha, short=1)
In [5]: short_sha
Out[5]: u'd5afd'
You can read more about this from the git side here. Also, as mentioned in the man-page for git-rev-parse, --short will by default take 7 as its value, and minimum 4.
--short=number
Instead of outputting the full SHA-1 values of object names try to abbreviate them to a shorter unique name. When no length is specified 7 is used. The minimum length is 4.