Programmatically `git status` with dulwich
-
12-06-2021 - |
문제
I'm wondering how I can perform the equivalent of git status
with dulwich?
I tried this:
After adding/changing/renaming some files and staging them for commit, this is what I've tried doing:
from dulwich.repo import Repo
from dulwich.index import changes_from_tree
r = Repo('my-git-repo')
index = r.open_index()
changes = index.changes_from_tree(r.object_store, r['HEAD'].tree)
Outputs the following:
>>> list(changes)
(('Makefile', None), (33188, None), ('9b20...', None))
(('test/README.txt', 'test/README.txt'), (33188, 33188), ('484b...', '4f89...'))
((None, 'Makefile.mk'), (None, 33188), (None, '9b20...'))
((None, 'TEST.txt'), (None, 33188), (None, '2a02...'))
But this output requires that I further process it to detect:
- I modified
README.txt
. - I renamed
Makefile
toMakefile.mk
. - I added
TEST.txt
to the repository.
The functions in dulwich.diff_tree
provide a much nicer interface to tree changes... is this not possible before actually committing?
해결책
You should be able to use dulwich.diff_tree.tree_changes
to detect the changes between two trees.
One of the requirements for this is that you add the relevant tree objects to the object store - you can use dulwich.index.commit_index
for this.
다른 팁
For completeness, a working sample:
from dulwich.repo import Repo
from dulwich.diff_tree import tree_changes
repo = Repo("./")
index = repo.open_index()
try:
head_tree = repo.head().tree
except KeyError: # in case of empty tree
head_tree = dulwich.objects.Tree()
changes = list(tree_changes(repo, head_tree, index.commit(repo.object_store)))
for change in changes:
print "%s: %s"%(change.type,change.new.path)
제휴하지 않습니다 StackOverflow