Exemplo n.º 1
0
def run(cloud, parser, _help):
    group = get_command_group(list(parser.unparsed), parser.arguments)
    if not group:
        #parser.parser.print_help()
        parser.print_help()
        _groups_help(parser.arguments)
        exit(0)

    nonargs = [term for term in parser.unparsed if not term.startswith('-')]
    set_command_params(nonargs)

    global _best_match
    _best_match = []

    _cnf = parser.arguments['config']
    group_spec = _cnf.get('global', '%s_cli' % group)
    spec_module = _load_spec_module(group_spec, parser.arguments, '_commands')
    if spec_module is None:
        raise CLIUnknownCommand(
            'Could not find specs for %s commands' % group,
            details=[
                'Make sure %s is a valid command group' % group,
                'Refer to kamaki documentation for setting custom command',
                'groups or overide existing ones'])
    cmd_tree = _get_cmd_tree_from_spec(group, spec_module._commands)

    if _best_match:
        cmd = cmd_tree.get_command('_'.join(_best_match))
    else:
        cmd = _get_best_match_from_cmd_tree(cmd_tree, parser.unparsed)
        _best_match = cmd.path.split('_')
    if cmd is None:
        kloger.info('Unexpected error: failed to load command (-d for more)')
        exit(1)

    update_parser_help(parser, cmd)

    if _help or not cmd.is_command:
        if cmd.cmd_class:
            parser.required = getattr(cmd.cmd_class, 'required', None)
        parser.print_help()
        if getattr(cmd, 'long_help', False):
            print 'Details:\n', cmd.long_help
        print_subcommands_help(cmd)
        exit(0)

    cls = cmd.cmd_class
    auth_base = init_cached_authenticator(_cnf, cloud, kloger) if (
        cloud) else None
    executable = cls(parser.arguments, auth_base, cloud)
    parser.required = getattr(cls, 'required', None)
    parser.update_arguments(executable.arguments)
    for term in _best_match:
        parser.unparsed.remove(term)
    exec_cmd(executable, parser.unparsed, parser.print_help)
Exemplo n.º 2
0
 def help_method(self):
     print('%s (%s -h for more options)' % (cmd.help, cmd.name))
     if cmd.is_command:
         cls = cmd.cmd_class
         ldescr = getattr(cls, 'long_description', '')
         plist = self.prompt[len(self._prefix):-len(self._suffix)]
         plist = plist.split(' ')
         clist = cmd.path.split('_')
         upto = 0
         if ldescr:
             print('%s' % ldescr)
         for i, term in enumerate(plist):
             try:
                 if clist[i] == term:
                     upto += 1
             except IndexError:
                 break
         print('Syntax: %s %s' % (' '.join(clist[upto:]), cls.syntax))
     if cmd.subcommands:
         print_subcommands_help(cmd)
Exemplo n.º 3
0
 def help_method(self):
     print('%s (%s -h for more options)' % (cmd.help, cmd.name))
     if cmd.is_command:
         cls = cmd.cmd_class
         ldescr = getattr(cls, 'long_description', '')
         plist = self.prompt[len(self._prefix):-len(self._suffix)]
         plist = plist.split(' ')
         clist = cmd.path.split('_')
         upto = 0
         if ldescr:
             print('%s' % ldescr)
         for i, term in enumerate(plist):
             try:
                 if clist[i] == term:
                     upto += 1
             except IndexError:
                 break
         print('Syntax: %s %s' % (' '.join(clist[upto:]), cls.syntax))
     if cmd.subcommands:
         print_subcommands_help(cmd)
Exemplo n.º 4
0
        def do_method(new_context, line):
            """ Template for all cmd.Cmd methods of the form do_<cmd name>
                Parse cmd + args and decide to execute or change context
                <cmd> <term> <term> <args> is always parsed to most specific
                even if cmd_term_term is not a terminal path
            """
            line = line.decode(pref_enc)
            subcmd, cmd_args = cmd.parse_out(split_input(line))
            self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
            cmd_parser = ArgumentParseManager(
                cmd.name, dict(self._parser.arguments))
            cmd_parser.parser.description = subcmd.help

            # exec command or change context
            if subcmd.is_command:  # exec command
                try:
                    cls = subcmd.cmd_class
                    cmd_parser.required = getattr(cls, 'required', None)
                    ldescr = getattr(cls, 'long_description', '')
                    if subcmd.path == 'history_run':
                        instance = cls(
                            dict(cmd_parser.arguments), self.astakos,
                            cmd_tree=self.cmd_tree)
                    else:
                        instance = cls(
                            dict(cmd_parser.arguments),
                            self.astakos, self.cloud)
                    cmd_parser.update_arguments(instance.arguments)
                    cmd_parser.arguments = instance.arguments
                    subpath = subcmd.path.split('_')[
                        (len(cmd.path.split('_')) - 1):]
                    cmd_parser.syntax = '%s %s' % (
                        ' '.join(subpath), instance.syntax)
                    help_method = self._create_help_method(
                        cmd.name, cmd_parser.arguments,
                        cmd_parser.required, subcmd.help, cmd_parser.syntax)
                    if '-h' in cmd_args or '--help' in cmd_args:
                        help_method()
                        if ldescr.strip():
                            print('\nDetails:')
                            print('%s' % ldescr)
                        return
                    cmd_parser.parse(cmd_args)

                    for name, arg in instance.arguments.items():
                        arg.value = getattr(
                            cmd_parser.parsed, name, arg.default)

                    exec_cmd(instance, cmd_parser.unparsed, help_method)
                except (ClientError, CLIError) as err:
                    print_error_message(err)
            elif ('-h' in cmd_args or '--help' in cmd_args) or len(cmd_args):
                # print options
                print('%s' % cmd.help)
                print_subcommands_help(cmd)
            else:  # change context
                backup_context = self._backup()
                old_prompt = self.prompt
                new_context._roll_command(cmd.parent_path)
                new_context.set_prompt(subcmd.path.replace('_', ' '))
                newcmds = [scmd for scmd in subcmd.subcommands.values()]
                for scmd in newcmds:
                    new_context._register_command(scmd.path)
                new_context.cmdloop()
                self.prompt = old_prompt
                # when new context is over, roll back to the old one
                self._restore(backup_context)
Exemplo n.º 5
0
def run(cloud, parser):
    group = get_command_group(list(parser.unparsed), parser.arguments)
    if not group:
        parser.print_help()
        _groups_help(parser.arguments)
        exit(0)

    nonargs = [term for term in parser.unparsed if not term.startswith('-')]
    set_command_params(nonargs)

    global _best_match
    _best_match = []

    _cnf = parser.arguments['config']
    group_spec = _cnf.get('global', '%s_cli' % group)
    spec_module = _load_spec_module(group_spec, parser.arguments, 'namespaces')
    if spec_module is None:
        raise CLIUnknownCommand(
            'Could not find specs for %s commands' % group,
            details=[
                'Make sure %s is a valid command group' % group,
                'Refer to kamaki documentation for setting custom command',
                'groups or overide existing ones'
            ])
    #  Get command tree from group
    try:
        cmd_tree = [t for t in spec_module.namespaces if t.name == group][0]
    except IndexError:
        raise CLIUnknownCommand('Unknown command group: %s' % group)

    cmd = None
    if _best_match:
        cmd = cmd_tree.get_command('_'.join(_best_match))
    else:
        match = [term for term in parser.unparsed if not term.startswith('-')]
        while match:
            try:
                cmd = cmd_tree.get_command('_'.join(match))
                _best_match = cmd.path.split('_')
                break
            except KeyError:
                match = match[:-1]
    if cmd is None:
        kloger.info('Unexpected error: failed to load command (-d for more)')
        exit(1)

    update_parser_help(parser, cmd)

    _help = parser.arguments['help'].value
    if _help or not cmd.is_command:
        if cmd.cmd_class:
            parser.required = getattr(cmd.cmd_class, 'required', None)
        parser.print_help()
        if getattr(cmd, 'long_help', False):
            print 'Details:\n', cmd.long_help
        print_subcommands_help(cmd)
        exit(0)

    cls = cmd.cmd_class
    astakos, help_message = init_cached_authenticator(
        _cnf, cloud, kloger) if (cloud) else (None, [])
    if not astakos:
        from kamaki.cli import is_non_api
        if not is_non_api(parser):
            raise CLIError('Failed to initialize an identity client',
                           importance=3,
                           details=help_message)
    executable = cls(parser.arguments, astakos, cloud)
    parser.required = getattr(cls, 'required', None)
    parser.update_arguments(executable.arguments)
    for term in _best_match:
        parser.unparsed.remove(term)
    exec_cmd(executable, parser.unparsed, parser.print_help)
Exemplo n.º 6
0
def run(cloud, parser):
    group = get_command_group(list(parser.unparsed), parser.arguments)
    if not group:
        parser.print_help()
        _groups_help(parser.arguments)
        exit(0)

    nonargs = [term for term in parser.unparsed if not term.startswith('-')]
    set_command_params(nonargs)

    global _best_match
    _best_match = []

    _cnf = parser.arguments['config']
    group_spec = _cnf.get('global', '%s_cli' % group)
    spec_module = _load_spec_module(group_spec, parser.arguments, 'namespaces')
    if spec_module is None:
        raise CLIUnknownCommand(
            'Could not find specs for %s commands' % group,
            details=[
                'Make sure %s is a valid command group' % group,
                'Refer to kamaki documentation for setting custom command',
                'groups or overide existing ones'])
    #  Get command tree from group
    try:
        cmd_tree = [t for t in spec_module.namespaces if t.name == group][0]
    except IndexError:
        raise CLIUnknownCommand('Unknown command group: %s' % group)

    cmd = None
    if _best_match:
        cmd = cmd_tree.get_command('_'.join(_best_match))
    else:
        match = [term for term in parser.unparsed if not term.startswith('-')]
        while match:
            try:
                cmd = cmd_tree.get_command('_'.join(match))
                _best_match = cmd.path.split('_')
                break
            except KeyError:
                match = match[:-1]
    if cmd is None:
        kloger.info('Unexpected error: failed to load command (-d for more)')
        exit(1)

    update_parser_help(parser, cmd)

    _help = parser.arguments['help'].value
    if _help or not cmd.is_command:
        if cmd.cmd_class:
            parser.required = getattr(cmd.cmd_class, 'required', None)
        parser.print_help()
        if getattr(cmd, 'long_help', False):
            print 'Details:\n', cmd.long_help
        print_subcommands_help(cmd)
        exit(0)

    cls = cmd.cmd_class
    astakos, help_message = init_cached_authenticator(_cnf, cloud, kloger) if (
        cloud) else (None, [])
    if not astakos:
        from kamaki.cli import is_non_api
        if not is_non_api(parser):
            raise CLIError(
                'Failed to initialize an identity client',
                importance=3, details=help_message)
    executable = cls(parser.arguments, astakos, cloud)
    parser.required = getattr(cls, 'required', None)
    parser.update_arguments(executable.arguments)
    for term in _best_match:
        parser.unparsed.remove(term)
    exec_cmd(executable, parser.unparsed, parser.print_help)
Exemplo n.º 7
0
        def do_method(new_context, line):
            """ Template for all cmd.Cmd methods of the form do_<cmd name>
                Parse cmd + args and decide to execute or change context
                <cmd> <term> <term> <args> is always parsed to most specific
                even if cmd_term_term is not a terminal path
            """
            line = line.decode(pref_enc)
            subcmd, cmd_args = cmd.parse_out(split_input(line))
            self._history.add(' '.join([cmd.path.replace('_', ' '), line]))
            cmd_parser = ArgumentParseManager(cmd.name,
                                              dict(self._parser.arguments))
            cmd_parser.parser.description = subcmd.help

            # exec command or change context
            if subcmd.is_command:  # exec command
                try:
                    cls = subcmd.cmd_class
                    cmd_parser.required = getattr(cls, 'required', None)
                    ldescr = getattr(cls, 'long_description', '')
                    if subcmd.path == 'history_run':
                        instance = cls(dict(cmd_parser.arguments),
                                       self.astakos,
                                       cmd_tree=self.cmd_tree)
                    else:
                        instance = cls(dict(cmd_parser.arguments),
                                       self.astakos, self.cloud)
                    cmd_parser.update_arguments(instance.arguments)
                    cmd_parser.arguments = instance.arguments
                    subpath = subcmd.path.split('_')[(
                        len(cmd.path.split('_')) - 1):]
                    cmd_parser.syntax = '%s %s' % (' '.join(subpath),
                                                   instance.syntax)
                    help_method = self._create_help_method(
                        cmd.name, cmd_parser.arguments, cmd_parser.required,
                        subcmd.help, cmd_parser.syntax)
                    if '-h' in cmd_args or '--help' in cmd_args:
                        help_method()
                        if ldescr.strip():
                            print('\nDetails:')
                            print('%s' % ldescr)
                        return
                    cmd_parser.parse(cmd_args)

                    for name, arg in instance.arguments.items():
                        arg.value = getattr(cmd_parser.parsed, name,
                                            arg.default)

                    exec_cmd(instance, cmd_parser.unparsed, help_method)
                except (ClientError, CLIError) as err:
                    print_error_message(err)
            elif ('-h' in cmd_args or '--help' in cmd_args) or len(cmd_args):
                # print options
                print('%s' % cmd.help)
                print_subcommands_help(cmd)
            else:  # change context
                backup_context = self._backup()
                old_prompt = self.prompt
                new_context._roll_command(cmd.parent_path)
                new_context.set_prompt(subcmd.path.replace('_', ' '))
                newcmds = [scmd for scmd in subcmd.subcommands.values()]
                for scmd in newcmds:
                    new_context._register_command(scmd.path)
                new_context.cmdloop()
                self.prompt = old_prompt
                # when new context is over, roll back to the old one
                self._restore(backup_context)