Example #1
0
    def _special_cases(self, cmd, outside):
        break_flag = False
        continue_flag = False
        args = parse_quotes(cmd)
        cmd_stripped = cmd.strip()
        if cmd_stripped and cmd.split(' ', 1)[0].lower() == 'az':
            telemetry.track_ssg('az', cmd)
            cmd = ' '.join(cmd.split()[1:])
        if self.default_command:
            cmd = self.default_command + " " + cmd

        if cmd_stripped == "quit" or cmd_stripped == "exit":
            break_flag = True
        elif cmd_stripped == "clear-history":
            # clears the history, but only when you restart
            outside = True
            cmd = 'echo -n "" >' +\
                os.path.join(
                    SHELL_CONFIG_DIR(),
                    SHELL_CONFIGURATION.get_history())
        elif cmd_stripped == CLEAR_WORD:
            outside = True
            cmd = CLEAR_WORD
        if cmd_stripped:
            if cmd_stripped[0] == SELECT_SYMBOL['outside']:
                cmd = cmd_stripped[1:]
                outside = True
                if cmd.strip() and cmd.split()[0] == 'cd':
                    self.handle_cd(parse_quotes(cmd))
                    continue_flag = True
                telemetry.track_ssg('outside', '')

            elif cmd_stripped[0] == SELECT_SYMBOL['exit_code']:
                meaning = "Success" if self.last_exit == 0 else "Failure"

                print(meaning + ": " + str(self.last_exit), file=self.output)
                continue_flag = True
                telemetry.track_ssg('exit code', '')
            elif SELECT_SYMBOL['query'] in cmd_stripped and self.last and self.last.result:
                continue_flag = self.handle_jmespath_query(args)
                telemetry.track_ssg('query', '')

            elif args[0] == '--version' or args[0] == '-v':
                try:
                    continue_flag = True
                    show_version_info_exit(self.output)
                except SystemExit:
                    pass
            elif "|" in cmd or ">" in cmd:
                # anything I don't parse, send off
                outside = True
                cmd = "az " + cmd

            elif SELECT_SYMBOL['example'] in cmd:
                cmd, continue_flag = self.handle_example(cmd, continue_flag)
                telemetry.track_ssg('tutorial', cmd)
            elif len(cmd_stripped) > 2 and SELECT_SYMBOL['scope'] == cmd_stripped[0:2]:
                continue_flag, cmd = self.handle_scoping_input(continue_flag, cmd, cmd_stripped)

        return break_flag, continue_flag, outside, cmd
Example #2
0
    def test_parse_quotes(self):
        cmd1 = 'account set --subscription \'Visual Studeio enterprizse (msft)\''
        args1 = parse_quotes(cmd1)
        self.assertEqual(args1, [
            'account', 'set', '--subscription',
            'Visual Studeio enterprizse (msft)'
        ])

        cmd2 = 'account set --subscription \"Visual Studeio enterprizse (msft)\"'
        args2 = parse_quotes(cmd2)
        self.assertEqual(args2, [
            'account', 'set', '--subscription',
            'Visual Studeio enterprizse (msft)'
        ])

        cmd3 = 'account set --subscription'
        args3 = parse_quotes(cmd3)
        self.assertEqual(args3, ['account', 'set', '--subscription'])

        cmd4 = 'word1 "quote1" word2 "quote is 3" words are fun'
        args4 = parse_quotes(cmd4)
        self.assertEqual(
            args4,
            ['word1', "quote1", 'word2', "quote is 3", 'words', 'are', 'fun'])

        cmd5 = '"??[?resourceGroup == "CJ101"].name"'
        args5 = parse_quotes(cmd5)
        self.assertEqual(args5, ['??[?resourceGroup == CJ101].name'])
Example #3
0
    def _special_cases(self, cmd, outside):
        break_flag = False
        continue_flag = False
        args = parse_quotes(cmd)
        cmd_stripped = cmd.strip()
        if cmd_stripped and cmd.split(' ', 1)[0].lower() == 'az':
            self.telemetry.track_ssg('az', cmd)
            cmd = ' '.join(cmd.split()[1:])
        if self.default_command:
            cmd = self.default_command + " " + cmd

        if cmd_stripped == "quit" or cmd_stripped == "exit":
            break_flag = True
        elif cmd_stripped == "clear-history":
            # clears the history, but only when you restart
            outside = True
            cmd = 'echo -n "" >' +\
                os.path.join(
                    self.config.config_dir(),
                    self.config.get_history())
        elif cmd_stripped == CLEAR_WORD:
            outside = True
            cmd = CLEAR_WORD
        if cmd_stripped:
            if cmd_stripped[0] == SELECT_SYMBOL['outside']:
                cmd = cmd_stripped[1:]
                outside = True
                if cmd.strip() and cmd.split()[0] == 'cd':
                    self.handle_cd(parse_quotes(cmd))
                    continue_flag = True
                self.telemetry.track_ssg('outside', '')

            elif cmd_stripped[0] == SELECT_SYMBOL['exit_code']:
                meaning = "Success" if self.last_exit == 0 else "Failure"

                print(meaning + ": " + str(self.last_exit), file=self.output)
                continue_flag = True
                self.telemetry.track_ssg('exit code', '')
            elif SELECT_SYMBOL['query'] in cmd_stripped and self.last and self.last.result:
                continue_flag = self.handle_jmespath_query(args)
                self.telemetry.track_ssg('query', '')

            elif args[0] == '--version' or args[0] == '-v':
                try:
                    continue_flag = True
                    self.cli_ctx.show_version()
                except SystemExit:
                    pass
            elif "|" in cmd or ">" in cmd:
                # anything I don't parse, send off
                outside = True
                cmd = "az " + cmd

            elif SELECT_SYMBOL['example'] in cmd:
                cmd, continue_flag = self.handle_example(cmd, continue_flag)
                self.telemetry.track_ssg('tutorial', cmd)
            elif len(cmd_stripped) > 2 and SELECT_SYMBOL['scope'] == cmd_stripped[0:2]:
                continue_flag, cmd = self.handle_scoping_input(continue_flag, cmd, cmd_stripped)

        return break_flag, continue_flag, outside, cmd
Example #4
0
    def test_parse_quotes(self):
        cmd1 = 'account set --subscription \'Visual Studeio enterprizse (msft)\''
        args1 = parse_quotes(cmd1)
        self.assertEqual(
            args1, ['account', 'set', '--subscription', 'Visual Studeio enterprizse (msft)'])

        cmd2 = 'account set --subscription \"Visual Studeio enterprizse (msft)\"'
        args2 = parse_quotes(cmd2)
        self.assertEqual(
            args2, ['account', 'set', '--subscription', 'Visual Studeio enterprizse (msft)'])

        cmd3 = 'account set --subscription'
        args3 = parse_quotes(cmd3)
        self.assertEqual(args3, ['account', 'set', '--subscription'])

        cmd4 = 'word1 "quote1" word2 "quote is 3" words are fun'
        args4 = parse_quotes(cmd4)
        self.assertEqual(
            args4, ['word1', "quote1", 'word2', "quote is 3", 'words', 'are', 'fun'])

        cmd5 = '"??[?resourceGroup == "CJ101"].name"'
        args5 = parse_quotes(cmd5)
        self.assertEqual(
            args5, ['??[?resourceGroup == CJ101].name']
        )
 def test_list_replacement(self):
     # tests that the query replaces the values in the command
     args = 'vm show -g "?[].group" -n "?[].name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup2',
             'name': 'myname2'
         },
         {
             'group': 'mygroup3',
             'name': 'myname3'
         }
     ]
     flag = self.shell.handle_jmespath_query(args, False)
     self.assertTrue(flag)
     results = self.stream.getvalue().strip().split('\n')
     self.assertTrue(len(results) == 3)
     self.assertEqual(results[0], 'vm show -g mygroup -n myname')
     self.assertEqual(results[1], 'vm show -g mygroup2 -n myname2')
     self.assertEqual(results[2], 'vm show -g mygroup3 -n myname3')
 def test_list_replacement(self):
     """ tests that the query replaces the values in the command """
     args = 'vm show -g "?[].group" -n "?[].name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup2',
             'name': 'myname2'
         },
         {
             'group': 'mygroup3',
             'name': 'myname3'
         }
     ]
     flag = self.shell.handle_jmespath_query(args, False)
     self.assertTrue(flag)
     results = self.stream.getvalue().strip().split('\n')
     self.assertTrue(len(results) == 3)
     self.assertEqual(results[0], 'vm show -g mygroup -n myname')
     self.assertEqual(results[1], 'vm show -g mygroup2 -n myname2')
     self.assertEqual(results[2], 'vm show -g mygroup3 -n myname3')
Example #7
0
    def cli_execute(self, cmd):
        try:
            args = parse_quotes(cmd)
            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)
            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.out(result)
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter,
                                   file=sys.stdout).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #8
0
    def _special_cases(self, text, cmd, outside):
        break_flag = False
        continue_flag = False

        if text and len(text.split()) > 0 and text.split()[0].lower() == 'az':
            telemetry.track_ssg('az', text)
            cmd = ' '.join(text.split()[1:])
        if self.default_command:
            cmd = self.default_command + " " + cmd

        if text.strip() == "quit" or text.strip() == "exit":
            break_flag = True
        elif text.strip(
        ) == "clear-history":  # clears the history, but only when you restart
            outside = True
            cmd = 'echo -n "" >' +\
                os.path.join(
                    SHELL_CONFIG_DIR(),
                    SHELL_CONFIGURATION.get_history())
        elif text.strip() == CLEAR_WORD:
            outside = True
            cmd = CLEAR_WORD
        if '--version' in text:
            try:
                continue_flag = True
                show_version_info_exit(sys.stdout)
            except SystemExit:
                pass
        if text:
            if text[0] == SELECT_SYMBOL['outside']:
                cmd = text[1:]
                outside = True
                if cmd.strip() and cmd.split()[0] == 'cd':
                    handle_cd(parse_quotes(cmd))
                    continue_flag = True
                telemetry.track_ssg('outside', '')

            elif text[0] == SELECT_SYMBOL['exit_code']:
                meaning = "Success" if self.last_exit == 0 else "Failure"

                print(meaning + ": " + str(self.last_exit))
                continue_flag = True
                telemetry.track_ssg('exit code', '')

            elif text[0] == SELECT_SYMBOL['query']:  # query previous output
                continue_flag = self.handle_jmespath_query(text, continue_flag)

            elif "|" in text or ">" in text:  # anything I don't parse, send off
                outside = True
                cmd = "az " + cmd

            elif SELECT_SYMBOL['example'] in text:
                cmd, continue_flag = self.handle_example(cmd, continue_flag)
                telemetry.track_ssg('tutorial', text)

        continue_flag, cmd = self.handle_scoping_input(continue_flag, cmd,
                                                       text)

        return break_flag, continue_flag, outside, cmd
Example #9
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)

            if len(args) > 0 and args[0] == 'feedback':
                self.config.set_feedback('yes')
                self.user_feedback = False

            azure_folder = self.config.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)

            if '--progress' in args:
                args.remove('--progress')
                execute_args = [args]
                thread = Thread(target=self.app.execute, args=execute_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                progress_args = [self]
                thread = Thread(target=progress_view, args=progress_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None
            else:
                invocation = self.cli_ctx.invocation_cls(
                    cli_ctx=self.cli_ctx,
                    parser_cls=self.cli_ctx.parser_cls,
                    commands_loader_cls=self.cli_ctx.commands_loader_cls,
                    help_cls=self.cli_ctx.help_cls)
                result = invocation.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.cli_ctx.invocation.data['output'])
                    OutputProducer(formatter=formatter).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #10
0
    def gen_dynamic_completions(self, text):
        """ generates the dynamic values, like the names of resource groups """
        try:  # pylint: disable=too-many-nested-blocks
            is_param, started_param, prefix, param = dynamic_param_logic(text)

            # command table specific name
            arg_name = self.get_arg_name(is_param, param)

            if arg_name and (
                (text.split()[-1].startswith('-') and text[-1].isspace())
                    or text.split()[-2].startswith('-')):

                for comp in self.gen_enum_completions(arg_name, text,
                                                      started_param, prefix):
                    yield comp

                parse_args = self.argsfinder.get_parsed_args(
                    parse_quotes(text, quotes=False, string=False))

                # there are 3 formats for completers the cli uses
                # this try catches which format it is
                if self.cmdtab[
                        self.curr_command].arguments[arg_name].completer:
                    try:
                        for comp in self.cmdtab[self.curr_command].arguments[
                                arg_name].completer(prefix=prefix,
                                                    action=None,
                                                    parsed_args=parse_args):

                            for comp in gen_dyn_completion(
                                    comp, started_param, prefix, text):
                                yield comp

                    except TypeError:
                        try:
                            for comp in self.cmdtab[self.curr_command].\
                                    arguments[arg_name].completer(prefix=prefix):

                                for comp in gen_dyn_completion(
                                        comp, started_param, prefix, text):
                                    yield comp
                        except TypeError:
                            try:
                                for comp in self.cmdtab[self.curr_command].\
                                        arguments[arg_name].completer():

                                    for comp in gen_dyn_completion(
                                            comp, started_param, prefix, text):
                                        yield comp

                            except TypeError:
                                pass  # other completion method used

        # if the user isn't logged in
        except (CLIError, AttributeError, ValueError):  # service client throws
            pass
Example #11
0
    def mute_parse_args(self, text):
        """ mutes the parser error when parsing, the puts it back """
        error = AzCliCommandParser.error
        AzCliCommandParser.error = error_pass

        parse_args = self.argsfinder.get_parsed_args(
            parse_quotes(text, quotes=False, string=False))

        AzCliCommandParser.error = error
        return parse_args
Example #12
0
 def test_query_result_spaces(self):
     # tests a singleton example
     args = 'vm show -g "??group" -n "??name"'
     args = parse_quotes(args)
     self.shell.last.result = {'group': 'mygroup', 'name': 'my name'}
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0],
                      '"vm" "show" "-g" "mygroup" "-n" "my name"')
Example #13
0
 def test_string_replacement(self):
     # tests that the query replaces the values in the command
     args = 'vm show -g "??group" -n "??name"'
     args = parse_quotes(args)
     self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0],
                      '"vm" "show" "-g" "mygroup" "-n" "myname"')
Example #14
0
    def mute_parse_args(self, text):
        """ mutes the parser error when parsing, the puts it back """
        error = AzCliCommandParser.error
        AzCliCommandParser.error = error_pass

        parse_args = self.argsfinder.get_parsed_args(
            parse_quotes(text, quotes=False, string=False))

        AzCliCommandParser.error = error
        return parse_args
Example #15
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            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)

            self.app.initialize(Configuration())

            if '--progress' in args:
                args.remove('--progress')
                thread = ExecuteThread(self.app.execute, args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                thread = ProgressViewThread(progress_view, self)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None

            else:
                result = self.app.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter,
                                   file=self.output).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
Example #16
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            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)

            self.app.initialize(Configuration())

            if '--progress' in args:
                args.remove('--progress')
                thread = ExecuteThread(self.app.execute, args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                thread = ProgressViewThread(progress_view, self)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None

            else:
                result = self.app.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter, file=self.output).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
 def test_query_result_spaces(self):
     # tests a singleton example
     args = 'vm show -g "??group" -n "??name"'
     args = parse_quotes(args)
     self.shell.last.result = {
         'group': 'mygroup',
         'name': 'my name'
     }
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "my name"')
Example #18
0
 def test_string_replacement(self):
     """ tests that the query replaces the values in the command """
     args = 'vm show -g "?group" -n "?name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}
     flag = self.shell.handle_jmespath_query(args, False)
     self.assertTrue(flag)
     self.assertEqual(u"vm show -g mygroup -n myname\n",
                      self.stream.getvalue())
 def test_string_replacement(self):
     # tests that the query replaces the values in the command
     args = 'vm show -g "??group" -n "??name"'
     args = parse_quotes(args)
     self.shell.last.result = {
         'group': 'mygroup',
         'name': 'myname'
     }
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "myname"')
Example #20
0
    def test_validation(self):
        # tests line validation that the command is an injection
        args = 'foo bar --foo=?bar'
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g ?bar '
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --isfun=bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --is ?[?group == \'word\'].name '
        self.assertTrue(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query [?group == \'word\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query=[?group == \'w or =?d\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))
Example #21
0
 def test_usage_error(self):
     # tests case when multiple args but first arg starts with query
     args = '??[].group foo bar'
     args = parse_quotes(args)
     self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     self.assertEqual(
         self.stream.getvalue().strip(), "Usage Error: " + os.linesep +
         "1. Use ?? stand-alone to display previous result with optional filtering "
         "(Ex: ??[jmespath query])" + os.linesep + "OR:" + os.linesep +
         "2. Use ?? to query the previous result for argument values "
         "(Ex: group show --name ??[jmespath query])")
Example #22
0
    def test_singleton(self):
        """ tests a singleton example """
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {'group': 'mygroup', 'name': 'myname'}

        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g mygroup -n myname')
    def test_validation(self):
        """ tests line validation that the command is an injection """
        args = 'foo bar --foo=?bar'
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g ?bar '
        self.assertTrue(self.validation_func(args.split(), '?'))

        args = 'foo bar --is fun -g bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --isfun=bar '
        self.assertFalse(self.validation_func(args.split(), '?'))

        args = 'foo bar --is ?[?group == \'word\'].name '
        self.assertTrue(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query [?group == \'word\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))

        args = 'foo bar --query=[?group == \'w or =?d\'].name '
        self.assertFalse(self.validation_func(parse_quotes(args), '?'))
Example #24
0
def scrub(text):
    """ scrubs the parameter values from args """
    args = parse_quotes(text)
    next_scrub = False
    values = []
    for arg in args:
        if arg.startswith('-'):
            next_scrub = True
            values.append(arg)
        elif next_scrub:
            values.append('*****')
        else:
            values.append(arg)
    return ' '.join(values)
 def test_string_replacement(self):
     """ tests that the query replaces the values in the command """
     args = 'vm show -g "?group" -n "?name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = {
         'group': 'mygroup',
         'name': 'myname'
     }
     flag = self.shell.handle_jmespath_query(args, False)
     self.assertTrue(flag)
     self.assertEqual(u"vm show -g mygroup -n myname\n", self.stream.getvalue())
Example #26
0
def scrub(text):
    """ scrubs the parameter values from args """
    args = parse_quotes(text)
    next_scrub = False
    values = []
    for arg in args:
        if arg.startswith('-'):
            next_scrub = True
            values.append(arg)
        elif next_scrub:
            values.append('*****')
        else:
            values.append(arg)
    return ' '.join(values)
Example #27
0
 def test_errors(self):
     # tests invalid query
     args = 'vm show -g "??[0].group" -n "??[1].name"'
     args = parse_quotes(args)
     self.shell.last.result = [{
         'group': 'mygroup',
         'name': 'myname'
     }, {
         'group': 'mygroup3',
     }]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "None"')
Example #28
0
    def test_spaces_with_equal(self):
        # tests quotes with spaces
        args = 'foo doo -bar="??[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [{
            'group': 'myg roup',
            'name': 'fred'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "doo" "-bar=[\'fred\']"')
    def test_singleton(self):
        """ tests a singleton example """
        args = 'vm show -g "?group" -n "?name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = {
            'group': 'mygroup',
            'name': 'myname'
        }

        flag = self.shell.handle_jmespath_query(args, False)
        self.assertTrue(flag)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g mygroup -n myname')
 def test_errors(self):
     # tests invalid query
     args = 'vm show -g "??[0].group" -n "??[1].name"'
     args = parse_quotes(args)
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup3',
         }
     ]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().split(os.linesep)
     self.assertEqual(results[0], '"vm" "show" "-g" "mygroup" "-n" "None"')
 def test_usage_error(self):
     # tests case when multiple args but first arg starts with query
     args = '??[].group foo bar'
     args = parse_quotes(args)
     self.shell.last.result = {
         'group': 'mygroup',
         'name': 'myname'
     }
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     self.assertEqual(self.stream.getvalue().strip(),
                      "Usage Error: " + os.linesep +
                      "1. Use ?? stand-alone to display previous result with optional filtering "
                      "(Ex: ??[jmespath query])" +
                      os.linesep + "OR:" + os.linesep +
                      "2. Use ?? to query the previous result for argument values "
                      "(Ex: group show --name ??[jmespath query])")
    def test_spaces_with_equal(self):
        # tests quotes with spaces
        args = 'foo doo -bar="??[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        self.shell.last.result = [
            {
                'group': 'myg roup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args)
        results = self.stream.getvalue().split(os.linesep)
        self.assertEqual(results[0], '"foo" "doo" "-bar=[\'fred\']"')
Example #33
0
 def test_print_list_replacement(self):
     # tests that the query replaces the values in the command
     args = '??[].group'
     args = parse_quotes(args)
     self.shell.last.result = [{
         'group': 'mygroup',
         'name': 'myname'
     }, {
         'group': 'mygroup2',
         'name': 'myname2'
     }, {
         'group': 'mygroup3',
         'name': 'myname3'
     }]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     self.assertEqual(json.loads(self.stream.getvalue()),
                      ['mygroup', 'mygroup2', 'mygroup3'])
Example #34
0
 def test_errors(self):
     """ tests invalid query """
     args = 'vm show -g "?[].group" -n "?[].name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = [{
         'group': 'mygroup',
         'name': 'myname'
     }, {
         'group': 'mygroup3',
     }]
     flag = self.shell.handle_jmespath_query(args, False)
     results = self.stream.getvalue().split('\n')
     self.assertTrue(flag)
     self.assertEqual(results[0], 'vm show -g mygroup -n myname')
     self.assertEqual(len(results), 2)
Example #35
0
    def test_spaces_with_equal(self):
        """ tests quotes with spaces """
        args = 'vm show -g="?[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [{
            'group': 'myg roup',
            'name': 'fred'
        }, {
            'group': 'mygroup3',
            'name': 'myname3'
        }]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g=fred')
    def test_spaces_with_equal(self):
        """ tests quotes with spaces """
        args = 'vm show -g="?[?group == \'myg roup\'].name"'
        args = parse_quotes(args)
        args_no_quotes = []
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))
        self.shell.last.result = [
            {
                'group': 'myg roup',
                'name': 'fred'
            },
            {
                'group': 'mygroup3',
                'name': 'myname3'
            }
        ]

        self.shell.handle_jmespath_query(args_no_quotes, False)
        results = self.stream.getvalue().split('\n')
        self.assertEqual(results[0], u'vm show -g=fred')
 def test_errors(self):
     """ tests invalid query """
     args = 'vm show -g "?[].group" -n "?[].name"'
     args = parse_quotes(args)
     args_no_quotes = []
     for arg in args:
         args_no_quotes.append(arg.strip("/'").strip('/"'))
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup3',
         }
     ]
     flag = self.shell.handle_jmespath_query(args, False)
     results = self.stream.getvalue().split('\n')
     self.assertTrue(flag)
     self.assertEqual(results[0], 'vm show -g mygroup -n myname')
     self.assertEqual(len(results), 2)
 def test_print_list_replacement(self):
     # tests that the query replaces the values in the command
     args = '??[].group'
     args = parse_quotes(args)
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup2',
             'name': 'myname2'
         },
         {
             'group': 'mygroup3',
             'name': 'myname3'
         }
     ]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     self.assertEqual(json.loads(self.stream.getvalue()), ['mygroup', 'mygroup2', 'mygroup3'])
Example #39
0
 def test_list_replacement(self):
     # tests that the query replaces the values in the command
     args = 'foo update --set blah=??[].group'
     args = parse_quotes(args)
     self.shell.last.result = [{
         'group': 'mygroup',
         'name': 'myname'
     }, {
         'group': 'mygroup2',
         'name': 'myname2'
     }, {
         'group': 'mygroup3',
         'name': 'myname3'
     }]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().strip().split(os.linesep)
     self.assertTrue(len(results) == 1)
     self.assertEqual(
         results[0],
         '"foo" "update" "--set" "blah=[\'mygroup\', \'mygroup2\', \'mygroup3\']"'
     )
 def test_list_replacement(self):
     # tests that the query replaces the values in the command
     args = 'foo update --set blah=??[].group'
     args = parse_quotes(args)
     self.shell.last.result = [
         {
             'group': 'mygroup',
             'name': 'myname'
         },
         {
             'group': 'mygroup2',
             'name': 'myname2'
         },
         {
             'group': 'mygroup3',
             'name': 'myname3'
         }
     ]
     flag = self.shell.handle_jmespath_query(args)
     self.assertTrue(flag)
     results = self.stream.getvalue().strip().split(os.linesep)
     self.assertTrue(len(results) == 1)
     self.assertEqual(results[0], '"foo" "update" "--set" "blah=[\'mygroup\', \'mygroup2\', \'mygroup3\']"')
Example #41
0
    def _special_cases(self, text, cmd, outside):
        break_flag = False
        continue_flag = False
        args = parse_quotes(text)
        args_no_quotes = []
        text_stripped = text.strip()
        for arg in args:
            args_no_quotes.append(arg.strip("/'").strip('/"'))

        if text and len(text.split()) > 0 and text.split()[0].lower() == 'az':
            telemetry.track_ssg('az', text)
            cmd = ' '.join(text.split()[1:])
        if self.default_command:
            cmd = self.default_command + " " + cmd

        if text_stripped == "quit" or text_stripped == "exit":
            break_flag = True
        elif text_stripped == "clear-history":  # clears the history, but only when you restart
            outside = True
            cmd = 'echo -n "" >' +\
                os.path.join(
                    SHELL_CONFIG_DIR(),
                    SHELL_CONFIGURATION.get_history())
        elif text_stripped == CLEAR_WORD:
            outside = True
            cmd = CLEAR_WORD
        if text_stripped:
            if text_stripped[0] == SELECT_SYMBOL['outside']:
                cmd = text_stripped[1:]
                outside = True
                if cmd.strip() and cmd.split()[0] == 'cd':
                    self.handle_cd(parse_quotes(cmd))
                    continue_flag = True
                telemetry.track_ssg('outside', '')

            elif text_stripped[0] == SELECT_SYMBOL['exit_code']:
                meaning = "Success" if self.last_exit == 0 else "Failure"

                print(meaning + ": " + str(self.last_exit), file=self.output)
                continue_flag = True
                telemetry.track_ssg('exit code', '')
            elif validate_contains_query(
                    args_no_quotes,
                    SELECT_SYMBOL['query']) and self.last and self.last.result:
                continue_flag = self.handle_jmespath_query(
                    args_no_quotes, continue_flag)
                telemetry.track_ssg('query', '')

            elif args[0] == '--version' or args[0] == '-v':
                try:
                    continue_flag = True
                    show_version_info_exit(self.output)
                except SystemExit:
                    pass
            elif "|" in text or ">" in text:  # anything I don't parse, send off
                outside = True
                cmd = "az " + cmd

            elif SELECT_SYMBOL['example'] in text:
                cmd, continue_flag = self.handle_example(cmd, continue_flag)
                telemetry.track_ssg('tutorial', text)
            elif len(text_stripped
                     ) > 2 and SELECT_SYMBOL['scope'] == text_stripped[0:2]:
                continue_flag, cmd = self.handle_scoping_input(
                    continue_flag, cmd, text_stripped)

        return break_flag, continue_flag, outside, cmd