gamesheet_sdk.common.cli

Shared CLI utilities for GameSheet CLIs.

Functions

confirm_destructive([target])

Add --force/-f flag and confirmation prompt to destructive commands.

parse_columns_spec(spec)

Parse a comma-separated column specification.

resolve_exit(exc)

Map a click/Python exit-style exception to its conventional exit code.

resolve_system_exit(exc)

Mirror Python's SystemExit code-to-int convention.

Classes

ResourceGroup

A click.RichGroup for resource-oriented sub-command trees.

class gamesheet_sdk.common.cli.ResourceGroup[source]

Bases: RichGroup

A click.RichGroup for resource-oriented sub-command trees.

Adds two pieces of architectural plumbing on top of the stock group:

Aliases:

Pass aliases={"list": ("ls",), "delete": ("rm", "remove")} and ls resolves to the same callback as list without re-binding it. The canonical name is what shows up in tracebacks and --help output; aliases appear in parentheses next to it.

Default sub-command:

Pass default="list" and a bare invocation of the group implicitly runs list. Explicit sub-command calls still flow through normally.

Initialize a ResourceGroup with alias support and an optional default sub-command.

Constructs a click.RichGroup and configures command aliases and a default sub-command behavior. The alias mapping is flattened at construction time from {canonical: (alias1, alias2, ...)} into {alias1: canonical, alias2: canonical, ...} for O(1) lookup during command resolution.

Parameters:
  • args (Any) – Positional arguments forwarded to the decorated function.

  • default (str | None) – Name of the sub-command to invoke when the group is called with no arguments. For example, default="list" makes a bare gamesheet-admin associations implicitly run associations list.

  • aliases (Mapping[str, Iterable[str]] | None) – Mapping of canonical command names to their aliases. For example, {"list": ("ls",), "delete": ("rm", "remove")} allows ls to resolve to list and both rm and remove to resolve to delete. Aliases appear in parentheses next to the canonical name in --help output and are included in tab-completion results.

  • kwargs (Any) – Keyword arguments forwarded to the decorated function.

__init__(*args, default=None, aliases=None, **kwargs)[source]

Initialize a ResourceGroup with alias support and an optional default sub-command.

Constructs a click.RichGroup and configures command aliases and a default sub-command behavior. The alias mapping is flattened at construction time from {canonical: (alias1, alias2, ...)} into {alias1: canonical, alias2: canonical, ...} for O(1) lookup during command resolution.

Parameters:
  • args (Any) – Positional arguments forwarded to the decorated function.

  • default (str | None) – Name of the sub-command to invoke when the group is called with no arguments. For example, default="list" makes a bare gamesheet-admin associations implicitly run associations list.

  • aliases (Mapping[str, Iterable[str]] | None) – Mapping of canonical command names to their aliases. For example, {"list": ("ls",), "delete": ("rm", "remove")} allows ls to resolve to list and both rm and remove to resolve to delete. Aliases appear in parentheses next to the canonical name in --help output and are included in tab-completion results.

  • kwargs (Any) – Keyword arguments forwarded to the decorated function.

get_command(ctx, cmd_name)[source]

Resolve cmd_name against the canonical commands.

Falls back to aliases if no canonical match is found.

Parameters:
  • ctx (Context) – The click context.

  • cmd_name (str) – The command name to resolve.

Returns:

The resolved Command object, or None if not found.

Return type:

Command | None

parse_args(ctx, args)[source]

Inject the default sub-command when invoked bare, then delegate to click.

When the group is invoked with no further args, inject the configured default sub-command so the rest of click’s parsing machinery treats it exactly like an explicit call. Skip the injection when click is parsing for shell completion (resilient_parsing=True). Otherwise click’s completion walker would silently descend into the default sub-command, and a bare gamesheet-admin associations <TAB> would yield the leaf command’s options instead of the group’s verbs.

Parameters:
  • ctx (Context) – The click context.

  • args (list[str]) – The command-line arguments to parse.

Returns:

Parsed argument list.

Return type:

list[str]

format_commands(ctx, formatter)[source]

Render the command list with aliases in parentheses.

Parameters:
  • ctx (Context) – The click context

  • formatter (HelpFormatter) – The help formatter to write to

shell_complete(ctx, incomplete)[source]

Tab-completion candidates for this group.

Augments click’s stock list (canonical sub-commands, plus options inherited from parent groups via the chained-completion walk) with any registered aliases whose underlying command is visible. Hidden commands and aliases pointing at hidden commands are skipped, matching click’s default visibility rules. :param ctx: The click context :type ctx: Context :param incomplete: The partial command string being completed :type incomplete: str :returns: List of results. :rtype: list[CompletionItem]

Return type:

list[CompletionItem]

add_command(cmd, name=None, aliases=None, panel=None)

Register another Command with this group. If the name is not provided, the name of the command is used.

add_command_to_panel(command, panel_name)
add_panel(panel)

Add a RichPanel to the RichCommand.

allow_extra_args = True

the default for the Context.allow_extra_args flag.

allow_interspersed_args = False

the default for the Context.allow_interspersed_args flag.

collect_usage_pieces(ctx)

Returns all the pieces that go into the usage line and returns it as a list of strings.

Return type:

list[str]

command(*args, **kwargs)

A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as command() and immediately registers the created command with this group by calling add_command().

To customize the command class used, set the command_class attribute.

Changed in version 8.1: This decorator can be applied without parentheses.

Changed in version 8.0: Added the command_class attribute.

Return type:

Callable[[Callable[[…], Any]], RichCommand] | RichCommand

command_class

alias of RichCommand

property console: 'Console' | None

Rich Console.

This is a separate instance from the help formatter that allows full control of the console configuration.

See rich_config decorator for how to apply the settings.

context_class

alias of RichContext

format_epilog(ctx, formatter)

Writes the epilog into the formatter if it exists.

format_help(ctx, formatter)

Writes the help into the formatter if it exists.

This is a low-level method called by get_help().

This calls the following methods:

format_help_text(ctx, formatter)

Writes the help text to the formatter if it exists.

format_options(ctx, formatter)

Writes all the options into the formatter if they exist.

format_usage(ctx, formatter)

Writes the usage line into the formatter.

This is a low-level method called by get_usage().

get_help(ctx)

Formats the help into a string and returns it.

Calls format_help() internally.

Return type:

str

get_help_option(ctx)

Return the help option object.

Skipped if add_help_option is False.

Changed in version 8.1.8: The help option is now cached to avoid creating it multiple times.

Return type:

Option | None

get_help_option_names(ctx)

Returns the names for the help option.

Return type:

list[str]

get_params(ctx)
Return type:

list[Parameter]

get_rich_table_row(ctx, formatter, panel=None)

Create a row for the rich table corresponding with this parameter.

Return type:

RichPanelRow

get_short_help_str(limit=45)

Gets short help for the command or makes it by shortening the long help string.

Return type:

str

get_usage(ctx)

Formats the usage line into a string and returns it.

Calls format_usage() internally.

Return type:

str

group(*args, **kwargs)

A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as group() and immediately registers the created group with this group by calling add_command().

To customize the group class used, set the group_class attribute.

Changed in version 8.1: This decorator can be applied without parentheses.

Changed in version 8.0: Added the group_class attribute.

Return type:

Callable[[Callable[[…], Any]], RichGroup] | RichGroup

group_class

alias of type

property help_config: RichHelpConfiguration | None

Rich Help Configuration.

ignore_unknown_options = False

the default for the Context.ignore_unknown_options flag.

invoke(ctx)

Given a context, this invokes the attached callback (if it exists) in the right way.

Return type:

Any

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

Return type:

list[str]

main(args=None, prog_name=None, complete_var=None, standalone_mode=True, windows_expand_args=True, **extra)

This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.

This method is also available by directly calling the instance of a Command.

Parameters:
  • args (Sequence[str] | None) – the arguments that should be used for parsing. If not provided, sys.argv[1:] is used.

  • prog_name (str | None) – the program name that should be used. By default the program name is constructed by taking the file name from sys.argv[0].

  • complete_var (str | None) – the environment variable that controls the bash completion support. The default is "_<prog_name>_COMPLETE" with prog_name in uppercase.

  • standalone_mode (bool) – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of invoke().

  • windows_expand_args (bool) – Expand glob patterns, user dir, and env vars in command line args on Windows.

  • extra (Any) – extra keyword arguments are forwarded to the context constructor. See Context for more information.

Return type:

Any

Changed in version 8.0.1: Added the windows_expand_args parameter to allow disabling command line arg expansion on Windows.

Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded.

Changed in version 3.0: Added the standalone_mode parameter.

make_context(info_name, args, parent=None, **extra)

This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.

To quickly customize the context class used without overriding this method, set the context_class attribute.

Parameters:
  • info_name (str | None) – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.

  • args (list[str]) – the arguments to parse as list of strings.

  • parent (Context | None) – the parent context if available.

  • extra (Any) – extra keyword arguments forwarded to the context constructor.

Return type:

Context

Changed in version 8.0: Added the context_class attribute.

make_parser(ctx)

Creates the underlying option parser for this command.

Return type:

_OptionParser

resolve_command(ctx, args)
Return type:

tuple[str | None, Command | None, list[str]]

result_callback(replace=False)

Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.

Example:

@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
    return 42

@cli.result_callback()
def process_result(result, input):
    return result + input
Parameters:

replace (bool) – if set to True an already existing result callback will be removed.

Return type:

Callable[[F], F]

Changed in version 8.0: Renamed from resultcallback.

Added in version 3.0.

to_info_dict(ctx)
Return type:

Dict[str, Any]

commands

The registered subcommands by their exported names.

invoke_without_command
subcommand_metavar
chain
name

the name the command thinks it has. Upon registering a command on a Group the group will default the command name with this information. You should instead use the Context's info_name attribute.

context_settings

an optional dictionary with defaults passed to the context.

callback

the callback to execute when the command fires. This might be None in which case nothing happens.

params

the list of parameters for this command in the order they should show up in the help page and execute. Eager parameters will automatically be handled before non eager ones.

help
epilog
options_metavar
short_help
add_help_option
no_args_is_help
hidden
deprecated
gamesheet_sdk.common.cli.confirm_destructive(target='this resource')[source]

Add --force/-f flag and confirmation prompt to destructive commands.

Decorated commands gain a --force flag. When not set, the user is prompted "Delete {target}? [y/N]". Answering anything other than y or yes aborts with Exit(1). Example:

@cli.command("delete")
@click.argument("resource_id")
@confirm_destructive("this association")
def delete_association(resource_id: str):
    # Deletion logic here
    pass
Parameters:

target (str) – The resource name shown in the prompt (e.g., "this association").

Returns:

A decorator that wraps the command function with confirmation logic.

Return type:

Callable[[F], F]

gamesheet_sdk.common.cli.parse_columns_spec(spec)[source]

Parse a comma-separated column specification.

Whitespace around column names is stripped. Empty strings and whitespace-only columns are filtered out. Example:

>>> parse_columns_spec("id, name, created_at")
['id', 'name', 'created_at']
>>> parse_columns_spec(None)
None
>>> parse_columns_spec("  ")
None
Parameters:

spec (str | None) – A comma-separated string of column names (e.g., "id,title,created_at") or None.

Returns:

A list of column names, or None if spec is None or contains only whitespace.

Return type:

list[str] | None

gamesheet_sdk.common.cli.resolve_exit(exc)[source]

Map a click/Python exit-style exception to its conventional exit code.

Handles click-specific exceptions and delegates to resolve_system_exit() for standard Python exits: - Exit → the exception’s exit_code - UsageError → 2 (after showing the error) - Abort → 1 (after printing “Aborted.”) - Other exceptions → delegated to resolve_system_exit() :param exc: The exception to resolve. :type exc: BaseException :returns: An integer exit code following Unix conventions (0 = success, 1 = general error, 2 = usage

error).

Return type:

int

gamesheet_sdk.common.cli.resolve_system_exit(exc)[source]

Mirror Python’s SystemExit code-to-int convention.

Extracts the exit code from a SystemExit exception following Python’s standard behavior: - None code → 0 (success) - Integer code → the integer itself - Any other code → 1 (failure) :param exc: A BaseException, typically a SystemExit. :type exc: BaseException :returns: Integer exit code. :rtype: int

Return type:

int