May 10, 2023
By: 马海强

利用git log统计代码情况

使用git log命令统计

git log 功能何其强大,配上SHELL 基础+三剑客无所不能。 以下是最近用到的几个统计场景。

统计代码行数

  1. 按author统计一段时间内的所有提交的行数

git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --author="$name" --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }'; done

  1. 统计文档以外的代码行数,下面忽略.md和.org文件格式文件

git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --author="$name" --pretty=tformat: --numstat | awk '!/(\.md$|\.org$)/ { add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }'; done

  1. 排除doc和docs两个文件夹的统计

git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --author="$name" --pretty=tformat: --numstat | awk 'NR==FNR && /doc|docs/ { excluded[$0]++; next } !($0 in excluded) { add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", int(add), int(subs), int(loc) }' - <(find . -path "./doc" -prune -o -path "./docs" -prune -o -type f -print); done

4 只统计某些类型的文件


 git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59"  --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log  --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --author="$name" --pretty=tformat: --numstat | grep "\(|.clj\|.cljs\|.js\|.ts\|.css\|.vue\|.scss\|.java\|.sql\)$" | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }' -; done
  1. 增加文件夹过滤,比如统计src目录下的,同时排除md文件和org文件

git log --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log --author="$name" --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --pretty=tformat: --numstat -- src/ | awk '!/(\.md$|\.org$)/ { add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", int(add), int(subs), int(loc) }'; done


统计代码提交次数

以下统计,前20名成员commit次数

 git log  --after="2023-01-01 00:00:00" --before="2023-03-31 23:59:59" --pretty='%aN' | sort | uniq -c | sort -k1 -n -r | head -n 20

统计文件修改频次

git log --after="2022-01-01 00:00:00" --before="2023-03-31 23:59:59" --pretty=format: --name-only | grep -v '^$' | sort | uniq -c | sort -rn | head -n 10

使用codeup阿里云统计

aliyun提供了可视化的度量表,可供关注用户使用

image-20220906212054307

其他

还有些统计工具,像大神还针对clojure做了扩展的clocgitinspectorgitstats等,学无止境。

Tags: git