click_extra.carapace module¶
classDiagram
ShellComplete <|-- CarapaceComplete
Export a Click command tree as a Carapace completion spec.
Carapace is a multi-shell completion engine: a single spec file drives identical completions across Bash, Zsh, Fish, Nushell, PowerShell, Elvish, Xonsh, Oil and more. This module walks a Click/Cloup command tree and serializes it to the YAML carapace-spec format, answering the request for native Carapace support in pallets/click#3188 (closed as out of scope for core Click, redirected here).
Two completion strategies cooperate:
Static. Choices, file/directory operands and the command hierarchy are inlined straight into the spec. These complete with no process launch and work in every shell Carapace supports, which is the advantage a spec has over Carapace’s existing bridge to a single shell’s native Click completion.
Dynamic. A parameter carrying a custom
shell_complete(a callback, or aParamTypethat overridesshell_complete()) cannot be frozen into the spec, so its action calls back into the CLI through Carapace’s shell macro. The callback reuses Click’s own completion machinery viaCarapaceComplete.
Note
Dynamic completion needs the CarapaceComplete class registered in
the target process, which happens on import click_extra. A CLI built with
Click Extra gets it for free; a plain Click CLI would have to import
click_extra for the dynamic callback to resolve. Static completion has no
such requirement.
The dataclasses below mirror the upstream carapace-spec JSON schema; the
flag-key grammar and macro contract are taken from that project’s flag.go and
core.go.
Todo
Mark a required flag group once
carapace-sh/carapace-spec#437 ships a Command key for cobra’s
MarkFlagsOneRequired. It closes two gaps at once: a required boolean pair
(--foo / --no-foo) reaches the spec unmarked, since ! marks one flag at a
time and either spelling satisfies Click; and Cloup’s RequireAtLeast
constraint is dropped for want of anywhere to put it.
- click_extra.carapace.CARAPACE_DOCS_URL = 'https://kdeldycke.github.io/click-extra/carapace.html'¶
Documentation page stamped into every generated spec’s header comment, so a reader of the raw YAML knows where the feature is documented.
- click_extra.carapace.xdg_dir(variable, fallback, *parts)[source]¶
A directory under an XDG base directory, resolved at call time.
Reads the base directory from the environment variable
variable(XDG_CONFIG_HOME, say) and appendspartsto it. An unset or empty variable falls back tofallback, the full default path the XDG spec derives from that variable’s own default base, which already carries theparts. A leading~is expanded against theHOMEin force at the call, so neither the environment nor the home directory is read at import time: a value set for one invocation, by a test fixture or a packaging script staging into a build root, is the one honored. Passfallbackin its~form for that: a path expanded at import carries thatHOMEfor good.- Return type:
- click_extra.carapace.get_cache_dir(app_name)[source]¶
The user cache directory of
app_name, resolved at call time.The cache counterpart of
click.get_app_dir(), which locates the configuration directory:Windows:
%LOCALAPPDATA%\<app_name>\Cache.macOS:
$XDG_CACHE_HOME/<app_name>, else~/Library/Caches/<app_name>.Linux and other POSIX systems:
$XDG_CACHE_HOME/<app_name>, else~/.cache/<app_name>.
A user who sets
XDG_CACHE_HOMEasks every tool to keep its cache there, macOS included. Unlikexdg_dir(), a relative value is ignored, as the XDG specification says: a cache must not move with the working directory.- Return type:
- class click_extra.carapace.CarapaceCompletion(flag=dict(), positional=list(), positionalany=list())[source]¶
Bases:
objectThe
completionblock of a command: per-flag and positional actions.
- class click_extra.carapace.CarapaceDocumentation(positional=list(), positionalany='')[source]¶
Bases:
objectThe
documentationblock of a command: prose the spec has no other slot for.Carapace keys a flag’s own description off
flags, and leaves an operand with nowhere to carry one:completion.positionalholds actions, not text. This block is where the upstream schema puts that prose, indexed the same way, socarapace --styleand the spec’s own readers can show what an operand means.Only the two members Click can fill are modeled. The schema also carries
command,flag,dashanddashany: the first two would restate whatdescriptionandflagsalready say, and Click has no---separated argument family to feed the last two.
- class click_extra.carapace.CarapaceCommand(name, description='', aliases=(), hidden=False, flags=dict(), persistentflags=dict(), exclusiveflags=list(), completion=CarapaceCompletion(), documentation=CarapaceDocumentation(), commands=list())[source]¶
Bases:
objectOne node of a Carapace spec: a command and its flags, completions and subcommands, mirroring the upstream
Commandschema.Whether the command is hidden from listings (still completable).
- persistentflags: dict[str, str]¶
Flags inherited by every subcommand.
extract_carapace_command()leaves it empty: Click parses an option only at the level of the command declaring it, so no option is inherited.
- completion: CarapaceCompletion¶
Static and dynamic completion actions for this command’s parameters.
- documentation: CarapaceDocumentation¶
Prose for the operands, which carry theirs nowhere else in the spec.
- commands: list[CarapaceCommand]¶
Nested subcommands.
- click_extra.carapace.extract_carapace_command(command, ctx, *, command_path)[source]¶
Build a
CarapaceCommandfrom a Click command and its context.The context must have been created for
command(typically viaclick.Command.make_context()withresilient_parsing=True). Subcommands are discovered dynamically and recursed into.Every option lands in the
flagsof the command declaring it. Click parses an option only at the level of its own command: a group option goes before the subcommand, never after it. Carapacepersistentflagswould offer it after the subcommand too, where Click rejects it.command_pathis the chain of command names from the root down to this command, grown by one name per recursion and baked into dynamic callback macros (see_dynamic_action()).- Return type:
- click_extra.carapace.to_carapace_spec(command, prog_name=None, ctx=None)[source]¶
Build the Carapace spec for a command tree as a plain dict.
Reuses
ctxwhen given (the live invocation context), otherwise builds a throwaway one withresilient_parsing=True. The returned mapping conforms to thecarapace-specschema and is ready to hand toyaml.safe_dump.- Return type:
- click_extra.carapace.dump_carapace_spec(command, prog_name=None, ctx=None, *, invocation=None)[source]¶
Serialize a command tree to a Carapace spec YAML string.
Requires the optional PyYAML dependency (
click-extra[carapace]). The output keeps Click’s declaration order rather than sorting keys, so flags and subcommands line up with the help screen, and is prefixed with a provenance header: the generator, theinvocationcommand line that produced it (when given), and a link to the documentation.- Return type:
- click_extra.carapace.write_carapace_spec(command, target, prog_name=None, *, invocation=None)[source]¶
Render the spec and write it to
target, returning the written path.Creates parent directories as needed.
invocationis recorded in the header comment (seedump_carapace_spec()).- Return type:
- click_extra.carapace.install_carapace_spec(command, prog_name=None, *, invocation=None)[source]¶
Write the spec into Carapace’s user spec directory.
Targets
$XDG_CONFIG_HOME/carapace/specs/<prog>.yamlwhen that variable is set, else~/.config/carapace/specs/<prog>.yaml, both resolved at call time byxdg_dir(): Carapace loads either on startup. Returns the path.- Return type:
- class click_extra.carapace.CarapaceComplete(cli, ctx_args, prog_name, complete_var)[source]¶
Bases:
ShellCompleteClick completion backend that emits Carapace’s value/description lines.
Registered as the
carapaceshell, so_FOO_COMPLETE=carapace_completemakes a Click CLI print completions in thevalue\tdescriptiontext format Carapace’s shell macro parses. This is the callback target of the dynamic actions emitted by_dynamic_action(); it reuses Click’s ownget_completions(), so a parameter’s customshell_completeis honored verbatim.The current word is left to Carapace to filter, so completion args are the already-typed words with an empty incomplete value.
- name: ClassVar[str] = 'carapace'¶
Shell name Click registers this backend under (the
carapace_completecompletion instruction).
- source_template: ClassVar[str] = ''¶
Completion script template formatted by
source(). This must be provided by subclasses.