Exemplo n.º 1
0
    def _check_value_key(action:Action, value:Any, key:str, cfg) -> Any:
        """Checks the value for a given action.

        Args:
            action: The action used for parsing.
            value: The value to parse.
            key: The configuration key.

        Raises:
            TypeError: If the value is not valid.
        """
        if action.choices is not None and isinstance(action, _ActionSubCommands):
            if key == action.dest:
                return value
            parser = action._name_parser_map[key]
            parser.check_config(value)  # type: ignore
        elif hasattr(action, '_check_type'):
            value = action._check_type(value, cfg=cfg)  # type: ignore
        elif action.type is not None:
            try:
                if action.nargs in {None, '?'} or action.nargs == 0:
                    value = action.type(value)
                elif value is not None:
                    for k, v in enumerate(value):
                        value[k] = action.type(v)
            except (TypeError, ValueError) as ex:
                raise TypeError('Parser key "'+str(key)+'": '+str(ex)) from ex
        return value
Exemplo n.º 2
0
    def _format_action(self, action: argparse.Action) -> str:
        # pylint: disable=attribute-defined-outside-init
        #
        if isinstance(action, argparse._SubParsersAction):
            self._subaction_max_length = max(
                len(i) for i in [
                    self._format_action_invocation(a)
                    for a in action._get_subactions()
                ])

        if isinstance(action, argparse._SubParsersAction._ChoicesPseudoAction):
            subaction = self._format_action_invocation(action)
            width = self._subaction_max_length
            help_text = self._expand_help(action) if action.help else str()

            return '{indent_first}{:{width}}{indent_help}{}\n'.format(
                subaction,
                help_text,
                indent_first=' ' * 2,
                width=width,
                indent_help=' ' * 10)
        elif isinstance(action, argparse._SubParsersAction):
            return '\n{}'.format(''.join(
                self._format_action(a) for a in action._get_subactions()))
        else:
            return super()._format_action(action)
Exemplo n.º 3
0
 def __init__(self,
              option_strings,
              dest=SUPPRESS,
              default=SUPPRESS,
              help=None, 
              nargs=None,
              metavar=None):
     Action.__init__(self, 
         option_strings=option_strings,
         dest=dest,
         default=default,
         nargs=nargs,
         help=help,
         metavar=metavar)
Exemplo n.º 4
0
    def _create_subparser(self, func: Callable,
                          subparsers: argparse.Action) -> None:
        """ A subparser adder function that wraps the input function.

        This helper method implements a subparser adder function given an input
        function. The core ``__call__`` method uses this function by creating
        a `functools.partial` object that fixes the ``func`` argument with the
        function to be decorated, which is then returned as the desired
        wrapper.

        Args:
            func: The function to be wrapped.
            subparsers: A special action object in the `argparse` module that
                has a single ``add_parser`` method.
        """
        parser = subparsers.add_parser(self.subcommand,
                                       help=self.subcommand_help)
        func_info = self._parse_func(func)
        for name, default, arg_help in func_info:
            parser.add_argument(f'--{name}',
                                type=type(default),
                                default=default,
                                help=arg_help)
        parser_function = partial(self._parser_function, func, func_info)
        parser.set_defaults(func=parser_function)
Exemplo n.º 5
0
 def define_signature(parser: Action):
     hook_parser = parser.add_parser(HookCommand.NAME,
                                     help=HookCommand.DESCRIPTION)
     hook_parser.add_argument('shell',
                              nargs=1,
                              help='Shell name to hook onto.',
                              metavar='{shell}')
Exemplo n.º 6
0
 def define_signature(parser: Action):
     use_parser = parser.add_parser(UseCommand.NAME,
                                    help=UseCommand.DESCRIPTION)
     use_parser.add_argument('version',
                             nargs=1,
                             help='Composer version to use.',
                             metavar='{version}')
Exemplo n.º 7
0
    def _format_action(self, action: Action):
        if isinstance(action, argparse._SubParsersAction):  # pylint: disable=protected-access
            parts = []
            subactions = action._get_subactions()  # pylint: disable=protected-access
            action_subcommnads, group_subcommnands = partition(
                lambda d: isinstance(ALL_COMMANDS_DICT[d.dest], GroupCommand), subactions
            )
            parts.append("\n")
            parts.append('%*s%s:\n' % (self._current_indent, '', "Groups"))
            self._indent()
            for subaction in group_subcommnands:
                parts.append(self._format_action(subaction))
            self._dedent()

            parts.append("\n")
            parts.append('%*s%s:\n' % (self._current_indent, '', "Commands"))
            self._indent()

            for subaction in action_subcommnads:
                parts.append(self._format_action(subaction))
            self._dedent()

            # return a single string
            return self._join_parts(parts)

        return super()._format_action(action)
Exemplo n.º 8
0
def add_argparse_subparser(subparsers: argparse.Action, source_paths_arg_name: str) -> None:
    # TODO: Better fix? Have to silence mypy since Action does not have add_parser() and
    #       argparse._SubParserAction is not public.
    parser = subparsers.add_parser('asm',  # type: ignore
                                   aliases=['assembler'],
                                   help='output assembler for compilation unit')

    parser.set_defaults(run_command=run)

    parser.add_argument('-c',
                        '--count',
                        action='store_true',
                        help='Count occurance of different opcodes per global label and in '
                             'total if there is more than one global label. Result is printed '
                             'as a comment before the generated assembly.')

    parser.add_argument('-va',
                        '--verbose-asm',
                        action='store_true',
                        help='Tell compiler to output verbose assembler.')

    parser.add_argument(source_paths_arg_name,
                        nargs=1,
                        help='Source file to output assembler for.',
                        metavar='<file>')
Exemplo n.º 9
0
 def _get_default_metavar_for_positional(self,
                                         action: argparse.Action) -> str:
     """
     Function to return positional metavariable type with circum-symbols
     """
     if action.type is not None:
         return "<" + action.type.__name__ + ">"  # type: ignore
     else:
         action.metavar = cast(str, action.metavar)
         return action.metavar
Exemplo n.º 10
0
 def add_argument(self, action: Action) -> None:
     '''Format arguments summary.'''
     # XXX: action.choice fails tests when colored
     if (ArgufyHelpFormatter.format_choices
             and isinstance(action, argparse._SubParsersAction)):
         if action.choices is not None:
             for choice in list(action.choices):
                 parser = action.choices.pop(choice)
                 choice = self.shade(choice)
                 action.choices[choice] = parser
     super(ArgufyHelpFormatter, self).add_argument(action)
def _build_hint(parser: argparse.ArgumentParser, arg_action: argparse.Action) -> str:
    """Build tab completion hint for a given argument"""
    # Check if hinting is disabled for this argument
    suppress_hint = arg_action.get_suppress_tab_hint()  # type: ignore[attr-defined]
    if suppress_hint or arg_action.help == argparse.SUPPRESS:
        return ''
    else:
        # Use the parser's help formatter to display just this action's help text
        formatter = parser._get_formatter()
        formatter.start_section("Hint")
        formatter.add_argument(arg_action)
        formatter.end_section()
        return formatter.format_help()
Exemplo n.º 12
0
    def _complete(self, act: ap.Action, **kwargs):
        if act.choices:
            yield from act.choices
        elif hasattr(act, "completer") and callable(
                act.completer):  # type: ignore
            # call the completer function
            from xonsh.built_ins import XSH

            kwargs.update(self.kwargs)
            yield from act.completer(xsh=XSH,
                                     action=act,
                                     completer=self,
                                     **kwargs)  # type: ignore
Exemplo n.º 13
0
    def _complete(self, act: ap.Action, **kwargs):
        if hasattr(act, "completer") and callable(act.completer):  # type: ignore
            # call the completer function
            kwargs.update(self.kwargs)
            yield from act.completer(xsh=XSH, action=act, completer=self, **kwargs)  # type: ignore

        if (
            hasattr(act, "choices")
            and act.choices
            and not isinstance(act.choices, dict)
        ):
            # any sequence or iterable
            yield from act.choices
Exemplo n.º 14
0
 def _format_action_invocation(self, action: argparse.Action) -> str:
     orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
     if orgstr and orgstr[0] != "-":  # only optional arguments
         return orgstr
     res = getattr(action, "_formatted_action_invocation",
                   None)  # type: Optional[str]
     if res:
         return res
     options = orgstr.split(", ")
     if len(options) == 2 and (len(options[0]) == 2
                               or len(options[1]) == 2):
         # a shortcut for '-h, --help' or '--abc', '-a'
         action._formatted_action_invocation = orgstr  # type: ignore
         return orgstr
     return_list = []
     short_long = {}  # type: Dict[str, str]
     for option in options:
         if len(option) == 2 or option[2] == " ":
             continue
         if not option.startswith("--"):
             raise ArgumentError(
                 'long optional argument without "--": [%s]' % (option),
                 option)
         xxoption = option[2:]
         shortened = xxoption.replace("-", "")
         if shortened not in short_long or len(
                 short_long[shortened]) < len(xxoption):
             short_long[shortened] = xxoption
     # now short_long has been filled out to the longest with dashes
     # **and** we keep the right option ordering from add_argument
     for option in options:
         if len(option) == 2 or option[2] == " ":
             return_list.append(option)
         if option[2:] == short_long.get(option.replace("-", "")):
             return_list.append(option.replace(" ", "=", 1))
     formatted_action_invocation = ", ".join(return_list)
     action._formatted_action_invocation = (formatted_action_invocation
                                            )  # type: ignore
     return formatted_action_invocation
Exemplo n.º 15
0
def add_loadchat_args(subparser: Action) -> None:
    parser_help = 'start an interactive session with Qualichat'
    parser = subparser.add_parser('load', help=parser_help) # type: ignore
    parser.set_defaults(func=loadchat) # type: ignore

    path_arg_help = 'the paths for the chats'
    parser.add_argument('paths', help=path_arg_help, nargs='+') # type: ignore

    debug_args = ('-d', '--debug')
    debug_args_help = 'set the logging level to debug'
    parser.add_argument( # type: ignore
        *debug_args, help=debug_args_help, action='store_true'
    )
Exemplo n.º 16
0
def add_argparse_subparser(subparsers: argparse.Action, source_paths_arg_name: str) -> None:
    # TODO: Better fix? Have to silence mypy since Action does not have add_parser() and
    #       argparse._SubParserAction is not public.
    parser = subparsers.add_parser('analyze', help='run static analyzer')  # type: ignore

    parser.set_defaults(run_command=run)

    parser.add_argument(source_paths_arg_name,
                        nargs='*',
                        help='Analyze path(s). Directories are recursed. All source code in '
                             'project, subject to configuration in .sork, is analyzed if no '
                             '%(metavar)s is passed or if only %(metavar)s passed is the '
                             'project\'s root.',
                        metavar='<path>')
Exemplo n.º 17
0
 def fix_default(self, action: Action) -> None:
     if hasattr(action, "default") and hasattr(
             action, "dest") and action.default != SUPPRESS:
         of_type = self.get_type(action)
         key = action.dest
         outcome = get_env_var(key, of_type=of_type)
         if outcome is None and self.file_config:
             outcome = self.file_config.get(key, of_type=of_type)
         if outcome is not None:
             action.default, action.default_source = outcome
     # noinspection PyProtectedMember
     if isinstance(action, argparse._SubParsersAction):
         for values in action.choices.values():
             values.fix_defaults()
Exemplo n.º 18
0
def get_default(action: argparse.Action, section: Dict, key: Text) -> Any:
    """
    Find default value for an option. This will only be used if an
    argument is not specified at the command line. The defaults will
    be found in this order (from lowest to highest):
        1. argparse default
        3. ini file
        3. environment variable

    """
    default = action.default
    env = get_env(key)

    # environment has higher presedence than config section
    if key in env:
        default = env[key]
    elif key in section:
        default = section[key]

    # if not env or section, keep default from argparse

    # parse true/yes as True and false/no as False for
    # action="store_true" and action="store_false"
    if action.const in (True, False) and isinstance(default, str):
        if default.lower() in ("true", "yes"):
            default = True
        elif default.lower() in ("false", "no"):
            default = False

    if action.nargs in (argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE):
        if isinstance(default, str):
            default = default.split()
        elif isinstance(default, list):
            pass
        else:
            raise ValueError("Not string or list in nargs")

    # If argument type is set and default is not None, enforce type
    # Eg, for this argument specification
    # parser.add_argument('--int-arg', type=int)
    # --int-arg 2
    # will give you int(2)
    # If --int-arg is omitted, it will use None
    if action.type is not None and default is not None:
        default = action.type(default)

    return default
Exemplo n.º 19
0
def config(
    subparsers: argparse.Action,
    config: Config,
    infer_type: bool = True,
) -> argparse.Action:
    '''
    Configuration function that returns a pregenerated argparse subparser
    to add to your CLIs using `xdgconfig`. The subparser has a callback
    attached to it, which you can call with the arguments from itself.
    Example :
        args = vars(parser.parse_args())
        callback = args.pop('callback', lambda *a, **kw: None)
        callback(**args)

    :param subparsers: The return value of argparse.add_subparsers
    :type subparsers: argparse._SubParsersAction
    :param config: The configuration object from xdgconfig.
    :type config: xdgconfig.Config
    :param infer_type: Whether to infer types from the value apparent
                       type, defaults to True
    :type infer_type: bool, optional
    :return: The modified argparse._SubParsersAction
    :rtype: argparse._SubParsersAction
    '''

    config_p = subparsers.add_parser(
        'config',
        help=HELP_TEXT,
    )

    config_p.add_argument('config_key', type=str, help='Config key to edit')
    config_p.add_argument('config_value',
                          type=str,
                          help='Value to assign to the config key.')
    config_p.add_argument(
        '--global',
        action='store_true',
        dest='_global',
        help='Whether to assign to value to the global configuration')
    config_p.set_defaults(
        callback=partial(
            config._cli_callback,
            infer_type=infer_type,  # noqa
        ), )
    return subparsers
Exemplo n.º 20
0
    def format_help(self):
        formatter = self._get_formatter()
        formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
        formatter.add_text(self.description)

        for action_group in self._action_groups:
            formatter.start_section(action_group.title)
            formatter.add_text(action_group.description)
            formatter.add_arguments(action_group._group_actions)
            formatter.end_section()
        formatter.add_text(self.epilog)

        formatter.start_section('commands')
        for name, command in sorted(COMMANDS.items()):
            descr = command.get_parser().description.split('\n')[0]
            formatter.add_argument(Action([name], '', help=descr))
        formatter.end_section()

        return formatter.format_help()
Exemplo n.º 21
0
 def __call__(self, *a, **kw):
     actions = [
         Action([i], help=getattr(pathmaker, i).__doc__, dest='')
         for i in sorted(pathmaker.__all__)
         if not i.startswith('_') and callable(getattr(pathmaker, i))
     ]
     formatter = HelpFormatter('')
     formatter.add_text(
         "An explicit layout strategy can be specified.  This is to "
         "instruct how ExplosiveFUSE should present file entries across "
         "all archive files within its mount point.  Do note that "
         "the final outcome of the layout is also influenced by the usage "
         "of the '--overwrite' and the '--omit-arcname' flags, and "
         "arguments which may associate with each of the strategies. "
         "They are specified by appending ':', followed by the value of "
         "each positional argument(s).")
     formatter.start_section('Available layout strategies')
     formatter.add_arguments(actions)
     formatter.end_section()
     print(formatter.format_help())
     sys.exit(0)
Exemplo n.º 22
0
def add_argparse_subparser(subparsers: argparse.Action, source_paths_arg_name: str) -> None:
    # TODO: Better fix? Have to silence mypy since Action does not have add_parser() and
    #       argparse._SubParserAction is not public.
    parser = subparsers.add_parser('check', help='style check source code')  # type: ignore

    parser.set_defaults(run_command=run)

    parser.add_argument('-c',
                        '--checks',
                        type=str,
                        help='Comma separated list of checks to perform. Overrides '
                             'configuration in .sork. Prepend - to disable a check. Regular '
                             'expressions may be used. All checks except foo: --checks=-foo . '
                             'Checks starting with clang-: --checks=clang-.* .',
                        metavar='<checks>')

    parser.add_argument(source_paths_arg_name,
                        nargs='*',
                        help='Check path(s). Directories are recursed. All source code in '
                             'project, subject to configuration in .sork, is checked if no '
                             '%(metavar)s is passed or if only %(metavar)s passed is the '
                             'project\'s root.',
                        metavar='<path>')
Exemplo n.º 23
0
def add_sub_command(sub_parsers: argparse.Action,
                    cmd_name: str) -> argparse.ArgumentParser:
    sub_command = sub_parsers.add_parser(
        cmd_name, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    return sub_command
Exemplo n.º 24
0
 def __init__(self, *args, **kwargs):
     if "nargs" not in kwargs:
         kwargs["nargs"] = 0
     Action.__init__(self, *args, **kwargs)
Exemplo n.º 25
0
 def __init__(self, option_strings, dest, nargs=None, **kwargs):
     Action.__init__(self, option_strings, dest, nargs=0, **kwargs)
Exemplo n.º 26
0
 def define_signature(parser: Action):
     parser.add_parser(ListCommand.NAME, help=ListCommand.DESCRIPTION)
Exemplo n.º 27
0
 def __init__(self, **kwargs):
     kwargs['required'] = False
     kwargs['nargs'] = 0
     Action.__init__(self, **kwargs)
     junit_arg_actions.append(self)
Exemplo n.º 28
0
 def test_format_action_invocation(self):
     action = Action("d", "a")
     fmt = lp.NewFormatter("lol.py")
     assert fmt._format_action_invocation(action) == "d A"
     action = Action("d", "a", nargs=0)
     assert fmt._format_action_invocation(action) == "d"
Exemplo n.º 29
0
 def test_format_args(self):
     action = Action("-a", "a")
     fmt = lp.NewFormatter("lol.py")
     assert fmt._format_args(action, "a") == "a"
Exemplo n.º 30
0
def register_completer(action: argparse.Action, completer) -> None:
    """Register the given completer with the specified action."""
    action.completer = completer  # type: ignore[attr-defined]  # intentionally using an attribute that does not exist
Exemplo n.º 31
0
 def __init__(self, *args, **kwargs):
     Action.__init__(self, *args, **kwargs)
Exemplo n.º 32
0
 def __init__(self, option_strings, dest, *args, **kwargs):
     Action.__init__(self, option_strings, dest, *args, **kwargs)
Exemplo n.º 33
0
 def __init__(self, *args, **kwargs):
     kwargs['nargs'] = 0
     Action.__init__(self, *args, **kwargs)
Exemplo n.º 34
0
def add_setup_args(subparser: Action) -> None:
    parser_help = 'setup internal libraries'
    parser = subparser.add_parser('setup', help=parser_help) # type: ignore
    parser.set_defaults(func=setup) # type: ignore