使用GitPython

时间:2017-07-14 12:24:17

标签: python git gitpython

使用GitPython,我试图在给定的提交中列出目录的内容(即当时目录的"快照")。

在终端中,我要做的是:

git ls-tree --name-only 4b645551aa82ec55d1794d0bae039dd28e6c5704

我怎样才能在GitPyhon中做同样的事情?

根据我在类似问题(GitPython get tree and blob object by sha)中找到的答案,我已经尝试递归遍历base_commit.tree及其.trees,但我没有&#39似乎无处可去。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

我找不到比实际调用execute更优雅的方式。 这是最终结果:

configFiles = repo.git.execute(
    ['git', 'ls-tree', '--name-only', commit.hexsha, path]).split()

其中commitgit.Commit个对象,path是我感兴趣的路径。

答案 1 :(得分:0)

实际上,遍历树/子树是正确的方法。但是,内置的traverse方法可能对子模块有问题。取而代之的是,我们可以迭代地遍历遍历并找到所有blob对象(这些对象包含给定提交中我们回购中的文件)。无需使用execute

def list_files_in_commit(commit):
    """
    Lists all the files in a repo at a given commit

    :param commit: A gitpython Commit object
    """
    file_list = []
    dir_list = []
    stack = [commit.tree]
    while len(stack) > 0:
        tree = stack.pop()
        # enumerate blobs (files) at this level
        for b in tree.blobs:
            file_list.append(b.path)
        for subtree in tree.trees:
            stack.append(subtree)
    # you can return dir_list if you want directories too
    return file_list

如果您希望文件受到给定提交的影响,可以通过commit.stats.files使用。

答案 2 :(得分:0)

如果您知道目录的路径,则假设它是foo/bar/baz,并且您有一个GitPython Commit对象,我们将其称为commit,然后您就可以访问{{1} {} blobs这样的目录中的},然后获取单个blob(文件)commit.tree['foo']['bar']['baz'].blobs,以在提交时提出该目录中的文件列表。

name