콘텐츠로 이동

spakky-typer

Typer CLI 통합 — CLI 컨트롤러 자동 등록

Main

spakky.plugins.typer.main

Plugin initialization for Typer CLI integration.

Registers post-processor for automatic CLI command registration from @CliController decorated classes.

initialize(app)

Initialize the Typer CLI plugin.

Registers the post-processor for automatic CLI command registration. This function is called automatically by the Spakky framework during plugin loading.

Parameters:

Name Type Description Default
app SpakkyApplication

The Spakky application instance.

required
Source code in plugins/spakky-typer/src/spakky/plugins/typer/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize the Typer CLI plugin.

    Registers the post-processor for automatic CLI command registration.
    This function is called automatically by the Spakky framework during
    plugin loading.

    Args:
        app: The Spakky application instance.
    """
    app.add(TyperCLIPostProcessor)

options: show_root_heading: false

Stereotypes

spakky.plugins.typer.stereotypes.cli_controller

CLI controller stereotype for Typer command grouping.

Provides the @CliController stereotype for marking classes as CLI controllers with automatic command registration and the @command decorator for methods.

TyperCommand(name=None, cls=None, context_settings=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False, rich_help_panel=Default(None)) dataclass

Bases: FunctionAnnotation

Function annotation for marking methods as Typer CLI commands.

Stores all Typer command configuration including name, help text, and command options.

Attributes:

Name Type Description
name str | None

Command name (defaults to method name in kebab-case).

cls type[TyperCommand] | None

Custom Typer command class.

context_settings dict[Any, Any] | None

Click context settings.

help str | None

Command help text.

epilog str | None

Text displayed after command help.

short_help str | None

Short help text for command list.

options_metavar str

Metavar for options display.

add_help_option bool

Whether to add --help option.

no_args_is_help bool

Show help when no args provided.

hidden bool

Hide command from help output.

deprecated bool

Mark command as deprecated.

rich_help_panel str | None

Rich console help panel name.

CliController(group_name=None, *, name='', scope=Scope.SINGLETON) dataclass

Bases: Pod

Stereotype for Typer CLI controllers.

Marks a class as a CLI controller with automatic command registration. Methods decorated with @command will be registered as CLI commands under the specified group name.

Attributes:

Name Type Description
group_name str | None

CLI command group name (defaults to class name in kebab-case).

group_name = None class-attribute instance-attribute

CLI command group name for organizing related commands.

__call__(obj)

Apply the CLI controller stereotype to a class.

Automatically generates the group name from the class name if not provided.

Parameters:

Name Type Description Default
obj AnyT

The class to decorate.

required

Returns:

Type Description
AnyT

The decorated class registered as a Pod.

Source code in plugins/spakky-typer/src/spakky/plugins/typer/stereotypes/cli_controller.py
def __call__(self, obj: AnyT) -> AnyT:
    """Apply the CLI controller stereotype to a class.

    Automatically generates the group name from the class name if not provided.

    Args:
        obj: The class to decorate.

    Returns:
        The decorated class registered as a Pod.
    """
    if self.group_name is None:
        self.group_name = pascal_to_kebab(
            obj.__name__  # type: ignore
        )
    return super().__call__(obj)

command(name=None, cls=None, context_settings=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False, rich_help_panel=Default(None))

Decorator to mark a controller method as a CLI command.

Attaches Typer command configuration to the method which will be registered by the TyperCLIPostProcessor during container initialization.

Parameters:

Name Type Description Default
name str | None

Command name (defaults to method name in kebab-case).

None
cls type[TyperCommand] | None

Custom Typer command class.

None
context_settings dict[Any, Any] | None

Click context settings.

None
help str | None

Command help text.

None
epilog str | None

Text displayed after command help.

None
short_help str | None

Short help text for command list.

None
options_metavar str

Metavar for options display.

'[OPTIONS]'
add_help_option bool

Whether to add --help option.

True
no_args_is_help bool

Show help when no args provided.

False
hidden bool

Hide command from help output.

False
deprecated bool

Mark command as deprecated.

False
rich_help_panel str | None

Rich console help panel name.

Default(None)

Returns:

Type Description
Callable[[Callable[..., AnyT]], Callable[..., AnyT]]

A decorator function that attaches the command configuration.

Source code in plugins/spakky-typer/src/spakky/plugins/typer/stereotypes/cli_controller.py
def command(
    name: str | None = None,
    cls: type[TyperCommandClass] | None = None,
    context_settings: dict[Any, Any] | None = None,
    help: str | None = None,
    epilog: str | None = None,
    short_help: str | None = None,
    options_metavar: str = "[OPTIONS]",
    add_help_option: bool = True,
    no_args_is_help: bool = False,
    hidden: bool = False,
    deprecated: bool = False,
    rich_help_panel: str | None = Default(None),
) -> Callable[[Callable[..., AnyT]], Callable[..., AnyT]]:
    """Decorator to mark a controller method as a CLI command.

    Attaches Typer command configuration to the method which will be registered
    by the TyperCLIPostProcessor during container initialization.

    Args:
        name: Command name (defaults to method name in kebab-case).
        cls: Custom Typer command class.
        context_settings: Click context settings.
        help: Command help text.
        epilog: Text displayed after command help.
        short_help: Short help text for command list.
        options_metavar: Metavar for options display.
        add_help_option: Whether to add --help option.
        no_args_is_help: Show help when no args provided.
        hidden: Hide command from help output.
        deprecated: Mark command as deprecated.
        rich_help_panel: Rich console help panel name.

    Returns:
        A decorator function that attaches the command configuration.
    """

    def wrapper(method: Callable[..., AnyT]) -> Callable[..., AnyT]:
        return TyperCommand(
            name=name,
            cls=cls,
            context_settings=context_settings,
            help=help,
            epilog=epilog,
            short_help=short_help,
            options_metavar=options_metavar,
            add_help_option=add_help_option,
            no_args_is_help=no_args_is_help,
            hidden=hidden,
            deprecated=deprecated,
            rich_help_panel=rich_help_panel,
        )(method)

    return wrapper

options: show_root_heading: false

Post Processor

spakky.plugins.typer.post_processor

Post-processor for registering Typer CLI commands.

Automatically discovers and registers CLI commands from @CliController decorated classes, with support for both sync and async command handlers.

TyperCLIPostProcessor(app)

Bases: IPostProcessor, IContainerAware, IApplicationContextAware

Post-processor that registers CLI commands from CLI controllers.

Scans @CliController decorated classes for @command decorated methods and automatically registers them as Typer commands with proper dependency injection and async support.

Initialize the Typer CLI post-processor.

Parameters:

Name Type Description Default
app Typer

The Typer application instance.

required
Source code in plugins/spakky-typer/src/spakky/plugins/typer/post_processor.py
def __init__(self, app: Typer) -> None:
    """Initialize the Typer CLI post-processor.

    Args:
        app: The Typer application instance.
    """
    super().__init__()
    self.__app = app

set_container(container)

Set the container for dependency injection.

Parameters:

Name Type Description Default
container IContainer

The IoC container.

required
Source code in plugins/spakky-typer/src/spakky/plugins/typer/post_processor.py
def set_container(self, container: IContainer) -> None:
    """Set the container for dependency injection.

    Args:
        container: The IoC container.
    """
    self.__container = container

set_application_context(application_context)

Set the application context.

Parameters:

Name Type Description Default
application_context IApplicationContext

The application context instance.

required
Source code in plugins/spakky-typer/src/spakky/plugins/typer/post_processor.py
def set_application_context(self, application_context: IApplicationContext) -> None:
    """Set the application context.

    Args:
        application_context: The application context instance.
    """
    self.__application_context = application_context

post_process(pod)

Register commands from CLI controllers.

Scans the controller for methods decorated with @command and registers them as Typer commands. Automatically wraps async methods with run_async.

Parameters:

Name Type Description Default
pod object

The Pod to process, potentially a CLI controller.

required

Returns:

Type Description
object

The Pod, with commands registered if it's a CLI controller.

Source code in plugins/spakky-typer/src/spakky/plugins/typer/post_processor.py
def post_process(self, pod: object) -> object:
    """Register commands from CLI controllers.

    Scans the controller for methods decorated with @command and registers
    them as Typer commands. Automatically wraps async methods with run_async.

    Args:
        pod: The Pod to process, potentially a CLI controller.

    Returns:
        The Pod, with commands registered if it's a CLI controller.
    """
    if not CliController.exists(pod):
        return pod
    controller = CliController.get(pod)
    command_group: Typer = Typer(name=controller.group_name)
    for name, method in getmembers(pod, callable):
        command: TyperCommand | None = TyperCommand.get_or_none(method)
        if command is not None:
            # pylint: disable=line-too-long
            logger.info(
                f"[{type(self).__name__}] {command.name!r} -> {'async' if iscoroutinefunction(method) else ''} {method.__qualname__}"
            )

            @wraps(method)
            def endpoint(
                *args: Any,
                method_name: str = name,
                controller_type: type[object] = controller.type_,
                container: IContainer = self.__container,
                **kwargs: Any,
            ) -> Any:
                # CLI invocations often share the same interpreter session,
                # so purge any context-scoped Pods to avoid cross-command leaks.
                self.__application_context.clear_context()
                controller_instance = container.get(controller_type)
                method_to_call = getattr(controller_instance, method_name)
                if iscoroutinefunction(method_to_call):
                    method_to_call = run_async(method_to_call)
                return method_to_call(*args, **kwargs)

            command_group.command(
                name=command.name,
                cls=command.cls,
                context_settings=command.context_settings,
                help=command.help,
                epilog=command.epilog,
                short_help=command.short_help,
                options_metavar=command.options_metavar,
                add_help_option=command.add_help_option,
                no_args_is_help=command.no_args_is_help,
                hidden=command.hidden,
                deprecated=command.deprecated,
                rich_help_panel=command.rich_help_panel,
            )(endpoint)
    self.__app.add_typer(command_group)
    return pod

options: show_root_heading: false

Utilities

spakky.plugins.typer.utils.asyncio

Asyncio utilities for Typer CLI integration.

Provides utilities for running async functions in synchronous contexts, enabling async command handlers in Typer CLI applications.

run_async(func)

Convert an async function to a synchronous function.

Wraps an async function so it can be called synchronously by running it in an asyncio event loop. Useful for CLI commands that need to perform async operations.

Parameters:

Name Type Description Default
func Callable[P, Awaitable[R]]

The async function to wrap.

required

Returns:

Type Description
Callable[P, R]

A synchronous wrapper function that runs the async function.

Source code in plugins/spakky-typer/src/spakky/plugins/typer/utils/asyncio.py
def run_async(func: Callable[P, Awaitable[R]]) -> Callable[P, R]:
    """Convert an async function to a synchronous function.

    Wraps an async function so it can be called synchronously by running
    it in an asyncio event loop. Useful for CLI commands that need to
    perform async operations.

    Args:
        func: The async function to wrap.

    Returns:
        A synchronous wrapper function that runs the async function.
    """

    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        async def coroutine_wrapper() -> R:
            return await func(*args, **kwargs)

        return asyncio.run(coroutine_wrapper())

    return wrapper

options: show_root_heading: false

spakky.plugins.typer.utils.casing

String casing conversion utilities.

Provides utilities for converting between different string casing formats commonly used in CLI applications.

pascal_to_kebab(pascal_case)

Convert PascalCase string to kebab-case.

Parameters:

Name Type Description Default
pascal_case str

A string in PascalCase format.

required

Returns:

Type Description
str

The string converted to kebab-case format.

Example

pascal_to_kebab("UserController") 'user-controller'

Source code in plugins/spakky-typer/src/spakky/plugins/typer/utils/casing.py
def pascal_to_kebab(pascal_case: str) -> str:
    """Convert PascalCase string to kebab-case.

    Args:
        pascal_case: A string in PascalCase format.

    Returns:
        The string converted to kebab-case format.

    Example:
        >>> pascal_to_kebab("UserController")
        'user-controller'
    """
    return PATTERN.sub("-", pascal_case).lower()

options: show_root_heading: false