Ejemplo n.º 1
0
    def run(self):
        """ starts the REPL """
        telemetry.start()
        from azure.cli.core.application import APPLICATION
        APPLICATION.get_progress_controller = self.progress_patch

        # refresh the cache and completer
        self.command_table_thread = LoadCommandTableThread(
            restart_completer, self)
        self.command_table_thread.start()

        from azclishell.configuration import SHELL_HELP
        self.cli.buffers['symbols'].reset(
            initial_document=Document(u'{}'.format(SHELL_HELP)))
        while True:
            try:
                try:
                    document = self.cli.run(reset_current_buffer=True)
                    text = document.text
                    if not text:
                        # not input
                        self.set_prompt()
                        continue
                    cmd = text
                    outside = False

                except AttributeError:
                    # when the user pressed Control D
                    break
                else:
                    b_flag, c_flag, outside, cmd = self._special_cases(
                        cmd, outside)
                    if not self.default_command:
                        self.history.append(text)
                    if b_flag:
                        break
                    if c_flag:
                        self.set_prompt()
                        continue

                    self.set_prompt()

                    if outside:
                        subprocess.Popen(cmd, shell=True).communicate()
                    else:
                        self.cli_execute(cmd)
                        # because I catch the sys exit, I have to push out
                        cli_telemetry.conclude()

            except (KeyboardInterrupt, ValueError):
                # CTRL C
                self.set_prompt()
                continue

        print('Have a lovely day!!', file=self.output)
        telemetry.conclude()
Ejemplo n.º 2
0
    def run(self):
        """ starts the REPL """
        telemetry.start()
        from azure.cli.core.application import APPLICATION
        APPLICATION.get_progress_controller = self.progress_patch

        # refresh the cache and completer
        self.command_table_thread = LoadCommandTableThread(restart_completer, self)
        self.command_table_thread.start()

        from azclishell.configuration import SHELL_HELP
        self.cli.buffers['symbols'].reset(
            initial_document=Document(u'{}'.format(SHELL_HELP)))
        while True:
            try:
                try:
                    document = self.cli.run(reset_current_buffer=True)
                    text = document.text
                    if not text:
                        # not input
                        self.set_prompt()
                        continue
                    cmd = text
                    outside = False

                except AttributeError:
                    # when the user pressed Control D
                    break
                else:
                    b_flag, c_flag, outside, cmd = self._special_cases(cmd, outside)
                    if not self.default_command:
                        self.history.append(text)
                    if b_flag:
                        break
                    if c_flag:
                        self.set_prompt()
                        continue

                    self.set_prompt()

                    if outside:
                        subprocess.Popen(cmd, shell=True).communicate()
                    else:
                        self.cli_execute(cmd)
                        # because I catch the sys exit, I have to push out
                        cli_telemetry.conclude()

            except (KeyboardInterrupt, ValueError):
                # CTRL C
                self.set_prompt()
                continue

        print('Have a lovely day!!', file=self.output)
        telemetry.conclude()
Ejemplo n.º 3
0
    uuid.uuid1 = uuid.uuid4


logger = get_logger(__name__)


def cli_main(cli, args):
    return cli.invoke(args)


az_cli = get_default_cli()

telemetry.set_application(az_cli, ARGCOMPLETE_ENV_NAME)

try:
    telemetry.start()

    exit_code = cli_main(az_cli, sys.argv[1:])

    if exit_code and exit_code != 0:
        telemetry.set_failure()
    else:
        telemetry.set_success()

    sys.exit(exit_code)
except KeyboardInterrupt:
    telemetry.set_user_fault('keyboard interrupt')
    sys.exit(1)
finally:
    telemetry.conclude()
Ejemplo n.º 4
0
    def run(self):
        """ runs the CLI """
        telemetry.start()
        self.cli.buffers['symbols'].reset(
            initial_document=Document(u'%s' %shell_help)
        )
        while True:
            try:
                document = self.cli.run(reset_current_buffer=True)
                text = document.text
                cmd = text
                outside = False
                if text.split() and text.split()[0] == 'az':
                    cmd = ' '.join(text.split()[1:])
                if self.default_command:
                    cmd = self.default_command + " " + cmd
                # if self.default_params:
                #     for param in self.default_params:
                #         cmd += ' ' + param

            except AttributeError:  # when the user pressed Control Q
                break
            else:
                if text.strip() == "quit" or text.strip() == "exit":
                    break
                elif text.strip() == "clear":  # clears the history, but only when you restart
                    outside = True
                    cmd = 'echo -n "" >' +\
                        os.path.join(
                            SHELL_CONFIGURATION.get_config_dir(),
                            SHELL_CONFIGURATION.get_history())
                elif text.strip() == "help":
                    print(help_doc.dump(shell_help))
                if text:
                    if text[0] == SELECT_SYMBOL['outside']:
                        cmd = text[1:]
                        outside = True
                    # elif text.split()[0] == "az":  # dumps the extra az
                    #     cmd = " ".join(text.split()[1:])
                    elif text[0] == SELECT_SYMBOL['exit_code']:
                        print(self.last_exit)
                        self.set_prompt()
                        continue
                    elif SELECT_SYMBOL['query'] in text:  # query previous output
                        if self.last and self.last.result:
                            if hasattr(self.last.result, '__dict__'):
                                input_dict = dict(self.last.result)
                            else:
                                input_dict = self.last.result
                            try:
                                result = jmespath.search(
                                    text.partition(SELECT_SYMBOL['query'])[2], input_dict)
                                if isinstance(result, str):
                                    print(result)
                                else:
                                    print(json.dumps(result, sort_keys=True, indent=2))
                            except jmespath.exceptions.ParseError:
                                print("Invalid Query")

                        self.set_prompt()
                        continue
                    elif "|" in text or ">" in text:  # anything I don't parse, send off
                        outside = True
                        cmd = "az " + cmd
                    elif SELECT_SYMBOL['example'] in text:
                        global NOTIFICATIONS
                        cmd = self.handle_example(text)
                if SELECT_SYMBOL['default'] in text:
                    default = text.partition(SELECT_SYMBOL['default'])[2].split()
                    if default[0].startswith('-'):
                        value = self.handle_default_param(default)
                    else:
                        value = self.handle_default_command(default)
                    print("defaulting: " + value)
                    self.set_prompt()
                    continue
                if SELECT_SYMBOL['undefault'] in text:
                    value = text.partition(SELECT_SYMBOL['undefault'])[2].split()
                    if len(value) == 0:
                        self.default_command = ""
                        set_default_command("", add=False)
                        # self.default_params = []
                        print('undefaulting all')
                    elif len(value) == 1 and value[0] == self.default_command:
                        self.default_command = ""
                        set_default_command("", add=False)
                        print('undefaulting: ' + value[0])
                    # elif len(value) == 2 and ' '.join(value[:2]) in self.default_params:
                    #     self.default_params.remove(' '.join(value[:2]))
                    #     print('undefaulting: ' + ' '.join(value[:2]))

                    self.set_prompt()
                    continue

                if not text: # not input
                    self.set_prompt()
                    continue

                self.history.append(cmd)
                self.set_prompt()
                if outside:
                    subprocess.Popen(cmd, shell=True).communicate()
                else:
                    try:
                        args = [str(command) for command in cmd.split()]
                        azlogging.configure_logging(args)

                        azure_folder = get_config_dir()
                        if not os.path.exists(azure_folder):
                            os.makedirs(azure_folder)
                        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
                        CONFIG.load(os.path.join(azure_folder, 'az.json'))
                        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

                        config = Configuration(args)
                        self.app.initialize(config)

                        result = self.app.execute(args)
                        if result and result.result is not None:
                            from azure.cli.core._output import OutputProducer, format_json
                            if self.output:
                                self.output.out(result)
                            else:
                                formatter = OutputProducer.get_formatter(
                                    self.app.configuration.output_format)
                                OutputProducer(formatter=formatter, file=self.input).out(result)
                                self.last = result
                                self.last_exit = 0
                    except Exception as ex:  # pylint: disable=broad-except
                        self.last_exit = handle_exception(ex)
                    except SystemExit as ex:
                        self.last_exit = ex.code
                    if self.last_exit != 0:
                        telemetry.set_failure()
                    else:
                        telemetry.set_success()

        print('Have a lovely day!!')
        telemetry.conclude()