Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file data from a specific git commit using gitpython

Tags:

gitpython

I am trying get a file from a specific commit using gitpython python-module.

I'm able to get the file (with content) from the latest commit. However I want to get the file (with content) from a specific previous git commit.

repo = git.Repo("G:\myrespo")
obj = repo.git.get_object_data(x.a_blob)

How can I get it ?

like image 798
Hari K Avatar asked Feb 15 '18 07:02

Hari K


People also ask

How do you search for a specific commit?

Looking up changes for a specific commit If you have the hash for a commit, you can use the git show command to display the changes for that single commit. The output is identical to each individual commit when using git log -p .

How do I clone a git repo in Python?

We can use git module in python to clone the repository from git. Clone the repository you want to work with in local system. So in clone_from methods pass the two arguments in which first argument is url of your repository and second argument is the location of your directory where you want to cloned the repo.

What is the git commit command?

The git commit command captures a snapshot of the project's currently staged changes. Committed snapshots can be thought of as “safe” versions of a project—Git will never change them unless you explicitly ask it to.


1 Answers

Here's one way to get a file from a specific commit:

import io

repo = Repo('G:\myrespo')

# Retrieve specific commit from repo
# The revision specifier must be one of the specifiers defined in
# https://git-scm.com/docs/git-rev-parse#_specifying_revisions
# In this example, we'll use a SHA-1

commit = repo.commit('7ba4789adf73c0555fbffad3b62d61e411c3b1af')

# Retrieve a file from the commit tree
# You can use the path helper to get the file by filename 

targetfile = commit.tree / 'some_file.md'

# Retrieve contents of targetfile

with io.BytesIO(targetfile.data_stream.read()) as f:
    print(f.read().decode('utf-8'))

targetfile is a standard GitPython Object:

>>> targetfile.name
'some_file.md'
>>> targetfile.type
'blob'
like image 156
stacybrock Avatar answered Sep 17 '22 01:09

stacybrock