2012-05-05 27 views
4

我正在研究一個將在git回購中添加和更新文件的程序。由於我無法確定我正在使用的文件是否正在回購,我需要檢查它的存在 - 這似乎比我想象的要難。檢查一個對象是否在gitpython的回購中

'in'比較似乎不適用於gitpython中樹的非根級別。防爆。

>>> repo = Repo(path) 
>>> hct = repo.head.commit.tree 
>>>> 'A' in hct['documents'] 
False 
>>> hct['documents']['A'] 
<git.Tree "8c74cba527a814a3700a96d8b168715684013857"> 

所以我離開了懷疑,人們如何檢查一個給定的文件是一個Git樹試圖進行這項工作過嗎?試圖訪問一個不在樹中的文件的對象會拋出一個KeyError,所以我可以做試試。但是這對於例行存在檢查來說感覺像是對異常處理的使用不佳。

我錯過了一些非常明顯的東西嗎?如何使用gitpython(或者Python中的任何庫/方法)檢查​​提交樹中是否存在文件?

自答

OK,我在Tree class周圍挖,看看__contains__做什麼。原來,在子文件夾中搜索時,必須使用回購根的完整相對路徑來檢查文件是否存在。所以,檢查我上面做的工作版本是:

>>> 'documents/A' in hct['documents'] 
True 

回答

2

擴大比爾的解決方案,這裏是確定文件是否在回購的功能:

def fileInRepo(repo,path_to_file): 
    ''' 
    repo is a gitPython Repo object 
    path_to_file is the full path to the file from the repository root 
    returns true if file is found in the repo at the specified path, false otherwise 
    ''' 
    pathdir = os.path.dirname(path_to_file) 

    #Build up reference to desired repo path 
    rsub = repo.head.commit.tree 
    for path_element in pathdir.split(os.path.sep): 
     rsub = rsub[path_element] 
    return(path_to_file in rsub) 

用法示例:

file_found = fileInRepo(repo, 'documents/A') 
1

EricP的回答有一個錯誤。這裏有一個固定的版本:

def fileInRepo(repo,filePath): 
    ''' 
    repo is a gitPython Repo object 
    filePath is the full path to the file from the repository root 
    returns true if file is found in the repo at the specified path, false otherwise 
    ''' 
    pathdir = os.path.dirname(filePath) 

    #Build up reference to desired repo path 
    rsub = repo.head.commit.tree 

    for path_element in pathdir.split(os.path.sep): 

     # If dir on file path is not in repo, neither is file. 
     try : 
      rsub = rsub[path_element] 

     except KeyError : 

      return False 

    return(filePath in rsub) 

用法:

file_found = fileInRepo(repo, 'documents/A') 

這是非常相似的EricP的代碼,但處理將含有該文件的文件夾不在回購的情況。在這種情況下,EricP的函數會引發KeyError。這個函數返回False。

(我提供編輯EricP的代碼但被拒絕。)

相關問題