Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juergenpointinger/6b34a6def83470a196df7c6beb161858 to your computer and use it in GitHub Desktop.
Save juergenpointinger/6b34a6def83470a196df7c6beb161858 to your computer and use it in GitHub Desktop.
Remove unused GitLab Labels
# remove_unused_gitlab_labels.py
import requests
from requests.auth import HTTPBasicAuth
import uuid
import json
# *False* if Jira / GitLab is using self-signed certificates, otherwhise *True*
VERIFY_SSL_CERTIFICATE = True
## GitLab specifics
# GitLab URL
GITLAB_URL = 'https://gitlab.com/'
# GitLab token will be used whenever the API is invoked
GITLAB_TOKEN = 'your-private-gitlab-token'
# Gitlab project with group/namespace
GITLAB_PROJECT = 'your-group-name/your-project-name'
# GitLab project id.
GITLAB_PROJECT_ID = 'your-group-id'
if not GITLAB_PROJECT_ID:
# Find out the ID of the project.
for project in requests.get(
GITLAB_URL + 'api/v4/projects',
headers={'PRIVATE-TOKEN': GITLAB_TOKEN},
verify=VERIFY_SSL_CERTIFICATE
).json():
if project['path_with_namespace'] == GITLAB_PROJECT:
GITLAB_PROJECT_ID = project['id']
break
if not GITLAB_PROJECT_ID:
raise Exception("Unable to find %s in GitLab!" % GITLAB_PROJECT)
gl_labels=[]
def get_labels(next_page):
response = requests.get(
GITLAB_URL + 'api/v4/projects/%s/labels?with_counts=true&per_page=100&page=%s' % (GITLAB_PROJECT_ID, next_page),
headers={'PRIVATE-TOKEN': GITLAB_TOKEN},
verify=VERIFY_SSL_CERTIFICATE
)
if response.status_code != 200:
raise Exception("Unable to get project labels for %s!" % GITLAB_PROJECT)
for label in response.json():
label_id = label['id']
label_name = label['name']
open_issues = label['open_issues_count']
closed_issues = label['closed_issues_count']
merged_issues =label['open_merge_requests_count']
if open_issues == 0 and closed_issues == 0 and merged_issues == 0:
gl_labels.append({ 'id': label_id, 'name': label_name })
next_page = response.headers.get('X-Next-Page')
current_page = response.headers.get('X-Page')
if current_page < next_page:
get_labels(next_page)
return gl_labels
labels = get_labels(1)
for label in labels:
print("Try to delete label: %s (%s)" % (label['id'], label['name']))
response = requests.delete(
GITLAB_URL + 'api/v4/projects/%s/labels/%s' % (GITLAB_PROJECT_ID, label['id']),
headers={'PRIVATE-TOKEN': GITLAB_TOKEN},
verify=VERIFY_SSL_CERTIFICATE
)
if response.status_code == 200:
print("Label: %s (%s) deleted!" % (label['id'], label['name']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment