如何从 GitPython 中的 repo 获取目录 git 详细信息?

How to get the directory git detail from repo in GitPython?

我想从 GitPython 中的 repo(项目)中获取目录(称为模块)的提交数。

> print("before",modulePath) 
> repo = Repo(modulePath)                    
> print(len(list(repo.iter_commits())))

当我尝试打印提交的目录数量时,它说回购不是有效的 git 回购。

  • before /home/user/project/module
  • git.exc.InvalidGitRepositoryError: /home/user/project/module

欢迎任何帮助或想法:) 谢谢

这是我的一个旧项目的示例代码(未打开,因此没有存储库链接):

def parse_commit_log(repo, *params):
    commit = {}
    try:
        log = repo.git.log(*params).split("\n")
    except git.GitCommandError:
        return

    for line in log:
        if line.startswith("    "):
            if not 'message' in commit:
                commit['message'] = ""
            else:
                commit['message'] += "\n"
            commit['message'] += line[4:]
        elif line:
            if 'message' in commit:
                yield commit
                commit = {}
            else:
                field, value = line.split(None, 1)
                commit[field.strip(":")] = value
    if commit:
        yield commit

解释:

该函数需要 Repo 的实例以及您将传递给 git log 命令的相同参数。因此,您的情况下的用法可能如下所示:

repo = git.Repo('project_path')
commits = list(parse_commit_log(repo, 'module_dir'))

在内部,repo.git.log 正在调用 git log 命令。它的输出看起来有点像这样:

commit <commit1 sha>
Author: User <username@email.tld>
Date:   Sun Apr 7 17:08:31 2019 -0400

    Commit1 message

commit <commit2 sha>
Author: User2 <username2@email.tld>
Date:   Sun Apr 7 17:08:31 2019 -0400

    Commit2 message

parse_commit_log 解析此输出并生成提交消息。您需要再添加几行以获得提交 sha、作者和日期,但这应该不会太难。