2013-05-20 50 views
1

我需要使用python指定文件的作者姓名和上次提交時間。當前,我正在嘗試使用dulwich如何使用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 

謝謝。

回答

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 
+0

謝謝@djc。除非這不起作用。你提供瞭解決我的問題的線索。稍後我會添加我的解決方案。再次感謝你。 – ccoroom

+0

請注意,您可以爲get_graph_walker()指定* paths *參數,在這種情況下,它只會生成觸及這些路徑的條目。這應該簡化代碼。 – jelmer

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) 
相關問題