2012-05-05 21 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的代码但被拒绝。)

相关问题