gamesheet_sdk.common.cli¶
Shared CLI utilities for GameSheet CLIs.
Functions
|
Add the --columns option that restricts output to a subset of keys. |
|
Add standard --format and --output options to command. |
|
Add |
|
Emit shell completion script for the specified shell. |
Get the local system timezone name (IANA format). |
|
Get the local timezone offset in minutes from UTC. |
|
|
Parse a comma-separated column specification. |
Parse a flexible datetime string into a naive datetime.datetime preserving face values. |
|
|
Render get command output (single object as key-value pairs). |
|
Render list command output (table of objects). |
|
Render penalty report output. |
|
Resolve start/end for create: exactly 2 of 3 required. |
|
Merge split date+time inputs into one string, or return combined. |
|
Map a click/Python exit-style exception to its conventional exit code. |
|
Mirror Python's |
|
Resolve start/end for update: partial inputs OK. |
|
Run an action function with error handling. |
|
Raise if end is not strictly after start. |
|
Raise if combined and split inputs are both provided. |
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.
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.
Initialize a ResourceGroup instance.
- Parameters:
- get_command(ctx, cmd_name)[source]¶
Resolve
cmd_nameagainst the canonical commands.Falls back to aliases if no canonical match is found.
- 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.
- Parameters:
ctx (Context) – The click context
incomplete (str) – The partial command string being completed
- Returns:
list[CompletionItem] – List of results.
- 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.columns_option(func)[source]¶
Add the –columns option that restricts output to a subset of keys.
One option covers both shapes of output: on a
listit selects table columns, and on aget/create/updateit selects fields of the single rendered object. Both are “show me only these keys”, so there is one name for it, and-fis left to mean--forceeverywhere.- Parameters:
func (F) – The Click command function to decorate.
- Returns:
F – The decorated function with the –columns option.
- Return type:
F
- gamesheet_sdk.common.cli.common_output_options(func)[source]¶
Add standard –format and –output options to command.
- Parameters:
func (F) – The Click command function to decorate
- Returns:
F – The decorated function with –format and –output options
- Return type:
F
- 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
- gamesheet_sdk.common.cli.emit_shell_completion(shell, prog_name, complete_var)[source]¶
Emit shell completion script for the specified shell.
- gamesheet_sdk.common.cli.get_local_timezone_name()[source]¶
Get the local system timezone name (IANA format).
Returns the timezone name like ‘America/New_York’, ‘UTC’, etc. Falls back to ‘UTC’ if unable to determine.
- Returns:
str – IANA timezone name
- Return type:
- gamesheet_sdk.common.cli.get_local_timezone_offset()[source]¶
Get the local timezone offset in minutes from UTC.
Returns the offset as a signed integer (negative for west of UTC, positive for east). For example, EDT (UTC-4) returns -240.
- Returns:
int – Timezone offset in minutes
- Return type:
- 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.parse_flexible_datetime(raw)[source]¶
Parse a flexible datetime string into a naive datetime.datetime preserving face values.
Uses
dateutil.parser.parsefor flexible input. Any timezone information is stripped — the returned datetime.datetime contains the literal hour/minute/second the user typed. This matches GameSheet’s API behavior, which stores and displays time values as-is without timezone conversion.
- gamesheet_sdk.common.cli.render_get_command(data, output_format, output_path, columns_spec=None)[source]¶
Render get command output (single object as key-value pairs).
- Parameters:
data (dict[str, Any] | BaseModel) – The object to render (dict or pydantic model)
output_format (str) – Output format (json, yaml, csv, tsv, or tabulate format)
output_path (str | None) – Optional file path to write output to
columns_spec (str | None) – Optional comma-separated column names to include
- gamesheet_sdk.common.cli.render_list_command(items, output_format, output_path, columns_spec=None)[source]¶
Render list command output (table of objects).
- Parameters:
- gamesheet_sdk.common.cli.render_penalty_report(report, output_format, output_path)[source]¶
Render penalty report output.
- gamesheet_sdk.common.cli.resolve_create_times(start_raw, end_raw, duration)[source]¶
Resolve start/end for create: exactly 2 of 3 required.
- Parameters:
- Returns:
tuple[str, str] –
(start_utc_iso, end_utc_iso)tuple- Raises:
UsageError – If fewer than 2 of 3 are provided, or if all 3 are inconsistent, or end <= start
- Return type:
- gamesheet_sdk.common.cli.resolve_datetime_input(combined, date_part, time_part, label)[source]¶
Merge split date+time inputs into one string, or return combined.
- Parameters:
- Returns:
str | None – A merged datetime string or None
- Raises:
UsageError – If only one of date/time is provided
- Return type:
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 toresolve_system_exit()- Parameters:
exc (BaseException) – The exception to resolve.
- Returns:
int –
- An integer exit code following Unix conventions (0 = success, 1 = general error, 2 = usage
error).
- 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)- Parameters:
exc (BaseException) – A BaseException, typically a SystemExit.
- Returns:
int – Integer exit code.
- Return type:
- gamesheet_sdk.common.cli.resolve_update_times(start_raw, end_raw, duration, current_start, current_end)[source]¶
Resolve start/end for update: partial inputs OK.
Uses current game values as fallback when the user provides fewer than 2 inputs.
- Parameters:
- Returns:
tuple[str, str] –
(start_utc_iso, end_utc_iso)tuple- Return type:
- gamesheet_sdk.common.cli.run_action_or_exit(session, action, *args, **kwargs)[source]¶
Run an action function with error handling.
Wraps the action call in the session’s context manager and catches
AuthenticationErrorandGameSheetError. On either exception, prints a user-friendly error message to stderr and exits with code 1. The session context manager ensures proper cleanup (e.g., closing connections) regardless of success or failure.- Parameters:
session (BaseAuthenticatedSession) – The authenticated session to use as a context manager.
action (Callable[..., _R]) – A callable that takes
sessionand*argsand returns a result. Typically a domain action function (e.g.,list_associations).*args (object) – Positional arguments forwarded to
actionaftersession.**kwargs (object) – Keyword arguments forwarded to
action.
- Returns:
_R – The result of
action(session, *args, **kwargs)on success.- Raises:
Exit – If
actionraisesAuthenticationErrororGameSheetError. Exit code is 1 in both cases.- Return type:
_R
- gamesheet_sdk.common.cli.validate_end_after_start(start_dt, end_dt)[source]¶
Raise if end is not strictly after start.
- Parameters:
start_dt (datetime.datetime) – Start datetime.datetime (UTC)
end_dt (datetime.datetime) – End datetime.datetime (UTC)
- Raises:
UsageError – If end <= start