代码
因公司要求,需要每个月提交一次当月的代码修改记录,便于评估工作饱和度。因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()
注
代码的整体逻辑比较清晰简单,这里就不过多赘述了。
值得一提的是,我代码中虽然有针对分支的提交记录统计,不过只能一次统计一个分支,这里其实是有优化空间的。
感谢阅读,希望我们能在代码之路走的更远。