from os import environ
from time import sleep
import json
import requests
# If Gitlab token is not defined in the environment, it got read from this variable
GITLAB_API_TOKEN = 'some_random_gitlab_api_token'
HEADERS = {'PRIVATE-TOKEN': environ.get('GITLAB_API_TOKEN') or GITLAB_API_TOKEN}
def bulk_delete_developer(project_id, keep_n):
r = requests.get(
"https://gitlab.com/api/v4/projects/{}/registry/repositories".format(project_id),
headers=HEADERS
)
repository_id = r.json()[0]['id']
r = requests.get(
"https://gitlab.com/api/v4/projects/{}/registry/repositories/{}/tags".format(
project_id,
repository_id
),
headers=HEADERS
)
tags = [tag['name'] for tag in r.json()]
wait_period = 2
for tag in tags[:len(tags) - keep_n]:
r = requests.delete(
"https://gitlab.com/api/v4/projects/{}/registry/repositories/{}/tags/{}".format(
project_id,
repository_id,
tag
),
headers=HEADERS
)
if r.status_code != 200:
wait_period *= wait_period
sleep(wait_period)
def bulk_delete_maintainer(project_id, keep_n):
r = requests.get(
"https://gitlab.com/api/v4/projects/{}/registry/repositories".format(project_id),
headers=HEADERS
)
repository_id = r.json()[0]['id']
data = {
'name_regex_delete': '.*',
'keep_n': keep_n
}
r = requests.delete(
"https://gitlab.com/api/v4/projects/{}/registry/repositories/{}/tags".format(
project_id,
repository_id
),
data=data,
headers=HEADERS
)
return r.status_code
# return "curl -X DELETE --data 'name_regex_delete=.*' --data 'keep_n=5' --header 'PRIVATE-TOKEN: <private-token>' https://gitlab.com/api/v4/projects/{}/registry/repositories/{}/tags".format(project_id, repository_id)
projects = [
{'name': 'pr1', 'id': 1},
{'name': 'pr2', 'id': 2},
{'name': 'pr3', 'id': 3},
{'name': 'pr4', 'id': 4},
{'name': 'pr5, 'id': 5},
{'name': 'pr6', 'id': 6}
]
for project in projects:
print("service {}: {}".format(
project['name'],
bulk_delete_maintainer(project['id'], 6)
)
)