def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: commands = { "Operation": [ "up", "down", "restart", "update", ], "Instance Management": [ "init", "list", ], "Project and Service Management": [ "new", "enable", "disable", "logs", "shell", "cmd", ], "Image Handling": [ "build", "pull", "push", ], } # allow for 3 times the default spacing cmd_names = set(self.list_commands(ctx)) limit = formatter.width - 6 - max(len(cmd_name) for cmd_name in cmd_names) for purpose, cmd_list in commands.items(): with formatter.section(_(f"Commands for {purpose}")): formatter.write_dl([ (cmd_name, self.get_command(ctx, cmd_name).get_short_help_str(limit)) for cmd_name in cmd_list ]) cmd_names -= set(cmd_list) if len(cmd_names) > 0: raise CMDUnregisteredError(cmd_names)
def format_options( self, ctx: click.Context, formatter: click.HelpFormatter ) -> None: all_opts: dict[str, _OptionInfo] = {} for name, cmd in self.commands.items(): for _param in cmd.get_params(ctx): rv = _param.get_help_record(ctx) if rv is not None: opt, text = rv if opt in all_opts: all_opts[opt].commands.append(name) else: all_opts[opt] = _OptionInfo(text=text, commands=[name]) dl = [ (opt, info.text) if len(info.commands) == len(self.commands) else (opt, f"{info.text} [Commands: {', '.join(info.commands)}]") for opt, info in all_opts.items() ] with formatter.section(gettext("Options")): formatter.write_dl(dl) self.format_commands(ctx, formatter)
def format_options(self, ctx: Context, formatter: Formatter) -> None: """ Group options together. """ if not hasattr(self, '_groups'): return super().format_options(ctx, formatter) # building reverse look up lookup = {} for group, items in self._groups.items(): lookup.update({item: group for item in items}) groups = {group: [] for group in self._groups} #type: Dict[str, HelpDefList] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is None: continue current_group = lookup.get(param.name, "Other") groups[current_group].append(rv) for group_name, options in groups.items(): if not options: continue with formatter.section(group_name): formatter.write_dl(options)
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: commands = [] for name in self.commands: cmd = self.get_command(ctx, name) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((name, cmd)) # allow for 3 times the default spacing if len(commands) > 0: max_len = max(len(name) for name, cmd in commands) limit = formatter.width - 6 - max_len # format sections individually for section, cmd_list in self.sections.items(): rows = [] for name, cmd in cmd_list: name = name.ljust(max_len) help_str = cmd.get_short_help_str(limit) rows.append((name, help_str)) if rows: with formatter.section(section): formatter.write_dl(rows)
def format_epilog( self, ctx: click.Context, # noqa: U100 formatter: click.HelpFormatter, ) -> None: """Writes each line of the epilog, thus preserving newlines.""" with formatter.section("Environment variables"): formatter.write_dl(Settings.help())
def format_examples( self, ctx: Context, formatter: Formatter) -> None: # pylint: disable-msg=R0201 """ Writes the examples into the formatter. """ with formatter.section('Usage Examples'): formatter.write("\n") for line in self.EXAMPLES.split("\n"): formatter.write(" {}\n".format(line))
def format_example(example: str, formatter: click.HelpFormatter) -> None: with formatter.section(click.style("Examples", bold=True, underline=False)): for line in example.splitlines(): is_comment = line.startswith("#") if is_comment: formatter.write_text("\b\n" + click.style(line, dim=True)) else: formatter.write_text("\b\n" + " ".join(shlex.split(line)))
def format_options(self, ctx: click.Context, formatter: click.HelpFormatter): """Writes all the options into the formatter if they exist.""" opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: opts.append(rv) if opts: with formatter.section("Options(No current command options)"): formatter.write_dl(opts)
def format_synopsis(self, formatter: click.HelpFormatter) -> None: """Wirte the synopsis to the formatter if exist. Arguments: formatter: The help formatter of the command. """ if not self.synopsis: return with formatter.section("Synopsis"): for example in self.synopsis: formatter.write_text(example)
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: self.format_usage(ctx, formatter) formatter.write_paragraph() assert ctx.parent is not None alias_cmd = self.alias["cmd"] formatter.write( "Alias for " + click.style(f'"{ctx.parent.info_name} {alias_cmd}"', bold=True)) formatter.write_paragraph() help = self.alias.get("help") if help is not None: formatter.write_paragraph() formatter.write_text(help) self.format_options(ctx, formatter)
def format_help_text(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: formatter.write_paragraph() alias_cmd = self.alias["exec"] formatter.write_text("Alias for " + click.style(f'"{alias_cmd}"', bold=True)) help = self.alias.get("help") if help is not None: formatter.write("\n") formatter.write_text(help)
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for name in self.commands: cmd = self.get_command(ctx, name) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((name, cmd)) # allow for 3 times the default spacing if len(commands): max_len = max(len(name) for name, cmd in commands) limit = formatter.width - 6 - max_len # type: ignore sections: Dict[str, List[Tuple[str, click.Command]]] = {} # group commands into sections for name, cmd in commands: try: sections[cmd.section].append((name, cmd)) # type: ignore except KeyError: sections[cmd.section] = [(name, cmd)] # type: ignore # format sections individually for section, cmds in sections.items(): rows = [] for name, cmd in cmds: name = name.ljust(max_len) help = cmd.get_short_help_str(limit) rows.append((name, help)) if rows: with formatter.section(section): formatter.write_dl(rows)
async def _get_forwarded_commands(self, formatter: HelpFormatter): [help_proc, *_], help_done = await run("-help", namespace="kube-system", container="vault", stderr=PIPE) _, help_stderr = await help_proc.communicate() groups = help_stderr.decode("utf-8").split("\n\n")[1:] await help_done for group in groups: name, *rows = group.splitlines() with formatter.section("{} Vault commands".format( name.split()[0])): formatter.write_dl( (name, "{}.".format(help)) for (name, help) in map(lambda row: row.split(maxsplit=1), rows) if name not in self.commands)
def format_help_text(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: """Writes the help text to the formatter if it exists.""" help = self.help # type: ignore deprecated = self.deprecated # type: ignore if help: help_text, *examples = split_examples(help) if help_text: formatter.write_paragraph() with formatter.indentation(): if deprecated: help_text += DEPRECATED_HELP_NOTICE formatter.write_text(help_text) examples = [example.strip() for example in examples] for example in examples: format_example(example, formatter) elif deprecated: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(DEPRECATED_HELP_NOTICE)
def _format_group( self, title: str, grp: Sequence[Tuple[str, click.Command]], formatter: click.HelpFormatter, ) -> None: # allow for 3 times the default spacing if not grp: return width = formatter.width assert width is not None limit = width - 6 - max(len(cmd[0]) for cmd in grp) rows = [] for subcommand, cmd in grp: help = cmd.get_short_help_str(limit) rows.append((subcommand, help)) if rows: with formatter.section(title): formatter.write_dl(rows)
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: """Extra format methods for multi methods that adds all the commands after the options. """ commands = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) # What is this, the tool lied about a command. Ignore it if cmd is None: continue if cmd.hidden: continue commands.append((subcommand, cmd)) # allow for 3 times the default spacing if len(commands): limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) categories: t.Dict[str, t.List[t.Tuple[ str, str]]] = collections.defaultdict(list) for subcommand, cmd in commands: help = cmd.get_short_help_str(limit) # NOTE: Instead we could make it into a separate click # group and add both groups to the cli entrypoint group. if subcommand in APPLICATION_CMDS: categories["Application Commands"].append( (subcommand, help)) else: categories["Cluster Management Commands"].append( (subcommand, help)) if categories: for category, rows in categories.items(): with formatter.section(gettext(category)): formatter.write_dl(rows)
def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: self.format_commands(ctx, formatter) formatter.write_paragraph() formatter.write_text( f'Use "{ctx.info_name} help <command>" for more information ' "about a given command or topic.") formatter.write_text( f'Use "{ctx.info_name} --options" for a list of global command-line ' "options (applies to all commands).")
def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: self.format_commands(ctx, formatter) formatter.write_paragraph() formatter.write_text( 'Use "neuro <command> --help" for more information about a given command.' ) formatter.write_text( 'Use "neuro --options" for a list of global command-line options ' "(applies to all commands).")
def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: # Group options first groups = defaultdict(list) for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: if isinstance(param, GroupedOption): group = param.group else: group = ParameterGroup.generic groups[group].append(rv) # Then display groups separately with optional description for group in ParameterGroup: opts = groups[group] group_name, description = group.value with formatter.section(f"{group_name} options"): if description: formatter.write_paragraph() formatter.write_text(description) formatter.write_paragraph() formatter.write_dl(opts)
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: """Writes the custom help into the formatter if it exists. Override the original ``click.Command.format_help`` method by adding :meth:`CustomCommand.format_synopsis` to form custom help message. Arguments: ctx: The context of the command. formatter: The help formatter of the command. """ formatter.width = 100 self.format_usage(ctx, formatter) self.format_help_text(ctx, formatter) self.format_synopsis(formatter) # Add synopsis in command help. self.format_options(ctx, formatter) self.format_epilog(ctx, formatter)
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter): """Print help message. Includes information about commands that were registered by extensions. """ # click won't parse config file from envvar if no other options # provided, except for `--help`. In this case it has to be done # manually. if not ctx.obj: _add_ctx_object(ctx) _add_external_commands(ctx) commands = [] ext_commands = defaultdict(lambda: defaultdict(list)) for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) if cmd is None: continue if cmd.hidden: continue help = cmd.short_help or u'' meta = getattr(cmd, META_ATTR, None) if meta: ext_commands[meta[u'type']][meta[u'name']].append( (subcommand, help)) else: commands.append((subcommand, help)) if commands: with formatter.section(u'Commands'): formatter.write_dl(commands) for section, group in ext_commands.items(): with formatter.section(self._section_titles.get(section, section)): for rows in group.values(): formatter.write_dl(rows)
def _typer_format_options(self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter) -> None: args = [] opts = [] for param in self.get_params(ctx): rv = param.get_help_record(ctx) if rv is not None: if param.param_type_name == "argument": args.append(rv) elif param.param_type_name == "option": opts.append(rv) # TODO: explore adding Click's gettext support, e.g.: # from gettext import gettext as _ # with formatter.section(_("Options")): # ... if args: with formatter.section("Arguments"): formatter.write_dl(args) if opts: with formatter.section("Options"): formatter.write_dl(opts)
def format_usage(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: formatter.write_usage(ctx.command_path, "[OPTIONS] -- [QEMU_ARGS]...")
def format_help_text(self, ctx: Context, formatter: Formatter) -> None: """ Writes the help text to the formatter if it exists. """ formatter.write_paragraph() formatter.write_text(self.help)
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: if self.help is None: return formatter.write_paragraph() formatter.write(apply_styling(self.help))
def format_help_text(self, _: Any, formatter: click.HelpFormatter) -> None: formatter.write(get_tool_help(self.help_summary)) formatter.write("\n")
def format_help_text(text: str, formatter: click.HelpFormatter): text = inspect.cleandoc(text).partition("\f")[0] formatter.write_paragraph() with formatter.indentation(): formatter.write_text(text)
def format_usage( self, ctx: click.Context, formatter: click.HelpFormatter ) -> None: formatter.write_usage(ctx.command_path, "COMMAND [OPTIONS]")