You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Git获取repo.iter_commits(branch)提交的改动数据?

获取Git提交的改动文件数、新增行数与删除行数

在GitPython中,你可以通过两种方式获取提交的改动文件数量、新增行数和删除行数:

方法一:使用commit.stats属性(简洁高效)

GitPython的Commit对象内置了stats属性,直接封装了提交的统计信息,无需手动遍历diff:

import datetime
from git import Repo

repo = Repo("/path/to/your/repository")
branch = "main"  # 替换为目标分支名

for commit in repo.iter_commits(branch):
    author_name = commit.author.name
    commit_id = commit.hexsha  # 推荐用hexsha获取字符串格式的提交ID
    commit_authored_date = datetime.datetime.fromtimestamp(commit.authored_date)
    commit_committed_date = datetime.datetime.fromtimestamp(commit.committed_date)
    
    # 提取统计数据
    commit_stats = commit.stats
    num_files_touched = commit_stats.total['files']
    num_lines_added = commit_stats.total['insertions']
    num_lines_removed = commit_stats.total['deletions']
    
    # 示例输出
    print(f"提交 {commit_id}: 作者{author_name},改动{num_files_touched}个文件,新增{num_lines_added}行,删除{num_lines_removed}行")

commit.stats.total字典包含三个核心字段:

  • files: 改动的文件总数
  • insertions: 新增行数
  • deletions: 删除行数

如果需要查看单个文件的变更统计,可以遍历commit.stats.files,每个键是文件名,对应的值包含该文件的insertions、deletions和lines(总行数变更)。

方法二:通过diff手动计算(自定义场景)

如果需要更细粒度的控制(比如过滤特定类型文件),可以通过对比当前提交与父提交的diff来统计:

import datetime
from git import Repo

repo = Repo("/path/to/your/repository")
branch = "main"

for commit in repo.iter_commits(branch):
    author_name = commit.author.name
    commit_id = commit.hexsha
    commit_authored_date = datetime.datetime.fromtimestamp(commit.authored_date)
    commit_committed_date = datetime.datetime.fromtimestamp(commit.committed_date)
    
    num_files_touched = 0
    num_lines_added = 0
    num_lines_removed = 0
    
    # 处理初始提交(无父提交)
    if commit.parents:
        diffs = commit.diff(commit.parents[0])
    else:
        # 对比空树获取初始提交的所有文件变更
        diffs = commit.diff(repo.tree())
    
    # 遍历diff统计数据
    for diff in diffs:
        num_files_touched += 1
        file_stats = diff.stats
        num_lines_added += file_stats['insertions']
        num_lines_removed += file_stats['deletions']
    
    # 示例输出
    print(f"提交 {commit_id}: 作者{author_name},改动{num_files_touched}个文件,新增{num_lines_added}行,删除{num_lines_removed}行")

这种方法适合需要对diff进行额外处理的场景,比如跳过二进制文件、只统计特定目录下的变更等。

内容的提问来源于stack exchange,提问作者Gargee Suresh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:55:25