Search code examples
gitpython-2.7gitpython

How to get the unique part of a ref ID with GitPython?


GitPython allows me to work on Git working copies. I'd like to use it. But how would I fetch the unique part, i.e. the "abbreviated ref ID", using GitPython?

So I am interested in what the --abbrev-commit option to git log gives me (e.g. in git log --abbrev-commit --pretty=oneline -n 1).

How can I get that in GitPython - or will I have to implement this by enumerating through the ref IDs and figuring out the required length on my own?


Solution

  • The following code is an example on how to use the git rev-parse --short functionality from GitPython:

    import git
    r = git.Repo()
    short = r.git.rev_parse(r.head, short=True)
    print(short)
    # u'f360ecd'
    

    It appears that using the git-command is preferable over implementing it yourself in a safe fashion.

    A naive pure-python implementation could look like this though:

    r.head.commit.hexsha[:7]
    

    However, it doesn't check if the obtained prefix is truly unique at the time of creation, which is why the git-command based approach should be preferred.