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:
bakereads its configuration from thebakeapp dir and theBAKE_*environment variables, the way a standalone binary would, and not from the group’skitchennamespace.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
.exeshims, so a symlink namedbakelands inargv[0]asbake.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:
- 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:
_InjectedCommandSynthetic subcommand listing every name a
MulticallGroupanswers to.Auto-injected into every
MulticallGroup, the wayHelpCommandis injected into everyGroup: 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.
- class click_extra.multicall.MulticallGroup(*args, personalities=None, personalities_command=True, **kwargs)[source]¶
Bases:
GroupA
Groupdispatching 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:
an explicit
prog_namepassed tomain()(whatclick_extra.testing.CliRunneruses to simulate a symlink),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 trailingWINDOWS_EXE_SUFFIXis stripped for Windows console-script shims. Click’s own_detect_program_name()is deliberately not used: it reads__main__.__package__and answerspython -m …in the module case. Seeclick_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, whereargv[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 toNone, every non-hidden, non-synthetic subcommand is its own personality.personalities_command (
bool) – whenTrue(the default), apersonalitiessubcommand is auto-registered on the group, listing every invocation name the binary answers to. Register your ownpersonalitiessubcommand to override it.
- 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.exestripped on Windows.
- list_personalities()[source]¶
Every personality name mapped to the tokens it invokes.
The explicit
personalitiesmapping when one was declared, else every subcommand_is_default_personalityadmits, mapped to itself. The lazy subcommands of a lazy group are imported to be judged, which a listing has to pay for.
- 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:
- 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
paramsattribute is patched after the fact. Two reasons make the re-instantiation mandatory:Cloup computes its help layout (
arguments,option_groups,ungrouped_options) fromparamsinside__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_endreordering, option priorities, auto envvar population and help-keyword collection.
Every parameter is deep-copied, because
Command.__init__re-runspopulate_auto_envvarsover the merged set under the personality’s ownauto_envvar_prefix: sharing instances would rewrite the group’s and subcommand’senvvarattributes and leak that back into group mode. This is the same class of leaky statedefault_params()warns about.- Return type: