gamesheet_sdk.common.cli¶
Shared CLI utilities for GameSheet CLIs.
Functions
|
Add |
|
Parse a comma-separated column specification. |
|
Map a click/Python exit-style exception to its conventional exit code. |
|
Mirror Python's |
Classes
A |
- class gamesheet_sdk.common.cli.ResourceGroup[source]¶
Bases:
RichGroupA
click.RichGroupfor 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")}andlsresolves to the same callback aslistwithout re-binding it. The canonical name is what shows up in tracebacks and--helpoutput; aliases appear in parentheses next to it.- Default sub-command:
Pass
default="list"and a bare invocation of the group implicitly runslist. Explicit sub-command calls still flow through normally.
Initialize a ResourceGroup with alias support and an optional default sub-command.
Constructs a
click.RichGroupand 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 baregamesheet-admin associationsimplicitly runassociations list.aliases (Mapping[str, Iterable[str]] | None) – Mapping of canonical command names to their aliases. For example,
{"list": ("ls",), "delete": ("rm", "remove")}allowslsto resolve tolistand bothrmandremoveto resolve todelete. Aliases appear in parentheses next to the canonical name in--helpoutput 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.RichGroupand 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 baregamesheet-admin associationsimplicitly runassociations list.aliases (Mapping[str, Iterable[str]] | None) – Mapping of canonical command names to their aliases. For example,
{"list": ("ls",), "delete": ("rm", "remove")}allowslsto resolve tolistand bothrmandremoveto resolve todelete. Aliases appear in parentheses next to the canonical name in--helpoutput and are included in tab-completion results.kwargs (Any) – Keyword arguments forwarded to the decorated function.
- get_command(ctx, cmd_name)[source]¶
Resolve
cmd_nameagainst 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
Noneif 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 baregamesheet-admin associations <TAB>would yield the leaf command’s options instead of the group’s verbs.
- 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:
- add_command(cmd, name=None, aliases=None, panel=None)¶
Register another
Commandwith 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_argsflag.
- allow_interspersed_args = False¶
the default for the
Context.allow_interspersed_argsflag.
- collect_usage_pieces(ctx)¶
Returns all the pieces that go into the usage line and returns it as a list of strings.
- 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 callingadd_command().To customize the command class used, set the
command_classattribute.Changed in version 8.1: This decorator can be applied without parentheses.
Changed in version 8.0: Added the
command_classattribute.
- 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:
- get_help_option(ctx)¶
Return the help option object.
Skipped if
add_help_optionisFalse.Changed in version 8.1.8: The help option is now cached to avoid creating it multiple times.
- Return type:
Option | None
- 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:
- get_usage(ctx)¶
Formats the usage line into a string and returns it.
Calls
format_usage()internally.- Return type:
- 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 callingadd_command().To customize the group class used, set the
group_classattribute.Changed in version 8.1: This decorator can be applied without parentheses.
Changed in version 8.0: Added the
group_classattribute.
- ignore_unknown_options = False¶
the default for the
Context.ignore_unknown_optionsflag.
- invoke(ctx)¶
Given a context, this invokes the attached callback (if it exists) in the right way.
- Return type:
- list_commands(ctx)¶
Returns a list of subcommand names in the order they should appear.
- 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,
SystemExitneeds 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
Contextfor more information.
- Return type:
Changed in version 8.0.1: Added the
windows_expand_argsparameter to allow disabling command line arg expansion on Windows.Changed in version 8.0: When taking arguments from
sys.argvon Windows, glob patterns, user dir, and env vars are expanded.Changed in version 3.0: Added the
standalone_modeparameter.
- 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_classattribute.- 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:
Changed in version 8.0: Added the
context_classattribute.
- make_parser(ctx)¶
Creates the underlying option parser for this command.
- Return type:
_OptionParser
- 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.
- 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
Groupthe group will default the command name with this information. You should instead use theContext'sinfo_nameattribute.
- 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¶
- deprecated¶
- gamesheet_sdk.common.cli.confirm_destructive(target='this resource')[source]¶
Add
--force/-fflag and confirmation prompt to destructive commands.Decorated commands gain a
--forceflag. When not set, the user is prompted"Delete {target}? [y/N]". Answering anything other thanyoryesaborts withExit(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
- 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 toresolve_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 = usageerror).
- Return type:
- gamesheet_sdk.common.cli.resolve_system_exit(exc)[source]¶
Mirror Python’s
SystemExitcode-to-int convention.Extracts the exit code from a SystemExit exception following Python’s standard behavior: -
Nonecode → 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: