2012-11-08 105 views
7

我試圖做一個相當於git log filename在git倉庫使用pygit2。該文件只解釋如何做這樣的git logpygit2 blob歷史

from pygit2 import GIT_SORT_TIME 
for commit in repo.walk(oid, GIT_SORT_TIME): 
    print(commit.hex) 

你有什麼想法嗎?

感謝

編輯:

我有這樣的事情在此刻,或多或少精確:

from pygit2 import GIT_SORT_TIME, Repository 


repo = Repository('/path/to/repo') 

def iter_commits(name): 
    last_commit = None 
    last_oid = None 

    # loops through all the commits 
    for commit in repo.walk(repo.head.oid, GIT_SORT_TIME): 

     # checks if the file exists 
     if name in commit.tree: 
      # has it changed since last commit? 
      # let's compare it's sha with the previous found sha 
      oid = commit.tree[name].oid 
      has_changed = (oid != last_oid and last_oid) 

      if has_changed: 
       yield last_commit 

      last_oid = oid 
     else: 
      last_oid = None 

     last_commit = commit 

    if last_oid: 
     yield last_commit 


for commit in iter_commits("AUTHORS"): 
    print(commit.message, commit.author.name, commit.commit_time) 

回答

1

我會建議你只使用Git的命令行界面,它可以提供很好的格式化輸出,使用Python很容易解析。例如,要得到作者的名字,日誌信息,並提交給定文件的哈希值:

import subprocess 
subprocess.check_output(['git','log','--pretty="%H,%cn%n----%B----"','some_git_file.py']) 

對於格式說明符的完整列表,你可以傳遞給--pretty,看看文檔git loghttps://www.kernel.org/pub/software/scm/git/docs/git-log.html

0

另一種解決方法是懶惰地從給定提交中產生修訂文件。由於它是遞歸的,如果歷史記錄太大,它可能會中斷。

def revisions(commit, file, last=None): 
    try: 
     entry = commit.tree[file] 
    except KeyError: 
     return 
    if entry != last: 
     yield entry 
     last = entry 
    for parent in commit.parents: 
     for rev in revisions(parent, file, last): 
      yield rev