Как получить данные файла из определенного коммита git с помощью gitpython

Я пытаюсь получить файл из определенного коммита, используя python-модуль gitpython.

Я могу получить файл (с содержимым) из последней фиксации. Однако я хочу получить файл (с содержимым) из определенного предыдущего коммита git.

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

Как я могу это получить?


person Hari K    schedule 15.02.2018    source источник
comment
Вы нашли способ сделать это? Столкнулся с той же проблемой :^   -  person Kioko Key    schedule 08.11.2018


Ответы (2)


Вот один из способов получить файл из определенного коммита:

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 — это стандартный объект GitPython:

>>> targetfile.name
'some_file.md'
>>> targetfile.type
'blob'
person stacybrock    schedule 27.02.2019

Вы также можете использовать PyDriller (оболочку для GitPython), это упрощает задачу:

for commit in RepositoryMining("repo", single="commit_hash").traverse_commits():
    # list of modified files of the commit
    commit.modifications
person Davide Spadini    schedule 06.03.2019