click_extra.multicall module¶

Multicall / argv[0] dispatch: one binary answering to many names.

A multicall binary is a single executable whose behavior is selected by the name it is invoked with: bzip2, bunzip2 and bzcat are the same file, vim and view differ by default options, and BusyBox multiplexes hundreds of applets behind symlinks pointing at one binary. MulticallGroup brings the pattern to Click Extra: a group that, when invoked under the name of one of its subcommands, skips the group and behaves exactly like that subcommand as a standalone binary.

Declare one with multicall_group():

from click_extra import argument, echo, multicall_group, option


@multicall_group()
def kitchen():
    '''A multicall kitchen appliance.'''


@kitchen.command()
@option("--temperature", default="180")
@argument("dishes", nargs=-1)
def bake(temperature, dishes):
    '''Bake dishes in the oven.'''


@kitchen.command()
@option("--hours", default="2")
@argument("bottles", nargs=-1)
def chill(hours, bottles):
    '''Chill bottles in the fridge.'''

Invoked as kitchen, the CLI is a regular group. Invoked through a symlink named bake (or any other subcommand name), it is the bake command: one flat argument parse, its own usage line and help screen, and the full set of Click Extra options merged in:

$ kitchen bake --temperature 200 pie       # regular group dispatch
$ ln -s $(which kitchen) bake
$ bake --temperature 200 pie               # same thing, no subcommand

A personality maps to a sequence of tokens, not just a subcommand, so a name can also pre-fill options (bzcat is bzip2 --decompress --stdout):

@multicall_group(personalities={"chill-fast": ("chill", "--hours", "1")})
def kitchen():
    ...

Note

Behavioral notes for personality mode:

  • The group’s own callback does not run: the personality is a standalone command with no parent context.

  • Configuration and environment variable namespaces follow the personality name: bake reads its configuration from the bake app dir and the BAKE_* environment variables, the way a standalone binary would, and not from the group’s kitchen namespace.

  • The invocation name a command was started under is also exposed on its own, for custom dispatch logic: see click_extra.context.INVOCATION_NAME.

click_extra.multicall.WINDOWS_EXE_SUFFIX = '.exe'¶

Suffix of Windows console-script wrappers, stripped from argv[0].

On Windows, entry points are materialized as .exe shims, so a symlink named bake lands in argv[0] as bake.exe.

click_extra.multicall.normalize_personality(tokens)[source]¶

Normalize a personality mapping value into a tuple of CLI tokens.

Accepts a bare subcommand name ("chill") or a token sequence (("chill", "--hours", "1")). The first token names the subcommand the personality dispatches to; the rest is prepended to the user’s arguments.

Raises:
  • TypeError – when the value is neither a string nor a sequence.

  • ValueError – on an empty sequence or a non-string token.

Return type:

tuple[str, ...]

class click_extra.multicall.PersonalitiesCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]¶

Bases: _InjectedCommand

Synthetic subcommand listing every name a MulticallGroup answers to.

Auto-injected into every MulticallGroup, the way HelpCommand is injected into every Group: the group mode needs a place to enumerate the symlink names, and a subcommand costs no new top-level option on the group’s help screen.

invoke(ctx)[source]¶

List each personality next to the command line it invokes.

Return type:

None

class click_extra.multicall.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶

Bases: Group

A Group dispatching on its invocation name, BusyBox-style.

When the name the binary was invoked under matches a personality, the group steps aside entirely and runs the matching subcommand as a standalone command: the personality carries the group’s options merged into the subcommand’s, parses them in one flat pass with no positional ordering constraint, and renders its own usage line and help screen. Any other invocation name falls through to regular group behavior.

The invocation name is, in precedence order:

  1. an explicit prog_name passed to main() (what click_extra.testing.CliRunner uses to simulate a symlink),

  2. else the unresolved basename of sys.argv[0].

The basename is used unresolved: resolving through os.path.realpath() would return the symlink’s target and destroy the personality. A trailing WINDOWS_EXE_SUFFIX is stripped for Windows console-script shims. Click’s own _detect_program_name() is deliberately not used: it reads __main__.__package__ and answers python -m … in the module case. See click_extra.cli_wrapper.invoke_target() for the full trap. A name matching no personality is not an error: it falls through, which is also what keeps the feature inert under test runners, where argv[0] is the runner’s own binary.

Like Group.__init__, but with multicall dispatch.

Parameters:
  • personalities (Mapping[str, str | Sequence[str]] | None) – maps an invocation name to the tokens it invokes: a bare subcommand name ("chill") or a token sequence (("chill", "--hours", "1")) whose extra tokens are prepended to the user’s arguments. Left to None, every non-hidden, non-synthetic subcommand is its own personality.

  • personalities_command (bool) – when True (the default), a personalities subcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your own personalities subcommand to override it.

personalities: dict[str, tuple[str, ...]]¶
resolve_invocation_name(prog_name=None)[source]¶

The name this binary was invoked under.

An explicit prog_name wins: it is what makes the feature testable without symlinks on disk. Otherwise the unresolved basename of sys.argv[0] is used, with a trailing .exe stripped on Windows.

Return type:

str | None

list_personalities()[source]¶

Every personality name mapped to the tokens it invokes.

The explicit personalities mapping when one was declared, else every subcommand _is_default_personality admits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.

Return type:

dict[str, tuple[str, ...]]

match_personality(name)[source]¶

Tokens to invoke when called under name, or None to fall through.

Return type:

tuple[str, ...] | None

main(args=None, prog_name=None, **kwargs)[source]¶

Dispatch on the invocation name before any argument parsing.

A matching personality runs as a standalone command, the group’s own options merged into it, its extra tokens prepended to the arguments. Anything else delegates to the regular group main().

Return type:

Any

build_personality(name, tokens)[source]¶

Synthesize the standalone command the name personality runs as.

The personality is a fresh instance of the subcommand’s own class, re-instantiated over the group’s parameters merged with the subcommand’s, not a copy whose params attribute is patched after the fact. Two reasons make the re-instantiation mandatory:

  • Cloup computes its help layout (arguments, option_groups, ungrouped_options) from params inside __init__, so a patched copy parses every merged option but only renders the subcommand’s own on its help screen.

  • Click Extra’s own Command.__init__ does work that must run over the merged set: extra_option_at_end reordering, option priorities, auto envvar population and help-keyword collection.

Every parameter is deep-copied, because Command.__init__ re-runs populate_auto_envvars over the merged set under the personality’s own auto_envvar_prefix: sharing instances would rewrite the group’s and subcommand’s envvar attributes and leak that back into group mode. This is the same class of leaky state default_params() warns about.

Return type:

Command