python脚本:实现gitlab当月代码量修改统计

代码

因公司要求,需要每个月提交一次当月的代码修改记录,便于评估工作饱和度。因gitlab似乎并不具备该功能,故而实现python脚本来完成上述需求。

代码实现

import requests
import datetime

#GitLab 配置
GITLAB_URL = ''   #更改为您的 GitLab URL
PRIVATE_TOKEN = ''   #使用您的私人令牌
GROUP_ID = ''   #您的项目 I
Author = '' #gitlab用户名
#请求头部
headers = {
    'Private-Token': PRIVATE_TOKEN
}


def get_projects(group_id):
    url = f"{GITLAB_URL}/api/v4/groups/{group_id}/projects"

    response = requests.get(url, headers=headers)
    response.raise_for_status()
    #如果请求失败,抛出异常
    return response.json()

def get_commits(project_id, since, until, ref_name='master'):
    url = f"{GITLAB_URL}/api/v4/projects/{project_id}/repository/commits"
    params = {
        "since": since,
        "until": until,
        "per_page": 1000, #每页返回100个提交
        "ref_name": ref_name
    }

    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()


def get_diff(project_id, commit_id):
    url = f"{GITLAB_URL}/api/v4/projects/{project_id}/repository/commits/{commit_id}/diff"

    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.json()


def main():
    #获取当前日期的月份范围
    today = datetime.date.today()
    month_start = today.replace(day=1)
    month_end = (month_start.replace(day=1) + datetime.timedelta(days=31)).replace(day=1) - datetime.timedelta(days=1)

    #打开并准备写入文件
    with open('gitlab_commit_diff.txt', 'w', encoding='utf-8') as f:
        projects = get_projects(GROUP_ID)

        for project in projects:
            project_id = project['id']
            f.write(f"Project: {project['name']}\n")
            commits = get_commits(project_id, month_start.isoformat() + 'T00:00:00Z', month_end.isoformat() + 'T23:59:59Z', ref_name='test')

            for commit in commits:
                commit_id = commit['id']
                commit_message = commit['message']
                commit_Author=commit['author_name']
                if Author != commit_Author:
                    continue
                f.write(f"Commit ID: {commit_id} - Author: {commit['author_name']} - Date: {commit['created_at']}\n")
                f.write(f'Message: {commit_message}')
                diffs = get_diff(project_id, commit_id)
                for diff in diffs:
                    f.write(f"File: {diff['new_path']}\nChange Value:\n {diff['diff']}\n")
            f.write("\n")
            #在每个项目之间添加空行

if __name__ == "__main__":
    main()

代码的整体逻辑比较清晰简单,这里就不过多赘述了。
值得一提的是,我代码中虽然有针对分支的提交记录统计,不过只能一次统计一个分支,这里其实是有优化空间的。
感谢阅读,希望我们能在代码之路走的更远。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值