nanounanue
nanounanue

Reputation: 8362

How to get the last commit of an specific file using python?

I tried with GitPython, but I am just getting the actual commit git hash.

import git
repo = git.Repo(search_parent_directories=True)
repo.head.commit.hexsha

But, for trazability I want to store the git commit hash of an specific file, i.e. the equivalent of this command (using git)

git log -n 1 --pretty=format:%h -- experiments/test.yaml

Is it possible to achive with GitPython?

Upvotes: 1

Views: 1635

Answers (1)

VonC
VonC

Reputation: 1329122

An issue like how do I get sha key for any repository' file. points to the Tree object, as providing an access for recursive traversal of git trees, with access to all meta-data, including the SHA1 hash.

self.assertEqual(tree['smmap'], tree / 'smmap')          # access by index and by sub-path
for entry in tree:                                         # intuitive iteration of tree members
    print(entry)
blob = tree.trees[0].blobs[0]                              # let's get a blob in a sub-tree
assert blob.name

blob.hexsha would be the SHA1 of the blob.

Upvotes: 1

Related Questions