如何在GitPython中从repo获取git详细目录?

2024-10-01 11:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

当我试图打印目录中提交的数量时,它显示repo不是有效的git repo。在

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

欢迎任何帮助或建议:) 谢谢


Tags: 项目git目录projecthomelenrepo次数
1条回答
网友
1楼 · 发布于 2024-10-01 11:27:18

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

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命令的相同参数。因此,在您的案例中,用法如下:

^{pr2}$

在内部,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解析此输出并生成提交消息。您需要再添加几行来获得commit sha、author和date,但这不应该太难。在

相关问题 更多 >