sonar-cleanup.py

Script to automate the deletion of old projects from SonarQube.

1

Votes

#!/usr/bin/env python
import argparse,collections,json,shlex,urllib,re
from datetime import datetime
from datetime import timedelta
from dateutil.parser import parse
from termcolor import colored

# Command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--dry-run", dest="dryrun", action="store_const", const=True, default=False, help="Do not delete SonarQube projects.")
parser.add_argument("--url", dest="url", required=True, help="URL to the SonarQube server. Use http://user:password@host/ to include authentication.")
parser.add_argument("--days", dest="days", type=int, required=True, help="Number of days since the last analysis to keep the project.")
parser.add_argument("--keep", dest="keep", action="append", nargs="?", help="Regex to filter out projects, which should not be deleted.")
args = parser.parse_args()

# retrieve all SonarQube projects
def get_data():
    data = urllib.urlopen(args.url + "/api/resources/index").read()
    output = json.loads(data)
    return output

def is_excluded(project):
    if args.keep:
        for pattern in args.keep:
            if re.match(pattern, project['name']):
                return True

    cutoff_date = (datetime.now() - timedelta(days=args.days)).date()
    project_date = parse(project['date']).date()

    if project_date >= cutoff_date:
        return True

    return False

def remove_project(project):
    params = urllib.urlencode({'id': project['id']})
    status = urllib.urlopen(args.url + "/api/projects/destroy", params).read()

# main logic
data = get_data()
for project in data:
    if not is_excluded(project):
        print colored("removing {}".format(project['name']), 'green')
        if not args.dryrun:
           remove_project(project)
    else:
        print colored("exluded {}".format(project['name']), 'yellow')

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png