def get_compartment()

in mds_plugin/compartment.py [0:0]


def get_compartment(compartment_path=None, **kwargs):
    """Gets a compartment by path

    If the path was not specified or does not match an existing compartment,
    show the user a list to select a compartment

    Args:
        compartment_path (str): The name of the compartment
        **kwargs: Optional parameters

    Keyword Args:
        parent_compartment_id (str): OCID of the parent compartment
        config (object): An OCI config object or None.
        config_profile (str): The name of an OCI config profile
        interactive (bool): Whether exceptions are raised

    Returns:
        The compartment object
    """

    compartment_id = kwargs.get("compartment_id")
    parent_compartment_id = kwargs.get("parent_compartment_id")

    config = kwargs.get("config")
    config_profile = kwargs.get("config_profile")

    interactive = kwargs.get("interactive", core.get_interactive_default())
    raise_exceptions = kwargs.get("raise_exceptions", not interactive)
    return_formatted = kwargs.get("return_formatted", interactive)

    # Get the active config and compartment
    try:
        config = configuration.get_current_config(
            config=config, config_profile=config_profile,
            interactive=interactive)
        compartment_id = configuration.get_current_compartment_id(
            compartment_id=parent_compartment_id, config=config)
    except ValueError as e:
        if raise_exceptions:
            raise
        print(f"ERROR: {str(e)}")
        return

    import oci.identity
    import mysqlsh

    # Start with an empty compartment
    compartment = None

    # If a compartment path was given, look it up
    if compartment_path is not None:
        compartment = get_compartment_by_path(
            compartment_path, compartment_id, config)
        if compartment is not None:
            return compartment
        else:
            print(
                f"The compartment with the path {compartment_path} was not found.")
            if not interactive:
                return
            print("Please select another compartment.\n")

    # Initialize the identity client
    identity = core.get_oci_identity_client(config=config)

    # List the compartments. If no compartment_id was given, take the id from
    # the tenancy and display full subtree of compartments
    data = identity.list_compartments(
        compartment_id=compartment_id,
        compartment_id_in_subtree=False).data

    # Filter out all deleted compartments
    data = [c for c in data if c.lifecycle_state != "DELETED"]

    # Print special path descriptions
    full_path = get_compartment_full_path(compartment_id, config)
    is_tenancy = compartment_id == config.get('tenancy')
    print(f"Directory of compartment {full_path}"
          f"{' (the tenancy)' if is_tenancy else ''}\n")
    if compartment_id != config.get("tenancy"):
        print("   / Root compartment (the tenancy)\n"
              "   . Current compartment\n"
              "  .. Parent compartment\n")

    # If the compartment_name was not given or found, print out the list
    comp_list = format_compartment_listing(data)
    if comp_list == "":
        comp_list = "Child Compartments:\n   - None\n"
    print(comp_list)

    # Let the user choose from the list
    while compartment is None:
        # Prompt the user for specifying a compartment
        prompt = mysqlsh.globals.shell.prompt(
            "Please enter the name, index or path of the compartment: ",
            {'defaultValue': ''}).strip().lower()

        if prompt == "":
            return

        try:
            if prompt.startswith('/'):
                if prompt == '/':
                    # The compartment will be the tenancy
                    compartment = get_compartment_by_id(
                        compartment_id=config.get('tenancy'), config=config)
                    continue
                else:
                    # Get the compartment by full path
                    compartment = get_compartment_by_path(
                        compartment_path=prompt, compartment_id=compartment_id,
                        config=config)
                    if compartment is None:
                        raise ValueError
                    continue
            elif prompt == '.':
                # The compartment will be the current compartment
                compartment = get_compartment_by_id(
                    compartment_id=compartment_id, config=config)
                continue
            elif prompt == '..':
                # The compartment will be the parent compartment or none
                compartment = get_parent_compartment(
                    get_compartment_by_id(
                        compartment_id=compartment_id, config=config),
                    config=config)
                if compartment is None:
                    raise ValueError
                continue

            try:
                # If the user provided an index, try to map that to a compartment
                nr = int(prompt)
                if nr > 0 and nr <= len(data):
                    compartment = data[nr - 1]
                else:
                    raise IndexError
            except ValueError:
                # Search by name
                for c in data:
                    if c.name.lower() == prompt:
                        compartment = c
                        break
                if compartment is None:
                    raise ValueError

        except ValueError:
            print(
                f'The compartment {prompt} was not found. Please try again.\n')
        except IndexError:
            print(f'A compartment with the index {prompt} was not found. '
                  f'Please try again.\n')

    return compartment