【问题标题】:List the content of a directory for a specific git commit using GitPython使用 GitPython 列出特定 git 提交的目录内容
【发布时间】:2017-07-14 12:24:16
【问题描述】:

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

在终端,我要做的是:

git ls-tree --name-only 4b645551aa82ec55d1794d0bae039dd28e6c5704

如何在 GitPyhon 中做同样的事情?

根据我找到的类似问题 (GitPython get tree and blob object by sha) 的答案,我尝试递归遍历 base_commit.tree 及其 .trees,但我似乎一无所获。

有什么想法吗?

【问题讨论】:

    标签: python git gitpython


    【解决方案1】:

    确实,遍历树/子树是正确的方法。但是,内置的 traverse 方法可能会对子模块产生问题。相反,我们可以自己迭代地进行遍历并找到所有 blob 对象(其中包含给定提交时我们的 repo 中的文件)。无需使用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】:

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

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

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

      【讨论】:

        【解决方案3】:

        如果你知道目录的路径,假设它是foo/bar/baz,并且你有一个 GitPython Commit 对象,我们称之为commit,那么你可以访问目录中的blobs,就像@987654325 @ 然后获取单个 blob(文件)names 以在提交时间点提供该目录中的文件列表。

        import git
        
        repo = git.Repo('path/to/my/repo')
        commit = next(repo.iter_commits(max_count=1))
        files_in_dir = [b.name for b in commit.tree['foo']['bar']['baz'].blobs]
        

        【讨论】:

          猜你喜欢
          • 2013-02-02
          • 1970-01-01
          • 2016-07-25
          • 1970-01-01
          • 2016-08-07
          • 2015-02-02
          • 2012-12-29
          • 1970-01-01
          • 2012-06-16
          相关资源
          最近更新 更多