我正在开发一个程序,该程序将在 git 存储库中添加和更新文件。由于我无法确定我正在使用的文件当前是否在 repo 中,因此我需要检查它是否存在——这个操作似乎比我想象的要难。
“in”比较似乎不适用于 gitpython 树的非根级别。前任。
>>> repo = Repo(path)
>>> hct = repo.head.commit.tree
>>>> 'A' in hct['documents']
False
>>> hct['documents']['A']
<git.Tree "8c74cba527a814a3700a96d8b168715684013857">
Run Code Online (Sandbox Code Playgroud)
所以我想知道,人们如何在尝试处理之前检查给定的文件是否在 git 树中?尝试访问不在树中的文件的对象将引发 KeyError,因此我可以尝试捕获。但这感觉就像在例行存在检查中使用异常处理很差。
我错过了一些非常明显的东西吗?一次如何使用 gitpython(或 Python 中的任何库/方法)检查提交树中文件的存在?
自我回答
好的,我在Tree 类中四处挖掘,看看 __contains__ 做了什么。事实证明,在子文件夹中搜索时,必须使用来自 repo 根目录的完整相对路径来检查文件是否存在。所以我上面做的检查的一个工作版本是:
>>> 'documents/A' in hct['documents']
True
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
用法:
file_found = fileInRepo(repo, 'documents/A')
Run Code Online (Sandbox Code Playgroud)
这与 EricP 的代码非常相似,但处理包含文件的文件夹不在存储库中的情况。KeyError在这种情况下,EricP 的函数会引发 a 。该函数返回False.
(我提出编辑 EricP 的代码,但被拒绝了。)