gamesheet_sdk.common.cli

Shared CLI utilities for GameSheet CLIs.

Functions

columns_option(func)

Add the --columns option that restricts output to a subset of keys.

common_output_options(func)

Add standard --format and --output options to command.

confirm_destructive([target])

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

emit_shell_completion(shell, prog_name, ...)

Emit shell completion script for the specified shell.

get_local_timezone_name()

Get the local system timezone name (IANA format).

get_local_timezone_offset()

Get the local timezone offset in minutes from UTC.

parse_columns_spec(spec)

Parse a comma-separated column specification.

parse_flexible_datetime(raw)

Parse a flexible datetime string into a naive datetime.datetime preserving face values.

render_get_command(data, output_format, ...)

Render get command output (single object as key-value pairs).

render_list_command(items, output_format, ...)

Render list command output (table of objects).

render_penalty_report(report, output_format, ...)

Render penalty report output.

resolve_create_times(start_raw, end_raw, ...)

Resolve start/end for create: exactly 2 of 3 required.

resolve_datetime_input(combined, date_part, ...)

Merge split date+time inputs into one string, or return combined.

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.

resolve_update_times(start_raw, end_raw, ...)

Resolve start/end for update: partial inputs OK.

run_action_or_exit(session, action, *args, ...)

Run an action function with error handling.

validate_end_after_start(start_dt, end_dt)

Raise if end is not strictly after start.

validate_no_input_conflict(combined, ...)

Raise if combined and split inputs are both provided.

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.

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.

Initialize a ResourceGroup instance.

Parameters:
  • *args (Any) – Positional arguments passed to superclass.

  • default (str | None) – Default sub-command name.

  • aliases (Mapping[str, Iterable[str]] | None) – Mapping of command names to aliases.

  • **kwargs (Any) – Keyword arguments passed to superclass.

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

Initialize a ResourceGroup instance.

Parameters:
  • *args (Any) – Positional arguments passed to superclass.

  • default (str | None) – Default sub-command name.

  • aliases (Mapping[str, Iterable[str]] | None) – Mapping of command names to aliases.

  • **kwargs (Any) – Keyword arguments passed to superclass.

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:

Command | None – 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:

list[str] – 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.

Parameters:
  • ctx (Context) – The click context

  • incomplete (str) – The partial command string being completed

Returns:

list[CompletionItem] – List of results.

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.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 list it selects table columns, and on a get / create / update it selects fields of the single rendered object. Both are “show me only these keys”, so there is one name for it, and -f is left to mean --force everywhere.

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/-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:

Callable[[F], F] – A decorator that wraps the command function with confirmation logic.

Return type:

Callable[[F], F]

gamesheet_sdk.common.cli.emit_shell_completion(shell, prog_name, complete_var)[source]

Emit shell completion script for the specified shell.

Parameters:
  • shell (str) – Target shell (bash, zsh, or fish).

  • prog_name (str) – The CLI program name.

  • complete_var (str) – Environment variable name for completion.

Raises:

Exit – If the specified shell is unsupported.

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:

str

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:

int

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:

list[str] | None

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

whitespace.

Return type:

list[str] | 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.parse for 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.

Parameters:

raw (str) – A human-readable datetime string

Returns:

datetime.datetime – A timezone-naive datetime.datetime with the face-value time

Raises:

UsageError – If the string cannot be parsed

Return type:

datetime

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:
  • items (list[Any]) – List of objects to render (dicts or pydantic models)

  • 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_penalty_report(report, output_format, output_path)[source]

Render penalty report output.

Parameters:
  • report (dict[str, Any]) – The penalty report dictionary to render

  • output_format (str) – Output format (json or yaml)

  • output_path (str | None) – Optional file path to write output to

gamesheet_sdk.common.cli.resolve_create_times(start_raw, end_raw, duration)[source]

Resolve start/end for create: exactly 2 of 3 required.

Parameters:
  • start_raw (str | None) – Raw start datetime string, or None

  • end_raw (str | None) – Raw end datetime string, or None

  • duration (int | None) – Duration in minutes, or None

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:

tuple[str, str]

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:
  • combined (str | None) – The --start-datetime or --end-datetime value

  • date_part (str | None) – The --start-date or --end-date value

  • time_part (str | None) – The --start-time or --end-time value

  • label (str) – "start" or "end", for error messages

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 to resolve_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:

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)

Parameters:

exc (BaseException) – A BaseException, typically a SystemExit.

Returns:

int – Integer exit code.

Return type:

int

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:
  • start_raw (str | None) – New start datetime string, or None

  • end_raw (str | None) – New end datetime string, or None

  • duration (int | None) – Duration in minutes, or None

  • current_start (str) – Current game start time (ISO 8601)

  • current_end (str) – Current game end time (ISO 8601)

Returns:

tuple[str, str](start_utc_iso, end_utc_iso) tuple

Return type:

tuple[str, str]

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 AuthenticationError and GameSheetError. 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 session and *args and returns a result. Typically a domain action function (e.g., list_associations).

  • *args (object) – Positional arguments forwarded to action after session.

  • **kwargs (object) – Keyword arguments forwarded to action.

Returns:

_R – The result of action(session, *args, **kwargs) on success.

Raises:

Exit – If action raises AuthenticationError or GameSheetError. 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:
Raises:

UsageError – If end <= start

gamesheet_sdk.common.cli.validate_no_input_conflict(combined, date_part, time_part, label)[source]

Raise if combined and split inputs are both provided.

Parameters:
  • combined (str | None) – The --start-datetime or --end-datetime value

  • date_part (str | None) – The --start-date or --end-date value

  • time_part (str | None) – The --start-time or --end-time value

  • label (str) – "start" or "end", for error messages

Raises:

UsageError – If combined and any split input coexist