gpt4 book ai didi

gitpython - 检查一个对象是否在 gitpython 的 repo 中

转载 作者:行者123 更新时间:2023-12-01 01:18:50 25 4
gpt4 key购买 nike

我正在开发一个程序,该程序将在 git 存储库中添加和更新文件。由于我无法确定我正在使用的文件当前是否在 repo 中,因此我需要检查它是否存在——这个操作似乎比我想象的要难。

“in”比较似乎不适用于 gitpython 树的非根级别。前任。

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

所以我想知道,人们如何在尝试处理之前检查给定的文件是否在 git 树中?尝试访问不在树中的文件的对象将引发 KeyError,因此我可以 try catch 。但这感觉就像在例行存在检查中使用异常处理很差。

我错过了一些非常明显的东西吗?一次如何使用 gitpython(或 Python 中的任何库/方法)检查​​提交树中文件的存在?

自我回答

好的,我在 Tree class 中挖掘了看看 __contains__ 做了什么。事实证明,在子文件夹中搜索时,必须使用来自 repo 根目录的完整相对路径来检查文件是否存在。所以我上面做的检查的一个工作版本是:
>>> 'documents/A' in hct['documents']
True

最佳答案

EricP's answer有一个错误。这是一个固定版本:

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 的代码非常相似,但处理包含文件的文件夹不在 repo 中的情况。 EricP 的函数引发了 KeyError在这种情况下。此函数返回 False .

(我提议编辑 EricP 的代码但被拒绝了。)

关于gitpython - 检查一个对象是否在 gitpython 的 repo 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10466449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com