как сделать git diff текущей фиксации с последней фиксацией с помощью gitpython?

Я пытаюсь понять модуль gitpython,

hcommit = repo.head.commit
tdiff = hcommit.diff('HEAD~1')

но tdiff = hcommit.diff('HEAD^ HEAD') не работает!! также не ('HEAD~ HEAD').,

Я пытаюсь получить разностный вывод!


person Ciasto piekarz    schedule 25.02.2014    source источник
comment
Я признаю, что никогда не использовал код gitpython, но кажется очевидным, что если hcommit равен repo.head.commit, он привязан к этой конкретной фиксации, и, таким образом, hcommit.diff означает сравнение этой конкретной фиксации с чем-то другим. Чтобы получить различия двух произвольных коммитов, вам нужно выбрать другую отправную точку.   -  person torek    schedule 25.02.2014


Ответы (5)


import git

repo = git.Repo('repo_path')
commits_list = list(repo.iter_commits())

# --- To compare the current HEAD against the bare init commit
a_commit = commits_list[0]
b_commit = commits_list[-1]

a_commit.diff(b_commit)

Это вернет объект diff для коммитов. Есть и другие способы добиться этого. Например (это копия/вставка из http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information):

```

    hcommit = repo.head.commit
    hcommit.diff()                  # diff tree against index
    hcommit.diff('HEAD~1')          # diff tree against previous tree
    hcommit.diff(None)              # diff tree against working tree

    index = repo.index
    index.diff()                    # diff index against itself yielding empty diff
    index.diff(None)                # diff index against working copy
    index.diff('HEAD')              # diff index against current HEAD tree

```

person Jon Sonesen    schedule 22.09.2015

Я понял, как получить git diff с помощью gitPython.

import git
repo = git.Repo("path/of/repo/")

# the below gives us all commits
repo.commits()

# take the first and last commit

a_commit = repo.commits()[0]
b_commit = repo.commits()[1]

# now get the diff
repo.diff(a_commit,b_commit)

Вуаля !!!

person Ciasto piekarz    schedule 26.02.2014
comment
Я получаю AttributeError: 'Repo' object has no attribute 'diff', а Repo.diff не упоминается в документе по API. Нужно ли обновлять этот ответ? - person phihag; 06.09.2016
comment
Я не нашел commits() метод для repo, который я сделал: - person Viraj Wadate; 25.09.2019

Чтобы получить содержимое diff:

import git
repo = git.Repo("path/of/repo/")

# define a new git object of the desired repo
gitt = repo.git
diff_st = gitt.diff("commitID_A", "commitID_B")
person kebb    schedule 31.03.2016

Для правильного решения (без использования обратного вызова команды git) вы должны использовать опцию create_patch.

Чтобы сравнить текущий индекс с предыдущим коммитом:

diff_as_patch = repo.index.diff(repo.commit('HEAD~1'), create_patch=True)
print(diff_as_patch)
person Skapin    schedule 20.01.2016

Извините, что поднимаю старую тему... Если вам нужно узнать, какие файлы были изменены, вы можете использовать атрибут .a_path или .b_path объекта diff в зависимости от того, какой из них вы передадите ему первым. В приведенном ниже примере я использую головную фиксацию как a, поэтому я смотрю на a.

e.g:

# this will compare the most recent commit to the one prior to find out what changed.

from git import repo

repo = git.Repo("path/to/.git directory")
repoDiffs = repo.head.commit.diff('HEAD~1')

for item in repoDiffs:
    print(item.a_path)
person dan    schedule 25.10.2019