使用gitpython解析git日志

2024-09-27 07:20:02 发布

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

在python中,我希望获取git存储库中文件的所有提交日志,并解析日志中的信息(散列、作者姓名、作者邮件、作者日期、提交者姓名、提交者邮件、提交日期和提交消息)。目前,我可以使用gitpython或通过子进程调用shell命令来获取原始git日志。在

使用gitpython:

g=git.Git(path)
loginfo=g.log("--pretty=fuller",'--follow',"<filename>")

使用子程序调用:

^{pr2}$

但是,在这之后,我想解析原始日志,但是在gitpython中找不到合适的库/方法。另外,我还希望日期以python日期时间格式进行解析。你能帮忙吗?在


Tags: 文件pathgit命令信息消息进程邮件
2条回答

您可以考虑使用PyDriller,这是一个围绕GitPython的包装器,它使这些事情变得更简单。有一个名为get_commits_modified_file()的函数:

gr = GitRepository("repo_path")
commits = gr.get_commits_modified_file("filepath") # this return a list of commits hash

然后您可以:

^{pr2}$

您可以使用以下方法获取所有存储库提交:

import git
repo = git.Repo("/home/user/.emacs.d")
commits = list(repo.iter_commits("master", max_count=5)))

然后您就可以确定gitpython提供了什么样的数据:

^{pr2}$

其中包括:

  • 作者
  • 承诺日期时间
  • 赫什
  • 消息
  • 统计

举个例子:

>>> commits[0].author
<git.Actor "azzamsa <foo@bar.com>">

>>> commits[0].hexsha
'fe4326e94eca2e651bf0081bee02172fedaf0b90'

>>> commits[0].message
'Add ocaml mode\n'

如果要检查提交是否包含文件(如果 你想从该文件获取所有提交)。您可以使用:

def is_exists(filename, sha):
    """Check if a file in current commit exist."""
    files = repo.git.show(" pretty=", " name-only", sha)
    if filename in files:
        return True

然后从文件中获取所有提交:

def get_file_commits(filename):
    file_commits = []
    for commit in commits:
        if is_exists(filename, commit.hexsha):
            file_commits.append(commit)

    return file_commits

例如,我想从'初始标高'文件:

initel_file_commits = get_file_commits('init.el')

>>> initel_file_commits
[<git.Commit "fe4326e94eca2e651bf0081bee02172fedaf0b90">, <git.Commit
"e4f39891fb484a95ea76e8e07244b908e732e7b3">]

确保功能正常工作:

>>> initel_file_commits[0].stats.files
{'init.el': {'insertions': 1, 'deletions': 0, 'lines': 1}, 'modules/aza-ocaml.el': {'insertions': 28, 'deletions': 0, 'lines': 28}}

>>> initel_file_commits[1].stats.files
{'init.el': {'insertions': 1, 'deletions': 0, 'lines': 1}, 'modules/aza-calfw.el': {'insertions': 65, 'deletions': 0, 'lines': 65}, 'modules/aza-home.el': {'insertions': 0, 'deletions': 57, 'lines': 57}}

希望有帮助。在

相关问题 更多 >

    热门问题