2011-11-28 28 views
2

我正在編寫一個Python腳本以獲取將由git pull操作應用的提交列表。優秀的GitPython library是一個很好的開始,但git的微妙的內部運作正在殺死我。現在,這裏是我的時刻(簡體和註釋的版本):GitPython:獲取尚未應用的遠程提交列表

repo = git.Repo(path)       # get the local repo 
local_commit = repo.commit()     # latest local commit 
remote = git.remote.Remote(repo, 'origin')  # remote repo 
info = remote.fetch()[0]      # fetch changes 
remote_commit = info.commit      # latest remote commit 
if local_commit.hexsha == remote_commit.hexsha: # local is updated; end 
    return 
               # for every remote commit 
while remote_commit.hexsha != local_commit.hexsha: 
    authors.append(remote_commit.author.email) # note the author 
    remote_commit = remote_commit.parents[0]  # navigate up to the parent 

本質上,它獲得了作者對於將在未來git pull應用於所有的提交。這是行之有效的,但它有以下問題:

  • 當本地提交超前遠程,我的代碼只是打印所有提交到第一個。
  • 遠程提交可以有多個父代,並且本地提交可以是第二個父代。這意味着我的代碼將永遠不會在遠程存儲庫中找到本地提交。

我可以處理位於本地的遠程存儲庫:在同一時間看另一個方向(本地到遠程),代碼會變得雜亂,但它的工作原理。但是最後一個問題是讓我失望:現在我需要爲一個(可能無限的)樹找到一個匹配的本地提交。這不僅僅是理論上的問題:我最近的變化是一個回購合併,它提出了這個問題,所以我的腳本不能工作。

獲取遠程存儲庫中提交的有序列表,如repo.iter_commits()對本地回購會有幫助。但我還沒有在documentation找到如何做到這一點。我能否獲得遠程存儲庫的Repo對象?

是否有另一種方法可能讓我在那裏,我用錘子釘螺釘?

回答

0

我意識到提交樹總是這樣:一個提交有兩個父母,並且父母都有相同的父母。這意味着第一次提交有兩個父母,但只有一個祖父母。

因此,編寫自定義迭代器來檢查提交(包括髮散樹)並不困難。它看起來像這樣:

def repo_changes(commit): 
    "Iterator over repository changes starting with the given commit." 
    number = 0 
    next_parent = None 
    yield commit       # return the first commit itself 
    while len(commit.parents) > 0:   # iterate 
    same_parent(commit.parents)   # check only one grandparent 
    for parent in commit.parents:  # go over all parents 
     yield parent      # return each parent 
     next_parent = parent    # for the next iteration 
    commit = next_parent     # start again 

函數same_parent()當有兩個父母和多個祖父母時發出警報。現在迭代未提交的提交是一件簡單的事情:

for commit in repo_changes(remote_commit): 
    if commit.hexsha == local_commit.hexsha: 
    return 
    authors.append(remote_commit.author.email) 

爲了清楚起見,我已經留下了一些細節。爲了避免到回購期結束,我再也沒有超過預定數量的提交(在我的案例中爲20)。我還事先檢查了本地回購不在遠程回購之前。除此之外,它工作得很好!現在我可以提醒所有提交作者他們的更改正在合併。

相關問題