pythongitdulwich

How to get last commit for specified file with python(dulwich)?


I need author name and last commit time for a specified file with python. Currentrly, I'm trying to use dulwich.

There're plenty of apis to retrieve objects for a specific SHA like:

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

But, how do i know the recent commit for the specific file? Is there a way to retrieve it like:

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

or

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

Thank you.


Solution

  • Something like this seems to work:

    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