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

久未见 提交于 2020-01-16 07:08:11

问题


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.


回答1:


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



回答2:


A shorter example, using 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)


来源:https://stackoverflow.com/questions/16642203/how-to-get-last-commit-for-specified-file-with-pythondulwich

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!