我正在使用GitPython和裸存储库,我试图通过它的SHA获取特定的git对象.如果我直接使用git,我会这样做
git ls-tree sha_of_tree
git show sha_of_blob
Run Code Online (Sandbox Code Playgroud)
由于我正在使用GitPython并且我想获得一个特定的树,我执行以下操作:
repo = Repo("path_to_my_repo")
repo.tree("b466a6098a0287ac568ef0ad783ae2c35d86362b")
Run Code Online (Sandbox Code Playgroud)
并得到回报
<git.Tree "b466a6098a0287ac568ef0ad783ae2c35d86362b">
Run Code Online (Sandbox Code Playgroud)
现在我有一个树对象,但我无法访问其属性,如路径,名称,blob等.
repo.tree("b466a6098a0287ac568ef0ad783ae2c35d86362b").path
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\Python27\lib\site-packages\gitdb\util.py", line 238, in __getattr__
self._set_cache_(attr)
File "c:\Python27\lib\site-packages\git\objects\tree.py", line 147, in _set_cache_
super(Tree, self)._set_cache_(attr)
File "c:\Python27\lib\site-packages\git\objects\base.py", line 157, in _set_cache_
raise AttributeError( "path and mode attributes must have been set during %s object creation" % type(self).__name__ )
AttributeError: path and mode attributes must have been set during Tree object creation
Run Code Online (Sandbox Code Playgroud)
但如果我键入以下内容,它就可以了
repo.tree().trees[0].path
Run Code Online (Sandbox Code Playgroud)
我的问题的另一部分是如何使用GitPython获取blob对象.我注意到唯一的对象树有属性blob,所以为了通过SHA获得blob,我必须(a)首先知道它属于哪个树,(b)找到这个blob,然后(c)调用该data_stream方法.我可以这样做
repo.git.execute("git show blob_sha")
Run Code Online (Sandbox Code Playgroud)
但我想首先知道这是实现这一目标的唯一方法.
尝试这个:
def read_file_from_branch(self, repo, branch, path, charset='ascii'):
'''
return the contents of a file in a branch, without checking out the
branch
'''
if branch in repo.heads:
blob = (repo.heads[branch].commit.tree / path)
if blob:
data = blob.data_stream.read()
if charset:
return data.decode(charset)
return data
return None
Run Code Online (Sandbox Code Playgroud)
一般来说,一棵树有一些孩子,它们是斑点和更多的树。Blob 是该树的直接子级文件,其他树是该树的直接子级目录。
访问该树正下方的文件:
repo.tree().blobs # returns a list of blobs
Run Code Online (Sandbox Code Playgroud)
访问该树正下方的目录:
repo.tree().trees # returns a list of trees
Run Code Online (Sandbox Code Playgroud)
查看子目录中的 blob 怎么样:
for t in repo.tree().trees:
print t.blobs
Run Code Online (Sandbox Code Playgroud)
让我们获取之前第一个 blob 的路径:
repo.tree().blobs[0].path # gives the relative path
repo.tree().blobs[0].abspath # gives the absolute path
Run Code Online (Sandbox Code Playgroud)
希望这能让您更好地了解如何导航此数据结构以及如何访问这些对象的属性。
| 归档时间: |
|
| 查看次数: |
3140 次 |
| 最近记录: |