Python利用gitee API批量修改webhook的URL

因为最近换了jenkins地址,之前CI环节依赖的gitee webhook。但是之前webhook的URL写的是ip。所以需要批量修改。

然而仓库上百个,头皮发麻。不过好在看到gitee有提供了API,虽然没找到sdk,但是也好很多了。

简单写了一个,放上来存档。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/bin/env python3
# coding:utf-8
import requests
import json
# 需要access_token 拥有webhook以及项目权限
access_token = '<your_ak>'
old_str = 'x.x.x.x:10000'
new_str = 'jenkins.xxx.com'


def get_repo_list():
"""
获取所有仓库信息
:return:
"""
playload = dict()
playload['access_token'] = access_token
playload['visibility'] = 'private'
playload['affiliation'] = 'owner, collaborator, organization_member'
playload['page'] = '1'
playload['per_page'] = '100'
result = requests.get('https://gitee.com/api/v5/user/repos', params=playload)
return result.text


def get_repo_hooks(repo):
"""
获取仓库webhook信息
:param repo:
:return:
"""
playload = dict()
playload['access_token'] = access_token
playload['page'] = '1'
playload['per_page'] = '100'
result = requests.get('https://gitee.com/api/v5/repos/{repo}/hooks'.format(repo=repo), params=playload)
return result.text


def set_repo_hooks(repo, webhook_id, webhook_url):
"""
设置仓库webhook
:param repo:
:param webhook_id:
:param webhook_url:
:return:
"""
playload = dict()
playload['access_token'] = access_token
playload['id'] = webhook_id
playload['url'] = webhook_url
result = requests.patch('https://gitee.com/api/v5/repos/{repo}/hooks/{id}'.format(repo=repo, id=webhook_id),
data=playload)
return result.text


repo_list = json.loads(get_repo_list())
for item in repo_list:
repo_name = item['full_name']
webhook_info = json.loads(get_repo_hooks(repo_name))
for webhook in webhook_info:
webhook_id = webhook['id']
webhook_url = webhook['url']
if old_str in webhook_url:
webhook_url = webhook_url.replace(old_str, new_str)
print(set_repo_hooks(repo_name, webhook_id, webhook_url))

参考资料

关注公众号 尹安灿