def _format_commands(self, formatter: argparse.HelpFormatter, command: Command = None) -> None: prefix = self.prefixes['commands'] if command: if command.group: prefix = self.prefixes['group'] elif command.guesses: prefix = self.prefixes['guesses'] formatter.start_section(Fore.YELLOW + prefix + Fore.RESET) prev_group = '' colors = {True: Fore.GREEN, False: Fore.BLUE} color = True for name, handler in self._handlers.items(): if command and command.guesses and name not in command.guesses: continue # switch colors for every group group, _, subname = name.rpartition(' ') if group != prev_group: prev_group = group color = not color formatter.add_argument( argparse.Action( option_strings=[colors[color] + name + Fore.RESET], dest='', help=handler.summary, )) formatter.end_section()
def add_usage(self, usage, actions, groups, prefix=None): actions = list(actions) actions.append( argparse.Action([], dest='worker_options', metavar='worker options', nargs='?')) super().add_usage(usage, actions, groups, prefix)
def add_arguments(self, actions): if not actions or not actions[0].choices: super(SubcommandHelpFormatter, self).add_arguments(actions) return new_actions = [ argparse.Action((), dest=k, help=v.description) for k, v in sorted(actions[0].choices.items(), key=lambda i: i[0]) ] super(SubcommandHelpFormatter, self).add_arguments(new_actions)
def _parse_union(parsers: List[Parser], union: type, flags: List[str], value: str) -> Any: for p in parsers: try: return p(value) except Exception: continue pretty = str(union)[len("typing."):] msg = f"invalid {pretty} value: '{value}'" action = argparse.Action(flags, "") raise argparse.ArgumentError(action, msg)
def make_action( flags=("--option", "-o"), dest="option", nargs=None, help="do 42 things", metavar="OPTION", ): return argparse.Action(flags, dest, nargs=nargs, help=help, metavar=metavar)
def _parse_enum(enum: enum.EnumMeta, flags: List[str], value: str) -> enum.Enum: members = tuple(enum.__members__) # enum members might be case sensitive. if value in members: return enum[value] if value.upper() in members: return enum[value.upper()] # Mimick argparse error message for choices. # See https://github.com/python/cpython/blob/3.7/Lib/argparse.py#L2420 msg = f"invalid choice: '{value}' (choose from {', '.join(members)})" action = argparse.Action(flags, "") raise argparse.ArgumentError(action, msg)
def add_usage(self, usage, actions, groups, prefix=None): orig_actions = actions actions = [ act for act in orig_actions if set(act.option_strings) & self.important_options ] actions += [ argparse.Action(['options'], 'options', nargs=0, required=False) ] actions += [ act for act in orig_actions if (act.required or isinstance(act, ArgumentParser.set_output)) ] return argparse.HelpFormatter.add_usage(self, usage, actions, groups, prefix)
def test_example_no_value(): parser = ArgumentParser(conflict_handler="resolve") # When store_true option value is True, then it should not be commented action = parser.add_argument("--option", action="store_true") option_line = interactive.example_no_value(parser, action, {"option": True}) assert option_line.strip() == "--option" option_line = interactive.example_no_value(parser, action, {"option": False}) assert option_line.strip() == "# --option" # When store_false option value is False, then it should not be commented action = parser.add_argument("--option", action="store_false") option_line = interactive.example_no_value(parser, action, {"option": False}) assert option_line.strip() == "--option" option_line = interactive.example_no_value(parser, action, {"option": True}) assert option_line.strip() == "# --option" # When store_const option value is const, then it should not be commented action = parser.add_argument("--option", action="store_const", const=44, default=33) option_line = interactive.example_no_value(parser, action, {"option": 44}) assert option_line.strip() == "--option" option_line = interactive.example_no_value(parser, action, {"option": 33}) assert option_line.strip() == "# --option" # When no value is available in opts, then it should be commented action = argparse.Action(["--option", "-o"], "option", nargs=0) option_line = interactive.example_no_value(parser, action, {}) assert option_line.strip() == "# --option" # When an extension is available, then it should not be commented option_line = interactive.example_no_value( parser, action, {"extensions": [Mock(flag="--option")]}) assert option_line.strip() == "--option"
def test_example(): parser = ArgumentParser() # Options with variable nargs action = make_action(nargs=1) assert interactive.example(parser, action, {}).strip() == "# --option OPTION" assert interactive.example(parser, action, { "option": 32 }).strip() == "--option 32" action = make_action(nargs=3) example = interactive.example(parser, action, {}).strip() assert example == "# --option OPTION OPTION OPTION" example = interactive.example(parser, action, { "option": [32, 21, 5] }).strip() assert example == "--option 32 21 5" action = make_action(nargs="*") example = interactive.example(parser, action, {}).strip() expected = ("# --option [OPTION [OPTION ...]]", "# --option [OPTION ...]") assert example in expected action = make_action(nargs="+") example = interactive.example(parser, action, {}).strip() assert example == "# --option OPTION [OPTION ...]" action = make_action(nargs="?") assert interactive.example(parser, action, {}).strip() == "# --option [OPTION]" # Positional argument: action = argparse.Action([], "arg", nargs=1, metavar="ARGUMENT") assert interactive.example(parser, action, {}).strip() == "# ARGUMENT" assert interactive.example(parser, action, { "arg": "value" }).strip() == "value"
"""toil_container pasers.""" import argparse from toil.job import Job import click from toil_container import validators CUSTOM_TOIL_ACTIONS = [ argparse.Action( ["TOIL OPTIONAL ARGS"], dest="", default=argparse.SUPPRESS, help="see --help-toil for a full list of toil parameters", ), argparse.Action( [], dest="jobStore", help="the location of the job store for the workflow. " "See --help-toil for more information [REQUIRED]", ), ] class _ToilHelpAction(argparse._HelpAction): def __call__(self, parser, namespace, values, option_string=None): """Print parser help and exist whilst adding a flag to the parser.""" parser.show_toil_groups = True parser.print_help() parser.exit()
"""toil_container pasers.""" import argparse from toil.job import Job import click from toil_container import validators SHOW_TOILGROUPS_PROPERTY = "_show_toil_groups" SHOW_CONTGROUPS_PROPERTY = "_show_container_groups" CUSTOM_TOIL_ACTIONS = [ argparse.Action( [], dest="jobStore", help="the location of the job store for the workflow. " "See --help-toil for more toil options and information [REQUIRED]", ) ] class _ToilHelpAction(argparse._HelpAction): def __call__(self, parser, namespace, values, option_string=None): """Print parser help and exist whilst adding a flag to the parser.""" setattr(parser, SHOW_TOILGROUPS_PROPERTY, True) parser.print_help() parser.exit() class _ContainerHelpAction(argparse._HelpAction): def __call__(self, parser, namespace, values, option_string=None):
def test_alternative_flags(): for flags in (["-o", "--option", "-b"], ["--option", "-b", "-o"]): action = argparse.Action(flags, "dest") text = interactive.alternative_flags(action) assert "--option" not in text assert all([flag in text for flag in ("-o", "-b")])
def test_long_option(): for flags in (["-o", "--option"], ["--option", "-o"]): action = argparse.Action(flags, "dest") assert interactive.long_option(action).strip() == "--option"
def add_choice(self, choice, help=""): self.choices.append(choice) choice_action = argparse.Action(option_strings=[], dest=choice, help=help) self._choices_actions.append(choice_action)