Created
January 24, 2025 18:17
-
-
Save jnhmcknight/1455fc4e12c349d625864dbe0e7d0f01 to your computer and use it in GitHub Desktop.
Show all help for a whole Click command tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
import os | |
import click | |
@click.group() | |
def cli(): | |
"""A grouping of commands""" | |
pass | |
@cli.command() | |
@click.option( | |
'-n', '--real-cli-name', | |
type=str, | |
default=None, | |
help="If desired, set this to replace the current filename with the correct wrapper filename", | |
) | |
@click.pass_context | |
def list_tree(ctx, real_cli_name): | |
"""Lists all (sub)commands and their help for updating a README more easily""" | |
def walk_command_tree(obj, parents=None): | |
if isinstance(obj, click.Group): | |
new_parents = [] if parents is None else copy.copy(parents) | |
for name, value in obj.commands.items(): | |
walk_command_tree(value, parents=[*new_parents, name]) | |
if isinstance(obj, click.Command): | |
help = obj.get_help(ctx) | |
if real_cli_name: | |
help = help.replace(os.path.basename(__file__), real_cli_name) | |
# Since we're using the current context when getting the help, the command line returned is | |
# wrong. The following fixes that. | |
if parents: | |
help = help.replace(' list-tree ', ' '+' '.join(parents)+' ', 1) | |
else: | |
help = help.replace(' list-tree ', ' ', 1) | |
click.echo(help) | |
click.echo('') | |
walk_command_tree(cli) | |
if __name__ == '__main__': | |
# Add subcommands to the cli here: | |
# cli.add_command(my_other_cmd_group) | |
cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment