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
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)
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)
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)
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}')
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}')
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)
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>')
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
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()
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
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
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
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' )
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>')
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()
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
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
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()
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)
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>')
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
def __init__(self, *args, **kwargs): if "nargs" not in kwargs: kwargs["nargs"] = 0 Action.__init__(self, *args, **kwargs)
def __init__(self, option_strings, dest, nargs=None, **kwargs): Action.__init__(self, option_strings, dest, nargs=0, **kwargs)
def define_signature(parser: Action): parser.add_parser(ListCommand.NAME, help=ListCommand.DESCRIPTION)
def __init__(self, **kwargs): kwargs['required'] = False kwargs['nargs'] = 0 Action.__init__(self, **kwargs) junit_arg_actions.append(self)
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"
def test_format_args(self): action = Action("-a", "a") fmt = lp.NewFormatter("lol.py") assert fmt._format_args(action, "a") == "a"
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
def __init__(self, *args, **kwargs): Action.__init__(self, *args, **kwargs)
def __init__(self, option_strings, dest, *args, **kwargs): Action.__init__(self, option_strings, dest, *args, **kwargs)
def __init__(self, *args, **kwargs): kwargs['nargs'] = 0 Action.__init__(self, *args, **kwargs)
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