0

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

Gihan
  • 3,144
  • 2
  • 9
  • 36
Viren Sow
  • 41
  • 2
  • 4

1 Answers1

6

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.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
  • to get it as a clean string one can augment like follows: `subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode('ascii')` as per https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script#comment93332441_21901260 and elsewhere – matanster May 06 '20 at 11:21