Reputation: 41
I would like to know the exact git commit id in a repository. May be like latest commit(most recent) and 2nd most recent commit.
I have tried git commands like below, but I need the same in python script.
$ git rev-parse @ most recent Output: 669ec6662bedc7a9962bef83612a33522a8e4fb8
$ git rev-parse @~ 2nd most recent Output: 97a90650792efdbef3f6abb92bd6108c11889cc6
Upvotes: 0
Views: 6695
Reputation: 11328
You can do that using subprocess
module. This code will return a list containing the last two commits, where the first item in the list is the latest.
import subprocess
def get_git_revisions_hash():
hashes = []
hashes.append(subprocess.check_output(['git', 'rev-parse', 'HEAD']))
hashes.append(subprocess.check_output(['git', 'rev-parse', 'HEAD^']))
return hashes
The same can also be achieved with list comprehension. This solution is more extendable, because you don't need to add additional subprocess calls:
commits = ['HEAD', 'HEAD^']
def get_git_revisions_hash2():
return [subprocess.check_output(['git', 'rev-parse', '{}'.format(x)])
for x in commits]
There is also GitPython module, which gives you an interface to git. You can read the docs, it gives more builtin tools for git.
Upvotes: 6