0

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?

0xC0000022L
  • 20,597
  • 9
  • 86
  • 152
  • I understand it's kind of nice to have shorter identifiers, but is that really worth taking the time to write a bunch of code? A full-length commit hash will work anywhere an abbreviated one would, and in the worst case, the "abbreviation" is the full commit hash anyway. So you have to be able to handle full-length hashes regardless... – Borealid Jul 20 '15 at 21:58
  • @Borealid: I didn't mean to go into any detail as to why and what for I need this. But since this is merely for the "build ID" and there is limited space in the place it gets displayed, the abbreviated ref ID along with the traditional version number *is* the preferred form as the full length hash would anyway not be fully shown (lack of space). Also, the program isn't mine, so I'd like to keep my changes minimally invasive. – 0xC0000022L Jul 20 '15 at 22:34
  • @0xC00000022L Okay, it's your show. I don't think GitPython lets you get the abbreviated commit hash. If you have the ability to run git commands directly, you can use `git rev-parse --short`. Just keep in mind that sometimes the "short" name is going to be exactly the same length as the full name... – Borealid Jul 20 '15 at 22:37
  • @Borealid: thanks, the issue is that I cannot rely on Git being available. But it seems that GitPython functionality reaches far enough to achieve this even without the hybrid mode (which requires a Git binary). – 0xC0000022L Jul 21 '15 at 08:04

1 Answers1

3

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.

Byron
  • 3,908
  • 3
  • 26
  • 35