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

时间:2013-05-20 03:38:05

标签: python git dulwich

我需要使用python的指定文件的作者姓名和上次提交时间。 Currentrly,我正在尝试使用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

谢谢。

2 个答案:

答案 0 :(得分:5)

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

r = Repo(".")
p = "the/file/to/look/for"

w = r.get_walker(paths=[p], max_entries=1)
try:
    c = iter(w).next().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)

答案 1 :(得分:1)

这样的事似乎有效:

from dulwich import repo, diff_tree

fn = 'a.txt'
r = repo.Repo('.')
prev = None
walker = r.get_graph_walker()
cset = walker.next()
while cset is not None:

    commit = r.get_object(cset)
    if prev is None:
        prev = commit.tree
        cset = walker.next()
        continue


    res = None
    delta = diff_tree.tree_changes(r, prev, commit.tree)
    for x in diff_tree.tree_changes(r, prev, commit.tree):
        if x.new.path == fn:
            res = cset
            break

    if res:
        break

    prev = commit.tree
    cset = walker.next()

print fn, res