GitPython get tree and blob object by sha

前端 未结 3 940
礼貌的吻别
礼貌的吻别 2021-01-12 10:06

I\'m using GitPython with a bare repository and I\'m trying to get specific git object by its SHA. If I used git directly, I would just do this

git ls-tree s         


        
相关标签:
3条回答
  • 2021-01-12 10:18

    Try this:

       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
    
    0 讨论(0)
  • 2021-01-12 10:22

    In general, a tree has children which are blobs and more trees. The blobs are files that are direct children of that tree and the other trees are directories that are direction children of that tree.

    Accessing the files directly below that tree:

    repo.tree().blobs # returns a list of blobs
    

    Accessing the directories directly below that tree:

    repo.tree().trees # returns a list of trees
    

    How about looking at the blobs in the subdirectories:

    for t in repo.tree().trees:
        print t.blobs
    

    Let's get the path of the first blob from earlier:

    repo.tree().blobs[0].path # gives the relative path
    repo.tree().blobs[0].abspath # gives the absolute path
    

    Hopefully this gives you a better idea of how to navigate this data structure and how to access the attributes of these objects.

    0 讨论(0)
  • 2021-01-12 10:36

    I was looking for this because I had the same issue, and I found a solution:

    >>> import binascii
    >>> id_to_find = repo.head.commit.tree['README'].hexsha  # For example
    >>> id_to_find
    "aee35f14ee5515ee98d546a170be60690576db4b"
    >>> git.objects.blob.Blob(repo, binascii.a2b_hex(id_to_find))
    <git.Blob "aee35f14ee5515ee98d546a170be60690576db4b">
    

    I feel like there should be a way to reference Blob through the repo, but I couldn't find it.

    0 讨论(0)
提交回复
热议问题