# # 克隆仓库(如果已经克隆,则不需要这一步)
# git clone https://github.com/username/repo-name.git
# # 进入仓库目录
# cd repo-name
# # 统计代码行数(包括了所有的commit)
# git log --pretty=tformat: --numstat | awk '{add += $1; subs += $2; loc += $1 - $2} END {print "Added lines:", add, "Removed lines:", subs, "Total lines of code:", loc}'
# # 如果只想统计最新一次commit的代码行数
# git log -1 --pretty=tformat: --numstat | awk '{add += $1; subs += $2; loc += $1 - $2} END {print "Added lines:", add, "Removed lines:", subs, "Total lines of code:", loc}'
import subprocess
additions = 0
subtractions = 0
total = 0
# 统计所有commit的代码行数
def count_lines_of_code(repo_path, sincetime="2025-03-25", untiltime="2025-05-30"):
global additions
global subtractions
global total
additions = 0
subtractions = 0
total = 0
process = subprocess.Popen(['git', 'log', "--since={}".format(sincetime), "--until={}".format(untiltime) ,'--pretty=tformat:', '--numstat'], cwd=repo_path, stdout=subprocess.PIPE)
output, _ = process.communicate()
lines = output.decode('utf-8').replace("\t", " ").splitlines()
for _ in lines:
if _.split(" ")[0].isdigit():
print("##A formatted string: {}".format(_))
additions += int(_.strip(" ").split(" ")[0])
subtractions += int(_.strip(" ").split(" ")[1])
else:
print("##Ignore non formatted strings: {}".format(_))
total = additions - subtractions
return additions, subtractions, total
# 统计最新一次commit的代码行数
def count_lines_of_code_latest(repo_path):
global additions
global subtractions
global total
additions = 0
subtractions = 0
total = 0
process = subprocess.Popen(['git', 'log', '-1', '--pretty=tformat:', '--numstat'], cwd=repo_path, stdout=subprocess.PIPE)
output, _ = process.communicate()
lines = output.decode('utf-8').replace("\t", " ").splitlines()
for _ in lines:
if _.split(" ")[0].isdigit():
print("##A formatted string: {}".format(_))
additions += int(_.strip(" ").split(" ")[0])
subtractions += int(_.strip(" ").split(" ")[1])
else:
print("##Ignore non formatted strings: {}".format(_))
total = additions - subtractions
return additions, subtractions, total
# 使用方法
repo_path = r'D:\workspace\product_code' # 替换为你的仓库路径
additions, subtractions, total = count_lines_of_code(repo_path, sincetime="2025-05-01", untiltime="2025-05-30")
print(f"Added lines: {additions}, Removed lines: {subtractions}, Total lines of code: {total}")
# additions_latest, subtractions_latest, total_latest = count_lines_of_code_latest(repo_path)
# print(f"Added lines (latest commit): {additions_latest}, Removed lines (latest commit): {subtractions_latest}, Total lines of code (latest commit): {total_latest}")
【Python统计git提交代码量】
最新推荐文章于 2025-12-04 22:56:41 发布

3303

被折叠的 条评论
为什么被折叠?



