Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get short sha of commit with gitpython

Tags:

The long SHA can be gotten like below:

repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

Or, in git 3.1.7:

sha = repo.head.commit.hexsha

How about short one? (short SHA is decided by the scale of the repo, so it should not be like sha[:7])

like image 997
Kentaro Wada Avatar asked Aug 12 '15 05:08

Kentaro Wada


People also ask

Which command returns the shortest SHA1?

A Git commit ID is a 40 digits long SHA-1 hash, that can be abbreviated up to the shortest 4 digits version (7 by default).

Which command returns the shortest unique SHA1 for a commit inside the current repository in git?

You can use git rev-parse HEAD to get the new commit's SHA1 hash, or you can use git log -1 HEAD to get all of its information.

How do I find the commit ID?

To find a git commit id (or hash), you can simply use the git log command. This would show you the commit history, listing the commits in chronological order, with the latest commit first.


2 Answers

As far as I can tell, the gitpython Commit object does not support the short sha directly. However, you can use still gitpython's support for calling git directly to retrieve it (as of git 3.1.7):

repo = git.Repo(search_parent_directories=True)
sha = repo.head.commit.hexsha
short_sha = repo.git.rev_parse(sha, short=4)

This is the equivalent of running

git rev-parse --short=4 ...

on the command-line, which is the usual way of getting the short hash. This will return the shortest possible unambiguous hash of length >= 4 (You could pass in a smaller number, but since git's internal min is 4 it will have the same effect).

like image 80
lemonhead Avatar answered Sep 18 '22 18:09

lemonhead


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.

like image 26
Anshul Goyal Avatar answered Sep 22 '22 18:09

Anshul Goyal