【问题标题】:How to get number of commits of a repo using GitPython?如何使用 GitPython 获取 repo 的提交次数?
【发布时间】:2019-04-25 07:58:39
【问题描述】:

我是 GitPython 的新手,我想知道一个 repo 的提交次数。 我希望在 GitPython 中替代“git rev-list --count HEAD”,是否有特定的功能可以做到这一点?

我试图让 repo 的每个提交的列表显示然后它的大小,但最后一次提交只出现。 感谢帮助, 问候。

【问题讨论】:

    标签: python-3.x git gitpython


    【解决方案1】:

    试试代码:

    import git
    
    repo_path = 'foo'
    repo = git.Repo(repo_path)
    # get all commits reachable from "HEAD"
    commits = list(repo.iter_commits('HEAD'))
    # get the number of commits
    count = len(commits)
    

    我不熟悉 Python 3.x。由于 Python 2.x 和 3.x 之间的差异,可能会出现错误。

    经过一番研究,我发现我们可以直接调用git rev-list --count HEAD

    import git
    
    repo_path = 'foo'
    repo = git.Repo(repo_path)
    count = repo.git.rev_list('--count', 'HEAD')
    

    注意命令名中的-在代码中应该是_

    【讨论】:

    • 如果没有提交历史记录(0 次提交),第一个带有 iter_commits 的示例可能会引发异常。
    【解决方案2】:

    您可以使用iter_commits() 获取所有提交的列表。迭代它并计算提交数

    from git import Repo
    
    repo = Repo()
    
    print(len(list(repo.iter_commits())))
    

    【讨论】:

    • 现在可以使用了!非常感谢我之前没有尝试过这种方式:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2012-12-29
    相关资源
    最近更新 更多