Skip to content

Instantly share code, notes, and snippets.

@rantoniuk
Last active January 14, 2021 18:40
Show Gist options
  • Save rantoniuk/fda6ebf22138d9b2e5840cf1cc50b133 to your computer and use it in GitHub Desktop.
Save rantoniuk/fda6ebf22138d9b2e5840cf1cc50b133 to your computer and use it in GitHub Desktop.
SonarQube set main branch
### Dependencies:
### pip3 install python-sonarqube-api
###
### Usage:
### SONARQUBE_API_TOKEN=123 SONARQUBE_API_URL=https://my.sonar.service.com/ python3 sonar.py <project-name>
import os
import sys
from distutils.util import strtobool
from sonarqube import SonarQubeClient
SONAR = SonarQubeClient(token=os.getenv('SONARQUBE_API_TOKEN'), sonarqube_url=os.getenv('SONARQUBE_API_URL'))
def get_projects_where_develop_is_not_the_default_branch():
global SONAR
p = []
for project in list(SONAR.projects.search_projects()):
print(project["key"])
for branch in SONAR.project_branches.search_project_branches(project=project['key']):
if branch['name'] == 'master' and branch['isMain'] is True:
print(f"{project['name']} have master branch has default")
p.append(project['key'])
return p
def set_default_branch_to_develop(project_key):
global SONAR
user_input = input(f"Delete develop branch and set develop as the main branch for project {project_key}? [y/n] ")
if user_input and strtobool(user_input):
SONAR.project_branches.delete_project_branch(project_key, 'develop')
SONAR.project_branches.rename_project_branch(project_key, 'develop')
if __name__ == '__main__':
# projects = get_projects_where_develop_is_not_the_default_branch()
# for project_key in projects:
# else:
# print('Did not find any project to convert :)')
if len(sys.argv) != 1:
project = sys.argv[1]
else:
project = input("Project key: ")
set_default_branch_to_develop(project)
import os
import sys
from sonarqube import SonarQubeClient
from sonarqube.utils.exceptions import AuthError
import time
SONAR = SonarQubeClient(token=os.getenv('SONARQUBE_API_TOKEN'), sonarqube_url=os.getenv('SONARQUBE_API_URL'))
def update_branch(pattern):
global SONAR
p = []
for project in list(SONAR.projects.search_projects()):
time.sleep(1)
if pattern not in project["key"]:
continue
try:
result = SONAR.project_branches.search_project_branches(project=project['key'])
for branch in result['branches']:
if branch['name'] == 'master' and branch['isMain'] is True:
print("%s" % project['key'])
if any("develop" in b.values() for b in result['branches']):
SONAR.project_branches.delete_project_branch(project['key'], 'develop')
SONAR.project_branches.rename_project_branch(project['key'], 'develop')
print("updated")
except AuthError:
print(" - permission denied")
return p
if __name__ == '__main__':
if len(sys.argv) != 1:
pattern = sys.argv[1]
else:
pattern = input("project pattern: ")
update_branch(pattern)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment