in services/jenkins-run-statistics/jenkins_utils.py [0:0]
def get_job_hierarchy(self):
"""
Query the jenkins API to get the real job hierarchy - e.g. which part of the job name is a folder, which one
is the job name and which one is the branch name (if applicable). This is necessary because there are multiple
methods to define Jenkins jobs.
:return: Dictionary
"""
if self.job_hierarchy:
# Cached result
return self.job_hierarchy
# By looking at the parent job, if applicable, we can see whether we are currently part of a multi-branch job.
# If we are, we have to take the last part of the job name as branch name instead.
job_groups = REGEX_URL_EXTRACT_JOB_NAME.findall(self.job_url)
self.job_hierarchy = {}
if len(job_groups) > 1:
# This job has a parent. Inspect it.
job_paths = '/'.join(['job/' + job for job in job_groups[:-1]])
url = JENKINS_JOB_METADATA_API.format(jenkins_url=self.jenkins_url, job_paths=job_paths)
try:
metadata = ast.literal_eval(
requests.get(
url=url,
params={'tree': '_class,fullName'}, allow_redirects=False).text)
except SyntaxError:
raise Exception(f'Unable to retrieve meta data for parent job of {self} at {url}')
if metadata['_class'] == 'org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject':
logging.debug('%s is part of a MultiBranchProject', self)
branch_name = job_groups[-1] # Last entry is the branch name
else:
logging.debug('%s is probably not part of a MultiBranchProject since the parent class is a %s. Thus,'
'considering it as independenct job.', self, metadata['_class'])
branch_name = None
job_name = metadata['fullName']
else:
logging.debug('%s has no parent, considering it a standalone job', self)
branch_name = None
job_name = job_groups[0]
self.job_hierarchy['job_name'] = job_name
self.job_hierarchy['branch_name'] = branch_name
return self.job_hierarchy