此脚本实现的功能是自动合并gitlab的分支
整个过程通过python-gitlab库实现
1 创建一个merge request请求
2 接受merge request请求
其中的private_token要在自己公司的gitlab系统里申请
001.png
#!/usr/bin/python3
#coding=utf-8
# 自动合并项目dev分支到release分支
import sys
import datetime
import urllib.request
import gitlab
argsc = len(sys.argv)
if argsc <= 1:
print("缺少git项目命称\r\n")
exit(1)
project_name = sys.argv[1]
# 生成gitlab对象
gl = gitlab.Gitlab('http://gitlab.xxx.com/', private_token='xxxxxxxxxxxxxxxxxxx')
project = gl.projects.get(project_name)
# print(project.id)
print("正在合并:{0} 的dev分支 到 release分支...\r\n".format(project_name))
# mr合并请求的对象
mr = None
try:
# 创建mr
mr = project.mergerequests.create({'source_branch': 'dev',
'target_branch': 'release',
'title': 'Dev to Release --- ' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
# print(mr.id)
# 接受合并请求
url = "http://gitlab.xxx.com/api/v3/projects/{0}/merge_request/{1}/merge".format(project.id, mr.id)
# print(url)
# print("\r\n")
headers = {
"PRIVATE-TOKEN":'xxxxxxxxxxxxxxxxxxxxx'
}
req = urllib.request.Request(url=url,headers=headers,method="PUT")
resp = urllib.request.urlopen(req)
# print(resp)
print("合并结束...\r\n")
exit(0)
except Exception as e:
print("合并出错,这可能是dev分支没有文件更新导致\r\n")
# print(e)
# 把刚创建的mr请求删除
project.mergerequests.delete(mr.id)
exit(1)
参考资料:
https://python-gitlab.readthedocs.io/en/stable/install.html
网友评论