Skip to content

Commit

Permalink
add command tree printing
Browse files Browse the repository at this point in the history
  • Loading branch information
brisvag committed Aug 4, 2023
1 parent 092efaa commit 9385a10
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
13 changes: 10 additions & 3 deletions stemia/__init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
import click
from pathlib import Path

from .utils.click import add_subcommands
from .utils.click import add_subcommands, print_command_tree

try:
from ._version import version
except ImportError:
version = 'unknown'


@click.group(context_settings=dict(help_option_names=['-h', '--help'], show_default=True))
def _print_tree(ctx, param, value):
print_command_tree(cli)
ctx.exit()


@click.group(name='stemia', context_settings=dict(help_option_names=['-h', '--help'], show_default=True))
@click.version_option(version=version)
def cli():
@click.option('-l', '--list', is_flag=True, is_eager=True, expose_value=False, callback=_print_tree,
help='print all the available commands')
def cli(list):
"""
Main entry point for stemia. Several subcommands are available.
Expand Down
1 change: 1 addition & 0 deletions stemia/imod/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""A collection of IMOD-related tools and scripts."""
23 changes: 22 additions & 1 deletion stemia/utils/click.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import pkgutil
import importlib
from pathlib import Path
from rich import print

import click

Expand Down Expand Up @@ -64,6 +65,7 @@ def add_subcommands(cli, base_dir, base_package):
module = importlib.import_module(full_name)
# get the cli if it exists
if hasattr(module, 'cli'):
module.cli.name = name
cli.add_command(module.cli, name=name)
has_subcommands = True
# go deeper if needed
Expand All @@ -74,11 +76,30 @@ def subcli():
subcli = click.group()(subcli)
has_subcommands = add_subcommands(subcli, source / name, full_name)
if has_subcommands:
subcli.name = name
cli.add_command(subcli, name=name)

# add shell scripts
for file in source.glob('*.sh'):
cli.add_command(make_command(file), name=file.stem)
subcli = make_command(file)
subcli.name = file.stem
cli.add_command(subcli, name=file.stem)
has_subcommands = True

return has_subcommands


def print_command_tree(cli, prefix='', last=True):
# top of three, put a dot
if not prefix:
print(f'.[bold]{cli.name}[/]')
subs = getattr(cli, 'commands', {})
for i, sub in enumerate(subs.values()):
last_sub = len(subs) - i == 1
end_prefix = '└──' if last_sub else '├──'
print(
f'[white]{prefix + end_prefix}[/][bold]{sub.name}[/]: '
f'[italic white]{(sub.__doc__ or "-").strip().splitlines()[0]}[/]'
)
sub_prefix = ' ' if last_sub else '│ '
print_command_tree(sub, prefix=prefix + sub_prefix, last=last_sub)

0 comments on commit 9385a10

Please sign in to comment.