in tools/gcp-org-hierarchy-viewer/gcpohv_cli.py [0:0]
def run(self):
""" Runs the CLI login flow.
Returns:
None
"""
fold_parents, org_parents = self._get_projects()
def recurse_and_attach(parent, tree):
""" Given a tree (a dict) and a parent node, traverses depth-first
in the org hierarchy, attaching children to parents in tree.
Args:
parent: parent node as str
tree: mapping to use to construct the org hierarchy
Returns:
None
"""
result = self._crm_v2.folders().list(parent=parent).execute()
if 'folders' in result:
for folder in result['folders']:
f_str = '{} {} ({})'.format(_FOLDER, folder["displayName"],
folder["name"].split("/")[1])
tree[f_str] = {}
_id = folder["name"].split('/')[1]
if _id in fold_parents:
for project in fold_parents[_id]:
proj_name = '{} {}'.format(_PROJ,
project["projectId"])
tree[f_str][proj_name] = {}
recurse_and_attach(folder['name'], tree[f_str])
t = {}
# If an org flag is set, finds the org by name or ID, walks the org
# hierarchy starting at the organization, uses the tree and attaches
# folders and projects recursively
if self.organization:
resp = self._crm_v1.organizations().search(body={}).execute()
orgs = resp.get('organizations')
if not orgs:
raise SystemExit('No organizations found')
org_id = [
org['name'].split('/')[1] for org in orgs
if self.organization in org['displayName']
or self.organization in org['name']
][0]
if self.use_org_id:
filter_func = functools.partial(resource_filter,
self.organization,
field='name')
else:
filter_func = functools.partial(resource_filter,
self.organization)
try:
org = next(filter(filter_func, orgs))
except StopIteration:
raise SystemExit('Could not find organization {}'
''.format(self.organization))
org_name = '{} {} ({})'.format(_ORG, org["displayName"],
org["name"].split('/')[1])
t[org_name] = {}
recurse_and_attach(org['name'], t[org_name])
for project in org_parents.get(org_id, []):
proj_name = '{} {}'.format(_PROJ, project["projectId"])
t[org_name][proj_name] = {}
# If the folder flag is set, walks the organization hierarchy starting
# at a folder node and attaches folders and projects.
if self.folder:
folder = self._crm_v2.folders().get(
name='folders/{}'.format(self.folder)).execute()
fold_name = '{} {} ({})'.format(_FOLDER, folder["displayName"],
self.folder)
t[fold_name] = {}
recurse_and_attach(folder['name'], t[fold_name])
for project in fold_parents.get(self.folder, []):
proj_name = '{} {}'.format(_PROJ, project["projectId"])
t[fold_name][proj_name] = {}
tr = asciitree.LeftAligned(draw=asciitree.BoxStyle())
print(tr(t))