Skip to main content
 首页 » 编程设计

python之如何使用 python(dulwich) 获取指定文件的最后一次提交

2025年05月04日18jyk

我需要使用 python 指定文件的作者姓名和上次提交时间。 目前,我正在尝试使用 dulwich .

有很多 API 可以检索特定 SHA 的对象,例如:

repo = Repo("myrepo") 
head = repo.head() 
object = repo.get_object(head) 
author = object.author 
time = object.commit_time 

但是,我如何知道特定文件的最近提交?有没有办法像这样检索它:

repo = Repo("myrepo") 
commit = repo.get_commit('a.txt') 
author = commit.author 
time = commit.commit_time 

或

repo = Repo("myrepo") 
sha = repo.get_sha_for('a.txt') 
object = repo.get_object(sha) 
author = object.author 
time = object.commit_time 

谢谢。

请您参考如下方法:

一个较短的示例,使用 Repo.get_walker:

r = Repo(".") 
p = b"the/file/to/look/for" 
 
w = r.get_walker(paths=[p], max_entries=1) 
try: 
    c = next(iter(w)).commit 
except StopIteration: 
     print "No file %s anywhere in history." % p 
else: 
    print "%s was last changed at %s by %s (commit %s)" % ( 
        p, time.ctime(c.author_time), c.author, c.id)