You need to enable JavaScript to run this app. 如何调整现有代码实现21天时间窗口的Git churn统计
优惠活动
大模型
产品
解决方案
定价
更多

如何调整现有代码实现21天时间窗口的Git churn统计

实现方案

你现有的代码已经完成了单个commit的行级改动位置提取核心能力,只需要补充「被改动行的原始提交归属校验」逻辑即可实现需求,几乎不需要改动原有churn计算的核心代码:

核心改造思路

补充2个能力即可:

  • 预构建全局行级代码归属映射,记录每一行代码的提交人、提交时间
  • 在原有churn计数逻辑中新增过滤规则:仅统计同一作者提交、且提交时间距当前改动不足21天的代码改动

具体实现步骤

1. 预构建行级代码归属映射

结合你已有的git日志DataFrame,用git blame批量拉取所有文件的行归属信息,生成全局映射表,结构如下:

# 映射结构:{文件路径: {行号: (提交sha, 作者名, 提交时间)}}
line_ownership_map = {}

可以直接复用你现有DataFrame里的sha/author/date字段做匹配,不需要额外爬取git数据。

2. 按时间线顺序处理commit

调整commit遍历顺序,按提交时间升序处理,保证归属映射的更新逻辑符合代码变更的时间线:

# 先把date字段转成datetime格式方便计算时间差
df['date'] = pd.to_datetime(df['date'])
# 按提交时间升序排序后取commit列表
commits = df.sort_values('date')['sha'].unique().tolist()

3. 新增churn过滤逻辑

复用你原有calculate_churn返回的行级改动结果,新增校验逻辑统计符合要求的churn:

for commit_sha in commits:
    # 从现有DataFrame取当前commit的基础信息
    commit_info = df[df['sha'] == commit_sha].iloc[0]
    current_author = commit_info['author']
    current_commit_date = commit_info['date']
    
    # 调用原有方法,拿到行级改动结果(可以稍微改造下calculate_churn把files变量也返回)
    changed_files, total_contribution, total_churn = await self.calculate_churn(commit_sha)
    
    # 统计符合条件的短期自改写churn
    short_term_self_churn = 0
    for file_path, loc_changes in changed_files.items():
        # 新文件无历史归属,直接跳过
        if file_path not in line_ownership_map:
            continue
        for loc, change_val in loc_changes.items():
            # 改动行无历史归属,直接跳过
            if loc not in line_ownership_map[file_path]:
                continue
            orig_sha, orig_author, orig_commit_date = line_ownership_map[file_path][loc]
            # 校验两个条件:同一作者、提交间隔不足21天
            if orig_author == current_author and (current_commit_date - orig_commit_date).days < 21:
                short_term_self_churn += abs(change_val)
    
    # 此处可存储short_term_self_churn作为当前commit的统计结果
    # 最后更新行归属映射:把当前commit改动的行的归属替换为当前commit的信息即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 15:09:02