|
| 1 | +"""List Tags.""" |
| 2 | +# :license: MIT, see LICENSE for more details. |
| 3 | + |
| 4 | +import click |
| 5 | + |
| 6 | +from SoftLayer.CLI import environment |
| 7 | +from SoftLayer.CLI import formatting |
| 8 | +from SoftLayer.exceptions import SoftLayerAPIError |
| 9 | +from SoftLayer.managers.tags import TagManager |
| 10 | +from SoftLayer import utils |
| 11 | + |
| 12 | +# pylint: disable=unnecessary-lambda |
| 13 | + |
| 14 | + |
| 15 | +@click.command() |
| 16 | +@click.option('--detail', '-d', is_flag=True, default=False, |
| 17 | + help="Show information about the resources using this tag.") |
| 18 | +@environment.pass_env |
| 19 | +def cli(env, detail): |
| 20 | + """List Tags.""" |
| 21 | + |
| 22 | + tag_manager = TagManager(env.client) |
| 23 | + |
| 24 | + if detail: |
| 25 | + tables = detailed_table(tag_manager, tag_manager.get_attached_tags()) |
| 26 | + for table in tables: |
| 27 | + env.fout(table) |
| 28 | + else: |
| 29 | + table = simple_table(tag_manager) |
| 30 | + env.fout(table) |
| 31 | + # pp(tags.list_tags()) |
| 32 | + |
| 33 | + |
| 34 | +def tag_row(tag): |
| 35 | + """Format a tag table row""" |
| 36 | + return [tag.get('id'), tag.get('name'), tag.get('referenceCount', 0)] |
| 37 | + |
| 38 | + |
| 39 | +def detailed_table(tag_manager, tags): |
| 40 | + """Creates a table for each tag, with details about resources using it""" |
| 41 | + tables = [] |
| 42 | + for tag in tags: |
| 43 | + references = tag_manager.get_tag_references(tag.get('id')) |
| 44 | + # pp(references) |
| 45 | + new_table = formatting.Table(['Id', 'Type', 'Resource'], title=tag.get('name')) |
| 46 | + for reference in references: |
| 47 | + tag_type = utils.lookup(reference, 'tagType', 'keyName') |
| 48 | + resource_id = reference.get('resourceTableId') |
| 49 | + resource_row = get_resource_name(tag_manager, resource_id, tag_type) |
| 50 | + new_table.add_row([resource_id, tag_type, resource_row]) |
| 51 | + tables.append(new_table) |
| 52 | + |
| 53 | + return tables |
| 54 | + |
| 55 | + |
| 56 | +def simple_table(tag_manager): |
| 57 | + """Just tags and how many resources on each""" |
| 58 | + tags = tag_manager.list_tags() |
| 59 | + table = formatting.Table(['Id', 'Tag', 'Count'], title='Tags') |
| 60 | + for tag in tags.get('attached', []): |
| 61 | + table.add_row(tag_row(tag)) |
| 62 | + for tag in tags.get('unattached', []): |
| 63 | + table.add_row(tag_row(tag)) |
| 64 | + return table |
| 65 | + |
| 66 | + |
| 67 | +def get_resource_name(tag_manager, resource_id, tag_type): |
| 68 | + """Returns a string to identify a resource""" |
| 69 | + name = None |
| 70 | + try: |
| 71 | + resource = tag_manager.reference_lookup(resource_id, tag_type) |
| 72 | + name = tag_manager.get_resource_name(resource, tag_type) |
| 73 | + except SoftLayerAPIError as exception: |
| 74 | + name = "{}".format(exception.reason) |
| 75 | + return name |
0 commit comments