60 lines
1.5 KiB
Python
Executable File
60 lines
1.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import re
|
|
import os
|
|
import requests
|
|
import secrets
|
|
import sys
|
|
|
|
|
|
def die(s):
|
|
print(s, file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
|
|
gitlab_token = os.getenv('GITLAB_TOKEN')
|
|
if gitlab_token is None:
|
|
die("GITLAB_TOKEN must be set in the environment")
|
|
|
|
if len(sys.argv) < 4:
|
|
die("Usage: {} GITLAB_INSTANCE HOOK_URL_BASE NAMESPACE/REPO\n\nExample: {} gitlab.example.com https://bot.example.com/bebot stuff/myrepo")
|
|
|
|
gitlab_instance = sys.argv[1]
|
|
hook_url = f"{sys.argv[2]}/hooks/gitlab"
|
|
repo_name = sys.argv[3]
|
|
|
|
gl_base = 'https://{}/api/v4/projects/{}/hooks'.format(
|
|
gitlab_instance,
|
|
re.sub('/', '%2F', repo_name)
|
|
)
|
|
headers = {
|
|
'authorization': 'Bearer {}'.format(gitlab_token),
|
|
}
|
|
payload = {
|
|
"issues_events": True,
|
|
"merge_requests_events": True,
|
|
"pipeline_events": True,
|
|
"push_events": True,
|
|
"tag_push_events": True,
|
|
}
|
|
|
|
resp = requests.get(gl_base, headers=headers)
|
|
if resp.status_code != 200:
|
|
resp.raise_for_status()
|
|
existing = resp.json()
|
|
|
|
for hook in existing:
|
|
if hook['url'] == hook_url:
|
|
upd_url = '{}/{}'.format(gl_base, hook['id'])
|
|
resp = requests.put(upd_url, headers=headers, json=payload)
|
|
print("Updated existing hook for {}".format(repo_name))
|
|
sys.exit(0)
|
|
|
|
token = secrets.token_urlsafe(32)
|
|
payload["url"] = hook_url
|
|
payload["token"] = token
|
|
resp = requests.post(gl_base, headers=headers, json=payload)
|
|
resp.raise_for_status()
|
|
print(' "{}/{}":'.format(gitlab_instance, repo_name))
|
|
print(' token: "{}"'.format(token))
|