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

Git命令行实现按文件统计作者贡献行及行号范围

Git文件作者贡献行号连续范围统计

你可以通过扩展Git命令结合Awk脚本实现需求,下面是直接可用的命令行方案,能批量处理所有文件,自动将每个作者的贡献行号合并为连续范围:

完整脚本

git ls-tree -r HEAD | cut -c54- | while read -r file; do
    echo "=== $file ==="
    git blame "$file" --line-porcelain | awk '
        /^author / {
            current_author = substr($0, 8)
        }
        /^line-number / {
            line = $2
            if (current_author != prev_author) {
                if (prev_author != "") {
                    print_range()
                }
                prev_author = current_author
                start_line = line
                end_line = line
            } else {
                if (line == end_line + 1) {
                    end_line = line
                } else {
                    print_range()
                    start_line = line
                    end_line = line
                }
            }
        }
        END {
            if (prev_author != "") {
                print_range()
            }
        }
        function print_range() {
            printf "%s: ", prev_author
            if (start_line == end_line) {
                printf "%d\n", start_line
            } else {
                printf "%d-%d\n", start_line, end_line
            }
        }
    ' | sort | uniq -c | sort -rn
done

脚本说明

  1. 文件遍历:用git ls-tree -r HEAD获取当前HEAD的所有文件,通过while read -r file安全处理含空格的文件名(替代原脚本的for循环,避免文件名拆分问题)。
  2. Blame数据提取:git blame --line-porcelain输出机器可读格式,从中提取每行的author(作者)和line-number(行号)。
  3. 行号范围合并:Awk脚本跟踪同一作者的连续行号,当行号不连续时输出上一段范围,最终将零散行号合并为x-y格式的连续区间。
  4. 统计与排序:通过sort | uniq -c | sort -rn统计每个作者的贡献行数并按降序排列,和你原脚本的统计逻辑一致。

注意事项

  • 处理200万行代码时,脚本会遍历每个文件执行git blame,耗时取决于仓库大小,建议后台运行(末尾加&)或分批次处理(比如通过grep过滤特定目录)。
  • 如需排除特定文件,可在git ls-tree后添加过滤,例如排除图片:git ls-tree -r HEAD | grep -vE '\.(png|jpg|gif)$' | cut -c54-。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:40:46